shellpuppet 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +4 -4
  2. package/dist/agents/claude/liveResumeId.d.ts +6 -0
  3. package/dist/agents/claude/liveResumeId.js +101 -0
  4. package/dist/agents/claude/liveResumeId.js.map +1 -0
  5. package/dist/agents/codex/draft.d.ts +3 -0
  6. package/dist/agents/codex/draft.js +88 -0
  7. package/dist/agents/codex/draft.js.map +1 -0
  8. package/dist/agents/codex/index.js +2 -0
  9. package/dist/agents/codex/index.js.map +1 -1
  10. package/dist/agents/codex/lineBreaks.d.ts +6 -0
  11. package/dist/agents/codex/lineBreaks.js +105 -0
  12. package/dist/agents/codex/lineBreaks.js.map +1 -0
  13. package/dist/agents/codex/nudge.js +7 -8
  14. package/dist/agents/codex/nudge.js.map +1 -1
  15. package/dist/agents/grok/nudge.js +8 -3
  16. package/dist/agents/grok/nudge.js.map +1 -1
  17. package/dist/agents/hermes/frame.d.ts +25 -0
  18. package/dist/agents/hermes/frame.js +145 -0
  19. package/dist/agents/hermes/frame.js.map +1 -0
  20. package/dist/agents/hermes/index.d.ts +2 -0
  21. package/dist/agents/hermes/index.js +20 -0
  22. package/dist/agents/hermes/index.js.map +1 -0
  23. package/dist/agents/hermes/nudge.d.ts +5 -0
  24. package/dist/agents/hermes/nudge.js +76 -0
  25. package/dist/agents/hermes/nudge.js.map +1 -0
  26. package/dist/agents/hermes/prompts.d.ts +7 -0
  27. package/dist/agents/hermes/prompts.js +101 -0
  28. package/dist/agents/hermes/prompts.js.map +1 -0
  29. package/dist/agents/hermes/reading.d.ts +7 -0
  30. package/dist/agents/hermes/reading.js +102 -0
  31. package/dist/agents/hermes/reading.js.map +1 -0
  32. package/dist/agents/index.d.ts +1 -1
  33. package/dist/agents/index.js +5 -3
  34. package/dist/agents/index.js.map +1 -1
  35. package/dist/agents/mimo/nudge.js +4 -3
  36. package/dist/agents/mimo/nudge.js.map +1 -1
  37. package/dist/agents/nudgeReading.d.ts +3 -3
  38. package/dist/agents/nudgeReading.js +10 -20
  39. package/dist/agents/nudgeReading.js.map +1 -1
  40. package/dist/agents/opencode/nudge.js +3 -1
  41. package/dist/agents/opencode/nudge.js.map +1 -1
  42. package/dist/agents/types.d.ts +15 -0
  43. package/dist/cli/index.js +35 -2
  44. package/dist/cli/index.js.map +1 -1
  45. package/dist/client/http.d.ts +3 -1
  46. package/dist/client/http.js +144 -51
  47. package/dist/client/http.js.map +1 -1
  48. package/dist/core/cron.d.ts +6 -0
  49. package/dist/core/cron.js +63 -0
  50. package/dist/core/cron.js.map +1 -0
  51. package/dist/core/environment.d.ts +6 -0
  52. package/dist/core/environment.js +35 -0
  53. package/dist/core/environment.js.map +1 -0
  54. package/dist/core/mailbox.d.ts +1 -0
  55. package/dist/core/mailbox.js +4 -0
  56. package/dist/core/mailbox.js.map +1 -1
  57. package/dist/core/manager.d.ts +1 -0
  58. package/dist/core/manager.js +3 -0
  59. package/dist/core/manager.js.map +1 -1
  60. package/dist/core/nudge.d.ts +1 -1
  61. package/dist/core/nudge.js +5 -2
  62. package/dist/core/nudge.js.map +1 -1
  63. package/dist/core/promptDetector.js +2 -0
  64. package/dist/core/promptDetector.js.map +1 -1
  65. package/dist/core/reasoning.js +12 -3
  66. package/dist/core/reasoning.js.map +1 -1
  67. package/dist/core/renderer.js +3 -1
  68. package/dist/core/renderer.js.map +1 -1
  69. package/dist/core/session.d.ts +17 -7
  70. package/dist/core/session.js +70 -47
  71. package/dist/core/session.js.map +1 -1
  72. package/dist/core/stringWidth.d.ts +2 -0
  73. package/dist/core/stringWidth.js +13 -0
  74. package/dist/core/stringWidth.js.map +1 -0
  75. package/dist/core/types.d.ts +2 -0
  76. package/dist/core/types.js.map +1 -1
  77. package/dist/daemon/auth.d.ts +14 -13
  78. package/dist/daemon/auth.js +42 -25
  79. package/dist/daemon/auth.js.map +1 -1
  80. package/dist/daemon/config.d.ts +2 -0
  81. package/dist/daemon/config.js +7 -0
  82. package/dist/daemon/config.js.map +1 -1
  83. package/dist/daemon/index.js +4 -0
  84. package/dist/daemon/index.js.map +1 -1
  85. package/dist/daemon/launchProfiles.js +12 -8
  86. package/dist/daemon/launchProfiles.js.map +1 -1
  87. package/dist/daemon/logger.js +1 -1
  88. package/dist/daemon/logger.js.map +1 -1
  89. package/dist/daemon/paths.d.ts +1 -1
  90. package/dist/daemon/paths.js +52 -9
  91. package/dist/daemon/paths.js.map +1 -1
  92. package/dist/daemon/restartHold.js +16 -15
  93. package/dist/daemon/restartHold.js.map +1 -1
  94. package/dist/daemon/schedules.d.ts +57 -0
  95. package/dist/daemon/schedules.js +181 -0
  96. package/dist/daemon/schedules.js.map +1 -0
  97. package/dist/daemon/screenshot.d.ts +4 -2
  98. package/dist/daemon/screenshot.js +10 -1
  99. package/dist/daemon/screenshot.js.map +1 -1
  100. package/dist/daemon/server.d.ts +20 -15
  101. package/dist/daemon/server.js +221 -132
  102. package/dist/daemon/server.js.map +1 -1
  103. package/dist/daemon/viewerLauncher.js +3 -2
  104. package/dist/daemon/viewerLauncher.js.map +1 -1
  105. package/dist/daemon/wrappedLaunch.d.ts +1 -0
  106. package/dist/daemon/wrappedLaunch.js +38 -0
  107. package/dist/daemon/wrappedLaunch.js.map +1 -0
  108. package/dist/daemon/wrappedStart.d.ts +13 -0
  109. package/dist/daemon/wrappedStart.js +113 -0
  110. package/dist/daemon/wrappedStart.js.map +1 -0
  111. package/dist/daemon/wrappedSupervisor.d.ts +1 -0
  112. package/dist/daemon/wrappedSupervisor.js +55 -0
  113. package/dist/daemon/wrappedSupervisor.js.map +1 -0
  114. package/dist/mcp/index.js +16 -0
  115. package/dist/mcp/index.js.map +1 -1
  116. package/dist/mcp/tools.js +4 -2
  117. package/dist/mcp/tools.js.map +1 -1
  118. package/package.json +1 -1
