kimaki 0.26.0 → 0.27.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 (214) hide show
  1. package/dist/agent-model.e2e.test.js +25 -122
  2. package/dist/anthropic-account-identity.js +1 -0
  3. package/dist/anthropic-auth-plugin.js +1 -0
  4. package/dist/anthropic-auth-state.js +1 -0
  5. package/dist/bin.js +73 -19
  6. package/dist/cli-commands/maintenance.js +46 -7
  7. package/dist/cli-commands/send.js +24 -0
  8. package/dist/cli-commands/session.js +183 -8
  9. package/dist/cli-commands/task.js +13 -1
  10. package/dist/cli-parsing.test.js +59 -3
  11. package/dist/cli-runner.js +28 -4
  12. package/dist/cli-runner.test.js +27 -0
  13. package/dist/cli-send-thread.e2e.test.js +1 -1
  14. package/dist/cli.js +32 -0
  15. package/dist/commands/abort.js +5 -1
  16. package/dist/commands/agent.js +6 -8
  17. package/dist/commands/ask-question.js +21 -32
  18. package/dist/commands/ask-question.test.js +43 -1
  19. package/dist/commands/login.js +6 -0
  20. package/dist/commands/merge-worktree.js +36 -10
  21. package/dist/commands/model-variant.js +7 -1
  22. package/dist/commands/model.js +14 -8
  23. package/dist/commands/multioauth.js +1 -0
  24. package/dist/commands/new-worktree.js +170 -102
  25. package/dist/commands/user-command.js +6 -8
  26. package/dist/commands/worktrees.js +5 -13
  27. package/dist/config.js +16 -1
  28. package/dist/database.js +124 -3
  29. package/dist/db.js +22 -0
  30. package/dist/db.test.js +167 -1
  31. package/dist/discord-bot.js +34 -32
  32. package/dist/discord-command-registration.js +9 -1
  33. package/dist/discord-utils.js +13 -5
  34. package/dist/discord-utils.test.js +17 -1
  35. package/dist/errors.js +5 -0
  36. package/dist/exec-async.js +17 -5
  37. package/dist/external-directory-permissions.e2e.test.js +2 -2
  38. package/dist/file-edit-log.js +197 -0
  39. package/dist/file-edit-log.test.js +258 -0
  40. package/dist/format-tables.js +52 -0
  41. package/dist/format-tables.test.js +93 -0
  42. package/dist/gateway-proxy-reconnect.e2e.test.js +28 -8
  43. package/dist/gateway-proxy.e2e.test.js +5 -5
  44. package/dist/git-worktree-core.js +182 -17
  45. package/dist/ipc-tools-plugin.js +63 -3
  46. package/dist/kimaki-opencode-plugin-loading.e2e.test.js +122 -58
  47. package/dist/kimaki-opencode-plugin.js +7 -3
  48. package/dist/kimaki-workspace-adaptor.js +33 -10
  49. package/dist/logger.js +10 -1
  50. package/dist/markdown.js +3 -1
  51. package/dist/markdown.test.js +11 -3
  52. package/dist/message-formatting.js +18 -7
  53. package/dist/message-formatting.test.js +56 -9
  54. package/dist/oauth-rotation-shared.js +10 -0
  55. package/dist/openai-auth-plugin.js +1 -0
  56. package/dist/openai-auth-state.js +1 -0
  57. package/dist/opencode-command.test.js +60 -0
  58. package/dist/opencode.js +53 -12
  59. package/dist/question-abort-clears-dropdown.e2e.test.js +89 -0
  60. package/dist/question-text-before-dropdown.e2e.test.js +52 -0
  61. package/dist/queue-advanced-abort.e2e.test.js +1 -1
  62. package/dist/queue-advanced-action-buttons.e2e.test.js +3 -3
  63. package/dist/queue-advanced-e2e-setup.js +78 -5
  64. package/dist/queue-advanced-footer.e2e.test.js +40 -246
  65. package/dist/queue-advanced-model-switch.e2e.test.js +2 -2
  66. package/dist/queue-advanced-permissions-typing.e2e.test.js +7 -9
  67. package/dist/queue-advanced-question.e2e.test.js +31 -26
  68. package/dist/queue-advanced-typing-interrupt.e2e.test.js +2 -2
  69. package/dist/queue-delete-message.e2e.test.js +1 -1
  70. package/dist/queue-drain-after-interactive-ui.e2e.test.js +2 -2
  71. package/dist/queue-interrupt-drain.e2e.test.js +112 -2
  72. package/dist/queue-question-select-drain.e2e.test.js +30 -128
  73. package/dist/runtime-lifecycle.e2e.test.js +10 -37
  74. package/dist/schema.js +34 -0
  75. package/dist/session-handler/event-stream-state.js +267 -50
  76. package/dist/session-handler/event-stream-state.test.js +415 -8
  77. package/dist/session-handler/model-utils.js +159 -5
  78. package/dist/session-handler/model-utils.test.js +345 -0
  79. package/dist/session-handler/thread-session-runtime.js +252 -182
  80. package/dist/session-sleep.test.js +224 -0
  81. package/dist/session-title-rename.test.js +7 -39
  82. package/dist/sleep.e2e.test.js +491 -0
  83. package/dist/startup-time.e2e.test.js +2 -1
  84. package/dist/store.js +3 -0
  85. package/dist/system-message.js +59 -6
  86. package/dist/system-message.test.js +76 -6
  87. package/dist/task-runner.js +94 -4
  88. package/dist/task-schedule.js +56 -0
  89. package/dist/task-schedule.test.js +71 -1
  90. package/dist/thread-message-queue.e2e.test.js +10 -169
  91. package/dist/undo-redo.e2e.test.js +2 -2
  92. package/dist/voice-attachment.js +23 -1
  93. package/dist/voice-message.e2e.test.js +10 -10
  94. package/dist/voice.test.js +55 -29
  95. package/dist/worktree-clone-isolation.e2e.test.js +188 -0
  96. package/dist/worktree-lifecycle.e2e.test.js +29 -10
  97. package/dist/worktrees.js +226 -443
  98. package/dist/worktrees.test.js +435 -58
  99. package/dist/xai-auth-plugin.js +1 -0
  100. package/dist/xai-auth-state.js +1 -0
  101. package/package.json +8 -6
  102. package/skills/errore/SKILL.md +18 -0
  103. package/skills/goke/SKILL.md +150 -10
  104. package/skills/holocron/SKILL.md +37 -0
  105. package/skills/npm-package/SKILL.md +55 -35
  106. package/skills/profano/SKILL.md +17 -2
  107. package/skills/spiceflow/SKILL.md +39 -3
  108. package/skills/strada/SKILL.md +39 -0
  109. package/skills/zele/SKILL.md +19 -0
  110. package/src/agent-model.e2e.test.ts +25 -151
  111. package/src/anthropic-account-identity.ts +1 -0
  112. package/src/anthropic-auth-plugin.ts +1 -0
  113. package/src/anthropic-auth-state.ts +1 -0
  114. package/src/bin.ts +78 -26
  115. package/src/cli-commands/maintenance.ts +59 -13
  116. package/src/cli-commands/send.ts +25 -0
  117. package/src/cli-commands/session.ts +203 -9
  118. package/src/cli-commands/task.ts +13 -1
  119. package/src/cli-parsing.test.ts +69 -3
  120. package/src/cli-runner.test.ts +49 -0
  121. package/src/cli-runner.ts +28 -4
  122. package/src/cli-send-thread.e2e.test.ts +1 -1
  123. package/src/cli.ts +53 -0
  124. package/src/commands/abort.ts +6 -1
  125. package/src/commands/agent.ts +6 -6
  126. package/src/commands/ask-question.test.ts +48 -1
  127. package/src/commands/ask-question.ts +21 -32
  128. package/src/commands/login.ts +6 -0
  129. package/src/commands/merge-worktree.ts +43 -12
  130. package/src/commands/model-variant.ts +8 -1
  131. package/src/commands/model.ts +18 -8
  132. package/src/commands/multioauth.ts +1 -0
  133. package/src/commands/new-worktree.ts +138 -55
  134. package/src/commands/user-command.ts +6 -6
  135. package/src/commands/worktrees.ts +5 -12
  136. package/src/config.ts +18 -1
  137. package/src/database.ts +195 -3
  138. package/src/db.test.ts +188 -0
  139. package/src/db.ts +26 -0
  140. package/src/discord-bot.ts +35 -29
  141. package/src/discord-command-registration.ts +15 -1
  142. package/src/discord-utils.test.ts +19 -0
  143. package/src/discord-utils.ts +21 -6
  144. package/src/errors.ts +5 -0
  145. package/src/exec-async.ts +20 -11
  146. package/src/external-directory-permissions.e2e.test.ts +2 -2
  147. package/src/file-edit-log.test.ts +287 -0
  148. package/src/file-edit-log.ts +283 -0
  149. package/src/format-tables.test.ts +101 -0
  150. package/src/format-tables.ts +75 -0
  151. package/src/gateway-proxy-reconnect.e2e.test.ts +38 -8
  152. package/src/gateway-proxy.e2e.test.ts +5 -5
  153. package/src/git-worktree-core.ts +247 -20
  154. package/src/ipc-tools-plugin.ts +75 -5
  155. package/src/kimaki-opencode-plugin-loading.e2e.test.ts +188 -97
  156. package/src/kimaki-opencode-plugin.ts +7 -3
  157. package/src/kimaki-workspace-adaptor.ts +40 -11
  158. package/src/logger.ts +13 -4
  159. package/src/markdown.test.ts +13 -3
  160. package/src/markdown.ts +4 -1
  161. package/src/message-formatting.test.ts +86 -12
  162. package/src/message-formatting.ts +19 -7
  163. package/src/oauth-rotation-shared.ts +10 -0
  164. package/src/openai-auth-plugin.ts +1 -0
  165. package/src/openai-auth-state.ts +1 -0
  166. package/src/opencode-command.test.ts +81 -0
  167. package/src/opencode.ts +71 -11
  168. package/src/question-abort-clears-dropdown.e2e.test.ts +109 -0
  169. package/src/question-text-before-dropdown.e2e.test.ts +67 -0
  170. package/src/queue-advanced-abort.e2e.test.ts +1 -1
  171. package/src/queue-advanced-action-buttons.e2e.test.ts +3 -3
  172. package/src/queue-advanced-e2e-setup.ts +83 -4
  173. package/src/queue-advanced-footer.e2e.test.ts +47 -294
  174. package/src/queue-advanced-model-switch.e2e.test.ts +2 -2
  175. package/src/queue-advanced-permissions-typing.e2e.test.ts +7 -9
  176. package/src/queue-advanced-question.e2e.test.ts +35 -29
  177. package/src/queue-advanced-typing-interrupt.e2e.test.ts +2 -2
  178. package/src/queue-delete-message.e2e.test.ts +1 -1
  179. package/src/queue-drain-after-interactive-ui.e2e.test.ts +2 -2
  180. package/src/queue-interrupt-drain.e2e.test.ts +123 -2
  181. package/src/queue-question-select-drain.e2e.test.ts +32 -157
  182. package/src/runtime-lifecycle.e2e.test.ts +10 -41
  183. package/src/schema.sql +14 -1
  184. package/src/schema.ts +36 -0
  185. package/src/session-handler/event-stream-state.test.ts +437 -7
  186. package/src/session-handler/event-stream-state.ts +389 -53
  187. package/src/session-handler/model-utils.test.ts +415 -0
  188. package/src/session-handler/model-utils.ts +249 -5
  189. package/src/session-handler/thread-session-runtime.ts +300 -215
  190. package/src/session-sleep.test.ts +294 -0
  191. package/src/session-title-rename.test.ts +9 -48
  192. package/src/sleep.e2e.test.ts +562 -0
  193. package/src/startup-time.e2e.test.ts +5 -1
  194. package/src/store.ts +21 -0
  195. package/src/system-message.test.ts +86 -6
  196. package/src/system-message.ts +66 -7
  197. package/src/task-runner.ts +136 -2
  198. package/src/task-schedule.test.ts +76 -0
  199. package/src/task-schedule.ts +95 -0
  200. package/src/thread-message-queue.e2e.test.ts +10 -202
  201. package/src/undo-redo.e2e.test.ts +2 -2
  202. package/src/voice-attachment.ts +29 -1
  203. package/src/voice-message.e2e.test.ts +10 -10
  204. package/src/voice.test.ts +63 -29
  205. package/src/worktree-clone-isolation.e2e.test.ts +213 -0
  206. package/src/worktree-lifecycle.e2e.test.ts +29 -9
  207. package/src/worktrees.test.ts +505 -64
  208. package/src/worktrees.ts +257 -603
  209. package/src/xai-auth-plugin.ts +1 -0
  210. package/src/xai-auth-state.ts +1 -0
  211. package/dist/message-finish-field.e2e.test.js +0 -169
  212. package/dist/subagent-rate-limit-plugin.js +0 -184
  213. package/src/message-finish-field.e2e.test.ts +0 -196
  214. package/src/subagent-rate-limit-plugin.ts +0 -228
