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
package/src/cli.ts CHANGED
@@ -16,6 +16,7 @@ import {
16
16
  } from './config.js'
17
17
  import { getCurrentVersion } from './upgrade.js'
18
18
  import { store } from './store.js'
19
+ import { publicOpencodeBindRequiresPassword } from './opencode.js'
19
20
  import multioauthCommands from './commands/multioauth.js'
20
21
  import botCommands from './cli-commands/bot.js'
21
22
  import maintenanceCommands from './cli-commands/maintenance.js'
@@ -73,6 +74,10 @@ cli
73
74
  '--no-critique',
74
75
  'Disable automatic diff upload to critique.work in system prompts',
75
76
  )
77
+ .option(
78
+ '--skip-footer-mentions',
79
+ 'Do not mention the thread creator in final session footers',
80
+ )
76
81
  .option(
77
82
  '--auto-restart',
78
83
  'Automatically restart the bot on crash or OOM kill',
@@ -98,6 +103,14 @@ cli
98
103
  'Disable anonymous product analytics (Strada). Same as KIMAKI_STRADA_ENABLED=0',
99
104
  )
100
105
  .option('--no-auto-upgrade', 'Disable background auto-upgrade on startup')
106
+ .option(
107
+ '--opencode-hostname <host>',
108
+ 'Hostname the OpenCode server listens on (default: 127.0.0.1). Use 0.0.0.0 to expose it on a VPS',
109
+ )
110
+ .option(
111
+ '--opencode-port <port>',
112
+ 'Port the OpenCode server listens on (default: a random free port)',
113
+ )
101
114
  .option(
102
115
  '--gateway',
103
116
  'Force gateway mode (use the gateway Kimaki bot instead of a self-hosted bot)',
@@ -145,6 +158,7 @@ cli
145
158
  verbosity?: string
146
159
  mentionMode?: boolean
147
160
  noCritique?: boolean
161
+ skipFooterMentions?: boolean
148
162
  allowAllUsers?: boolean
149
163
  restrictDirectories?: boolean
150
164
  permissionTimeoutMinutes?: string
@@ -157,6 +171,8 @@ cli
157
171
  allowMention?: Array<'users' | 'roles' | 'everyone'>
158
172
  enableSkill?: string[]
159
173
  disableSkill?: string[]
174
+ opencodeHostname?: string
175
+ opencodePort?: string
160
176
  }) => {
161
177
  // Guard: only one kimaki bot process can run per lock port. Agents may run
162
178
  // a second dev bot only when they explicitly choose a different lock port.
@@ -269,12 +285,36 @@ cli
269
285
  return parsed * 60_000
270
286
  })()
271
287
 
288
+ const opencodeHostname = options.opencodeHostname?.trim() || undefined
289
+ const opencodePort = (() => {
290
+ if (!options.opencodePort) return undefined
291
+ const parsed = Number(options.opencodePort)
292
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
293
+ cliLogger.error(
294
+ `Invalid --opencode-port: ${options.opencodePort}. Must be an integer between 1 and 65535.`,
295
+ )
296
+ process.exit(EXIT_NO_RESTART)
297
+ }
298
+ return parsed
299
+ })()
300
+
301
+ if (
302
+ publicOpencodeBindRequiresPassword({ hostname: opencodeHostname }) &&
303
+ !process.env.OPENCODE_SERVER_PASSWORD
304
+ ) {
305
+ cliLogger.error(
306
+ `OPENCODE_SERVER_PASSWORD is required when --opencode-hostname is ${opencodeHostname}. Binding the OpenCode server on a public address without a password lets anyone control the agent.`,
307
+ )
308
+ process.exit(EXIT_NO_RESTART)
309
+ }
310
+
272
311
  store.setState({
273
312
  ...(defaultVerbosity && {
274
313
  defaultVerbosity,
275
314
  }),
276
315
  ...(options.mentionMode && { defaultMentionMode: true }),
277
316
  ...(options.noCritique && { critiqueEnabled: false }),
317
+ ...(options.skipFooterMentions && { footerMentionsEnabled: false }),
278
318
  ...(options.allowAllUsers && { allowAllUsers: true }),
279
319
  ...(options.restrictDirectories && { restrictExternalDirectories: true }),
280
320
  ...(permissionTimeoutMs !== undefined && { permissionTimeoutMs }),
@@ -283,6 +323,8 @@ cli
283
323
  ...(enabledSkills.length > 0 && { enabledSkills }),
284
324
  ...(disabledSkills.length > 0 && { disabledSkills }),
285
325
  ...(options.allowMention && { allowedMentions: options.allowMention }),
326
+ ...(opencodeHostname && { opencodeHostname }),
327
+ ...(opencodePort !== undefined && { opencodePort }),
286
328
  })
