kimaki 0.4.78 → 0.4.80

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 (90) hide show
  1. package/dist/anthropic-auth-plugin.js +628 -0
  2. package/dist/channel-management.js +2 -2
  3. package/dist/cli.js +316 -129
  4. package/dist/commands/action-buttons.js +1 -1
  5. package/dist/commands/login.js +634 -277
  6. package/dist/commands/model.js +91 -6
  7. package/dist/commands/paginated-select.js +57 -0
  8. package/dist/commands/resume.js +2 -2
  9. package/dist/commands/tasks.js +205 -0
  10. package/dist/commands/undo-redo.js +80 -18
  11. package/dist/context-awareness-plugin.js +347 -0
  12. package/dist/database.js +103 -7
  13. package/dist/db.js +39 -1
  14. package/dist/discord-bot.js +42 -19
  15. package/dist/discord-urls.js +11 -0
  16. package/dist/discord-ws-proxy.js +350 -0
  17. package/dist/discord-ws-proxy.test.js +500 -0
  18. package/dist/errors.js +1 -1
  19. package/dist/gateway-session.js +163 -0
  20. package/dist/hrana-server.js +114 -4
  21. package/dist/interaction-handler.js +30 -7
  22. package/dist/ipc-tools-plugin.js +186 -0
  23. package/dist/message-preprocessing.js +56 -11
  24. package/dist/onboarding-welcome.js +1 -1
  25. package/dist/opencode-interrupt-plugin.js +133 -75
  26. package/dist/opencode-plugin.js +12 -389
  27. package/dist/opencode.js +59 -5
  28. package/dist/parse-permission-rules.test.js +117 -0
  29. package/dist/queue-drain-after-interactive-ui.e2e.test.js +119 -0
  30. package/dist/session-handler/thread-session-runtime.js +68 -29
  31. package/dist/startup-time.e2e.test.js +295 -0
  32. package/dist/store.js +1 -0
  33. package/dist/system-message.js +3 -1
  34. package/dist/task-runner.js +7 -3
  35. package/dist/task-schedule.js +12 -0
  36. package/dist/thread-message-queue.e2e.test.js +13 -1
  37. package/dist/undo-redo.e2e.test.js +166 -0
  38. package/dist/utils.js +4 -1
  39. package/dist/voice-attachment.js +34 -0
  40. package/dist/voice-handler.js +11 -9
  41. package/dist/voice-message.e2e.test.js +78 -0
  42. package/dist/voice.test.js +31 -0
  43. package/package.json +12 -7
  44. package/skills/egaki/SKILL.md +80 -15
  45. package/skills/errore/SKILL.md +13 -0
  46. package/skills/lintcn/SKILL.md +749 -0
  47. package/skills/npm-package/SKILL.md +17 -3
  48. package/skills/spiceflow/SKILL.md +14 -0
  49. package/skills/zele/SKILL.md +9 -0
  50. package/src/anthropic-auth-plugin.ts +732 -0
  51. package/src/channel-management.ts +2 -2
  52. package/src/cli.ts +354 -132
  53. package/src/commands/action-buttons.ts +1 -0
  54. package/src/commands/login.ts +836 -337
  55. package/src/commands/model.ts +102 -7
  56. package/src/commands/paginated-select.ts +81 -0
  57. package/src/commands/resume.ts +6 -1
  58. package/src/commands/tasks.ts +293 -0
  59. package/src/commands/undo-redo.ts +87 -20
  60. package/src/context-awareness-plugin.ts +469 -0
  61. package/src/database.ts +138 -7
  62. package/src/db.ts +40 -1
  63. package/src/discord-bot.ts +46 -19
  64. package/src/discord-urls.ts +12 -0
  65. package/src/errors.ts +1 -1
  66. package/src/hrana-server.ts +124 -3
  67. package/src/interaction-handler.ts +41 -9
  68. package/src/ipc-tools-plugin.ts +228 -0
  69. package/src/message-preprocessing.ts +82 -11
  70. package/src/onboarding-welcome.ts +1 -1
  71. package/src/opencode-interrupt-plugin.ts +164 -91
  72. package/src/opencode-plugin.ts +13 -483
  73. package/src/opencode.ts +60 -5
  74. package/src/parse-permission-rules.test.ts +127 -0
  75. package/src/queue-drain-after-interactive-ui.e2e.test.ts +151 -0
  76. package/src/session-handler/thread-runtime-state.ts +4 -1
  77. package/src/session-handler/thread-session-runtime.ts +82 -20
  78. package/src/startup-time.e2e.test.ts +372 -0
  79. package/src/store.ts +8 -0
  80. package/src/system-message.ts +10 -1
  81. package/src/task-runner.ts +9 -22
  82. package/src/task-schedule.ts +15 -0
  83. package/src/thread-message-queue.e2e.test.ts +14 -1
  84. package/src/undo-redo.e2e.test.ts +207 -0
  85. package/src/utils.ts +7 -0
  86. package/src/voice-attachment.ts +51 -0
  87. package/src/voice-handler.ts +15 -7
  88. package/src/voice-message.e2e.test.ts +95 -0
  89. package/src/voice.test.ts +36 -0
  90. package/src/onboarding-tutorial-plugin.ts +0 -93