@@ -11,6 +11,12 @@ afterEach(async () => {
11
11
  }));
12
12
  });
13
13
  describe('system-message', () => {
14
+ test('requires reading the report-bugs guide before filing kimaki issues', () => {
15
+ const message = getOpencodeSystemMessage({
16
+ sessionId: 'ses_123',
17
+ });
18
+ expect(message).toContain('Never open a pull request on remorses/kimaki unless remorses asked for one in a comment on the issue');
19
+ });
14
20
  test('includes callout guidance for important content', () => {
15
21
  const message = getOpencodeSystemMessage({
16
22
  sessionId: 'ses_123',
@@ -33,6 +39,7 @@ describe('system-message', () => {
33
39
  expect(message).toContain('NEVER call `question` before your text');
34
40
  expect(message).toContain('`kimaki_action_buttons`');
35
41
  expect(message).toContain('`kimaki_file_upload`');
42
+ expect(message).toContain('`kimaki_sleep`');
36
43
  });
37
44
  test('persists and reads session system prompt for command path', async () => {
38
45
  const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'kimaki-system-'));
@@ -67,6 +74,17 @@ describe('system-message', () => {
67
74
  await fs.promises.mkdir(filePath);
68
75
  await expect(readSessionSystemPrompt({ sessionId, dataDir })).rejects.toMatchObject({ code: 'EISDIR' });
69
76
  });
77
+ test('includes session title update guidance when scope or goal changed', () => {
78
+ const message = getOpencodeSystemMessage({
79
+ sessionId: 'ses_123',
80
+ threadId: 'thread_123',
81
+ });
82
+ expect(message).toContain('## updating the session title');
83
+ expect(message).toContain("kimaki session title 'Short title' --session ses_123");
84
+ expect(message).toContain('When the session scope or goal changed from the first message, update the title:');
85
+ expect(message).toContain('thread-name="..."');
86
+ expect(message).toContain('Do not retitle every turn');
87
+ });
70
88
  test('includes parent session context when parentSessionId is set', () => {
71
89
  const message = getOpencodeSystemMessage({
72
90
  sessionId: 'ses_child',
@@ -107,6 +125,7 @@ describe('system-message', () => {
107
125
  ],
108
126
  }).replace(/`[^`]*\/kimaki\.log`/, '`<data-dir>/kimaki.log`');
109
127
  expect(message).toContain('When pulling submodules and they jump to a new commit, commit that submodule pointer update right away before doing other work.');
128
+ expect(message).toContain('while kimaki session list --active --exclude ses_123; do sleep 5; done');
110
129
  expect(message).toMatchInlineSnapshot(`
111
130
  "
112
131
  The user is reading your messages from inside Discord, via kimaki.dev
@@ -135,7 +154,7 @@ describe('system-message', () => {
135
154
  Your current Discord thread ID is: thread_123
136
155
  Your current Discord guild ID is: guild_123
137
156
 
138
- Per-turn Discord metadata like the current user and current agent is delivered in synthetic user message parts.
157
+ Per-turn Discord metadata like the current user, current agent, and Discord thread title is delivered in synthetic user message parts.
139
158
 
140
159
  ## permissions
141
160
 
@@ -158,6 +177,7 @@ describe('system-message', () => {
158
177
 
159
178
  ## debugging kimaki issues
160
179
 
180
+ ALWAYS read https://kimaki.dev/docs/guides/report-bugs first before submitting any issue to Kimaki. That page is the source of truth for exporting session jsonl, sharing evidence in a gist, and filing bugs. Never open a pull request on remorses/kimaki unless remorses asked for one in a comment on the issue.
161
181
  If there are internal kimaki issues (sessions not responding, bot errors, unexpected behavior), read the log file at \`<data-dir>/kimaki.log\`. This file contains detailed logs of all bot activity including session creation, event handling, errors, and API calls. The log file is reset every time the bot restarts, so it only contains logs from the current run.
162
182
 
163
183
  ## uploading files to discord
@@ -187,9 +207,16 @@ describe('system-message', () => {
187
207
  To ask the user to upload files from their device, use \`kimaki_file_upload\`. This shows a native file picker dialog in Discord. The files are downloaded to the project's \`uploads/\` directory and the tool returns the local file paths.
188
208
  You MUST call \`kimaki_file_upload\` LAST, after ALL text.
189
209
 
210
+ ## sleeping the session
211
+
212
+ Use \`kimaki_sleep\` to pause this session for hours or days, then continue when the time is reached. The sleep is stored in SQLite and survives bot restarts.
213
+ Pass either \`duration\` (\`30s\`, \`2h\`, \`1d\`) or \`until\` (UTC ISO ending with \`Z\`, example \`2026-08-20T09:00:00Z\`).
214
+ You MUST call \`kimaki_sleep\` LAST, after ALL text. Do not call more tools after it.
215
+ A new user message cancels the sleep. After wake, continue the wait reason.
216
+
190
217
  ## archiving the current thread
191
218
 
192
- To archive the current Discord thread (hide it from sidebar) and stop the session, run:
219
+ To archive the current Discord thread (hide it from sidebar) without stopping the session, run:
193
220
 
194
221
  kimaki session archive thread_123 (or --session ses_123)
195
222
 
@@ -204,6 +231,17 @@ describe('system-message', () => {
204
231
  This stops the AI from processing but keeps the thread visible in Discord.
205
232
  Different from \`kimaki session archive\` which hides the thread.
206
233
 
234
+ ## updating the session title
235
+
236
+ When the session scope or goal changed from the first message, update the title:
237
+
238
+ kimaki session title 'Short title' --session ses_123
239
+
240
+ The current Discord thread title is in the per-turn \`<discord-user thread-name="..." />\` metadata.
241
+ This updates the OpenCode title. Discord follows automatically.
242
+ Do not retitle every turn. Discord rate-limits thread renames.
243
+ Keep titles short. Do not add emoji. Do not copy ⬦, btw:, or Fork: prefixes.
244
+
207
245
  ## discord user mentions
208
246
 
209
247
  Prefer Discord user IDs for mentions. Discord bots cannot ping by @name; use \`<@userId>\` in message text or pass the ID to \`--user\`.
@@ -435,6 +473,9 @@ describe('system-message', () => {
435
473
  kimaki session list
436
474
  kimaki session list --json # machine-readable output
437
475
  kimaki session list --project /path/to/project # specific project
476
+
477
+ # List only in-progress sessions. Exit status is 1 when none remain.
478
+ kimaki session list --active
438
479
  \`\`\`
439
480
 
440
481
  To search past sessions for this project (supports plain text or /regex/flags):
@@ -455,6 +496,29 @@ describe('system-message', () => {
455
496
 
456
497
  Then use grep/read tools on the file to find what you need.
457
498
 
499
+ ### who edited a file
500
+
501
+ To find the session that last edited a file, run:
502
+
503
+ \`\`\`bash
504
+ kimaki session editors src/foo.ts
505
+ kimaki session editors src/foo.ts --json
506
+ \`\`\`
507
+
508
+ Output is newest first. Each row has:
509
+
510
+ - **session ID** (\`ses_xxx\`)
511
+ - **title** (Discord thread name, so you can tell what that session was doing)
512
+ - **time ago** (when that session last edited the file)
513
+
514
+ Use this before a commit when this session did not edit the file. Put the original session ID as the last line of the commit message:
515
+
516
+ \`\`\`
517
+ Session: ses_xxx
518
+ \`\`\`
519
+
520
+ If this session edited the file, use this session ID instead. If several files come from different sessions, split the commit by session. Do not attribute another session's edits to this one.
521
+
458
522
  ## cross-project commands
459
523
 
460
524
  When the user references another project by name, run \`kimaki project list\` to find its directory path and channel ID. Then read files, search code, or run commands directly in that directory. If the project is not listed, use \`kimaki project add /path/to/repo\` to register it and create a Discord channel for it. Do not add subfolders of an existing project — only add root project directories.
@@ -521,7 +585,7 @@ describe('system-message', () => {
521
585
 
522
586
  When the user asks you to wait for an existing session, run \`kimaki session wait <session_id>\` yourself via Bash, then continue from the printed session markdown. Do not tell the user to run the command.
523
587
 
524
- IMPORTANT: if you run \`kimaki send --wait\` or \`kimaki session wait <session_id>\` via the Bash tool, you must set the Bash tool \`timeout\` to **20 minutes or more** (example: \`timeout: 1_500_000\`). Otherwise the tool will terminate early (default is 2 minutes) and you won't see long sessions.
588
+ IMPORTANT: if you run \`kimaki send --wait\`, \`kimaki session wait <session_id>\`, or the active-session wait loop via the Bash tool, you must set the Bash tool \`timeout\` to **20 minutes or more** (example: \`timeout: 1_500_000\`). Otherwise the tool will terminate early (default is 2 minutes) and you won't see long sessions.
525
589
 
526
590
  If your Bash tool timeout triggers anyway, fall back to reading the session output from disk:
527
591
 
@@ -536,9 +600,14 @@ describe('system-message', () => {
536
600
 
537
601
  # Wait for a session that was already started elsewhere
538
602
  kimaki session wait <session_id>
603
+
604
+ # Wait until every other in-progress session in this project finishes
605
+ while kimaki session list --active --exclude ses_123; do sleep 5; done
539
606
  \`\`\`
540
607
 
541
- The command exits with the session markdown on stdout once the model finishes responding.
608
+ \`session list --active\` exits with status 0 while it finds active sessions and status 1 when none remain. Exclude the current session in a wait loop so the loop does not wait for itself.
609
+
610
+ \`session wait\` exits with the session markdown on stdout once the model finishes responding.
542
611
 
543
612
  Use \`--wait\` when you need to:
544
613
  - **Fix a bug in another project** before continuing here (e.g. fix a dependency, then resume)
@@ -803,7 +872,7 @@ describe('system-message', () => {
803
872
  You MUST call \`question\` LAST, after ALL text parts.
804
873
  NEVER call \`question\` before your text. Discord will hide the message.
805
874
 
806
- The same rule applies to \`kimaki_action_buttons\` and \`kimaki_file_upload\`.
875
+ The same rule applies to \`kimaki_action_buttons\`, \`kimaki_file_upload\`, and \`kimaki_sleep\`.
807
876
  You MUST call them LAST, after ALL text.
808
877
 
809
878
  ALWAYS use \`question\` when you ask the user a question. Do not write a numbered list in plain text.
@@ -831,6 +900,7 @@ describe('system-message', () => {
831
900
  userId: 'user_123',
832
901
  sourceMessageId: 'msg_123',
833
902
  sourceThreadId: 'thread_123',
903
+ threadName: 'Fix auth bug',
834
904
  repliedMessage: {
835
905
  authorUsername: 'alice',
836
906
  text: 'Original replied message',
@@ -843,7 +913,7 @@ describe('system-message', () => {
843
913
  mainRepoDirectory: '/repo',
844
914
  },
845
915
  })).toMatchInlineSnapshot(`
846
- "<discord-user name="Tommy" user-id="user_123" message-id="msg_123" thread-id="thread_123" />
916
+ "<discord-user name="Tommy" user-id="user_123" message-id="msg_123" thread-id="thread_123" thread-name="Fix auth bug" />
847
917
 
848
918
  This message was a reply to message
849
919
 
@@ -1,14 +1,14 @@
1
- // Scheduled task runner for executing due `send --send-at` jobs in the bot process.
2
- import { Routes } from 'discord.js';
1
+ // Scheduled task runner for due `send --send-at` jobs and session sleep wakes.
2
+ import { DiscordAPIError, Routes } from 'discord.js';
3
3
  import { createDiscordRest } from './discord-urls.js';
4
4
  import { ensureThreadMember } from './discord-utils.js';
5
5
  import YAML from 'yaml';
6
- import { claimScheduledTaskRunning, createScheduledTaskRun, failScheduledTaskRun, finishScheduledTaskRun, getDuePlannedScheduledTasks, getScheduledTask, getActiveScheduledTaskRuns, markScheduledTaskCronRescheduled, markScheduledTaskCronRetry, markScheduledTaskFailed, deleteScheduledTask, recoverStaleRunningScheduledTasks, releaseScheduledTaskClaim, setScheduledTaskRunThread, } from './database.js';
6
+ import { claimScheduledTaskRunning, createScheduledTaskRun, failScheduledTaskRun, finishScheduledTaskRun, getDuePlannedScheduledTasks, getScheduledTask, getActiveScheduledTaskRuns, markScheduledTaskCronRescheduled, markScheduledTaskCronRetry, markScheduledTaskFailed, deleteScheduledTask, recoverStaleRunningScheduledTasks, releaseScheduledTaskClaim, setScheduledTaskRunThread, claimSessionSleepAttempt, getDueSessionSleeps, getThreadIdBySessionId, markSessionSleepFailed, } from './database.js';
7
7
  import { execAsync } from './exec-async.js';
8
8
  import { initializeOpencodeForDirectory } from './opencode.js';
9
9
  import { createLogger, formatErrorWithStack, LogPrefix } from './logger.js';
10
10
  import { notifyError } from './sentry.js';
11
- import { appendTaskCommandOutput, getNextCronRun, getPromptPreview, parseScheduledTaskPayload, } from './task-schedule.js';
11
+ import { appendTaskCommandOutput, formatSessionSleepWakePrompt, getNextCronRun, getPromptPreview, parseScheduledTaskPayload, } from './task-schedule.js';
12
12
  const taskLogger = createLogger(LogPrefix.TASK);
13
13
  const MAX_SCHEDULED_PROMPT_LENGTH = 1_900;
14
14
  const PENDING_RUN_TIMEOUT_MS = 120_000;
@@ -76,6 +76,95 @@ async function executeThreadScheduledTask({ rest, task, payload, prompt, runId,
76
76
  return postResult;
77
77
  return payload.threadId;
78
78
  }
79
+ /** Wait before retrying a wake that ingress has not consumed yet. */
80
+ const SLEEP_WAKE_RETRY_AFTER_MS = 30_000;
81
+ const SLEEP_WAKE_MAX_ATTEMPTS = 5;
82
+ export function buildSessionSleepWakeBody({ deliveryId, wakeAt, reason, }) {
83
+ const marker = {
84
+ start: true,
85
+ sleepWake: true,
86
+ sleepId: deliveryId,
87
+ };
88
+ return {
89
+ content: formatSessionSleepWakePrompt({ wakeAt, reason }),
90
+ embeds: [{ color: 0x2b2d31, footer: { text: YAML.stringify(marker) } }],
91
+ // Discord limits nonces to 25 characters. The full ID stays in the marker.
92
+ // A stable nonce deduplicates retries when a successful response is lost.
93
+ nonce: deliveryId.replaceAll('-', '').slice(0, 25),
94
+ enforce_nonce: true,
95
+ };
96
+ }
97
+ async function postSessionSleepWake({ rest, sleep, threadId, }) {
98
+ // `.then(() => null)` keeps the success type concrete. Returning the raw post
99
+ // value would widen the union to `unknown` and erase the failure shape.
100
+ return await rest
101
+ .post(Routes.channelMessages(threadId), {
102
+ body: buildSessionSleepWakeBody({
103
+ deliveryId: sleep.delivery_id,
104
+ wakeAt: sleep.wake_at,
105
+ reason: sleep.reason,
106
+ }),
107
+ })
108
+ .then(() => {
109
+ return null;
110
+ })
111
+ .catch((error) => {
112
+ // Only an unknown channel/message is genuinely unrecoverable. A 403 is
113
+ // often temporary (permissions revoked, thread locked) so it keeps
114
+ // retrying until the attempt budget runs out.
115
+ const permanent = error instanceof DiscordAPIError &&
116
+ error.status === 404;
117
+ return {
118
+ error: new Error(`Failed to post sleep wake for session ${sleep.session_id}`, { cause: error }),
119
+ permanent,
120
+ };
121
+ });
122
+ }
123
+ export async function wakeDueSessionSleeps({ rest, now = new Date(), limit = 20, }) {
124
+ const dueSleeps = await getDueSessionSleeps({
125
+ now,
126
+ retryAfterMs: SLEEP_WAKE_RETRY_AFTER_MS,
127
+ limit,
128
+ });
129
+ for (const sleep of dueSleeps) {
130
+ // Reserves an attempt but stays `planned`. The row only leaves `planned`
131
+ // when ingress consumes the wake, so dying anywhere below costs one retry
132
+ // delay instead of losing the wake.
133
+ const claimed = await claimSessionSleepAttempt({
134
+ sessionId: sleep.session_id,
135
+ deliveryId: sleep.delivery_id,
136
+ now,
137
+ retryAfterMs: SLEEP_WAKE_RETRY_AFTER_MS,
138
+ });
139
+ if (!claimed)
140
+ continue;
141
+ // Resolved now, not when the tool ran, so a session rebound by /resume
142
+ // wakes in the thread that currently owns it.
143
+ const threadId = await getThreadIdBySessionId(claimed.session_id);
144
+ if (!threadId) {
145
+ await markSessionSleepFailed({
146
+ sessionId: claimed.session_id,
147
+ deliveryId: claimed.delivery_id,
148
+ });
149
+ taskLogger.warn(`[task-runner] no thread owns session ${claimed.session_id}, dropping sleep wake`);
150
+ continue;
151
+ }
152
+ // A successful post changes nothing here on purpose: ingress owns the
153
+ // transition out of `planned` when the wake actually becomes a turn.
154
+ const postResult = await postSessionSleepWake({ rest, sleep: claimed, threadId });
155
+ if (!postResult)
156
+ continue;
157
+ const exhausted = claimed.attempts >= SLEEP_WAKE_MAX_ATTEMPTS;
158
+ if (postResult.permanent || exhausted) {
159
+ await markSessionSleepFailed({
160
+ sessionId: claimed.session_id,
161
+ deliveryId: claimed.delivery_id,
162
+ });
163
+ }
164
+ taskLogger.error(`[task-runner] ${formatErrorWithStack(postResult.error)}`);
165
+ void notifyError(postResult.error, 'Session sleep wake failed');
166
+ }
167
+ }
79
168
  async function executeChannelScheduledTask({ rest, task, payload, prompt, runId, }) {
80
169
  const marker = payload.notifyOnly
81
170
  ? undefined
@@ -407,6 +496,7 @@ async function runTaskRunnerTick({ rest, staleRunningMs, dueBatchSize, }) {
407
496
  await previous;
408
497
  await processDueTask({ rest, task });
409
498
  }, Promise.resolve());
499
+ await wakeDueSessionSleeps({ rest });
410
500
  }
411
501
  export function startTaskRunner({ token, pollIntervalMs = 5_000, staleRunningMs = 120_000, dueBatchSize = 20, }) {
412
502
  const rest = createDiscordRest(token);
@@ -33,6 +33,62 @@ function parseUtcSendAtDate({ value, now, }) {
33
33
  }
34
34
  return runAt;
35
35
  }
36
+ const SLEEP_DURATION_REGEX = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i;
37
+ const SLEEP_DURATION_MS = {
38
+ ms: 1,
39
+ s: 1000,
40
+ m: 60_000,
41
+ h: 3_600_000,
42
+ d: 86_400_000,
43
+ };
44
+ function parseUtcFutureDate({ value, now, field, }) {
45
+ if (!UTC_SEND_AT_DATE_REGEX.test(value)) {
46
+ return new Error(`${field} must be UTC ISO format ending with Z (example: 2026-08-20T09:00:00Z). Received: ${value}`);
47
+ }
48
+ const parsed = new Date(value);
49
+ if (Number.isNaN(parsed.getTime())) {
50
+ return new Error(`Invalid UTC date for ${field}: ${value}`);
51
+ }
52
+ if (parsed.getTime() <= now.getTime()) {
53
+ return new Error(`${field} must be in the future (UTC): ${value}`);
54
+ }
55
+ return parsed;
56
+ }
57
+ export function parseSleepWakeAt({ duration, until, now, }) {
58
+ const trimmedDuration = duration?.trim() || '';
59
+ const trimmedUntil = until?.trim() || '';
60
+ if (trimmedDuration && trimmedUntil) {
61
+ return new Error('Pass either duration or until, not both');
62
+ }
63
+ if (!trimmedDuration && !trimmedUntil) {
64
+ return new Error('Pass duration or until');
65
+ }
66
+ if (trimmedUntil) {
67
+ return parseUtcFutureDate({
68
+ value: trimmedUntil,
69
+ now,
70
+ field: 'until',
71
+ });
72
+ }
73
+ const match = SLEEP_DURATION_REGEX.exec(trimmedDuration);
74
+ if (!match) {
75
+ return new Error(`Invalid duration: "${trimmedDuration}". Use a number plus ms, s, m, h, or d (example: 2h).`);
76
+ }
77
+ const amount = Number(match[1]);
78
+ const unit = match[2].toLowerCase();
79
+ if (!Number.isFinite(amount) || amount <= 0) {
80
+ return new Error('duration must be greater than 0');
81
+ }
82
+ return new Date(now.getTime() + amount * SLEEP_DURATION_MS[unit]);
83
+ }
84
+ export function formatSessionSleepWakeAt(wakeAt) {
85
+ return `${wakeAt.toISOString().slice(0, 16).replace('T', ' ')} UTC`;
86
+ }
87
+ export function formatSessionSleepWakePrompt({ wakeAt, reason, }) {
88
+ const until = formatSessionSleepWakeAt(wakeAt);
89
+ const reasonLine = reason?.trim() ? `\nReason: ${reason.trim()}` : '';
90
+ return `⬦ Woke after sleeping until ${until}${reasonLine}\nContinue the work you were waiting for.`;
91
+ }
36
92
  export function parseSendAtValue({ value, now, timezone, }) {
37
93
  const trimmed = value.trim();
38
94
  if (!trimmed) {
@@ -6,7 +6,7 @@ import { afterAll, afterEach, describe, expect, test } from 'vitest';
6
6
  import { completeScheduledTaskRunsForSession, createScheduledTask, createScheduledTaskRun, getActiveScheduledTaskRuns, getScheduledTask, startScheduledTaskRunSession, } from './database.js';
7
7
  import { closeDb } from './db.js';
8
8
  import { runTaskCommand } from './task-runner.js';
9
- import { appendTaskCommandOutput, parseScheduledTaskPayload, parseSendAtValue, } from './task-schedule.js';
9
+ import { appendTaskCommandOutput, parseScheduledTaskPayload, parseSendAtValue, parseSleepWakeAt, } from './task-schedule.js';
10
10
  describe('parseSendAtValue', () => {
11
11
  test('accepts UTC ISO date ending with Z', () => {
12
12
  const now = new Date('2026-02-22T13:00:00Z');
@@ -75,6 +75,76 @@ describe('parseSendAtValue', () => {
75
75
  expect(result.nextRunAt.toISOString()).toBe('2026-02-23T09:00:00.000Z');
76
76
  });
77
77
  });
78
+ describe('parseSleepWakeAt', () => {
79
+ const now = new Date('2026-08-19T12:00:00Z');
80
+ test('adds 2h to now', () => {
81
+ const result = parseSleepWakeAt({ duration: '2h', now });
82
+ expect(result).not.toBeInstanceOf(Error);
83
+ if (result instanceof Error)
84
+ throw result;
85
+ expect(result.toISOString()).toBe('2026-08-19T14:00:00.000Z');
86
+ });
87
+ test('adds 30s and 1d', () => {
88
+ const thirtySeconds = parseSleepWakeAt({ duration: '30s', now });
89
+ expect(thirtySeconds).not.toBeInstanceOf(Error);
90
+ if (thirtySeconds instanceof Error)
91
+ throw thirtySeconds;
92
+ expect(thirtySeconds.toISOString()).toBe('2026-08-19T12:00:30.000Z');
93
+ const oneDay = parseSleepWakeAt({ duration: '1d', now });
94
+ expect(oneDay).not.toBeInstanceOf(Error);
95
+ if (oneDay instanceof Error)
96
+ throw oneDay;
97
+ expect(oneDay.toISOString()).toBe('2026-08-20T12:00:00.000Z');
98
+ });
99
+ test('accepts until UTC ISO date ending with Z', () => {
100
+ const result = parseSleepWakeAt({
101
+ until: '2026-08-20T09:00:00Z',
102
+ now,
103
+ });
104
+ expect(result).not.toBeInstanceOf(Error);
105
+ if (result instanceof Error)
106
+ throw result;
107
+ expect(result.toISOString()).toBe('2026-08-20T09:00:00.000Z');
108
+ });
109
+ test('rejects past until', () => {
110
+ const result = parseSleepWakeAt({
111
+ until: '2026-08-19T11:59:59Z',
112
+ now,
113
+ });
114
+ expect(result).toBeInstanceOf(Error);
115
+ if (result instanceof Error) {
116
+ expect(result.message).toContain('until must be in the future (UTC)');
117
+ }
118
+ });
119
+ test('rejects both duration and until', () => {
120
+ const result = parseSleepWakeAt({
121
+ duration: '1h',
122
+ until: '2026-08-20T09:00:00Z',
123
+ now,
124
+ });
125
+ expect(result).toBeInstanceOf(Error);
126
+ if (result instanceof Error) {
127
+ expect(result.message).toContain('either duration or until');
128
+ }
129
+ });
130
+ test('rejects neither duration nor until', () => {
131
+ const result = parseSleepWakeAt({ now });
132
+ expect(result).toBeInstanceOf(Error);
133
+ if (result instanceof Error) {
134
+ expect(result.message).toContain('duration or until');
135
+ }
136
+ });
137
+ test('rejects until with a non-UTC offset', () => {
138
+ const result = parseSleepWakeAt({
139
+ until: '2026-08-20T09:00:00+01:00',
140
+ now,
141
+ });
142
+ expect(result).toBeInstanceOf(Error);
143
+ if (result instanceof Error) {
144
+ expect(result.message).toContain('UTC ISO format ending with Z');
145
+ }
146
+ });
147
+ });
78
148
  describe('scheduled task execution options', () => {
79
149
  const tempDirectories = [];
80
150
  afterEach(() => {