shellpuppet 0.3.0 → 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 (112) 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/config.d.ts +2 -0
  78. package/dist/daemon/config.js +7 -0
  79. package/dist/daemon/config.js.map +1 -1
  80. package/dist/daemon/index.js +4 -0
  81. package/dist/daemon/index.js.map +1 -1
  82. package/dist/daemon/launchProfiles.js +12 -8
  83. package/dist/daemon/launchProfiles.js.map +1 -1
  84. package/dist/daemon/logger.js +1 -1
  85. package/dist/daemon/logger.js.map +1 -1
  86. package/dist/daemon/paths.d.ts +1 -1
  87. package/dist/daemon/paths.js +52 -9
  88. package/dist/daemon/paths.js.map +1 -1
  89. package/dist/daemon/restartHold.js +16 -15
  90. package/dist/daemon/restartHold.js.map +1 -1
  91. package/dist/daemon/schedules.d.ts +57 -0
  92. package/dist/daemon/schedules.js +181 -0
  93. package/dist/daemon/schedules.js.map +1 -0
  94. package/dist/daemon/server.d.ts +12 -0
  95. package/dist/daemon/server.js +159 -54
  96. package/dist/daemon/server.js.map +1 -1
  97. package/dist/daemon/viewerLauncher.js +3 -2
  98. package/dist/daemon/viewerLauncher.js.map +1 -1
  99. package/dist/daemon/wrappedLaunch.d.ts +1 -0
  100. package/dist/daemon/wrappedLaunch.js +38 -0
  101. package/dist/daemon/wrappedLaunch.js.map +1 -0
  102. package/dist/daemon/wrappedStart.d.ts +13 -0
  103. package/dist/daemon/wrappedStart.js +113 -0
  104. package/dist/daemon/wrappedStart.js.map +1 -0
  105. package/dist/daemon/wrappedSupervisor.d.ts +1 -0
  106. package/dist/daemon/wrappedSupervisor.js +55 -0
  107. package/dist/daemon/wrappedSupervisor.js.map +1 -0
  108. package/dist/mcp/index.js +16 -0
  109. package/dist/mcp/index.js.map +1 -1
  110. package/dist/mcp/tools.js +4 -2
  111. package/dist/mcp/tools.js.map +1 -1
  112. 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,6 +458,10 @@ 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;