@@ -19,6 +19,7 @@ import { SessionManager, PolicyViolationError, SessionStartError } from '../core
19
19
  import { Mailbox, MailboxError, NAME_PATTERN, buildNudge } from '../core/mailbox.js';
20
20
  import { buildMessagingPolicy, DEFAULT_NUDGE_INTERVAL_MS, DEFAULT_NUDGES_PER_MINUTE } from './config.js';
21
21
  import { NudgeScheduler } from './nudgeScheduler.js';
22
+ import { ScheduleStore, PromptScheduler, watchSchedules } from './schedules.js';
22
23
  import { CommandNotFoundError, DEFAULT_SESSION_ENV, SessionInputFailedError, SessionProgramEndedError, WindowsWithoutConPTYError, credentialShapedNames, } from '../core/session.js';
23
24
  import { NativePtyUnavailableError } from '../core/nativePty.js';
24
25
  import { checkSessionCapacity, commandLine, compilePolicy, evaluateCommand } from '../core/policy.js';
@@ -457,14 +458,16 @@ export class Daemon {
457
458
  manager;
458
459
  mailbox;
459
460
  nudges;
461
+ schedules = new ScheduleStore();
462
+ pendingSchedules = new Map();
463
+ promptScheduler;
464
+ stopScheduleWatch;
460
465
  server;
466
+ /** Protocol accepted by dashboard authentication for this specific upgrade. */
467
+ dashboardUpgradeProtocols = new WeakMap();
461
468
  wss = new WebSocketServer({
462
469
  noServer: true,
463
- // Echo a subprotocol only when the dashboard credential opens the feed
464
- // or a session stream. A client token wins a session stream, so that
465
- // upgrade selects none even if the cookie and a live proof are also
466
- // offered. Returning false leaves the upgrade with none selected.
467
- handleProtocols: (protocols, request) => this.dashboardProtocol(protocols, request),
470
+ handleProtocols: (_protocols, request) => this.dashboardUpgradeProtocols.get(request) ?? false,
468
471
  });
469
472
  sockets = new Set();
470
473
  /** Every watcher of a session, with the gate that orders its stream across snapshots. */
@@ -506,8 +509,8 @@ export class Daemon {
506
509
  dashboardWindowIds = new Map();
507
510
  dashboardAssignments = new Map();
508
511
  dashboardDesignated = null;
509
- /** The document proof survives a feed reconnect and expires with the proof ring. */
510
- dashboardDocumentFocus = new Map();
512
+ /** Remember focus across reconnects for the lifetime of the document proof. */
513
+ dashboardDocumentFocus = new WeakMap();
511
514
  liveDashboardEventSockets = new Set();
512
515
  /** A launched dashboard has 30 seconds to connect before a start may retry. */
513
516
  dashboardWindowStartedAt = 0;
@@ -540,6 +543,7 @@ export class Daemon {
540
543
  promptGraceTimers = new Map();
541
544
  promptScanRunning = false;
542
545
  stopPromise = null;
546
+ shutdownRecords;
543
547
  audit;
544
548
  callerContext = new AsyncLocalStorage();
545
549
  /**
@@ -614,6 +618,9 @@ export class Daemon {
614
618
  perMinute: options.messaging?.nudgesPerMinute ?? DEFAULT_NUDGES_PER_MINUTE,
615
619
  deliver: (id) => this.deliverNudge(id),
616
620
  });
621
+ this.promptScheduler = new PromptScheduler(this.schedules, () => this.now(), (schedule, current) => this.deliverScheduled(schedule, current), (schedule, { sessionId, outcome, reason }) => this.audit.record('daemon', 'input', sessionId, {
622
+ source: 'schedule', name: schedule.name, session: schedule.session, outcome, reason,
623
+ }));
617
624
  this.mailbox.on('message', (event) => {
618
625
  const entry = this.mailbox.log().find((item) => item.id === event.id);
619
626
  if (entry !== undefined)
@@ -690,6 +697,9 @@ export class Daemon {
690
697
  if (this.stopping)
691
698
  throw new Error('Daemon stopped during startup.');
692
699
  }
700
+ const refusePending = (socket) => { socket.destroy(); };
701
+ if (this.options.afterPublish)
702
+ this.server.on('connection', refusePending);
693
703
  await new Promise((resolve, reject) => {
694
704
  this.server.once('error', reject);
695
705
  this.server.listen(0, '127.0.0.1', () => {
@@ -752,6 +762,10 @@ export class Daemon {
752
762
  // A failed rename leaves the entire predecessor record in place.
753
763
  writePrivateRecord(daemonStatePath(home), state);
754
764
  }
765
+ if (this.options.afterPublish) {
766
+ await this.options.afterPublish();
767
+ this.server.off('connection', refusePending);
768
+ }
755
769
  }
756
770
  catch (error) {
757
771
  this.releaseOwnership();
@@ -844,6 +858,8 @@ export class Daemon {
844
858
  });
845
859
  }, this.options.promptScanIntervalMs ?? PROMPT_SCAN_INTERVAL_MS);
846
860
  this.promptScanTimer.unref();
861
+ this.stopScheduleWatch = watchSchedules(home, this.schedules, this.logger);
862
+ this.promptScheduler.start();
847
863
  this.logger.info('daemon started', {
848
864
  port: this.portValue,
849
865
  pid: process.pid,
@@ -947,7 +963,6 @@ export class Daemon {
947
963
  closeServerOnly() {
948
964
  return new Promise((resolve) => {
949
965
  this.server.close(() => resolve());
950
- // close() waits for idle connections; nothing is connected this early.
951
966
  });
952
967
  }
953
968
  // ------------------------------------------------------------------- stop
@@ -961,25 +976,30 @@ export class Daemon {
961
976
  // awaits the one real shutdown.
962
977
  if (this.stopPromise === null) {
963
978
  this.stopping = true;
964
- if (opts.removeState !== false && this.publishedState && this.homeOwner) {
965
- const state = this.publishedState;
979
+ this.promptScheduler.stop();
980
+ this.stopScheduleWatch?.();
981
+ this.shutdownRecords = this.saveShutdownRecords(opts);
982
+ this.stopPromise = this.doStop();
983
+ }
984
+ return this.stopPromise;
985
+ }
986
+ saveShutdownRecords(opts) {
987
+ return Promise.resolve().then(() => {
988
+ const state = opts.removeState !== false && this.homeOwner ? this.publishedState : null;
989
+ if (state) {
990
+ // Publish the final claims, source, snapshot and handoff in one turn.
966
991
  this.writeShutdownRecord('launcher-claims.json', () => this.saveLauncherClaims());
967
992
  if (opts.restart) {
968
993
  this.writeShutdownRecord('restart-source.json', () => {
969
994
  this.requireHomeOwner();
970
995
  writePrivateRecord(path.join(this.options.home, 'restart-source.json'), { restartFrom: this.instanceId });
971
996
  });
972
- this.writeShutdownRecord('previous-sessions.json', () => {
973
- this.requireHomeOwner();
974
- this.savePreviousSessions();
975
- });
997
+ this.writeShutdownRecord('previous-sessions.json', () => this.savePreviousSessions());
976
998
  }
977
999
  this.writeShutdownRecord('daemon.json', () => this.finishDiscovery(state, opts.restart === true));
978
1000
  }
979
1001
  this.releaseOwnership();
980
- this.stopPromise = this.doStop();
981
- }
982
- return this.stopPromise;
1002
+ });
983
1003
  }
984
1004
  finishDiscovery(state, restart) {
985
1005
  const discovery = this.requireHomeOwner();
@@ -1005,11 +1025,14 @@ export class Daemon {
1005
1025
  write();
1006
1026
  }
1007
1027
  catch (error) {
1008
- const message = `Could not ${verb} ${file} during shutdown.`;
1009
- this.shutdownWarnings.push(message);
1010
- this.logger.warn(message, { code: error.code });
1028
+ this.shutdownRecordFailure(file, verb, error);
1011
1029
  }
1012
1030
  }
1031
+ shutdownRecordFailure(file, verb, error) {
1032
+ const message = `Could not ${verb} ${file} during shutdown.`;
1033
+ this.shutdownWarnings.push(message);
1034
+ this.logger.warn(message, { code: error.code });
1035
+ }
1013
1036
  releaseOwnership() {
1014
1037
  const owner = this.homeOwner;
1015
1038
  this.homeOwner = undefined;
@@ -1045,16 +1068,12 @@ export class Daemon {
1045
1068
  this.folderPickerAbort?.abort(new FolderPickerFailureError('The folder picker was stopped.'));
1046
1069
  for (const read of this.widerReads.values())
1047
1070
  read.abort.abort();
1048
- await Promise.allSettled([...this.widerReads.values()].map((read) => read.done));
1049
- // Stop LISTENING first, before tearing down session trees. Killing process
1050
- // trees is not fast (`taskkill /T` on a loaded machine can take seconds
1051
- // per session), and a daemon that still answers on its port while shutting
1052
- // down looks alive to every client polling /health. `close()` refuses new
1053
- // connections immediately while letting in-flight responses drain on
1054
- // their existing socket, notably the reply to this very shutdown request.
1055
- const listenerClosed = new Promise((resolve) => {
1056
- this.server.close(() => resolve());
1057
- });
1071
+ const readsDone = Promise.allSettled([...this.widerReads.values()].map((read) => read.done));
1072
+ await this.shutdownRecords;
1073
+ // A free port lets a successor retire the ownership marker. Keep it
1074
+ // bound through publication, then close without waiting for PTY teardown.
1075
+ const listenerClosed = this.closeServerOnly();
1076
+ await readsDone;
1058
1077
  for (const socket of this.sockets) {
1059
1078
  try {
1060
1079
  socket.close();
@@ -1262,7 +1281,7 @@ export class Daemon {
1262
1281
  if (grantPresented) {
1263
1282
  const redeemed = this.tokens.redeemDashboardGrant(grant, this.now());
1264
1283
  if (redeemed !== null) {
1265
- this.retireDashboardFeeds();
1284
+ this.retireDashboardSockets();
1266
1285
  this.audit.record('dashboard', 'grant-redeem');
1267
1286
  res.writeHead(303, {
1268
1287
  location: '/dashboard',
@@ -1276,8 +1295,13 @@ export class Daemon {
1276
1295
  return;
1277
1296
  }
1278
1297
  const proof = cookie === null ? null : this.tokens.issueDashboardProof();
1279
- if (proof !== null)
1280
- this.retireDashboardFeeds();
1298
+ if (cookie !== null && proof === null) {
1299
+ this.auditDashboardRefusal(req, 'limit');
1300
+ res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8',
1301
+ 'cache-control': 'no-store', 'content-security-policy': PAGE_CSP });
1302
+ res.end('Too many dashboard windows are open. Close one and reload this page.');
1303
+ return;
1304
+ }
1281
1305
  this.sendDashboardPage(res, proof, req.method === 'HEAD');
1282
1306
  return;
1283
1307
  }
@@ -1313,7 +1337,7 @@ export class Daemon {
1313
1337
  this.pendingDashboardGrants.delete(grant);
1314
1338
  if (this.stopping || !opened.launched || opened.mode === 'default-browser') {
1315
1339
  this.tokens.revokeDashboardGrant(grant);
1316
- this.retireDashboardFeeds();
1340
+ this.retireDashboardSockets();
1317
1341
  this.auditDashboardRefusal(req, 'launch-failed');
1318
1342
  return false;
1319
1343
  }
@@ -1383,9 +1407,10 @@ export class Daemon {
1383
1407
  json(res, 400, { error: hide === null ? BAD_HIDE_REASONING : 'waitingOnly must be true or false.' });
1384
1408
  return;
1385
1409
  }
1386
- json(res, 200, { sessions: waitingOnly ? this.waitingSessions(hide) : this.listWithPrompts(hide), version: this.version });
1410
+ const sessions = waitingOnly ? this.waitingSessions(hide, { includeCwd: true }) : this.listWithPrompts(hide);
1411
+ json(res, 200, { sessions, version: this.version });
1387
1412
  }
1388
- waitingSessions(hideReasoning, ids) {
1413
+ waitingSessions(hideReasoning, { includeCwd, ids }) {
1389
1414
  return this.listWithPrompts(hideReasoning).flatMap((session) => {
1390
1415
  const waiting = session.waitingOnPrompt;
1391
1416
  if (session.exited || waiting === undefined || (ids !== undefined && !ids.has(session.id)))
@@ -1393,6 +1418,7 @@ export class Daemon {
1393
1418
  return [{
1394
1419
  id: session.id,
1395
1420
  label: session.label,
1421
+ ...(includeCwd ? { cwd: session.cwd } : {}),
1396
1422
  ...(waiting.question === undefined ? {} : { question: waiting.question }),
1397
1423
  ...(waiting.options === undefined ? {} : { options: waiting.options }),
1398
1424
  ...(waiting.selectedOption === undefined ? {} : { selectedOption: waiting.selectedOption }),
@@ -1423,7 +1449,7 @@ export class Daemon {
1423
1449
  this.waitsInFlight += 1;
1424
1450
  try {
1425
1451
  while (!res.destroyed) {
1426
- const waiting = prompt ? this.waitingSessions(hide, ids) : [];
1452
+ const waiting = prompt ? this.waitingSessions(hide, { ids }) : [];
1427
1453
  const stalledSessions = stalled ? this.listWithPrompts(hide).flatMap(session => session.exited || session.stalled === undefined || (ids !== undefined && !ids.has(session.id)) ? [] :
1428
1454
  [{ id: session.id, label: session.label, reason: 'stalled', stalled: session.stalled }]) : [];
1429
1455
  const sessions = [...(stalled ? waiting.map(session => ({ ...session, reason: 'prompt' })) : waiting), ...stalledSessions];
@@ -1770,7 +1796,9 @@ export class Daemon {
1770
1796
  }
1771
1797
  }
1772
1798
  const requestedWindow = body['window'];
1773
- const launchingWindow = requestedWindow === undefined ? undefined : this.dashboardWindows().find((window) => window.pair === requestedWindow && dashboardProofFromProtocol(window.socket.protocol) === documentProof);
1799
+ const launchingWindow = requestedWindow === undefined || documentProof === undefined ? undefined
1800
+ : this.dashboardWindows().find(window => window.pair === requestedWindow &&
1801
+ tokensEqual(window.socket.protocol, `sp-csrf.${documentProof}`));
1774
1802
  if (requestedWindow !== undefined && launchingWindow === undefined) {
1775
1803
  json(res, 409, { error: 'The launching dashboard window has closed.' });
1776
1804
  return;
@@ -2184,9 +2212,7 @@ export class Daemon {
2184
2212
  json(res, 200, { id, name: body['name'], label: session.label });
2185
2213
  }
2186
2214
  /**
2187
- * Authenticate the dashboard event feed and retain its issuing credential.
2188
- * The client token on the query is not a way in. The proof is the
2189
- * subprotocol, not `X-ShellPuppet-CSRF`.
2215
+ * Authenticate a dashboard upgrade and select the offered protocol that proved it.
2190
2216
  */
2191
2217
  dashboardUpgradeCredential(req) {
2192
2218
  const token = this.dashboardCookieToken(req.headers.cookie);
@@ -2205,46 +2231,10 @@ export class Daemon {
2205
2231
  (site === undefined && mode === undefined))) {
2206
2232
  return { code: 403, reason: 'Forbidden', audit: 'fetch-site' };
2207
2233
  }
2208
- const accepted = offeredProtocols(req).some((protocol) => {
2209
- const proof = dashboardProofFromProtocol(protocol);
2210
- return proof !== null && this.tokens.acceptsDashboardProof(proof);
2211
- });
2212
- if (!accepted)
2234
+ const protocol = offeredProtocols(req).find(offer => this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(offer)));
2235
+ if (protocol === undefined)
2213
2236
  return { code: 403, reason: 'Forbidden', audit: 'proof' };
2214
- return token;
2215
- }
2216
- /**
2217
- * Select `sp-csrf.<proof>` when this upgrade's credential is the dashboard
2218
- * cookie: the dashboard feed, or a session stream the client token did not
2219
- * take. The echo names that credential. A viewer or client socket, including
2220
- * a client token that also carries the cookie and offers a live proof,
2221
- * selects none. Returning false leaves the upgrade with none selected.
2222
- */
2223
- dashboardProtocol(protocols, request) {
2224
- let url;
2225
- try {
2226
- url = new URL(request.url ?? '/', 'http://127.0.0.1');
2227
- }
2228
- catch {
2229
- return false;
2230
- }
2231
- const segments = url.pathname.split('/').filter((part) => part !== '');
2232
- const sessionStream = segments.length === 3 && segments[0] === 'sessions' && segments[2] === 'stream';
2233
- if (url.pathname !== '/dashboard/events' && !sessionStream)
2234
- return false;
2235
- // Same preference as sessionStreamDecision: a live client token opens a
2236
- // client socket, so the echoed protocol must not say this is the dashboard.
2237
- if (sessionStream && this.tokens.verify(url.searchParams.get('token'))?.kind === 'client') {
2238
- return false;
2239
- }
2240
- if (this.dashboardCookieToken(request.headers.cookie) === null)
2241
- return false;
2242
- for (const protocol of protocols) {
2243
- const proof = dashboardProofFromProtocol(protocol);
2244
- if (proof !== null && this.tokens.acceptsDashboardProof(proof))
2245
- return protocol;
2246
- }
2247
- return false;
2237
+ return { kind: 'dashboard', readOnly: false, dashboardToken: token, protocol };
2248
2238
  }
2249
2239
  /**
2250
2240
  * Who may open `/sessions/<id>/stream`, or why not.
@@ -2255,9 +2245,9 @@ export class Daemon {
2255
2245
  * upgrade's rules: a live `sp-csrf` subprotocol, a matching Origin, and
2256
2246
  * same-origin Fetch Metadata. A header is not the proof. A viewer cookie,
2257
2247
  * including a read-only one, is never treated as the dashboard credential.
2258
- * When both are present and the proof is live, the dashboard cookie is the
2248
+ * When both are present and the dashboard checks pass, the dashboard cookie is the
2259
2249
  * one that opens the socket, so a read-only viewer cookie in the same jar
2260
- * does not mask it. When the proof is missing, a viewer cookie for this
2250
+ * does not mask it. When the dashboard checks fail, a viewer cookie for this
2261
2251
  * session still opens the socket on its own rules.
2262
2252
  */
2263
2253
  sessionStreamDecision(req, url, sessionId) {
@@ -2269,9 +2259,8 @@ export class Daemon {
2269
2259
  return { ok: true, credential: { kind: 'client', readOnly: false } };
2270
2260
  }
2271
2261
  const dashboard = this.dashboardUpgradeCredential(req);
2272
- if (typeof dashboard === 'string') {
2273
- return { ok: true, credential: { kind: 'dashboard', readOnly: false,
2274
- dashboardToken: dashboard } };
2262
+ if ('kind' in dashboard) {
2263
+ return { ok: true, credential: dashboard };
2275
2264
  }
2276
2265
  const viewer = cookieValues(req.headers.cookie, VIEWER_COOKIE)
2277
2266
  .map((value) => ({ value, credential: this.tokens.verifyStreamToken(value) }))
@@ -2463,6 +2452,10 @@ export class Daemon {
2463
2452
  const candidates = headerOne(req, 'x-shellpuppet-resume-ids') ?? headerOne(req, 'x-shellpuppet-resume-id');
2464
2453
  if (candidates)
2465
2454
  session?.observeResumeId(...candidates.split(','));
2455
+ const fileResumeId = headerOne(req, 'x-shellpuppet-claude-file-resume-id');
2456
+ if (fileResumeId !== undefined && session?.observeClaudeFileResumeId(fileResumeId)) {
2457
+ res.setHeader('x-shellpuppet-resume-id-recorded', fileResumeId);
2458
+ }
2466
2459
  }
2467
2460
  return this.callerContext.run(caller.session, () => this.handleClientRequest(req, res, url, segments, actor));
2468
2461
  }
@@ -2515,12 +2508,12 @@ export class Daemon {
2515
2508
  return state.restartFrom === snapshot;
2516
2509
  }
2517
2510
  savePreviousSessions() {
2511
+ this.requireHomeOwner();
2518
2512
  const endedAt = new Date(this.now()).toISOString();
2519
- const sessions = this.manager.list().flatMap(summary => {
2520
- const session = this.manager.get(summary.id);
2513
+ const sessions = this.manager.liveProfileSessions().flatMap(session => {
2521
2514
  // A deferred start has no participant until the program has started and acquired its name.
2522
- const participant = this.mailbox.participant(summary.id);
2523
- if (!participant || !session || session.exited || session.isKilled || !session.launchProfile)
2515
+ const participant = this.mailbox.participant(session.id);
2516
+ if (!participant)
2524
2517
  return [];
2525
2518
  return [{ ...session.launchProfile, name: participant.name === session.id ? null : participant.name,
2526
2519
  agent: session.agent, resumeId: session.resumeId, endedAt }];
@@ -2563,6 +2556,9 @@ export class Daemon {
2563
2556
  });
2564
2557
  }
2565
2558
  endMailboxParticipant(id) {
2559
+ for (const [name, pendingId] of this.pendingSchedules)
2560
+ if (pendingId === id)
2561
+ this.pendingSchedules.delete(name);
2566
2562
  this.nudges.remove(id);
2567
2563
  // Audit before end can trim old tombstones from retained history.
2568
2564
  for (const entry of this.mailbox.log({ participantId: id })) {
@@ -2588,6 +2584,11 @@ export class Daemon {
2588
2584
  if (session === undefined || session.exited || this.mailbox.participant(id)?.kind !== 'session')
2589
2585
  return 'done';
2590
2586
  const pendingIds = session.nudgePendingLine() !== null ? [...session.nudgePendingIds()] : [];
2587
+ // A scheduled body has no mailbox ids. It can clear on proof of consumption,
2588
+ // but a later inbox message can never authorise its submit key.
2589
+ if (session.nudgePendingLine() !== null && pendingIds.length === 0 &&
2590
+ !await this.clearScheduledBody(session))
2591
+ return 'wait';
2591
2592
  const clearedIds = pendingIds.length > 0 && await session.clearConsumedNudge() ? pendingIds : [];
2592
2593
  const unread = this.mailbox.inbox(id, { markRead: false });
2593
2594
  if (clearedIds.length > 0) {
@@ -2596,6 +2597,8 @@ export class Daemon {
2596
2597
  }
2597
2598
  const pending = session.nudgePendingLine();
2598
2599
  if (pending !== null) {
2600
+ if (session.nudgePendingIds().length === 0)
2601
+ return 'wait';
2599
2602
  const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2600
2603
  if (ids.length === 0)
2601
2604
  return 'done';
@@ -2620,7 +2623,7 @@ export class Daemon {
2620
2623
  session.nudgeInputVersion() === inputVersion &&
2621
2624
  session.nudgeQueuedInputVersion() === queuedInputVersion &&
2622
2625
  session.nudgeScreenRevision() === screenRevision &&
2623
- session.answerablePrompt(screen) === null &&
2626
+ session.answerablePrompt(screen) === null && session.nudgePendingIds().length > 0 &&
2624
2627
  waitingIds.length === ids.length &&
2625
2628
  ids.every((messageId) => waitingIds.includes(messageId));
2626
2629
  });
@@ -2644,24 +2647,80 @@ export class Daemon {
2644
2647
  const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2645
2648
  if (ids.length === 0)
2646
2649
  return 'done';
2647
- const line = buildNudge(unread);
2648
2650
  if (!session.hasPainted() || !session.nudgeReady(this.now()))
2649
2651
  return 'wait';
2650
- const snapshot = await session.snapshot();
2651
- const state = session.nudgeState(this.now());
2652
- if (snapshot.exited || session.answerablePrompt(snapshot.screen) !== null || !state.ready)
2652
+ const line = buildNudge(unread);
2653
+ const result = await this.deliverLine(session, line, undefined, ids, () => {
2654
+ const current = this.mailbox.inbox(id, { markRead: false });
2655
+ return ids.every(messageId => current.some(entry => entry.id === messageId && entry.state === 'waiting'));
2656
+ });
2657
+ if (result.outcome === 'aborted') {
2658
+ this.audit.record('daemon', 'nudge-aborted', id, { messageIds: ids, count: ids.length, reason: result.reason });
2659
+ }
2660
+ if (result.outcome !== 'sent' && result.outcome !== 'queued')
2653
2661
  return 'wait';
2662
+ this.mailbox.markNudged(ids);
2663
+ this.audit.record('daemon', 'nudge', id, { messageIds: ids, count: ids.length,
2664
+ ...(result.outcome === 'queued' ? { queued: true } : {}) });
2665
+ return 'sent';
2666
+ }
2667
+ async clearScheduledBody(session) {
2668
+ const name = session.pendingSchedule();
2669
+ if (name === undefined || !await session.clearConsumedNudge())
2670
+ return false;
2671
+ if (this.pendingSchedules.get(name) === session.id)
2672
+ this.pendingSchedules.delete(name);
2673
+ return true;
2674
+ }
2675
+ async deliverScheduled(schedule, current) {
2676
+ const id = this.mailbox.sessionIdByName(schedule.session);
2677
+ const session = id === undefined ? undefined : this.manager.get(id);
2678
+ if (!session || session.exited)
2679
+ return { outcome: 'skipped', reason: 'no-session' };
2680
+ if (session.recentInput)
2681
+ return { sessionId: id, outcome: 'skipped', reason: 'recent-input' };
2682
+ const pendingId = this.pendingSchedules.get(schedule.name);
2683
+ if (pendingId !== undefined) {
2684
+ const previous = this.manager.get(pendingId);
2685
+ if (previous?.pendingSchedule() === schedule.name && !await this.clearScheduledBody(previous)) {
2686
+ return { sessionId: id, outcome: 'skipped', reason: 'pending' };
2687
+ }
2688
+ this.pendingSchedules.delete(schedule.name);
2689
+ }
2690
+ if (session.nudgePendingLine() !== null && !await this.clearScheduledBody(session)) {
2691
+ return { sessionId: id, outcome: 'skipped', reason: 'pending' };
2692
+ }
2693
+ try {
2694
+ const result = await this.deliverLine(session, schedule.message, schedule.whenBusy, [], () => current() && this.mailbox.sessionIdByName(schedule.session) === id, schedule.name);
2695
+ // Ordinary input can also arrive while the scheduled write waits in the input queue.
2696
+ if (result.outcome === 'skipped' && session.recentInput)
2697
+ result.reason = 'recent-input';
2698
+ return { ...result, sessionId: id };
2699
+ }
2700
+ finally {
2701
+ if (!session.exited && session.pendingSchedule() === schedule.name)
2702
+ this.pendingSchedules.set(schedule.name, session.id);
2703
+ }
2704
+ }
2705
+ async deliverLine(session, line, whenBusy, ids, currentDelivery, schedule) {
2706
+ if (!session.hasPainted())
2707
+ return { outcome: 'skipped', reason: 'unknown' };
2708
+ const inputVersion = session.nudgeInputVersion();
2709
+ const queuedInputVersion = session.nudgeQueuedInputVersion();
2710
+ const snapshot = await session.snapshot();
2711
+ const state = session.nudgeState(this.now(), whenBusy);
2712
+ if (snapshot.exited)
2713
+ return { outcome: 'skipped', reason: 'session-ended' };
2714
+ if (session.answerablePrompt(snapshot.screen) !== null)
2715
+ return { outcome: 'skipped', reason: 'prompt' };
2716
+ if (!state.ready)
2717
+ return { outcome: 'skipped',
2718
+ reason: state.reason === 'busy' && whenBusy === 'queue' ? 'cannot-queue' : state.reason ?? 'unknown' };
2654
2719
  // Check the same region again before typing. A running turn can repaint
2655
2720
  // its transcript, and a separate sidebar can repaint beside an idle pane.
2656
2721
  const queued = state.queued;
2657
2722
  const outputAt = session.lastChangeAt();
2658
- const inputVersion = session.nudgeInputVersion();
2659
- const queuedInputVersion = session.nudgeQueuedInputVersion();
2660
2723
  const screenRevision = session.nudgeScreenRevision();
2661
- const stillWaiting = () => {
2662
- const current = this.mailbox.inbox(id, { markRead: false });
2663
- return ids.every((messageId) => current.some((entry) => entry.id === messageId && entry.state === 'waiting'));
2664
- };
2665
2724
  let failedCheck = 'line-not-seen';
2666
2725
  const ready = (screen, phase) => {
2667
2726
  if (session.exited) {
@@ -2672,7 +2731,7 @@ export class Daemon {
2672
2731
  failedCheck = 'stalled';
2673
2732
  return false;
2674
2733
  }
2675
- const current = phase === 'before' ? session.nudgeState(this.now()) : undefined;
2734
+ const current = phase === 'before' ? session.nudgeState(this.now(), whenBusy) : undefined;
2676
2735
  if (session.nudgeScreenRevision() !== screenRevision ||
2677
2736
  (phase === 'before' && (queued || state.paneQuiet ? current?.regionKey !== state.regionKey
2678
2737
  : session.lastChangeAt() !== outputAt || screen !== snapshot.screen))) {
@@ -2688,34 +2747,33 @@ export class Daemon {
2688
2747
  failedCheck = 'prompt-showing';
2689
2748
  return false;
2690
2749
  }
2691
- if (!stillWaiting()) {
2692
- failedCheck = 'messages-changed';
2750
+ if (!currentDelivery()) {
2751
+ failedCheck = ids.length ? 'messages-changed' : 'schedule-changed';
2693
2752
  return false;
2694
2753
  }
2695
- if (phase === 'before' ? !current?.ready : !session.nudgeReadyWithLine(line)) {
2754
+ if (phase === 'before' ? !current?.ready || current.queued !== queued : !session.nudgeReadyWithLine(line, queued, whenBusy)) {
2696
2755
  failedCheck = 'line-not-seen';
2697
2756
  return false;
2698
2757
  }
2699
2758
  return true;
2700
2759
  };
2701
2760
  try {
2702
- const result = await session.writeNudgeWithReason(line + session.nudgeSubmit(), ready, ids, () => failedCheck);
2761
+ const result = await session.writeNudgeWithReason(line + session.nudgeSubmit(queued), ready, ids, () => failedCheck, schedule, queued);
2703
2762
  if (result === 'wait')
2704
- return 'wait';
2763
+ return { outcome: 'skipped', reason: session.nudgePendingLine() !== null ? 'pending' : failedCheck };
2705
2764
  if (result.startsWith('aborted-')) {
2706
2765
  const reason = result.slice('aborted-'.length);
2707
- this.audit.record('daemon', 'nudge-aborted', id, { messageIds: ids, count: ids.length, reason });
2708
- return 'wait';
2766
+ return { outcome: 'aborted', reason };
2709
2767
  }
2710
2768
  }
2711
2769
  catch (error) {
2712
- if (error instanceof SessionInputFailedError || error instanceof SessionProgramEndedError)
2713
- return 'wait';
2770
+ if (error instanceof SessionInputFailedError)
2771
+ return { outcome: 'skipped', reason: 'input-failed' };
2772
+ if (error instanceof SessionProgramEndedError)
2773
+ return { outcome: 'skipped', reason: 'session-ended' };
2714
2774
  throw error;
2715
2775
  }
2716
- this.mailbox.markNudged(ids);
2717
- this.audit.record('daemon', 'nudge', id, { messageIds: ids, count: ids.length, ...(queued ? { queued: true } : {}) });
2718
- return 'sent';
2776
+ return { outcome: queued ? 'queued' : 'sent' };
2719
2777
  }
2720
2778
  registerMailboxSession(session, profileName) {
2721
2779
  const label = profileName ?? session.label;
@@ -2919,9 +2977,14 @@ export class Daemon {
2919
2977
  }
2920
2978
  async handleClientRequest(req, res, url, segments, actor) {
2921
2979
  try {
2980
+ if (url.pathname === '/schedules' && req.method === 'GET') {
2981
+ json(res, 200, { schedules: this.promptScheduler.list() });
2982
+ return;
2983
+ }
2922
2984
  if (segments[0] === 'daemon' && segments[1] === 'shutdown' && req.method === 'POST') {
2923
2985
  const body = await readBody(req);
2924
2986
  if (this.stopping) {
2987
+ await this.shutdownRecords;
2925
2988
  json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
2926
2989
  return;
2927
2990
  }
@@ -2936,6 +2999,7 @@ export class Daemon {
2936
2999
  }
2937
3000
  const stopping = this.stop({ restart: body['restart'] === true });
2938
3001
  this.audit.record(actor, 'shutdown', undefined, { force, liveSessions: live });
3002
+ await this.shutdownRecords;
2939
3003
  json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
2940
3004
  void stopping.then(() => {
2941
3005
  this.options.onSelfStop?.('shutdown-request');
@@ -3723,6 +3787,10 @@ export class Daemon {
3723
3787
  }
3724
3788
  async handleStart(req, res, actor) {
3725
3789
  const body = await readBody(req);
3790
+ if (this.stopping) {
3791
+ json(res, 503, { error: 'The daemon is stopping.' });
3792
+ return;
3793
+ }
3726
3794
  const command = asString(body['command']);
3727
3795
  if (command === undefined || command === '') {
3728
3796
  json(res, 400, { error: 'command (string) is required.' });
@@ -4212,6 +4280,7 @@ export class Daemon {
4212
4280
  async scanForPromptStalls() {
4213
4281
  const stallMs = this.options.promptStallMs ?? PROMPT_STALL_MS;
4214
4282
  const seen = new Set();
4283
+ const scheduled = new Set(this.schedules.read().filter(s => s.enabled).map(s => this.mailbox.sessionIdByName(s.session)));
4215
4284
  for (const summary of this.manager.list()) {
4216
4285
  const session = this.manager.get(summary.id);
4217
4286
  if (session === undefined || session.exited)
@@ -4220,6 +4289,8 @@ export class Daemon {
4220
4289
  let detected;
4221
4290
  try {
4222
4291
  const snapshot = await session.snapshot();
4292
+ if (scheduled.has(session.id))
4293
+ session.nudgeState(this.now());
4223
4294
  detected = session.answerablePrompt(snapshot.screen);
4224
4295
  }
4225
4296
  catch (error) {
@@ -4432,15 +4503,16 @@ export class Daemon {
4432
4503
  const segments = url.pathname.split('/').filter((s) => s !== '');
4433
4504
  // The dashboard feed is cookie-only. Its Origin rule is stricter than the
4434
4505
  // client-token sockets below, which still allow a missing Origin.
4435
- if (segments[0] === 'dashboard' && segments[1] === 'events' && segments.length === 2) {
4506
+ if (url.pathname === '/dashboard/events') {
4436
4507
  const credential = this.dashboardUpgradeCredential(req);
4437
- if (typeof credential !== 'string') {
4508
+ if ('code' in credential) {
4438
4509
  this.auditDashboardRefusal(req, credential.audit);
4439
4510
  reject(credential.code, credential.reason);
4440
4511
  return;
4441
4512
  }
4513
+ this.dashboardUpgradeProtocols.set(req, credential.protocol);
4442
4514
  this.wss.handleUpgrade(req, socket, head, (ws) => {
4443
- this.attachDashboardSocket(ws, credential);
4515
+ this.attachDashboardSocket(ws, credential.dashboardToken);
4444
4516
  });
4445
4517
  return;
4446
4518
  }
@@ -4475,7 +4547,7 @@ export class Daemon {
4475
4547
  });
4476
4548
  return;
4477
4549
  }
4478
- if (segments[0] !== 'sessions' || segments[2] !== 'stream') {
4550
+ if (segments.length !== 3 || segments[0] !== 'sessions' || segments[2] !== 'stream') {
4479
4551
  reject(404, 'Not Found');
4480
4552
  return;
4481
4553
  }
@@ -4514,6 +4586,9 @@ export class Daemon {
4514
4586
  // dashboard credential is made passive in attachSocket, whatever the
4515
4587
  // query says, so this flag cannot turn that socket into a driver.
4516
4588
  const passive = passiveDrive(url);
4589
+ if (decision.credential.kind === 'dashboard') {
4590
+ this.dashboardUpgradeProtocols.set(req, decision.credential.protocol);
4591
+ }
4517
4592
  this.wss.handleUpgrade(req, socket, head, (ws) => {
4518
4593
  // Which credential opened the socket travels with it, so the audit log
4519
4594
  // names that credential rather than assuming a browser: `client` for
@@ -4564,7 +4639,9 @@ export class Daemon {
4564
4639
  for (const [id, previous] of this.dashboardTransferable) {
4565
4640
  const owner = windows.find(w => this.dashboardAssignments.get(w.pair)?.includes(id));
4566
4641
  const recipient = owner?.socket.protocol;
4567
- if (recipient === previous || (previous === null && windows.length === 0))
4642
+ const unchanged = recipient === undefined ? previous === undefined
4643
+ : typeof previous === 'string' && tokensEqual(previous, recipient);
4644
+ if (unchanged || (previous === null && windows.length === 0))
4568
4645
  continue;
4569
4646
  this.dashboardTransferable.set(id, recipient);
4570
4647
  const session = this.manager.get(id);
@@ -4612,14 +4689,11 @@ export class Daemon {
4612
4689
  return this.tokens.verifyDashboardToken(this.dashboardSocketCredential.get(ws)) &&
4613
4690
  this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(ws.protocol));
4614
4691
  }
4615
- retireDashboardFeeds() {
4616
- for (const protocol of this.dashboardDocumentFocus.keys()) {
4617
- if (!this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(protocol)))
4618
- this.dashboardDocumentFocus.delete(protocol);
4619
- }
4692
+ retireDashboardSockets() {
4620
4693
  let changed = false;
4621
- for (const ws of this.dashboardEventSockets) {
4622
- if (ws.readyState === ws.OPEN && !this.dashboardFeedCurrent(ws)) {
4694
+ for (const ws of this.sockets) {
4695
+ const credential = this.dashboardSocketCredential.get(ws);
4696
+ if (credential !== undefined && ws.readyState === ws.OPEN && !this.tokens.verifyDashboardToken(credential)) {
4623
4697
  if (this.dashboardWindowIds.delete(ws))
4624
4698
  changed = true;
4625
4699
  this.liveDashboardEventSockets.delete(ws);
@@ -4629,8 +4703,20 @@ export class Daemon {
4629
4703
  if (changed)
4630
4704
  this.publishDashboardWindows();
4631
4705
  }
4632
- attachDashboardSocket(ws, credential) {
4706
+ retainSocketProof(ws, credential) {
4707
+ const proof = this.tokens.retainDashboardProof(dashboardProofFromProtocol(ws.protocol));
4708
+ if (proof === undefined) {
4709
+ ws.close(1008, 'Dashboard access expired');
4710
+ return undefined;
4711
+ }
4633
4712
  this.dashboardSocketCredential.set(ws, credential);
4713
+ ws.once('close', () => this.tokens.releaseDashboardProof(proof));
4714
+ return proof;
4715
+ }
4716
+ attachDashboardSocket(ws, credential) {
4717
+ const proof = this.retainSocketProof(ws, credential);
4718
+ if (proof === undefined)
4719
+ return;
4634
4720
  this.sockets.add(ws);
4635
4721
  this.dashboardEventSockets.add(ws);
4636
4722
  this.liveDashboardEventSockets.add(ws);
@@ -4685,7 +4771,7 @@ export class Daemon {
4685
4771
  if (claim.type === 'window-focus') {
4686
4772
  const at = claim.focusedAt === undefined ? performance.timeOrigin + performance.now() : claim.focusedAt;
4687
4773
  current.focused = Math.max(current.focused, this.dashboardFocusTime(at));
4688
- this.dashboardDocumentFocus.set(ws.protocol, { id: current.id, focused: current.focused });
4774
+ this.dashboardDocumentFocus.set(proof, { id: current.id, focused: current.focused });
4689
4775
  this.publishDashboardWindows();
4690
4776
  }
4691
4777
  else if (claim.type === 'window-designate') {
@@ -4719,10 +4805,10 @@ export class Daemon {
4719
4805
  !/^[a-z0-9]+-[a-z0-9]+(?:-[1-9][0-9]*)?$/.test(claim.instance) ||
4720
4806
  claim.instance.length > 100)
4721
4807
  return;
4722
- const previous = this.dashboardDocumentFocus.get(ws.protocol);
4808
+ const previous = this.dashboardDocumentFocus.get(proof);
4723
4809
  const focused = Math.max(previous?.id === claim.id ? previous.focused : 0, this.dashboardFocusTime(claim.focusedAt));
4724
4810
  this.dashboardWindowIds.set(ws, { id: claim.id, instance: claim.instance, focused });
4725
- this.dashboardDocumentFocus.set(ws.protocol, { id: claim.id, focused });
4811
+ this.dashboardDocumentFocus.set(proof, { id: claim.id, focused });
4726
4812
  this.publishDashboardWindows();
4727
4813
  });
4728
4814
  ws.on('close', () => {
@@ -4788,7 +4874,7 @@ export class Daemon {
4788
4874
  }
4789
4875
  gridOfferedTo(id, ws) {
4790
4876
  const recipient = this.dashboardTransferable.get(id);
4791
- return (recipient === null || recipient === ws.protocol) &&
4877
+ return (recipient === null || (recipient !== undefined && tokensEqual(recipient, ws.protocol))) &&
4792
4878
  this.dashboardCredentialOwner.has(id) && this.dashboardSocketCredential.has(ws) &&
4793
4879
  tokensEqual(this.dashboardCredentialOwner.get(id), this.dashboardSocketCredential.get(ws));
4794
4880
  }
@@ -4858,9 +4944,10 @@ export class Daemon {
4858
4944
  // dashboard cookie did. The actor names the credential, not the person
4859
4945
  // or program behind it.
4860
4946
  const actor = credential.kind;
4947
+ if (credential.kind === 'dashboard' &&
4948
+ this.retainSocketProof(ws, credential.dashboardToken) === undefined)
4949
+ return;
4861
4950
  this.sockets.add(ws);
4862
- if (credential.dashboardToken !== undefined)
4863
- this.dashboardSocketCredential.set(ws, credential.dashboardToken);
4864
4951
  let watchers = this.sessionSockets.get(session.id);
4865
4952
  if (watchers === undefined) {
4866
4953
  watchers = new Map();
@@ -5226,6 +5313,8 @@ export class Daemon {
5226
5313
  this.broadcastControl(session.id, { type: 'input-source', source: 'human' });
5227
5314
  };
5228
5315
  ws.on('message', (message) => {
5316
+ if (actor === 'dashboard' && ws.readyState !== ws.OPEN)
5317
+ return;
5229
5318
  this.callerContext.run(options.callerSession, () => {
5230
5319
  void onViewerMessage(message).catch((error) => {
5231
5320
  this.logger.warn('viewer message failed', { id: session.id, error: String(error) });