287
329
 
288
330
  if (enabledSkills.length > 0) {
@@ -323,6 +365,11 @@ cli
323
365
  'Critique disabled: diffs will not be auto-uploaded to critique.work',
324
366
  )
325
367
  }
368
+ if (options.skipFooterMentions) {
369
+ cliLogger.log(
370
+ 'Footer mentions disabled: final session footers will not mention thread creators',
371
+ )
372
+ }
326
373
  if (options.noAutoUpgrade) {
327
374
  cliLogger.log(
328
375
  'Auto-upgrade disabled: kimaki will not check for updates on startup',
@@ -339,6 +386,12 @@ cli
339
386
  'Anonymous product analytics disabled (--no-analytics)',
340
387
  )
341
388
  }
389
+ if (opencodeHostname) {
390
+ cliLogger.log(`OpenCode server hostname: ${opencodeHostname}`)
391
+ }
392
+ if (opencodePort !== undefined) {
393
+ cliLogger.log(`OpenCode server port: ${opencodePort}`)
394
+ }
342
395
 
343
396
  if (options.installUrl) {
344
397
  await printDiscordInstallUrlAndExit({
@@ -7,7 +7,7 @@ import {
7
7
  type ThreadChannel,
8
8
  } from 'discord.js'
9
9
  import type { CommandContext } from './types.js'
10
- import { getThreadSession } from '../database.js'
10
+ import { cancelSessionSleepForThread, getThreadSession } from '../database.js'
11
11
  import { getOpencodeClient, initializeOpencodeForDirectory } from '../opencode.js'
12
12
  import {
13
13
  resolveWorkingDirectory,
@@ -66,6 +66,11 @@ export async function handleAbortCommand({
66
66
  return
67
67
  }
68
68
 
69
+ // Aborting is an explicit "stop waiting" from the user, and it never goes
70
+ // through enqueueIncoming, so cancel any pending sleep here too. Otherwise the
71
+ // wake would still fire later and restart a session the user just stopped.
72
+ await cancelSessionSleepForThread({ threadId: channel.id })
73
+
69
74
  // abortActiveRun delegates to session.abort(), run settlement stays event-driven.
70
75
  const runtime = getRuntime(channel.id)
71
76
  if (runtime) {
@@ -696,12 +696,12 @@ async function handleQuickAgentWithPrompt({
696
696
  })
697
697
  }
698
698
 
699
- const sessionDirectory = await (async () => {
700
- if (!worktreePromise) return projectDirectory
701
- const result = await worktreePromise
702
- if (result instanceof Error) return projectDirectory
703
- return result
704
- })()
699
+ const worktreeResult = worktreePromise ? await worktreePromise : projectDirectory
700
+ if (worktreeResult instanceof Error) {
701
+ await command.editReply(`Worktree creation failed: ${worktreeResult.message}`)
702
+ return
703
+ }
704
+ const sessionDirectory = worktreeResult
705
705
 
706
706
  await command
707
707
  .editReply(`Sent with **${resolvedAgentName}** agent in ${thread.toString()}`)
@@ -9,8 +9,11 @@ import {
9
9
  showAskUserQuestionDropdowns,
10
10
  } from './ask-question.js'
11
11
 
12
- function createFakeThread(): ThreadChannel {
12
+ function createFakeThread({ failSend }: { failSend?: boolean } = {}): ThreadChannel {
13
13
  const send = vi.fn(async () => {
14
+ if (failSend) {
15
+ throw new Error('Missing Permissions')
16
+ }
14
17
  return { id: 'msg-1' }
15
18
  })
16
19
 
@@ -109,6 +112,50 @@ describe('ask-question', () => {
109
112
  expect([...pendingQuestionContexts.keys()]).toEqual(['ctx-3'])
110
113
  })
111
114
 
115
+ test('does not schedule a question expiry timer', async () => {
116
+ const timeoutSpy = vi.spyOn(globalThis, 'setTimeout')
117
+
118
+ await showAskUserQuestionDropdowns({
119
+ thread: createFakeThread(),
120
+ sessionId: 'ses-1',
121
+ directory: '/project',
122
+ requestId: 'req-no-ttl',
123
+ input: {
124
+ questions: [{
125
+ question: 'Choose one',
126
+ header: 'Pick',
127
+ options: [
128
+ { label: 'Alpha', description: 'A' },
129
+ { label: 'Beta', description: 'B' },
130
+ ],
131
+ }],
132
+ },
133
+ })
134
+
135
+ expect(timeoutSpy).not.toHaveBeenCalled()
136
+ })
137
+
138
+ test('drops the context when the dropdown message fails to send', async () => {
139
+ await showAskUserQuestionDropdowns({
140
+ thread: createFakeThread({ failSend: true }),
141
+ sessionId: 'ses-1',
142
+ directory: '/project',
143
+ requestId: 'req-send-fails',
144
+ input: {
145
+ questions: [{
146
+ question: 'Choose one',
147
+ header: 'Pick',
148
+ options: [
149
+ { label: 'Alpha', description: 'A' },
150
+ { label: 'Beta', description: 'B' },
151
+ ],
152
+ }],
153
+ },
154
+ })
155
+
156
+ expect(pendingQuestionContexts.size).toBe(0)
157
+ })
158
+
112
159
  test('requires every question to have an answer', () => {
113
160
  expect(areAllQuestionsAnswered({
114
161
  totalQuestions: 3,
@@ -12,6 +12,7 @@ import {
12
12
  import crypto from 'node:crypto'
13
13
  import { sendThreadMessage, NOTIFY_MESSAGE_FLAGS, SILENT_MESSAGE_FLAGS } from '../discord-utils.js'
14
14
  import { getOpencodeClient } from '../opencode.js'
15
+ import { DiscordOperationError } from '../errors.js'
15
16
  import { createLogger, LogPrefix } from '../logger.js'
16
17
 
17
18
  const logger = createLogger(LogPrefix.ASK_QUESTION)
@@ -44,8 +45,9 @@ type PendingQuestionContext = {
44
45
  }
45
46
 
46
47
  // Store pending question contexts by hash.
47
- // TTL prevents unbounded growth if user never answers a question.
48
- const QUESTION_CONTEXT_TTL_MS = 10 * 60 * 1000
48
+ // No TTL on purpose: a question can only be answered by the user, so expiring it
49
+ // could only abort the run. Cleanup happens on answer, on a new user message, on
50
+ // abort (abortActiveRunInternal), and on thread dispose.
49
51
  export const pendingQuestionContexts = new Map<string, PendingQuestionContext>()
50
52
 
51
53
  export function areAllQuestionsAnswered({
@@ -157,32 +159,6 @@ export async function showAskUserQuestionDropdowns({
157
159
  }
158
160
 
159
161
  pendingQuestionContexts.set(contextHash, context)
160
- // On TTL expiry: hide the dropdown UI and abort the session so OpenCode
161
- // unblocks. We intentionally do NOT call question.reply() — sending 'Other'
162
- // made the model think the user chose an option when they didn't.
163
- setTimeout(async () => {
164
- const ctx = pendingQuestionContexts.get(contextHash)
165
- if (!ctx) {
166
- return
167
- }
168
- // Delete context first so the dropdown becomes inert immediately.
169
- // Without this, a user clicking during the abort() await would still
170
- // be accepted by handleAskQuestionSelectMenu, then abort() would
171
- // kill that valid run.
172
- deletePendingQuestionContextsForRequest({
173
- threadId: ctx.thread.id,
174
- requestId: ctx.requestId,
175
- })
176
- // Abort the session so OpenCode isn't stuck waiting for a reply
177
- const client = getOpencodeClient(ctx.directory)
178
- if (client) {
179
- await client.session.abort({
180
- sessionID: ctx.sessionId,
181
- }).catch((error) => {
182
- logger.error('Failed to abort session after question expiry:', error)
183
- })
184
- }
185
- }, QUESTION_CONTEXT_TTL_MS).unref()
186
162
 
187
163
  // Send one message per question with its dropdown directly underneath
188
164
  for (let i = 0; i < input.questions.length; i++) {
@@ -219,11 +195,24 @@ export async function showAskUserQuestionDropdowns({
219
195
  const actionRow =
220
196
  new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(selectMenu)
221
197
 
222
- await thread.send({
198
+ const sendResult = await thread.send({
223
199
  content: `**${(q.header || '').slice(0, 200)}**\n${q.question.slice(0, 1700)}`,
224
200
  components: [actionRow],
225
201
  flags: silent ? SILENT_MESSAGE_FLAGS : NOTIFY_MESSAGE_FLAGS,
226
- })
202
+ }).catch((e) => new DiscordOperationError({ operation: 'sendQuestionDropdown', cause: e }))
203
+ // Without a visible dropdown the user can never answer, and there is no TTL
204
+ // to rescue the run, so drop the context and abort so OpenCode unblocks.
205
+ if (sendResult instanceof Error) {
206
+ logger.error('Failed to send question dropdown:', sendResult)
207
+ deletePendingQuestionContextsForRequest({ threadId: thread.id, requestId })
208
+ const client = getOpencodeClient(directory)
209
+ if (client) {
210
+ await client.session.abort({ sessionID: sessionId }).catch((error) => {
211
+ logger.error('Failed to abort session after question send failure:', error)
212
+ })
213
+ }
214
+ return
215
+ }
227
216
  }
228
217
 
229
218
  logger.log(
@@ -414,7 +403,7 @@ export function parseAskUserQuestionTool(part: {
414
403
  * the tool answer so the model sees the user's response. The caller should
415
404
  * NOT also enqueue the message as a new prompt.
416
405
  * Returns 'replied' on success, 'reply-failed' if the reply call fails
417
- * (context kept pending so TTL can retry).
406
+ * (context kept pending so the user can retry).
418
407
  */
419
408
  export async function cancelPendingQuestion(
420
409
  threadId: string,
@@ -466,7 +455,7 @@ export async function cancelPendingQuestion(
466
455
  logger.log(`Answered question ${context.requestId} with user message`)
467
456
  } catch (error) {
468
457
  logger.error('Failed to answer question:', error)
469
- // Keep context pending so TTL can still fire.
458
+ // Keep context pending so the user can retry.
470
459
  // Caller should not consume the user message since reply failed.
471
460
  return 'reply-failed'
472
461
  }
@@ -34,6 +34,7 @@ import {
34
34
  getOpencodeServerAuthHeaders,
35
35
  } from '../opencode.js'
36
36
  import { resolveTextChannel, getKimakiMetadata } from '../discord-utils.js'
37
+ import { clearModelListCache } from '../session-handler/model-utils.js'
37
38
  import { createLogger, LogPrefix } from '../logger.js'
38
39
  import { buildPaginatedOptions, parsePaginationValue } from './paginated-select.js'
39
40
 
@@ -122,7 +123,9 @@ function createContextHash(context: LoginContext): string {
122
123
  // ── Provider popularity order ───────────────────────────────────
123
124
  // Discord select menus cap at 25 options, so we show popular ones first.
124
125
  // IDs sourced from opencode's provider.list() API (scripts/list-providers.ts).
126
+ // `subrouter` leads: it pools every subscription and cycles across them.
125
127
  const PROVIDER_POPULARITY_ORDER: string[] = [
128
+ 'subrouter',
126
129
  'anthropic',
127
130
  'openai',
128
131
  'google',
@@ -937,6 +940,7 @@ export async function handleOAuthCodeModalSubmit(
937
940
  }
938
941
 
939
942
  await getClient().instance.dispose({ directory: ctx.dir })
943
+ clearModelListCache()
940
944
  pendingLoginContexts.delete(hash)
941
945
 
942
946
  await interaction.editReply({
@@ -993,6 +997,7 @@ export async function handleApiKeyModalSubmit(
993
997
 
994
998
  // Dispose to refresh provider state so new credentials are recognized
995
999
  await getClient().instance.dispose({ directory: ctx.dir })
1000
+ clearModelListCache()
996
1001
 
997
1002
  await interaction.editReply({
998
1003
  content: `✅ **Successfully authenticated with ${ctx.providerName}!**\n\nYou can now use models from this provider.`,
@@ -1159,6 +1164,7 @@ async function startOAuthFlow(
1159
1164
  }
1160
1165
 
1161
1166
  await getClient().instance.dispose({ directory: ctx.dir })
1167
+ clearModelListCache()
1162
1168
  pendingLoginContexts.delete(hash)
1163
1169
 
1164
1170
  await interaction.editReply({
@@ -1,7 +1,5 @@
1
- // /merge-worktree command - Merge worktree commits into default branch.
2
- // Pipeline: rebase worktree commits onto target -> local fast-forward push.
3
- // Preserves all commits (no squash). On rebase conflicts, asks the AI model
4
- // in the thread to resolve them.
1
+ // /merge-worktree command - Rebase or squash worktree commits into a target branch.
2
+ // On rebase conflicts, asks the AI model in the thread to resolve them.
5
3
 
6
4
  import { type TextChannel, type ThreadChannel } from 'discord.js'
7
5
  import type { AutocompleteContext, CommandContext } from './types.js'
@@ -12,7 +10,12 @@ import {
12
10
  } from '../database.js'
13
11
  import { createLogger, LogPrefix } from '../logger.js'
14
12
  import { notifyError } from '../sentry.js'
15
- import { mergeWorktree, listBranchesByLastCommit, validateBranchRef } from '../worktrees.js'
13
+ import {
14
+ mergeWorktree,
15
+ listBranchesByLastCommit,
16
+ validateBranchRef,
17
+ formatMergeWorktreeError,
18
+ } from '../worktrees.js'
16
19
  import {
17
20
  sendThreadMessage,
18
21
  resolveWorkingDirectory,
@@ -30,6 +33,10 @@ import {
30
33
 
31
34
  const logger = createLogger(LogPrefix.WORKTREE)
32
35
 
36
+ function quoteShellArg(value: string): string {
37
+ return `'${value.replaceAll("'", "'\\''")}'`
38
+ }
39
+
33
40
  /** Worktree thread title prefix - indicates unmerged worktree */
34
41
  export const WORKTREE_PREFIX = '⬦ '
35
42
 
@@ -122,6 +129,15 @@ export async function handleMergeWorktreeCommand({
122
129
  return
123
130
  }
124
131
 
132
+ const strategyOption = command.options.getString('strategy') || 'rebase'
133
+ if (strategyOption !== 'rebase' && strategyOption !== 'squash') {
134
+ await command.editReply(`Invalid merge strategy: \`${strategyOption}\``)
135
+ return
136
+ }
137
+ const strategyName = strategyOption === 'squash'
138
+ ? 'Squash into one commit'
139
+ : 'Keep commits (rebase)'
140
+
125
141
  const rawTargetBranch = command.options.getString('target-branch') || undefined
126
142
  let targetBranch = rawTargetBranch
127
143
  if (targetBranch) {
@@ -141,6 +157,7 @@ export async function handleMergeWorktreeCommand({
141
157
  mainRepoDir: info.project_directory,
142
158
  worktreeName: info.workspace_name,
143
159
  targetBranch,
160
+ strategy: strategyOption,
144
161
  onProgress: (msg) => {
145
162
  logger.log(`[merge] ${msg}`)
146
163
  },
@@ -163,13 +180,23 @@ export async function handleMergeWorktreeCommand({
163
180
 
164
181
  if (result instanceof NothingToMergeError) {
165
182
  void removeWorktreePrefixFromTitle(thread)
166
- await command.editReply(`Merge failed: ${result.message}`)
183
+ await command.editReply(formatMergeWorktreeError(result))
167
184
  return
168
185
  }
169
186
 
170
187
  if (result instanceof RebaseConflictError) {
188
+ const mergedThreadName = thread.name.startsWith(WORKTREE_PREFIX)
189
+ ? thread.name.slice(WORKTREE_PREFIX.length)
190
+ : thread.name
191
+ const mergeCommand = [
192
+ 'kimaki merge-worktree',
193
+ `--strategy ${strategyOption}`,
194
+ `--target-branch ${quoteShellArg(String(result.target))}`,
195
+ `--thread ${quoteShellArg(thread.id)}`,
196
+ `--thread-name ${quoteShellArg(mergedThreadName)}`,
197
+ ].join(' ')
171
198
  await command.editReply(
172
- 'Rebase conflict detected. Asking the model to resolve...',
199
+ `Rebase conflict detected. Asking the model to resolve it and retry the merge with **${strategyName}**.`,
173
200
  )
174
201
  await sendPromptToModel({
175
202
  prompt: [
@@ -184,7 +211,8 @@ export async function handleMergeWorktreeCommand({
184
211
  '6. Stage resolved files with `git add`',
185
212
  '7. Continue the rebase with `git rebase --continue`',
186
213
  '8. If git reports more conflicts, repeat steps 1-7 until the rebase finishes (no more rebase in progress, `git status` is clean)',
187
- '9. Once the rebase is fully complete, tell me so I can run `/merge-worktree` again',
214
+ `9. Once the rebase is fully complete, run \`${mergeCommand}\` yourself`,
215
+ '10. If that command fails because the target changed or is not ready, stop and report the failure. The user can run it again later.',
188
216
  ].join('\n'),
189
217
  thread,
190
218
  projectDirectory: info.project_directory,
@@ -194,14 +222,17 @@ export async function handleMergeWorktreeCommand({
194
222
  return
195
223
  }
196
224
 
197
- await command.editReply(`Merge failed: ${result.message}`)
225
+ const formatted = formatMergeWorktreeError(result)
226
+ logger.error(formatted)
227
+ await command.editReply(formatted)
198
228
  return
199
229
  }
200
230
 
201
231
  void removeWorktreePrefixFromTitle(thread)
202
- await command.editReply(
203
- `Merged \`${result.branchName}\` into \`${result.defaultBranch}\` @ ${result.shortSha} (${result.commitCount} commit${result.commitCount === 1 ? '' : 's'})\nWorktree now at detached HEAD.`,
204
- )
232
+ const mergeSummary = strategyOption === 'squash'
233
+ ? `Squashed \`${result.branchName}\` into \`${result.defaultBranch}\` @ ${result.shortSha} (${result.commitCount} source commit${result.commitCount === 1 ? '' : 's'} → 1)`
234
+ : `Merged \`${result.branchName}\` into \`${result.defaultBranch}\` @ ${result.shortSha} (${result.commitCount} commit${result.commitCount === 1 ? '' : 's'})`
235
+ await command.editReply(`${mergeSummary}\nWorktree now at detached HEAD.`)
205
236
  }
206
237
 
207
238
  /**
@@ -34,6 +34,7 @@ import {
34
34
  } from './model.js'
35
35
 
36
36
  import { getThinkingValuesForModel } from '../thinking-utils.js'
37
+ import { resolveDisplayedModelId } from '../session-handler/model-utils.js'
37
38
  import { createLogger, LogPrefix } from '../logger.js'
38
39
 
39
40
  const logger = createLogger(LogPrefix.MODEL)
@@ -214,6 +215,12 @@ export async function showModelVariantPicker({
214
215
  const { providerID, modelID, model: fullModelId } = currentModelInfo
215
216
  const sourceLabel = formatSourceLabel(currentModelInfo)
216
217
  const variantLabel = cascadeVariant ? ` (${cascadeVariant})` : ''
218
+ const displayedModelId =
219
+ resolveDisplayedModelId({
220
+ providers: providersResponse.data.all,
221
+ providerID,
222
+ modelID,
223
+ }) ?? fullModelId
217
224
 
218
225
  const provider = providersResponse.data.all.find((p) => {
219
226
  return p.id === providerID
@@ -226,7 +233,7 @@ export async function showModelVariantPicker({
226
233
  modelId: modelID,
227
234
  })
228
235
 
229
- const statusText = `**Current model:** \`${fullModelId}\`${variantLabel} — ${sourceLabel}`
236
+ const statusText = `**Current model:** \`${displayedModelId}\`${variantLabel} — ${sourceLabel}`
230
237
 
231
238
  if (variants.length === 0) {
232
239
  await editReply({
@@ -28,7 +28,10 @@ import {
28
28
  } from '../database.js'
29
29
  import { initializeOpencodeForDirectory } from '../opencode.js'
30
30
  import { resolveTextChannel, getKimakiMetadata } from '../discord-utils.js'
31
- import { getDefaultModel } from '../session-handler/model-utils.js'
31
+ import {
32
+ getDefaultModel,
33
+ resolveDisplayedModelId,
34
+ } from '../session-handler/model-utils.js'
32
35
  import { getRuntime } from '../session-handler/thread-session-runtime.js'
33
36
  import { getThinkingValuesForModel } from '../thinking-utils.js'
34
37
  import {
@@ -545,21 +548,28 @@ export async function handleModelCommand({
545
548
  }
546
549
 
547
550
  const currentModelText = (() => {
551
+ if (currentModelInfo.type === 'none') {
552
+ return '**Current:** none'
553
+ }
554
+ const displayed =
555
+ resolveDisplayedModelId({
556
+ providers: allProviders,
557
+ providerID: currentModelInfo.providerID,
558
+ modelID: currentModelInfo.modelID,
559
+ }) ?? currentModelInfo.model
548
560
  switch (currentModelInfo.type) {
549
561
  case 'session':
550
- return `**Current (this thread):** \`${currentModelInfo.model}\``
562
+ return `**Current (this thread):** \`${displayed}\``
551
563
  case 'agent':
552
- return `**Current (agent "${currentModelInfo.agentName}"):** \`${currentModelInfo.model}\``
564
+ return `**Current (agent "${currentModelInfo.agentName}"):** \`${displayed}\``
553
565
  case 'channel':
554
- return `**Current (channel override):** \`${currentModelInfo.model}\``
566
+ return `**Current (channel override):** \`${displayed}\``
555
567
  case 'global':
556
- return `**Current (global default):** \`${currentModelInfo.model}\``
568
+ return `**Current (global default):** \`${displayed}\``
557
569
  case 'opencode-config':
558
570
  case 'opencode-recent':
559
571
  case 'opencode-provider-default':
560
- return `**Current (opencode default):** \`${currentModelInfo.model}\``
561
- case 'none':
562
- return '**Current:** none'
572
+ return `**Current (opencode default):** \`${displayed}\``
563
573
  }
564
574
  })()
565
575
 
@@ -1,3 +1,4 @@
1
+ // LEGACY rotation, superseded by @subrouter/opencode. See oauth-rotation-shared.ts.
1
2
  /**
2
3
  * CLI commands for multi-provider OAuth account management.
3
4
  * Mounted via goke .use() in cli.ts under the `multioauth` namespace.