461
466
  wss = new WebSocketServer({
462
467
  noServer: true,
@@ -540,6 +545,7 @@ export class Daemon {
540
545
  promptGraceTimers = new Map();
541
546
  promptScanRunning = false;
542
547
  stopPromise = null;
548
+ shutdownRecords;
543
549
  audit;
544
550
  callerContext = new AsyncLocalStorage();
545
551
  /**
@@ -614,6 +620,9 @@ export class Daemon {
614
620
  perMinute: options.messaging?.nudgesPerMinute ?? DEFAULT_NUDGES_PER_MINUTE,
615
621
  deliver: (id) => this.deliverNudge(id),
616
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
+ }));
617
626
  this.mailbox.on('message', (event) => {
618
627
  const entry = this.mailbox.log().find((item) => item.id === event.id);
619
628
  if (entry !== undefined)
@@ -690,6 +699,9 @@ export class Daemon {
690
699
  if (this.stopping)
691
700
  throw new Error('Daemon stopped during startup.');
692
701
  }
702
+ const refusePending = (socket) => { socket.destroy(); };
703
+ if (this.options.afterPublish)
704
+ this.server.on('connection', refusePending);
693
705
  await new Promise((resolve, reject) => {
694
706
  this.server.once('error', reject);
695
707
  this.server.listen(0, '127.0.0.1', () => {
@@ -752,6 +764,10 @@ export class Daemon {
752
764
  // A failed rename leaves the entire predecessor record in place.
753
765
  writePrivateRecord(daemonStatePath(home), state);
754
766
  }
767
+ if (this.options.afterPublish) {
768
+ await this.options.afterPublish();
769
+ this.server.off('connection', refusePending);
770
+ }
755
771
  }
756
772
  catch (error) {
757
773
  this.releaseOwnership();
@@ -844,6 +860,8 @@ export class Daemon {
844
860
  });
845
861
  }, this.options.promptScanIntervalMs ?? PROMPT_SCAN_INTERVAL_MS);
846
862
  this.promptScanTimer.unref();
863
+ this.stopScheduleWatch = watchSchedules(home, this.schedules, this.logger);
864
+ this.promptScheduler.start();
847
865
  this.logger.info('daemon started', {
848
866
  port: this.portValue,
849
867
  pid: process.pid,
@@ -947,7 +965,6 @@ export class Daemon {
947
965
  closeServerOnly() {
948
966
  return new Promise((resolve) => {
949
967
  this.server.close(() => resolve());
950
- // close() waits for idle connections; nothing is connected this early.
951
968
  });
952
969
  }
953
970
  // ------------------------------------------------------------------- stop
@@ -961,25 +978,30 @@ export class Daemon {
961
978
  // awaits the one real shutdown.
962
979
  if (this.stopPromise === null) {
963
980
  this.stopping = true;
964
- if (opts.removeState !== false && this.publishedState && this.homeOwner) {
965
- const state = this.publishedState;
981
+ this.promptScheduler.stop();
982
+ this.stopScheduleWatch?.();
983
+ this.shutdownRecords = this.saveShutdownRecords(opts);
984
+ this.stopPromise = this.doStop();
985
+ }
986
+ return this.stopPromise;
987
+ }
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.
966
993
  this.writeShutdownRecord('launcher-claims.json', () => this.saveLauncherClaims());
967
994
  if (opts.restart) {
968
995
  this.writeShutdownRecord('restart-source.json', () => {
969
996
  this.requireHomeOwner();
970
997
  writePrivateRecord(path.join(this.options.home, 'restart-source.json'), { restartFrom: this.instanceId });
971
998
  });
972
- this.writeShutdownRecord('previous-sessions.json', () => {
973
- this.requireHomeOwner();
974
- this.savePreviousSessions();
975
- });
999
+ this.writeShutdownRecord('previous-sessions.json', () => this.savePreviousSessions());
976
1000
  }
977
1001
  this.writeShutdownRecord('daemon.json', () => this.finishDiscovery(state, opts.restart === true));
978
1002
  }
979
1003
  this.releaseOwnership();
980
- this.stopPromise = this.doStop();
981
- }
982
- return this.stopPromise;
1004
+ });
983
1005
  }
984
1006
  finishDiscovery(state, restart) {
985
1007
  const discovery = this.requireHomeOwner();
@@ -1005,11 +1027,14 @@ export class Daemon {
1005
1027
  write();
1006
1028
  }
1007
1029
  catch (error) {
1008
- const message = `Could not ${verb} ${file} during shutdown.`;
1009
- this.shutdownWarnings.push(message);
1010
- this.logger.warn(message, { code: error.code });
1030
+ this.shutdownRecordFailure(file, verb, error);
1011
1031
  }
1012
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
+ }
1013
1038
  releaseOwnership() {
1014
1039
  const owner = this.homeOwner;
1015
1040
  this.homeOwner = undefined;
@@ -1045,16 +1070,12 @@ export class Daemon {
1045
1070
  this.folderPickerAbort?.abort(new FolderPickerFailureError('The folder picker was stopped.'));
1046
1071
  for (const read of this.widerReads.values())
1047
1072
  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
- });
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;
1058
1079
  for (const socket of this.sockets) {
1059
1080
  try {
1060
1081
  socket.close();
@@ -1383,9 +1404,10 @@ export class Daemon {
1383
1404
  json(res, 400, { error: hide === null ? BAD_HIDE_REASONING : 'waitingOnly must be true or false.' });
1384
1405
  return;
1385
1406
  }
1386
- 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 });
1387
1409
  }
1388
- waitingSessions(hideReasoning, ids) {
1410
+ waitingSessions(hideReasoning, { includeCwd, ids }) {
1389
1411
  return this.listWithPrompts(hideReasoning).flatMap((session) => {
1390
1412
  const waiting = session.waitingOnPrompt;
1391
1413
  if (session.exited || waiting === undefined || (ids !== undefined && !ids.has(session.id)))
@@ -1393,6 +1415,7 @@ export class Daemon {
1393
1415
  return [{
1394
1416
  id: session.id,
1395
1417
  label: session.label,
1418
+ ...(includeCwd ? { cwd: session.cwd } : {}),
1396
1419
  ...(waiting.question === undefined ? {} : { question: waiting.question }),
1397
1420
  ...(waiting.options === undefined ? {} : { options: waiting.options }),
1398
1421
  ...(waiting.selectedOption === undefined ? {} : { selectedOption: waiting.selectedOption }),
@@ -1423,7 +1446,7 @@ export class Daemon {
1423
1446
  this.waitsInFlight += 1;
1424
1447
  try {
1425
1448
  while (!res.destroyed) {
1426
- const waiting = prompt ? this.waitingSessions(hide, ids) : [];
1449
+ const waiting = prompt ? this.waitingSessions(hide, { ids }) : [];
1427
1450
  const stalledSessions = stalled ? this.listWithPrompts(hide).flatMap(session => session.exited || session.stalled === undefined || (ids !== undefined && !ids.has(session.id)) ? [] :
1428
1451
  [{ id: session.id, label: session.label, reason: 'stalled', stalled: session.stalled }]) : [];
1429
1452
  const sessions = [...(stalled ? waiting.map(session => ({ ...session, reason: 'prompt' })) : waiting), ...stalledSessions];
@@ -2463,6 +2486,10 @@ export class Daemon {
2463
2486
  const candidates = headerOne(req, 'x-shellpuppet-resume-ids') ?? headerOne(req, 'x-shellpuppet-resume-id');
2464
2487
  if (candidates)
2465
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
+ }
2466
2493
  }
2467
2494
  return this.callerContext.run(caller.session, () => this.handleClientRequest(req, res, url, segments, actor));
2468
2495
  }
@@ -2515,12 +2542,12 @@ export class Daemon {
2515
2542
  return state.restartFrom === snapshot;
2516
2543
  }
2517
2544
  savePreviousSessions() {
2545
+ this.requireHomeOwner();
2518
2546
  const endedAt = new Date(this.now()).toISOString();
2519
- const sessions = this.manager.list().flatMap(summary => {
2520
- const session = this.manager.get(summary.id);
2547
+ const sessions = this.manager.liveProfileSessions().flatMap(session => {
2521
2548
  // 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)
2549
+ const participant = this.mailbox.participant(session.id);
2550
+ if (!participant)
2524
2551
  return [];
2525
2552
  return [{ ...session.launchProfile, name: participant.name === session.id ? null : participant.name,
2526
2553
  agent: session.agent, resumeId: session.resumeId, endedAt }];
@@ -2563,6 +2590,9 @@ export class Daemon {
2563
2590
  });
2564
2591
  }
2565
2592
  endMailboxParticipant(id) {
2593
+ for (const [name, pendingId] of this.pendingSchedules)
2594
+ if (pendingId === id)
2595
+ this.pendingSchedules.delete(name);
2566
2596
  this.nudges.remove(id);
2567
2597
  // Audit before end can trim old tombstones from retained history.
2568
2598
  for (const entry of this.mailbox.log({ participantId: id })) {
@@ -2588,6 +2618,11 @@ export class Daemon {
2588
2618
  if (session === undefined || session.exited || this.mailbox.participant(id)?.kind !== 'session')
2589
2619
  return 'done';
2590
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';
2591
2626
  const clearedIds = pendingIds.length > 0 && await session.clearConsumedNudge() ? pendingIds : [];
2592
2627
  const unread = this.mailbox.inbox(id, { markRead: false });
2593
2628
  if (clearedIds.length > 0) {
@@ -2596,6 +2631,8 @@ export class Daemon {
2596
2631
  }
2597
2632
  const pending = session.nudgePendingLine();
2598
2633
  if (pending !== null) {
2634
+ if (session.nudgePendingIds().length === 0)
2635
+ return 'wait';
2599
2636
  const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2600
2637
  if (ids.length === 0)
2601
2638
  return 'done';
@@ -2620,7 +2657,7 @@ export class Daemon {
2620
2657
  session.nudgeInputVersion() === inputVersion &&
2621
2658
  session.nudgeQueuedInputVersion() === queuedInputVersion &&
2622
2659
  session.nudgeScreenRevision() === screenRevision &&
2623
- session.answerablePrompt(screen) === null &&
2660
+ session.answerablePrompt(screen) === null && session.nudgePendingIds().length > 0 &&
2624
2661
  waitingIds.length === ids.length &&
2625
2662
  ids.every((messageId) => waitingIds.includes(messageId));
2626
2663
  });
@@ -2644,24 +2681,80 @@ export class Daemon {
2644
2681
  const ids = unread.filter((entry) => entry.state === 'waiting').map((entry) => entry.id);
2645
2682
  if (ids.length === 0)
2646
2683
  return 'done';
2647
- const line = buildNudge(unread);
2648
2684
  if (!session.hasPainted() || !session.nudgeReady(this.now()))
2649
2685
  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)
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')
2653
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' };
2654
2753
  // Check the same region again before typing. A running turn can repaint
2655
2754
  // its transcript, and a separate sidebar can repaint beside an idle pane.
2656
2755
  const queued = state.queued;
2657
2756
  const outputAt = session.lastChangeAt();
2658
- const inputVersion = session.nudgeInputVersion();
2659
- const queuedInputVersion = session.nudgeQueuedInputVersion();
2660
2757
  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
2758
  let failedCheck = 'line-not-seen';
2666
2759
  const ready = (screen, phase) => {
2667
2760
  if (session.exited) {
@@ -2672,7 +2765,7 @@ export class Daemon {
2672
2765
  failedCheck = 'stalled';
2673
2766
  return false;
2674
2767
  }
2675
- const current = phase === 'before' ? session.nudgeState(this.now()) : undefined;
2768
+ const current = phase === 'before' ? session.nudgeState(this.now(), whenBusy) : undefined;
2676
2769
  if (session.nudgeScreenRevision() !== screenRevision ||
2677
2770
  (phase === 'before' && (queued || state.paneQuiet ? current?.regionKey !== state.regionKey
2678
2771
  : session.lastChangeAt() !== outputAt || screen !== snapshot.screen))) {
@@ -2688,34 +2781,33 @@ export class Daemon {
2688
2781
  failedCheck = 'prompt-showing';
2689
2782
  return false;
2690
2783
  }
2691
- if (!stillWaiting()) {
2692
- failedCheck = 'messages-changed';
2784
+ if (!currentDelivery()) {
2785
+ failedCheck = ids.length ? 'messages-changed' : 'schedule-changed';
2693
2786
  return false;
2694
2787
  }
2695
- if (phase === 'before' ? !current?.ready : !session.nudgeReadyWithLine(line)) {
2788
+ if (phase === 'before' ? !current?.ready || current.queued !== queued : !session.nudgeReadyWithLine(line, queued, whenBusy)) {
2696
2789
  failedCheck = 'line-not-seen';
2697
2790
  return false;
2698
2791
  }
2699
2792
  return true;
2700
2793
  };
2701
2794
  try {
2702
- const result = await session.writeNudgeWithReason(line + session.nudgeSubmit(), ready, ids, () => failedCheck);
2795
+ const result = await session.writeNudgeWithReason(line + session.nudgeSubmit(queued), ready, ids, () => failedCheck, schedule, queued);
2703
2796
  if (result === 'wait')
2704
- return 'wait';
2797
+ return { outcome: 'skipped', reason: session.nudgePendingLine() !== null ? 'pending' : failedCheck };
2705
2798
  if (result.startsWith('aborted-')) {
2706
2799
  const reason = result.slice('aborted-'.length);
2707
- this.audit.record('daemon', 'nudge-aborted', id, { messageIds: ids, count: ids.length, reason });
2708
- return 'wait';
2800
+ return { outcome: 'aborted', reason };
2709
2801
  }
2710
2802
  }
2711
2803
  catch (error) {
2712
- if (error instanceof SessionInputFailedError || error instanceof SessionProgramEndedError)
2713
- return 'wait';
2804
+ if (error instanceof SessionInputFailedError)
2805
+ return { outcome: 'skipped', reason: 'input-failed' };
2806
+ if (error instanceof SessionProgramEndedError)
2807
+ return { outcome: 'skipped', reason: 'session-ended' };
2714
2808
  throw error;
2715
2809
  }
2716
- this.mailbox.markNudged(ids);
2717
- this.audit.record('daemon', 'nudge', id, { messageIds: ids, count: ids.length, ...(queued ? { queued: true } : {}) });
2718
- return 'sent';
2810
+ return { outcome: queued ? 'queued' : 'sent' };
2719
2811
  }
2720
2812
  registerMailboxSession(session, profileName) {
2721
2813
  const label = profileName ?? session.label;
@@ -2919,9 +3011,14 @@ export class Daemon {
2919
3011
  }
2920
3012
  async handleClientRequest(req, res, url, segments, actor) {
2921
3013
  try {
3014
+ if (url.pathname === '/schedules' && req.method === 'GET') {
3015
+ json(res, 200, { schedules: this.promptScheduler.list() });
3016
+ return;
3017
+ }
2922
3018
  if (segments[0] === 'daemon' && segments[1] === 'shutdown' && req.method === 'POST') {
2923
3019
  const body = await readBody(req);
2924
3020
  if (this.stopping) {
3021
+ await this.shutdownRecords;
2925
3022
  json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
2926
3023
  return;
2927
3024
  }
@@ -2936,6 +3033,7 @@ export class Daemon {
2936
3033
  }
2937
3034
  const stopping = this.stop({ restart: body['restart'] === true });
2938
3035
  this.audit.record(actor, 'shutdown', undefined, { force, liveSessions: live });
3036
+ await this.shutdownRecords;
2939
3037
  json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
2940
3038
  void stopping.then(() => {
2941
3039
  this.options.onSelfStop?.('shutdown-request');
@@ -3723,6 +3821,10 @@ export class Daemon {
3723
3821
  }
3724
3822
  async handleStart(req, res, actor) {
3725
3823
  const body = await readBody(req);
3824
+ if (this.stopping) {
3825
+ json(res, 503, { error: 'The daemon is stopping.' });
3826
+ return;
3827
+ }
3726
3828
  const command = asString(body['command']);
3727
3829
  if (command === undefined || command === '') {
3728
3830
  json(res, 400, { error: 'command (string) is required.' });
@@ -4212,6 +4314,7 @@ export class Daemon {
4212
4314
  async scanForPromptStalls() {
4213
4315
  const stallMs = this.options.promptStallMs ?? PROMPT_STALL_MS;
4214
4316
  const seen = new Set();
4317
+ const scheduled = new Set(this.schedules.read().filter(s => s.enabled).map(s => this.mailbox.sessionIdByName(s.session)));
4215
4318
  for (const summary of this.manager.list()) {
4216
4319
  const session = this.manager.get(summary.id);
4217
4320
  if (session === undefined || session.exited)
@@ -4220,6 +4323,8 @@ export class Daemon {
4220
4323
  let detected;
4221
4324
  try {
4222
4325
  const snapshot = await session.snapshot();
4326
+ if (scheduled.has(session.id))
4327
+ session.nudgeState(this.now());
4223
4328
  detected = session.answerablePrompt(snapshot.screen);
4224
4329
  }
4225
4330
  catch (error) {