@@ -1,484 +1,14 @@
1
- // OpenCode plugin for Kimaki Discord bot.
2
- // Provides IPC-based tools (file upload, action buttons) and injects synthetic
3
- // message parts for branch changes and idle-time awareness.
4
- // Discord REST tools (user listing, thread archiving) were moved to CLI
5
- // commands (kimaki user list, kimaki session archive) so the plugin no
6
- // longer needs a Discord bot token or REST client.
7
- import type { Plugin } from '@opencode-ai/plugin'
8
- import type { ToolContext } from '@opencode-ai/plugin/tool'
9
- import crypto from 'node:crypto'
10
- import fs from 'node:fs'
11
- import path from 'node:path'
12
- import dedent from 'string-dedent'
13
- import { z } from 'zod'
14
-
15
- // Inlined from '@opencode-ai/plugin/tool' because the subpath value import
16
- // fails at runtime in global npm installs (#35). Opencode loads this plugin
17
- // file in its own process and resolves modules from kimaki's install dir,
18
- // but the '/tool' subpath export isn't found by opencode's module resolver.
19
- // The type-only imports above are fine (erased at compile time).
20
- // The opencode docs recommend `import { tool } from '@opencode-ai/plugin'`
21
- // (main entry) but their index.d.ts uses `export * from "./tool"` which
22
- // doesn't re-export the tool function under nodenext resolution because
23
- // tool is a merged function+namespace declaration.
24
- function tool<Args extends z.ZodRawShape>(input: {
25
- description: string
26
- args: Args
27
- execute(
28
- args: z.infer<z.ZodObject<Args>>,
29
- context: ToolContext,
30
- ): Promise<string>
31
- }) {
32
- return input
33
- }
34
- import * as errore from 'errore'
35
- import { getPrisma, createIpcRequest, getIpcRequestById } from './database.js'
36
- import { setDataDir } from './config.js'
37
- import {
38
- createLogger,
39
- formatErrorWithStack,
40
- LogPrefix,
41
- setLogFilePath,
42
- } from './logger.js'
43
- import { initSentry, notifyError } from './sentry.js'
44
- import { execAsync } from './worktrees.js'
45
-
46
- const logger = createLogger(LogPrefix.OPENCODE)
47
-
48
- // condenseMemoryMd lives in condense-memory.ts — must NOT be exported from
49
- // this file because OpenCode's plugin loader calls every exported function
50
- // as a plugin initializer, which would crash marked's Lexer with non-string input.
51
- import { condenseMemoryMd } from './condense-memory.js'
52
-
53
- const FILE_UPLOAD_TIMEOUT_MS = 6 * 60 * 1000
54
- const DEFAULT_FILE_UPLOAD_MAX_FILES = 5
55
- const ACTION_BUTTON_TIMEOUT_MS = 30 * 1000
56
-
57
- type GitState = {
58
- key: string
59
- kind: 'branch' | 'detached-head' | 'detached-submodule'
60
- label: string
61
- warning: string | null
62
- }
63
-
64
- async function resolveGitState({
65
- directory,
66
- }: {
67
- directory: string
68
- }): Promise<GitState | null> {
69
- const branchResult = await errore.tryAsync(() => {
70
- return execAsync('git symbolic-ref --short HEAD', { cwd: directory })
71
- })
72
- if (!(branchResult instanceof Error)) {
73
- const branch = branchResult.stdout.trim()
74
- if (branch) {
75
- return {
76
- key: `branch:${branch}`,
77
- kind: 'branch',
78
- label: branch,
79
- warning: null,
80
- }
81
- }
82
- }
83
-
84
- const shaResult = await errore.tryAsync(() => {
85
- return execAsync('git rev-parse --short HEAD', { cwd: directory })
86
- })
87
- if (shaResult instanceof Error) {
88
- return null
89
- }
90
-
91
- const shortSha = shaResult.stdout.trim()
92
- if (!shortSha) {
93
- return null
94
- }
95
-
96
- const superprojectResult = await errore.tryAsync(() => {
97
- return execAsync('git rev-parse --show-superproject-working-tree', {
98
- cwd: directory,
99
- })
100
- })
101
- const superproject =
102
- superprojectResult instanceof Error ? '' : superprojectResult.stdout.trim()
103
- if (superproject) {
104
- return {
105
- key: `detached-submodule:${shortSha}`,
106
- kind: 'detached-submodule',
107
- label: `detached submodule @ ${shortSha}`,
108
- warning:
109
- `\n[warning: submodule is in detached HEAD at ${shortSha}. ` +
110
- 'create or switch to a branch before committing.]',
111
- }
112
- }
113
-
114
- return {
115
- key: `detached-head:${shortSha}`,
116
- kind: 'detached-head',
117
- label: `detached HEAD @ ${shortSha}`,
118
- warning:
119
- `\n[warning: repository is in detached HEAD at ${shortSha}. ` +
120
- 'create or switch to a branch before committing.]',
121
- }
122
- }
123
-
124
- const kimakiPlugin: Plugin = async ({ directory }) => {
125
- // Initialize Sentry in the plugin process (runs inside OpenCode server, not bot)
126
- initSentry()
127
-
128
- const dataDir = process.env.KIMAKI_DATA_DIR
129
- if (dataDir) {
130
- setDataDir(dataDir)
131
- // Append to the same log file the bot process created (no truncation)
132
- setLogFilePath(dataDir)
133
- }
134
-
135
- // Per-session state for synthetic part injection
136
- const sessionGitStates = new Map<string, GitState>()
137
- const sessionLastMessageTime = new Map<string, number>()
138
- // Track whether we've already injected MEMORY.md contents for each session
139
- const sessionMemoryInjected = new Set<string>()
140
-
141
-
142
- return {
143
- tool: {
144
- kimaki_file_upload: tool({
145
- description:
146
- 'Prompt the Discord user to upload files using a native file picker modal. ' +
147
- 'The user sees a button, clicks it, and gets a file upload dialog. ' +
148
- 'Returns the local file paths of downloaded files in the project directory. ' +
149
- 'Use this when you need the user to provide files (images, documents, configs, etc.). ' +
150
- 'IMPORTANT: Always call this tool last in your message, after all text parts.',
151
- args: {
152
- prompt: z
153
- .string()
154
- .describe(
155
- 'Message shown to the user explaining what files to upload',
156
- ),
157
- maxFiles: z
158
- .number()
159
- .min(1)
160
- .max(10)
161
- .optional()
162
- .describe(
163
- 'Maximum number of files the user can upload (1-10, default 5)',
164
- ),
165
- },
166
- async execute({ prompt, maxFiles }, context) {
167
- const prisma = await getPrisma()
168
- const row = await prisma.thread_sessions.findFirst({
169
- where: { session_id: context.sessionID },
170
- select: { thread_id: true },
171
- })
172
-
173
- if (!row?.thread_id) {
174
- return 'Could not find thread for current session'
175
- }
176
-
177
- // Insert IPC request for the bot to pick up via polling
178
- const ipcRow = await createIpcRequest({
179
- type: 'file_upload',
180
- sessionId: context.sessionID,
181
- threadId: row.thread_id,
182
- payload: JSON.stringify({
183
- prompt,
184
- maxFiles: maxFiles || DEFAULT_FILE_UPLOAD_MAX_FILES,
185
- directory: context.directory,
186
- }),
187
- })
188
-
189
- // Poll for response from the bot process
190
- const deadline = Date.now() + FILE_UPLOAD_TIMEOUT_MS
191
- const POLL_INTERVAL_MS = 300
192
- while (Date.now() < deadline) {
193
- await new Promise((resolve) => {
194
- setTimeout(resolve, POLL_INTERVAL_MS)
195
- })
196
- const updated = await getIpcRequestById({ id: ipcRow.id })
197
- if (!updated || updated.status === 'cancelled') {
198
- return 'File upload was cancelled'
199
- }
200
- if (updated.response) {
201
- const parsed = JSON.parse(updated.response) as {
202
- filePaths?: string[]
203
- error?: string
204
- }
205
- if (parsed.error) {
206
- return `File upload failed: ${parsed.error}`
207
- }
208
- const filePaths = parsed.filePaths || []
209
- if (filePaths.length === 0) {
210
- return 'No files were uploaded (user may have cancelled or sent a new message)'
211
- }
212
- return `Files uploaded successfully:\n${filePaths.join('\n')}`
213
- }
214
- }
215
-
216
- return 'File upload timed out - user did not upload files within the time limit'
217
- },
218
- }),
219
- kimaki_action_buttons: tool({
220
- description: dedent`
221
- Show action buttons in the current Discord thread for quick confirmations.
222
- Use this when the user can respond by clicking one of up to 3 buttons.
223
- Prefer a single button whenever possible.
224
- Default color is white (same visual style as permission deny button).
225
- If you need more than 3 options, use the question tool instead.
226
- IMPORTANT: Always call this tool last in your message, after all text parts.
227
-
228
- Examples:
229
- - buttons: [{"label":"Yes, proceed"}]
230
- - buttons: [{"label":"Approve","color":"green"}]
231
- - buttons: [
232
- {"label":"Confirm","color":"blue"},
233
- {"label":"Cancel","color":"white"}
234
- ]
235
- `,
236
- args: {
237
- buttons: z
238
- .array(
239
- z.object({
240
- label: z
241
- .string()
242
- .min(1)
243
- .max(80)
244
- .describe('Button label shown to the user (1-80 chars)'),
245
- color: z
246
- .enum(['white', 'blue', 'green', 'red'])
247
- .optional()
248
- .describe(
249
- 'Optional button color. white is default and preferred for most confirmations.',
250
- ),
251
- }),
252
- )
253
- .min(1)
254
- .max(3)
255
- .describe(
256
- 'Array of 1-3 action buttons. Prefer one button whenever possible.',
257
- ),
258
- },
259
- async execute({ buttons }, context) {
260
- const prisma = await getPrisma()
261
- const row = await prisma.thread_sessions.findFirst({
262
- where: { session_id: context.sessionID },
263
- select: { thread_id: true },
264
- })
265
-
266
- if (!row?.thread_id) {
267
- return 'Could not find thread for current session'
268
- }
269
-
270
- // Insert IPC request for the bot to pick up via polling
271
- const ipcRow = await createIpcRequest({
272
- type: 'action_buttons',
273
- sessionId: context.sessionID,
274
- threadId: row.thread_id,
275
- payload: JSON.stringify({
276
- buttons,
277
- directory: context.directory,
278
- }),
279
- })
280
-
281
- // Wait for bot to acknowledge (status changes from pending to processing/completed)
282
- const deadline = Date.now() + ACTION_BUTTON_TIMEOUT_MS
283
- const POLL_INTERVAL_MS = 200
284
- while (Date.now() < deadline) {
285
- await new Promise((resolve) => {
286
- setTimeout(resolve, POLL_INTERVAL_MS)
287
- })
288
- const updated = await getIpcRequestById({ id: ipcRow.id })
289
- if (!updated || updated.status === 'cancelled') {
290
- return 'Action button request was cancelled'
291
- }
292
- if (updated.response) {
293
- const parsed = JSON.parse(updated.response) as {
294
- ok?: boolean
295
- error?: string
296
- }
297
- if (parsed.error) {
298
- return `Action button request failed: ${parsed.error}`
299
- }
300
- return `Action button(s) shown: ${buttons.map((button) => button.label).join(', ')}`
301
- }
302
- }
303
-
304
- return 'Action button request timed out'
305
- },
306
- }),
307
- },
308
-
309
- // Inject synthetic parts for branch changes and idle-time gaps.
310
- // Synthetic parts are hidden from the TUI but sent to the model,
311
- // keeping it aware of context changes without cluttering the UI.
312
- 'chat.message': async (input, output) => {
313
- const hookResult = await errore.tryAsync({
314
- try: async () => {
315
- const now = Date.now()
316
- const first = output.parts.find((part) => {
317
- if (part.type !== 'text') {
318
- return true
319
- }
320
- return part.synthetic !== true
321
- })
322
- if (!first || first.type !== 'text' || first.text.trim().length === 0) {
323
- return
324
- }
325
-
326
- const { sessionID } = input
327
- const messageID = first.messageID
328
-
329
- // -- Branch / detached HEAD detection --
330
- // Resolved early but injected last so it appears at the end of parts.
331
- const gitState = await resolveGitState({ directory })
332
-
333
- // -- MEMORY.md injection --
334
- // On the first user message in a session, read MEMORY.md from the
335
- // project root and inject a condensed table of contents (headings
336
- // with line numbers, bodies collapsed to ...). The agent can use
337
- // Read with offset/limit to drill into specific sections.
338
- if (!sessionMemoryInjected.has(sessionID)) {
339
- sessionMemoryInjected.add(sessionID)
340
- const memoryPath = path.join(directory, 'MEMORY.md')
341
- const memoryContent = await fs.promises
342
- .readFile(memoryPath, 'utf-8')
343
- .catch(() => null)
344
- if (memoryContent) {
345
- const condensed = condenseMemoryMd(memoryContent)
346
- output.parts.push({
347
- id: `prt_${crypto.randomUUID()}`,
348
- sessionID,
349
- messageID,
350
- type: 'text' as const,
351
- text: `<system-reminder>Project memory from MEMORY.md (condensed table of contents, line numbers shown):\n${condensed}\nOnly headings are shown above — section bodies are hidden. Use Grep to search MEMORY.md for specific topics, or Read with offset and limit to read a section's content. When writing to MEMORY.md, make headings detailed and descriptive since they are the only thing visible in this prompt. You can update MEMORY.md to store learnings, tips, insights that will help prevent same mistakes, and context worth preserving across sessions.</system-reminder>`,
352
- synthetic: true,
353
- })
354
- }
355
- }
356
-
357
- // -- Time since last message --
358
- // If more than 10 minutes passed since the last user message in this session,
359
- // inject current time context so the model is aware of the gap.
360
- const lastTime = sessionLastMessageTime.get(sessionID)
361
- sessionLastMessageTime.set(sessionID, now)
362
-
363
- if (lastTime) {
364
- const elapsed = now - lastTime
365
- const TEN_MINUTES = 10 * 60 * 1000
366
- if (elapsed >= TEN_MINUTES) {
367
- const totalMinutes = Math.floor(elapsed / 60_000)
368
- const hours = Math.floor(totalMinutes / 60)
369
- const minutes = totalMinutes % 60
370
- const elapsedStr =
371
- hours > 0 ? `${hours}h ${minutes}m` : `${totalMinutes}m`
372
-
373
- const utcStr = new Date(now)
374
- .toISOString()
375
- .replace('T', ' ')
376
- .replace(/\.\d+Z$/, ' UTC')
377
- const localTz = Intl.DateTimeFormat().resolvedOptions().timeZone
378
- const localStr = new Date(now).toLocaleString('en-US', {
379
- timeZone: localTz,
380
- year: 'numeric',
381
- month: '2-digit',
382
- day: '2-digit',
383
- hour: '2-digit',
384
- minute: '2-digit',
385
- hour12: false,
386
- })
387
-
388
- output.parts.push({
389
- id: `prt_${crypto.randomUUID()}`,
390
- sessionID,
391
- messageID,
392
- type: 'text' as const,
393
- text: `[${elapsedStr} since last message | UTC: ${utcStr} | Local (${localTz}): ${localStr}]`,
394
- synthetic: true,
395
- })
396
-
397
- // -- Memory save reminder on idle gap --
398
- // When the user comes back after a long break, remind the model
399
- // to save any important context from the previous conversation.
400
- output.parts.push({
401
- id: `prt_${crypto.randomUUID()}`,
402
- sessionID,
403
- messageID,
404
- type: 'text' as const,
405
- text: '<system-reminder>Long gap since last message. If the previous conversation had important learnings, tips, insights that will help prevent same mistakes, or context worth preserving, update MEMORY.md before starting the new task.</system-reminder>',
406
- synthetic: true,
407
- })
408
- }
409
- }
410
-
411
- // -- Branch injection (last synthetic part) --
412
- // Placed last so branch context appears at the end of all injected parts.
413
- if (gitState) {
414
- const previousState = sessionGitStates.get(sessionID)
415
- if (!previousState || previousState.key !== gitState.key) {
416
- const info = (() => {
417
- if (gitState.warning) {
418
- return gitState.warning
419
- }
420
- if (previousState?.kind === 'branch') {
421
- return `\n[current git branch is ${gitState.label}]`
422
- }
423
- return `\n[current git branch is ${gitState.label}]`
424
- })()
425
-
426
- sessionGitStates.set(sessionID, gitState)
427
- output.parts.push({
428
- id: `prt_${crypto.randomUUID()}`,
429
- sessionID,
430
- messageID,
431
- type: 'text' as const,
432
- text: info,
433
- synthetic: true,
434
- })
435
- }
436
- }
437
- },
438
- catch: (error) => {
439
- return new Error('chat.message hook failed', { cause: error })
440
- },
441
- })
442
- if (hookResult instanceof Error) {
443
- logger.warn(
444
- `[opencode-plugin chat.message] ${formatErrorWithStack(hookResult)}`,
445
- )
446
- void notifyError(hookResult, 'opencode-plugin chat.message hook failed')
447
- }
448
- },
449
-
450
- // Clean up per-session tracking state when sessions are deleted
451
- event: async ({ event }) => {
452
- const cleanupResult = await errore.tryAsync({
453
- try: async () => {
454
- if (event.type !== 'session.deleted') {
455
- return
456
- }
457
-
458
- const id = event.properties?.info?.id
459
- if (!id) {
460
- return
461
- }
462
-
463
- sessionGitStates.delete(id)
464
- sessionLastMessageTime.delete(id)
465
- sessionMemoryInjected.delete(id)
466
- },
467
- catch: (error) => {
468
- return new Error('event hook failed', { cause: error })
469
- },
470
- })
471
- if (cleanupResult instanceof Error) {
472
- logger.warn(
473
- `[opencode-plugin event] ${formatErrorWithStack(cleanupResult)}`,
474
- )
475
- void notifyError(cleanupResult, 'opencode-plugin event hook failed')
476
- }
477
- },
478
- }
479
- }
480
-
481
- export { kimakiPlugin }
1
+ // OpenCode plugin entry point for Kimaki Discord bot.
2
+ // Each export is treated as a separate plugin by OpenCode's plugin loader.
3
+ // CRITICAL: never export utility functions from this file — only plugin
4
+ // initializer functions. OpenCode calls every export as a plugin.
5
+ //
6
+ // Plugins are split into focused modules:
7
+ // - ipc-tools-plugin: file upload + action buttons (IPC-based Discord tools)
8
+ // - context-awareness-plugin: branch, pwd, memory, time gap, onboarding tutorial
9
+ // - opencode-interrupt-plugin: interrupt queued messages at step boundaries
10
+
11
+ export { ipcToolsPlugin } from './ipc-tools-plugin.js'
12
+ export { contextAwarenessPlugin } from './context-awareness-plugin.js'
482
13
  export { interruptOpencodeSessionOnUserMessage } from './opencode-interrupt-plugin.js'
483
- export { onboardingTutorialPlugin } from './onboarding-tutorial-plugin.js'
484
-
14
+ export { anthropicAuthPlugin } from './anthropic-auth-plugin.js'
package/src/opencode.ts CHANGED
@@ -132,7 +132,8 @@ function buildStartupTimeoutReason({
132
132
  maxAttempts: number
133
133
  stderrTail: string[]
134
134
  }): string {
135
- const baseReason = `Server did not start after ${maxAttempts} seconds`
135
+ const timeoutSeconds = Math.round((maxAttempts * 100) / 1000)
136
+ const baseReason = `Server did not start after ${timeoutSeconds} seconds`
136
137
  if (stderrTail.length === 0) {
137
138
  return baseReason
138
139
  }
@@ -387,7 +388,7 @@ async function getOpenPort(): Promise<number> {
387
388
 
388
389
  async function waitForServer({
389
390
  port,
390
- maxAttempts = 30,
391
+ maxAttempts = 300,
391
392
  startupStderrTail,
392
393
  }: {
393
394
  port: number
@@ -401,8 +402,10 @@ async function waitForServer({
401
402
  catch: (e) => new FetchError({ url: endpoint, cause: e }),
402
403
  })
403
404
  if (response instanceof Error) {
404
- // Connection refused or other transient errors - continue polling
405
- await new Promise((resolve) => setTimeout(resolve, 1000))
405
+ // Connection refused or other transient errors - continue polling.
406
+ // Use 100ms interval instead of 1s so we detect readiness faster.
407
+ // Critical for scale-to-zero cold starts where every ms matters.
408
+ await new Promise((resolve) => setTimeout(resolve, 100))
406
409
  continue
407
410
  }
408
411
  if (response.status < 500) {
@@ -413,7 +416,7 @@ async function waitForServer({
413
416
  if (body.includes('BunInstallFailedError')) {
414
417
  return new ServerStartError({ port, reason: body.slice(0, 200) })
415
418
  }
416
- await new Promise((resolve) => setTimeout(resolve, 1000))
419
+ await new Promise((resolve) => setTimeout(resolve, 100))
417
420
  }
418
421
  return new ServerStartError({
419
422
  port,
@@ -510,6 +513,7 @@ async function startSingleServer(): Promise<ServerStartError | SingleServer> {
510
513
  if (kimakiShimDirectory instanceof Error) {
511
514
  opencodeLogger.warn(kimakiShimDirectory.message)
512
515
  }
516
+ const gatewayToken = store.getState().gatewayToken
513
517
 
514
518
  const serverProcess = spawn(
515
519
  spawnCommand,
@@ -559,8 +563,10 @@ async function startSingleServer(): Promise<ServerStartError | SingleServer> {
559
563
  },
560
564
  } satisfies Config),
561
565
  OPENCODE_PORT: port.toString(),
566
+ KIMAKI: '1',
562
567
  KIMAKI_DATA_DIR: getDataDir(),
563
568
  KIMAKI_LOCK_PORT: getLockPort().toString(),
569
+ ...(gatewayToken && { KIMAKI_DB_AUTH_TOKEN: gatewayToken }),
564
570
  // Guard: prevents agents from running `kimaki` root command inside
565
571
  // an OpenCode session, which would steal the lock port and break the bot.
566
572
  KIMAKI_OPENCODE_PROCESS: '1',
@@ -875,6 +881,55 @@ export function buildSessionPermissions({
875
881
  return rules
876
882
  }
877
883
 
884
+ /**
885
+ * Parse raw permission strings into PermissionRuleset entries.
886
+ *
887
+ * Accepted formats:
888
+ * "tool:action" → { permission: tool, pattern: "*", action }
889
+ * "tool:pattern:action" → { permission: tool, pattern, action }
890
+ *
891
+ * The action must be one of "allow", "deny", "ask" (case-insensitive).
892
+ * Parts are trimmed to tolerate whitespace from YAML deserialization.
893
+ * Invalid entries are silently skipped (bad user input shouldn't crash the bot).
894
+ * If `raw` is not an array, returns empty (defensive against malformed YAML markers).
895
+ */
896
+ export function parsePermissionRules(raw: unknown): PermissionRuleset {
897
+ if (!Array.isArray(raw)) {
898
+ return []
899
+ }
900
+ const validActions = new Set(['allow', 'deny', 'ask'])
901
+ return raw.flatMap((entry) => {
902
+ if (typeof entry !== 'string') {
903
+ return []
904
+ }
905
+ const parts = entry.split(':').map((s) => {
906
+ return s.trim()
907
+ })
908
+ if (parts.length === 2) {
909
+ const [permission, rawAction] = parts
910
+ const action = rawAction!.toLowerCase()
911
+ if (!permission || !validActions.has(action)) {
912
+ return []
913
+ }
914
+ return [{ permission, pattern: '*', action: action as 'allow' | 'deny' | 'ask' }]
915
+ }
916
+ if (parts.length >= 3) {
917
+ // Last segment is the action, first segment is the permission,
918
+ // everything in between is the pattern (may contain colons in theory,
919
+ // but unlikely for tool patterns).
920
+ const permission = parts[0]!
921
+ const rawAction = parts[parts.length - 1]!
922
+ const action = rawAction.toLowerCase()
923
+ const pattern = parts.slice(1, -1).join(':')
924
+ if (!permission || !pattern || !validActions.has(action)) {
925
+ return []
926
+ }
927
+ return [{ permission, pattern, action: action as 'allow' | 'deny' | 'ask' }]
928
+ }
929
+ return []
930
+ })
931
+ }
932
+
878
933
  // ── Public helpers ───────────────────────────────────────────────
879
934
  // These helpers expose the single shared server and directory-scoped clients.
880
935