kimaki 0.4.44 → 0.4.46

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 (45) hide show
  1. package/dist/channel-management.js +6 -15
  2. package/dist/cli.js +54 -37
  3. package/dist/commands/create-new-project.js +2 -0
  4. package/dist/commands/fork.js +2 -0
  5. package/dist/commands/permissions.js +21 -5
  6. package/dist/commands/queue.js +5 -1
  7. package/dist/commands/resume.js +10 -16
  8. package/dist/commands/session.js +20 -42
  9. package/dist/commands/user-command.js +10 -17
  10. package/dist/commands/verbosity.js +53 -0
  11. package/dist/commands/worktree-settings.js +2 -2
  12. package/dist/commands/worktree.js +134 -25
  13. package/dist/database.js +49 -0
  14. package/dist/discord-bot.js +26 -38
  15. package/dist/discord-utils.js +51 -13
  16. package/dist/discord-utils.test.js +20 -0
  17. package/dist/escape-backticks.test.js +14 -3
  18. package/dist/interaction-handler.js +4 -0
  19. package/dist/session-handler.js +581 -414
  20. package/package.json +1 -1
  21. package/src/__snapshots__/first-session-no-info.md +1344 -0
  22. package/src/__snapshots__/first-session-with-info.md +1350 -0
  23. package/src/__snapshots__/session-1.md +1344 -0
  24. package/src/__snapshots__/session-2.md +291 -0
  25. package/src/__snapshots__/session-3.md +20324 -0
  26. package/src/__snapshots__/session-with-tools.md +1344 -0
  27. package/src/channel-management.ts +6 -17
  28. package/src/cli.ts +63 -45
  29. package/src/commands/create-new-project.ts +3 -0
  30. package/src/commands/fork.ts +3 -0
  31. package/src/commands/permissions.ts +31 -5
  32. package/src/commands/queue.ts +5 -1
  33. package/src/commands/resume.ts +11 -18
  34. package/src/commands/session.ts +21 -44
  35. package/src/commands/user-command.ts +11 -19
  36. package/src/commands/verbosity.ts +71 -0
  37. package/src/commands/worktree-settings.ts +2 -2
  38. package/src/commands/worktree.ts +163 -27
  39. package/src/database.ts +65 -0
  40. package/src/discord-bot.ts +29 -42
  41. package/src/discord-utils.test.ts +23 -0
  42. package/src/discord-utils.ts +52 -13
  43. package/src/escape-backticks.test.ts +14 -3
  44. package/src/interaction-handler.ts +5 -0
  45. package/src/session-handler.ts +711 -436
@@ -2,7 +2,7 @@
2
2
  // Creates, maintains, and sends prompts to OpenCode sessions from Discord threads.
3
3
  // Handles streaming events, permissions, abort signals, and message queuing.
4
4
  import prettyMilliseconds from 'pretty-ms';
5
- import { getDatabase, getSessionModel, getChannelModel, getSessionAgent, getChannelAgent, setSessionAgent, getThreadWorktree, } from './database.js';
5
+ import { getDatabase, getSessionModel, getChannelModel, getSessionAgent, getChannelAgent, setSessionAgent, getThreadWorktree, getChannelVerbosity, } from './database.js';
6
6
  import { initializeOpencodeForDirectory, getOpencodeServers, getOpencodeClientV2, } from './opencode.js';
7
7
  import { sendThreadMessage, NOTIFY_MESSAGE_FLAGS, SILENT_MESSAGE_FLAGS } from './discord-utils.js';
8
8
  import { formatPart } from './message-formatting.js';
@@ -10,7 +10,7 @@ import { getOpencodeSystemMessage } from './system-message.js';
10
10
  import { createLogger } from './logger.js';
11
11
  import { isAbortError } from './utils.js';
12
12
  import { showAskUserQuestionDropdowns, cancelPendingQuestion, pendingQuestionContexts, } from './commands/ask-question.js';
13
- import { showPermissionDropdown, cleanupPermissionContext } from './commands/permissions.js';
13
+ import { showPermissionDropdown, cleanupPermissionContext, addPermissionRequestToContext, } from './commands/permissions.js';
14
14
  import * as errore from 'errore';
15
15
  const sessionLogger = createLogger('SESSION');
16
16
  const voiceLogger = createLogger('VOICE');
@@ -20,9 +20,16 @@ export const abortControllers = new Map();
20
20
  // OpenCode handles blocking/sequencing - we just need to track all pending permissions
21
21
  // to avoid duplicates and properly clean up on auto-reject
22
22
  export const pendingPermissions = new Map();
23
+ function buildPermissionDedupeKey({ permission, directory, }) {
24
+ const normalizedPatterns = [...permission.patterns].sort((a, b) => {
25
+ return a.localeCompare(b);
26
+ });
27
+ return `${directory}::${permission.permission}::${normalizedPatterns.join('|')}`;
28
+ }
23
29
  // Queue of messages waiting to be sent after current response finishes
24
30
  // Key is threadId, value is array of queued messages
25
31
  export const messageQueue = new Map();
32
+ const activeEventHandlers = new Map();
26
33
  export function addToQueue({ threadId, message, }) {
27
34
  const queue = messageQueue.get(threadId) || [];
28
35
  queue.push(message);
@@ -56,11 +63,11 @@ export async function abortAndRetrySession({ sessionId, thread, projectDirectory
56
63
  sessionLogger.error(`[ABORT+RETRY] Failed to initialize OpenCode client:`, getClient.message);
57
64
  return false;
58
65
  }
59
- try {
60
- await getClient().session.abort({ path: { id: sessionId } });
61
- }
62
- catch (e) {
63
- sessionLogger.log(`[ABORT+RETRY] API abort call failed (may already be done):`, e);
66
+ const abortResult = await errore.tryAsync(() => {
67
+ return getClient().session.abort({ path: { id: sessionId } });
68
+ });
69
+ if (abortResult instanceof Error) {
70
+ sessionLogger.log(`[ABORT+RETRY] API abort call failed (may already be done):`, abortResult);
64
71
  }
65
72
  // Small delay to let the abort propagate
66
73
  await new Promise((resolve) => {
@@ -82,15 +89,21 @@ export async function abortAndRetrySession({ sessionId, thread, projectDirectory
82
89
  sessionLogger.log(`[ABORT+RETRY] Re-triggering session ${sessionId} with new model`);
83
90
  // Use setImmediate to avoid blocking
84
91
  setImmediate(() => {
85
- handleOpencodeSession({
86
- prompt,
87
- thread,
88
- projectDirectory,
89
- images,
90
- }).catch(async (e) => {
91
- sessionLogger.error(`[ABORT+RETRY] Failed to retry:`, e);
92
- const errorMsg = e instanceof Error ? e.message : String(e);
93
- await sendThreadMessage(thread, `✗ Failed to retry with new model: ${errorMsg.slice(0, 200)}`);
92
+ void errore
93
+ .tryAsync(async () => {
94
+ return handleOpencodeSession({
95
+ prompt,
96
+ thread,
97
+ projectDirectory,
98
+ images,
99
+ });
100
+ })
101
+ .then(async (result) => {
102
+ if (!(result instanceof Error)) {
103
+ return;
104
+ }
105
+ sessionLogger.error(`[ABORT+RETRY] Failed to retry:`, result);
106
+ await sendThreadMessage(thread, `✗ Failed to retry with new model: ${result.message.slice(0, 200)}`);
94
107
  });
95
108
  });
96
109
  return true;
@@ -100,6 +113,16 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
100
113
  const sessionStartTime = Date.now();
101
114
  const directory = projectDirectory || process.cwd();
102
115
  sessionLogger.log(`Using directory: ${directory}`);
116
+ // Get worktree info early so we can use the correct directory for events and prompts
117
+ const worktreeInfo = getThreadWorktree(thread.id);
118
+ const worktreeDirectory = worktreeInfo?.status === 'ready' && worktreeInfo.worktree_directory
119
+ ? worktreeInfo.worktree_directory
120
+ : undefined;
121
+ // Use worktree directory for SDK calls if available, otherwise project directory
122
+ const sdkDirectory = worktreeDirectory || directory;
123
+ if (worktreeDirectory) {
124
+ sessionLogger.log(`Using worktree directory for SDK calls: ${worktreeDirectory}`);
125
+ }
103
126
  const getClient = await initializeOpencodeForDirectory(directory);
104
127
  if (getClient instanceof Error) {
105
128
  await sendThreadMessage(thread, `✗ ${getClient.message}`);
@@ -114,22 +137,26 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
114
137
  let session;
115
138
  if (sessionId) {
116
139
  sessionLogger.log(`Attempting to reuse existing session ${sessionId}`);
117
- try {
118
- const sessionResponse = await getClient().session.get({
140
+ const sessionResponse = await errore.tryAsync(() => {
141
+ return getClient().session.get({
119
142
  path: { id: sessionId },
143
+ query: { directory: sdkDirectory },
120
144
  });
145
+ });
146
+ if (sessionResponse instanceof Error) {
147
+ voiceLogger.log(`[SESSION] Session ${sessionId} not found, will create new one`);
148
+ }
149
+ else {
121
150
  session = sessionResponse.data;
122
151
  sessionLogger.log(`Successfully reused session ${sessionId}`);
123
152
  }
124
- catch (error) {
125
- voiceLogger.log(`[SESSION] Session ${sessionId} not found, will create new one`);
126
- }
127
153
  }
128
154
  if (!session) {
129
155
  const sessionTitle = prompt.length > 80 ? prompt.slice(0, 77) + '...' : prompt.slice(0, 80);
130
156
  voiceLogger.log(`[SESSION] Creating new session with title: "${sessionTitle}"`);
131
157
  const sessionResponse = await getClient().session.create({
132
158
  body: { title: sessionTitle },
159
+ query: { directory: sdkDirectory },
133
160
  });
134
161
  session = sessionResponse.data;
135
162
  sessionLogger.log(`Created new session ${session?.id}`);
@@ -150,6 +177,15 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
150
177
  if (existingController) {
151
178
  voiceLogger.log(`[ABORT] Cancelling existing request for session: ${session.id}`);
152
179
  existingController.abort(new Error('New request started'));
180
+ const abortResult = await errore.tryAsync(() => {
181
+ return getClient().session.abort({
182
+ path: { id: session.id },
183
+ query: { directory: sdkDirectory },
184
+ });
185
+ });
186
+ if (abortResult instanceof Error) {
187
+ sessionLogger.log(`[ABORT] Server abort failed (may be already done):`, abortResult);
188
+ }
153
189
  }
154
190
  // Auto-reject ALL pending permissions for this thread
155
191
  const threadPermissions = pendingPermissions.get(thread.id);
@@ -157,21 +193,26 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
157
193
  const clientV2 = getOpencodeClientV2(directory);
158
194
  let rejectedCount = 0;
159
195
  for (const [permId, pendingPerm] of threadPermissions) {
160
- try {
161
- sessionLogger.log(`[PERMISSION] Auto-rejecting permission ${permId} due to new message`);
162
- if (clientV2) {
163
- await clientV2.permission.reply({
164
- requestID: permId,
165
- reply: 'reject',
166
- });
167
- }
196
+ sessionLogger.log(`[PERMISSION] Auto-rejecting permission ${permId} due to new message`);
197
+ if (!clientV2) {
198
+ sessionLogger.log(`[PERMISSION] OpenCode v2 client unavailable for permission ${permId}`);
168
199
  cleanupPermissionContext(pendingPerm.contextHash);
169
200
  rejectedCount++;
201
+ continue;
170
202
  }
171
- catch (e) {
172
- sessionLogger.log(`[PERMISSION] Failed to auto-reject permission ${permId}:`, e);
173
- cleanupPermissionContext(pendingPerm.contextHash);
203
+ const rejectResult = await errore.tryAsync(() => {
204
+ return clientV2.permission.reply({
205
+ requestID: permId,
206
+ reply: 'reject',
207
+ });
208
+ });
209
+ if (rejectResult instanceof Error) {
210
+ sessionLogger.log(`[PERMISSION] Failed to auto-reject permission ${permId}:`, rejectResult);
174
211
  }
212
+ else {
213
+ rejectedCount++;
214
+ }
215
+ cleanupPermissionContext(pendingPerm.contextHash);
175
216
  }
176
217
  pendingPermissions.delete(thread.id);
177
218
  if (rejectedCount > 0) {
@@ -199,12 +240,22 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
199
240
  sessionLogger.log(`[DEBOUNCE] Aborted before subscribe, exiting`);
200
241
  return;
201
242
  }
243
+ const previousHandler = activeEventHandlers.get(thread.id);
244
+ if (previousHandler) {
245
+ sessionLogger.log(`[EVENT] Waiting for previous handler to finish`);
246
+ await Promise.race([
247
+ previousHandler,
248
+ new Promise((resolve) => {
249
+ setTimeout(resolve, 1000);
250
+ }),
251
+ ]);
252
+ }
202
253
  // Use v2 client for event subscription (has proper types for question.asked events)
203
254
  const clientV2 = getOpencodeClientV2(directory);
204
255
  if (!clientV2) {
205
256
  throw new Error(`OpenCode v2 client not found for directory: ${directory}`);
206
257
  }
207
- const eventsResult = await clientV2.event.subscribe({ directory }, { signal: abortController.signal });
258
+ const eventsResult = await clientV2.event.subscribe({ directory: sdkDirectory }, { signal: abortController.signal });
208
259
  if (abortController.signal.aborted) {
209
260
  sessionLogger.log(`[DEBOUNCE] Aborted during subscribe, exiting`);
210
261
  return;
@@ -214,7 +265,7 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
214
265
  const sentPartIds = new Set(getDatabase()
215
266
  .prepare('SELECT part_id FROM part_messages WHERE thread_id = ?')
216
267
  .all(thread.id).map((row) => row.part_id));
217
- let currentParts = [];
268
+ const partBuffer = new Map();
218
269
  let stopTyping = null;
219
270
  let usedModel;
220
271
  let usedProviderID;
@@ -222,6 +273,8 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
222
273
  let tokensUsedInSession = 0;
223
274
  let lastDisplayedContextPercentage = 0;
224
275
  let modelContextLimit;
276
+ let assistantMessageId;
277
+ let handlerPromise = null;
225
278
  let typingInterval = null;
226
279
  function startTyping() {
227
280
  if (abortController.signal.aborted) {
@@ -232,12 +285,16 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
232
285
  clearInterval(typingInterval);
233
286
  typingInterval = null;
234
287
  }
235
- thread.sendTyping().catch((e) => {
236
- discordLogger.log(`Failed to send initial typing: ${e}`);
288
+ void errore.tryAsync(() => thread.sendTyping()).then((result) => {
289
+ if (result instanceof Error) {
290
+ discordLogger.log(`Failed to send initial typing: ${result}`);
291
+ }
237
292
  });
238
293
  typingInterval = setInterval(() => {
239
- thread.sendTyping().catch((e) => {
240
- discordLogger.log(`Failed to send periodic typing: ${e}`);
294
+ void errore.tryAsync(() => thread.sendTyping()).then((result) => {
295
+ if (result instanceof Error) {
296
+ discordLogger.log(`Failed to send periodic typing: ${result}`);
297
+ }
241
298
  });
242
299
  }, 8000);
243
300
  if (!abortController.signal.aborted) {
@@ -255,7 +312,14 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
255
312
  }
256
313
  };
257
314
  }
315
+ // Get verbosity setting for this channel (use parent channel for threads)
316
+ const verbosityChannelId = channelId || thread.parentId || thread.id;
317
+ const verbosity = getChannelVerbosity(verbosityChannelId);
258
318
  const sendPartMessage = async (part) => {
319
+ // In text-only mode, only send text parts (the ⬥ diamond messages)
320
+ if (verbosity === 'text-only' && part.type !== 'text') {
321
+ return;
322
+ }
259
323
  const content = formatPart(part) + '\n\n';
260
324
  if (!content.trim() || content.length === 0) {
261
325
  // discordLogger.log(`SKIP: Part ${part.id} has no content`)
@@ -264,351 +328,443 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
264
328
  if (sentPartIds.has(part.id)) {
265
329
  return;
266
330
  }
267
- try {
268
- const firstMessage = await sendThreadMessage(thread, content);
269
- sentPartIds.add(part.id);
270
- getDatabase()
271
- .prepare('INSERT OR REPLACE INTO part_messages (part_id, message_id, thread_id) VALUES (?, ?, ?)')
272
- .run(part.id, firstMessage.id, thread.id);
273
- }
274
- catch (error) {
275
- discordLogger.error(`ERROR: Failed to send part ${part.id}:`, error);
331
+ const sendResult = await errore.tryAsync(() => {
332
+ return sendThreadMessage(thread, content);
333
+ });
334
+ if (sendResult instanceof Error) {
335
+ discordLogger.error(`ERROR: Failed to send part ${part.id}:`, sendResult);
336
+ return;
276
337
  }
338
+ sentPartIds.add(part.id);
339
+ getDatabase()
340
+ .prepare('INSERT OR REPLACE INTO part_messages (part_id, message_id, thread_id) VALUES (?, ?, ?)')
341
+ .run(part.id, sendResult.id, thread.id);
277
342
  };
278
343
  const eventHandler = async () => {
279
344
  // Subtask tracking: child sessionId → { label, assistantMessageId }
280
345
  const subtaskSessions = new Map();
281
346
  // Counts spawned tasks per agent type: "explore" → 2
282
347
  const agentSpawnCounts = {};
283
- try {
284
- let assistantMessageId;
285
- for await (const event of events) {
286
- if (event.type === 'message.updated') {
287
- const msg = event.properties.info;
288
- // Track assistant message IDs for subtask sessions
289
- const subtaskInfo = subtaskSessions.get(msg.sessionID);
290
- if (subtaskInfo && msg.role === 'assistant') {
291
- subtaskInfo.assistantMessageId = msg.id;
292
- }
293
- if (msg.sessionID !== session.id) {
294
- continue;
295
- }
296
- if (msg.role === 'assistant') {
297
- const newTokensTotal = msg.tokens.input +
298
- msg.tokens.output +
299
- msg.tokens.reasoning +
300
- msg.tokens.cache.read +
301
- msg.tokens.cache.write;
302
- if (newTokensTotal > 0) {
303
- tokensUsedInSession = newTokensTotal;
304
- }
305
- assistantMessageId = msg.id;
306
- usedModel = msg.modelID;
307
- usedProviderID = msg.providerID;
308
- usedAgent = msg.mode;
309
- if (tokensUsedInSession > 0 && usedProviderID && usedModel) {
310
- if (!modelContextLimit) {
311
- try {
312
- const providersResponse = await getClient().provider.list({
313
- query: { directory },
314
- });
315
- const provider = providersResponse.data?.all?.find((p) => p.id === usedProviderID);
316
- const model = provider?.models?.[usedModel];
317
- if (model?.limit?.context) {
318
- modelContextLimit = model.limit.context;
319
- }
320
- }
321
- catch (e) {
322
- sessionLogger.error('Failed to fetch provider info for context limit:', e);
323
- }
324
- }
325
- if (modelContextLimit) {
326
- const currentPercentage = Math.floor((tokensUsedInSession / modelContextLimit) * 100);
327
- const thresholdCrossed = Math.floor(currentPercentage / 10) * 10;
328
- if (thresholdCrossed > lastDisplayedContextPercentage && thresholdCrossed >= 10) {
329
- lastDisplayedContextPercentage = thresholdCrossed;
330
- const chunk = `⬦ context usage ${currentPercentage}%`;
331
- await thread.send({ content: chunk, flags: SILENT_MESSAGE_FLAGS });
332
- }
333
- }
334
- }
335
- }
348
+ const storePart = (part) => {
349
+ const messageParts = partBuffer.get(part.messageID) || new Map();
350
+ messageParts.set(part.id, part);
351
+ partBuffer.set(part.messageID, messageParts);
352
+ };
353
+ const getBufferedParts = (messageID) => {
354
+ return Array.from(partBuffer.get(messageID)?.values() ?? []);
355
+ };
356
+ const shouldSendPart = ({ part, force }) => {
357
+ if (part.type === 'step-start' || part.type === 'step-finish') {
358
+ return false;
359
+ }
360
+ if (part.type === 'tool' && part.state.status === 'pending') {
361
+ return false;
362
+ }
363
+ if (!force && part.type === 'text' && !part.time?.end) {
364
+ return false;
365
+ }
366
+ if (!force && part.type === 'tool' && part.state.status === 'completed') {
367
+ return false;
368
+ }
369
+ return true;
370
+ };
371
+ const flushBufferedParts = async ({ messageID, force, skipPartId, }) => {
372
+ if (!messageID) {
373
+ return;
374
+ }
375
+ const parts = getBufferedParts(messageID);
376
+ for (const part of parts) {
377
+ if (skipPartId && part.id === skipPartId) {
378
+ continue;
336
379
  }
337
- else if (event.type === 'message.part.updated') {
338
- const part = event.properties.part;
339
- // Check if this is a subtask event (child session we're tracking)
340
- const subtaskInfo = subtaskSessions.get(part.sessionID);
341
- const isSubtaskEvent = Boolean(subtaskInfo);
342
- // Accept events from main session OR tracked subtask sessions
343
- if (part.sessionID !== session.id && !isSubtaskEvent) {
344
- continue;
345
- }
346
- // For subtask events, send them immediately with prefix (don't buffer in currentParts)
347
- if (isSubtaskEvent && subtaskInfo) {
348
- // Skip parts that aren't useful to show (step-start, step-finish, pending tools)
349
- if (part.type === 'step-start' || part.type === 'step-finish') {
350
- continue;
351
- }
352
- if (part.type === 'tool' && part.state.status === 'pending') {
353
- continue;
354
- }
355
- // Skip text parts - the outer agent will report the task result anyway
356
- if (part.type === 'text') {
357
- continue;
358
- }
359
- // Only show parts from assistant messages (not user prompts sent to subtask)
360
- // Skip if we haven't seen an assistant message yet, or if this part is from a different message
361
- if (!subtaskInfo.assistantMessageId ||
362
- part.messageID !== subtaskInfo.assistantMessageId) {
363
- continue;
364
- }
365
- const content = formatPart(part, subtaskInfo.label);
366
- if (content.trim() && !sentPartIds.has(part.id)) {
367
- try {
368
- const msg = await sendThreadMessage(thread, content + '\n\n');
369
- sentPartIds.add(part.id);
370
- getDatabase()
371
- .prepare('INSERT OR REPLACE INTO part_messages (part_id, message_id, thread_id) VALUES (?, ?, ?)')
372
- .run(part.id, msg.id, thread.id);
373
- }
374
- catch (error) {
375
- discordLogger.error(`ERROR: Failed to send subtask part ${part.id}:`, error);
376
- }
377
- }
378
- continue;
379
- }
380
- // Main session events: require matching assistantMessageId
381
- if (part.messageID !== assistantMessageId) {
382
- continue;
383
- }
384
- const existingIndex = currentParts.findIndex((p) => p.id === part.id);
385
- if (existingIndex >= 0) {
386
- currentParts[existingIndex] = part;
387
- }
388
- else {
389
- currentParts.push(part);
390
- }
391
- if (part.type === 'step-start') {
392
- // Don't start typing if user needs to respond to a question or permission
393
- const hasPendingQuestion = [...pendingQuestionContexts.values()].some((ctx) => ctx.thread.id === thread.id);
394
- const hasPendingPermission = (pendingPermissions.get(thread.id)?.size ?? 0) > 0;
395
- if (!hasPendingQuestion && !hasPendingPermission) {
396
- stopTyping = startTyping();
397
- }
398
- }
399
- if (part.type === 'tool' && part.state.status === 'running') {
400
- // Flush any pending text/reasoning parts before showing the tool
401
- // This ensures text the LLM generated before the tool call is shown first
402
- for (const p of currentParts) {
403
- if (p.type !== 'step-start' && p.type !== 'step-finish' && p.id !== part.id) {
404
- await sendPartMessage(p);
405
- }
406
- }
407
- await sendPartMessage(part);
408
- // Track task tool and register child session when sessionId is available
409
- if (part.tool === 'task' && !sentPartIds.has(part.id)) {
410
- const description = part.state.input?.description || '';
411
- const agent = part.state.input?.subagent_type || 'task';
412
- const childSessionId = part.state.metadata?.sessionId || '';
413
- if (description && childSessionId) {
414
- agentSpawnCounts[agent] = (agentSpawnCounts[agent] || 0) + 1;
415
- const label = `${agent}-${agentSpawnCounts[agent]}`;
416
- subtaskSessions.set(childSessionId, { label, assistantMessageId: undefined });
417
- const taskDisplay = `┣ task **${label}** _${description}_`;
418
- await sendThreadMessage(thread, taskDisplay + '\n\n');
419
- sentPartIds.add(part.id);
420
- }
421
- }
422
- }
423
- // Show token usage for completed tools with large output (>5k tokens)
424
- if (part.type === 'tool' && part.state.status === 'completed') {
425
- const output = part.state.output || '';
426
- const outputTokens = Math.ceil(output.length / 4);
427
- const LARGE_OUTPUT_THRESHOLD = 3000;
428
- if (outputTokens >= LARGE_OUTPUT_THRESHOLD) {
429
- const formattedTokens = outputTokens >= 1000 ? `${(outputTokens / 1000).toFixed(1)}k` : String(outputTokens);
430
- const percentageSuffix = (() => {
431
- if (!modelContextLimit) {
432
- return '';
433
- }
434
- const pct = (outputTokens / modelContextLimit) * 100;
435
- if (pct < 1) {
436
- return '';
437
- }
438
- return ` (${pct.toFixed(1)}%)`;
439
- })();
440
- const chunk = `⬦ ${part.tool} returned ${formattedTokens} tokens${percentageSuffix}`;
441
- await thread.send({ content: chunk, flags: SILENT_MESSAGE_FLAGS });
442
- }
443
- }
444
- if (part.type === 'reasoning') {
445
- await sendPartMessage(part);
446
- }
447
- // Send text parts when complete (time.end is set)
448
- // Text parts stream incrementally; only send when finished to avoid partial text
449
- if (part.type === 'text' && part.time?.end) {
450
- await sendPartMessage(part);
451
- }
452
- if (part.type === 'step-finish') {
453
- for (const p of currentParts) {
454
- if (p.type !== 'step-start' && p.type !== 'step-finish') {
455
- await sendPartMessage(p);
456
- }
457
- }
458
- setTimeout(() => {
459
- if (abortController.signal.aborted)
460
- return;
461
- // Don't restart typing if user needs to respond to a question or permission
462
- const hasPendingQuestion = [...pendingQuestionContexts.values()].some((ctx) => ctx.thread.id === thread.id);
463
- const hasPendingPermission = (pendingPermissions.get(thread.id)?.size ?? 0) > 0;
464
- if (hasPendingQuestion || hasPendingPermission)
465
- return;
466
- stopTyping = startTyping();
467
- }, 300);
468
- }
380
+ if (!shouldSendPart({ part, force })) {
381
+ continue;
469
382
  }
470
- else if (event.type === 'session.error') {
471
- sessionLogger.error(`ERROR:`, event.properties);
472
- if (event.properties.sessionID === session.id) {
473
- const errorData = event.properties.error;
474
- const errorMessage = errorData?.data?.message || 'Unknown error';
475
- sessionLogger.error(`Sending error to thread: ${errorMessage}`);
476
- await sendThreadMessage(thread, `✗ opencode session error: ${errorMessage}`);
477
- if (originalMessage) {
478
- try {
479
- await originalMessage.reactions.removeAll();
480
- await originalMessage.react('❌');
481
- voiceLogger.log(`[REACTION] Added error reaction due to session error`);
482
- }
483
- catch (e) {
484
- discordLogger.log(`Could not update reaction:`, e);
485
- }
486
- }
487
- }
488
- else {
489
- voiceLogger.log(`[SESSION ERROR IGNORED] Error for different session (expected: ${session.id}, got: ${event.properties.sessionID})`);
490
- }
491
- break;
383
+ await sendPartMessage(part);
384
+ }
385
+ };
386
+ const handleMessageUpdated = async (msg) => {
387
+ const subtaskInfo = subtaskSessions.get(msg.sessionID);
388
+ if (subtaskInfo && msg.role === 'assistant') {
389
+ subtaskInfo.assistantMessageId = msg.id;
390
+ }
391
+ if (msg.sessionID !== session.id) {
392
+ return;
393
+ }
394
+ if (msg.role !== 'assistant') {
395
+ return;
396
+ }
397
+ if (msg.tokens) {
398
+ const newTokensTotal = msg.tokens.input +
399
+ msg.tokens.output +
400
+ msg.tokens.reasoning +
401
+ msg.tokens.cache.read +
402
+ msg.tokens.cache.write;
403
+ if (newTokensTotal > 0) {
404
+ tokensUsedInSession = newTokensTotal;
492
405
  }
493
- else if (event.type === 'permission.asked') {
494
- const permission = event.properties;
495
- if (permission.sessionID !== session.id) {
496
- voiceLogger.log(`[PERMISSION IGNORED] Permission for different session (expected: ${session.id}, got: ${permission.sessionID})`);
497
- continue;
498
- }
499
- // Skip if this exact permission ID is already pending (dedupe)
500
- const threadPermissions = pendingPermissions.get(thread.id);
501
- if (threadPermissions?.has(permission.id)) {
502
- sessionLogger.log(`[PERMISSION] Skipping duplicate permission ${permission.id} (already pending)`);
503
- continue;
504
- }
505
- sessionLogger.log(`Permission requested: permission=${permission.permission}, patterns=${permission.patterns.join(', ')}`);
506
- // Stop typing - user needs to respond now, not the bot
507
- if (stopTyping) {
508
- stopTyping();
509
- stopTyping = null;
510
- }
511
- // Show dropdown instead of text message
512
- const { messageId, contextHash } = await showPermissionDropdown({
513
- thread,
514
- permission,
515
- directory,
516
- });
517
- // Track permission in nested map (threadId -> permissionId -> data)
518
- if (!pendingPermissions.has(thread.id)) {
519
- pendingPermissions.set(thread.id, new Map());
520
- }
521
- pendingPermissions.get(thread.id).set(permission.id, {
522
- permission,
523
- messageId,
524
- directory,
525
- contextHash,
406
+ }
407
+ assistantMessageId = msg.id;
408
+ usedModel = msg.modelID;
409
+ usedProviderID = msg.providerID;
410
+ usedAgent = msg.mode;
411
+ await flushBufferedParts({
412
+ messageID: assistantMessageId,
413
+ force: false,
414
+ });
415
+ if (tokensUsedInSession === 0 || !usedProviderID || !usedModel) {
416
+ return;
417
+ }
418
+ if (!modelContextLimit) {
419
+ const providersResponse = await errore.tryAsync(() => {
420
+ return getClient().provider.list({
421
+ query: { directory: sdkDirectory },
526
422
  });
423
+ });
424
+ if (providersResponse instanceof Error) {
425
+ sessionLogger.error('Failed to fetch provider info for context limit:', providersResponse);
527
426
  }
528
- else if (event.type === 'permission.replied') {
529
- const { requestID, reply, sessionID } = event.properties;
530
- if (sessionID !== session.id) {
531
- continue;
427
+ else {
428
+ const provider = providersResponse.data?.all?.find((p) => p.id === usedProviderID);
429
+ const model = provider?.models?.[usedModel];
430
+ if (model?.limit?.context) {
431
+ modelContextLimit = model.limit.context;
532
432
  }
533
- sessionLogger.log(`Permission ${requestID} replied with: ${reply}`);
534
- // Clean up the specific permission from nested map
535
- const threadPermissions = pendingPermissions.get(thread.id);
536
- if (threadPermissions) {
537
- const pending = threadPermissions.get(requestID);
538
- if (pending) {
539
- cleanupPermissionContext(pending.contextHash);
540
- threadPermissions.delete(requestID);
541
- // Remove thread entry if no more pending permissions
542
- if (threadPermissions.size === 0) {
543
- pendingPermissions.delete(thread.id);
544
- }
433
+ }
434
+ }
435
+ if (!modelContextLimit) {
436
+ return;
437
+ }
438
+ const currentPercentage = Math.floor((tokensUsedInSession / modelContextLimit) * 100);
439
+ const thresholdCrossed = Math.floor(currentPercentage / 10) * 10;
440
+ if (thresholdCrossed <= lastDisplayedContextPercentage || thresholdCrossed < 10) {
441
+ return;
442
+ }
443
+ lastDisplayedContextPercentage = thresholdCrossed;
444
+ const chunk = `⬦ context usage ${currentPercentage}%`;
445
+ await thread.send({ content: chunk, flags: SILENT_MESSAGE_FLAGS });
446
+ };
447
+ const handleMainPart = async (part) => {
448
+ const isActiveMessage = assistantMessageId ? part.messageID === assistantMessageId : false;
449
+ const allowEarlyProcessing = !assistantMessageId && part.type === 'tool' && part.state.status === 'running';
450
+ if (!isActiveMessage && !allowEarlyProcessing) {
451
+ if (part.type !== 'step-start') {
452
+ return;
453
+ }
454
+ }
455
+ if (part.type === 'step-start') {
456
+ const hasPendingQuestion = [...pendingQuestionContexts.values()].some((ctx) => ctx.thread.id === thread.id);
457
+ const hasPendingPermission = (pendingPermissions.get(thread.id)?.size ?? 0) > 0;
458
+ if (!hasPendingQuestion && !hasPendingPermission) {
459
+ stopTyping = startTyping();
460
+ }
461
+ return;
462
+ }
463
+ if (part.type === 'tool' && part.state.status === 'running') {
464
+ await flushBufferedParts({
465
+ messageID: assistantMessageId || part.messageID,
466
+ force: true,
467
+ skipPartId: part.id,
468
+ });
469
+ await sendPartMessage(part);
470
+ if (part.tool === 'task' && !sentPartIds.has(part.id)) {
471
+ const description = part.state.input?.description || '';
472
+ const agent = part.state.input?.subagent_type || 'task';
473
+ const childSessionId = part.state.metadata?.sessionId || '';
474
+ if (description && childSessionId) {
475
+ agentSpawnCounts[agent] = (agentSpawnCounts[agent] || 0) + 1;
476
+ const label = `${agent}-${agentSpawnCounts[agent]}`;
477
+ subtaskSessions.set(childSessionId, { label, assistantMessageId: undefined });
478
+ // Skip task messages in text-only mode
479
+ if (verbosity !== 'text-only') {
480
+ const taskDisplay = `┣ task **${label}** _${description}_`;
481
+ await sendThreadMessage(thread, taskDisplay + '\n\n');
545
482
  }
483
+ sentPartIds.add(part.id);
546
484
  }
547
485
  }
548
- else if (event.type === 'question.asked') {
549
- const questionRequest = event.properties;
550
- if (questionRequest.sessionID !== session.id) {
551
- sessionLogger.log(`[QUESTION IGNORED] Question for different session (expected: ${session.id}, got: ${questionRequest.sessionID})`);
552
- continue;
553
- }
554
- sessionLogger.log(`Question requested: id=${questionRequest.id}, questions=${questionRequest.questions.length}`);
555
- // Stop typing - user needs to respond now, not the bot
556
- if (stopTyping) {
557
- stopTyping();
558
- stopTyping = null;
559
- }
560
- // Flush any pending text/reasoning parts before showing the dropdown
561
- // This ensures text the LLM generated before the question tool is shown first
562
- for (const p of currentParts) {
563
- if (p.type !== 'step-start' && p.type !== 'step-finish') {
564
- await sendPartMessage(p);
486
+ return;
487
+ }
488
+ if (part.type === 'tool' && part.state.status === 'completed') {
489
+ const output = part.state.output || '';
490
+ const outputTokens = Math.ceil(output.length / 4);
491
+ const largeOutputThreshold = 3000;
492
+ if (outputTokens >= largeOutputThreshold) {
493
+ const formattedTokens = outputTokens >= 1000 ? `${(outputTokens / 1000).toFixed(1)}k` : String(outputTokens);
494
+ const percentageSuffix = (() => {
495
+ if (!modelContextLimit) {
496
+ return '';
565
497
  }
566
- }
567
- await showAskUserQuestionDropdowns({
568
- thread,
569
- sessionId: session.id,
570
- directory,
571
- requestId: questionRequest.id,
572
- input: { questions: questionRequest.questions },
573
- });
574
- // Process queued messages if any - queued message will cancel the pending question
575
- const queue = messageQueue.get(thread.id);
576
- if (queue && queue.length > 0) {
577
- const nextMessage = queue.shift();
578
- if (queue.length === 0) {
579
- messageQueue.delete(thread.id);
498
+ const pct = (outputTokens / modelContextLimit) * 100;
499
+ if (pct < 1) {
500
+ return '';
580
501
  }
581
- sessionLogger.log(`[QUEUE] Question shown but queue has messages, processing from ${nextMessage.username}`);
582
- await sendThreadMessage(thread, `» **${nextMessage.username}:** ${nextMessage.prompt.slice(0, 150)}${nextMessage.prompt.length > 150 ? '...' : ''}`);
583
- // handleOpencodeSession will call cancelPendingQuestion, which cancels the dropdown
584
- setImmediate(() => {
585
- handleOpencodeSession({
586
- prompt: nextMessage.prompt,
587
- thread,
588
- projectDirectory: directory,
589
- images: nextMessage.images,
590
- channelId,
591
- }).catch(async (e) => {
592
- sessionLogger.error(`[QUEUE] Failed to process queued message:`, e);
593
- const errorMsg = e instanceof Error ? e.message : String(e);
594
- await sendThreadMessage(thread, `✗ Queued message failed: ${errorMsg.slice(0, 200)}`);
595
- });
596
- });
597
- }
502
+ return ` (${pct.toFixed(1)}%)`;
503
+ })();
504
+ const chunk = `⬦ ${part.tool} returned ${formattedTokens} tokens${percentageSuffix}`;
505
+ await thread.send({ content: chunk, flags: SILENT_MESSAGE_FLAGS });
598
506
  }
599
- else if (event.type === 'session.idle') {
600
- const idleSessionId = event.properties.sessionID;
601
- // Session is done processing - abort to signal completion
602
- if (idleSessionId === session.id) {
603
- sessionLogger.log(`[SESSION IDLE] Session ${session.id} is idle, aborting`);
604
- abortController.abort('finished');
605
- }
606
- else if (subtaskSessions.has(idleSessionId)) {
607
- // Child session completed - clean up tracking
608
- const subtask = subtaskSessions.get(idleSessionId);
609
- sessionLogger.log(`[SUBTASK IDLE] Subtask "${subtask?.label}" completed`);
610
- subtaskSessions.delete(idleSessionId);
611
- }
507
+ }
508
+ if (part.type === 'reasoning') {
509
+ await sendPartMessage(part);
510
+ return;
511
+ }
512
+ if (part.type === 'text' && part.time?.end) {
513
+ await sendPartMessage(part);
514
+ return;
515
+ }
516
+ if (part.type === 'step-finish') {
517
+ await flushBufferedParts({
518
+ messageID: assistantMessageId || part.messageID,
519
+ force: true,
520
+ });
521
+ setTimeout(() => {
522
+ if (abortController.signal.aborted)
523
+ return;
524
+ const hasPendingQuestion = [...pendingQuestionContexts.values()].some((ctx) => ctx.thread.id === thread.id);
525
+ const hasPendingPermission = (pendingPermissions.get(thread.id)?.size ?? 0) > 0;
526
+ if (hasPendingQuestion || hasPendingPermission)
527
+ return;
528
+ stopTyping = startTyping();
529
+ }, 300);
530
+ }
531
+ };
532
+ const handleSubtaskPart = async (part, subtaskInfo) => {
533
+ // In text-only mode, skip all subtask output (they're tool-related)
534
+ if (verbosity === 'text-only') {
535
+ return;
536
+ }
537
+ if (part.type === 'step-start' || part.type === 'step-finish') {
538
+ return;
539
+ }
540
+ if (part.type === 'tool' && part.state.status === 'pending') {
541
+ return;
542
+ }
543
+ if (part.type === 'text') {
544
+ return;
545
+ }
546
+ if (!subtaskInfo.assistantMessageId || part.messageID !== subtaskInfo.assistantMessageId) {
547
+ return;
548
+ }
549
+ const content = formatPart(part, subtaskInfo.label);
550
+ if (!content.trim() || sentPartIds.has(part.id)) {
551
+ return;
552
+ }
553
+ const sendResult = await errore.tryAsync(() => {
554
+ return sendThreadMessage(thread, content + '\n\n');
555
+ });
556
+ if (sendResult instanceof Error) {
557
+ discordLogger.error(`ERROR: Failed to send subtask part ${part.id}:`, sendResult);
558
+ return;
559
+ }
560
+ sentPartIds.add(part.id);
561
+ getDatabase()
562
+ .prepare('INSERT OR REPLACE INTO part_messages (part_id, message_id, thread_id) VALUES (?, ?, ?)')
563
+ .run(part.id, sendResult.id, thread.id);
564
+ };
565
+ const handlePartUpdated = async (part) => {
566
+ storePart(part);
567
+ const subtaskInfo = subtaskSessions.get(part.sessionID);
568
+ const isSubtaskEvent = Boolean(subtaskInfo);
569
+ if (part.sessionID !== session.id && !isSubtaskEvent) {
570
+ return;
571
+ }
572
+ if (isSubtaskEvent && subtaskInfo) {
573
+ await handleSubtaskPart(part, subtaskInfo);
574
+ return;
575
+ }
576
+ await handleMainPart(part);
577
+ };
578
+ const handleSessionError = async ({ sessionID, error, }) => {
579
+ if (!sessionID || sessionID !== session.id) {
580
+ voiceLogger.log(`[SESSION ERROR IGNORED] Error for different session (expected: ${session.id}, got: ${sessionID})`);
581
+ return;
582
+ }
583
+ const errorMessage = error?.data?.message || 'Unknown error';
584
+ sessionLogger.error(`Sending error to thread: ${errorMessage}`);
585
+ await sendThreadMessage(thread, `✗ opencode session error: ${errorMessage}`);
586
+ if (!originalMessage) {
587
+ return;
588
+ }
589
+ const reactionResult = await errore.tryAsync(async () => {
590
+ await originalMessage.reactions.removeAll();
591
+ await originalMessage.react('❌');
592
+ });
593
+ if (reactionResult instanceof Error) {
594
+ discordLogger.log(`Could not update reaction:`, reactionResult);
595
+ }
596
+ else {
597
+ voiceLogger.log(`[REACTION] Added error reaction due to session error`);
598
+ }
599
+ };
600
+ const handlePermissionAsked = async (permission) => {
601
+ if (permission.sessionID !== session.id) {
602
+ voiceLogger.log(`[PERMISSION IGNORED] Permission for different session (expected: ${session.id}, got: ${permission.sessionID})`);
603
+ return;
604
+ }
605
+ const dedupeKey = buildPermissionDedupeKey({ permission, directory });
606
+ const threadPermissions = pendingPermissions.get(thread.id);
607
+ const existingPending = threadPermissions
608
+ ? Array.from(threadPermissions.values()).find((pending) => {
609
+ return pending.dedupeKey === dedupeKey;
610
+ })
611
+ : undefined;
612
+ if (existingPending) {
613
+ sessionLogger.log(`[PERMISSION] Deduped permission ${permission.id} (matches pending ${existingPending.permission.id})`);
614
+ if (stopTyping) {
615
+ stopTyping();
616
+ stopTyping = null;
617
+ }
618
+ if (!pendingPermissions.has(thread.id)) {
619
+ pendingPermissions.set(thread.id, new Map());
620
+ }
621
+ pendingPermissions.get(thread.id).set(permission.id, {
622
+ permission,
623
+ messageId: existingPending.messageId,
624
+ directory,
625
+ contextHash: existingPending.contextHash,
626
+ dedupeKey,
627
+ });
628
+ const added = addPermissionRequestToContext({
629
+ contextHash: existingPending.contextHash,
630
+ requestId: permission.id,
631
+ });
632
+ if (!added) {
633
+ sessionLogger.log(`[PERMISSION] Failed to attach duplicate request ${permission.id} to context`);
634
+ }
635
+ return;
636
+ }
637
+ sessionLogger.log(`Permission requested: permission=${permission.permission}, patterns=${permission.patterns.join(', ')}`);
638
+ if (stopTyping) {
639
+ stopTyping();
640
+ stopTyping = null;
641
+ }
642
+ const { messageId, contextHash } = await showPermissionDropdown({
643
+ thread,
644
+ permission,
645
+ directory,
646
+ });
647
+ if (!pendingPermissions.has(thread.id)) {
648
+ pendingPermissions.set(thread.id, new Map());
649
+ }
650
+ pendingPermissions.get(thread.id).set(permission.id, {
651
+ permission,
652
+ messageId,
653
+ directory,
654
+ contextHash,
655
+ dedupeKey,
656
+ });
657
+ };
658
+ const handlePermissionReplied = ({ requestID, reply, sessionID, }) => {
659
+ if (sessionID !== session.id) {
660
+ return;
661
+ }
662
+ sessionLogger.log(`Permission ${requestID} replied with: ${reply}`);
663
+ const threadPermissions = pendingPermissions.get(thread.id);
664
+ if (!threadPermissions) {
665
+ return;
666
+ }
667
+ const pending = threadPermissions.get(requestID);
668
+ if (!pending) {
669
+ return;
670
+ }
671
+ cleanupPermissionContext(pending.contextHash);
672
+ threadPermissions.delete(requestID);
673
+ if (threadPermissions.size === 0) {
674
+ pendingPermissions.delete(thread.id);
675
+ }
676
+ };
677
+ const handleQuestionAsked = async (questionRequest) => {
678
+ if (questionRequest.sessionID !== session.id) {
679
+ sessionLogger.log(`[QUESTION IGNORED] Question for different session (expected: ${session.id}, got: ${questionRequest.sessionID})`);
680
+ return;
681
+ }
682
+ sessionLogger.log(`Question requested: id=${questionRequest.id}, questions=${questionRequest.questions.length}`);
683
+ if (stopTyping) {
684
+ stopTyping();
685
+ stopTyping = null;
686
+ }
687
+ await flushBufferedParts({
688
+ messageID: assistantMessageId || '',
689
+ force: true,
690
+ });
691
+ await showAskUserQuestionDropdowns({
692
+ thread,
693
+ sessionId: session.id,
694
+ directory,
695
+ requestId: questionRequest.id,
696
+ input: { questions: questionRequest.questions },
697
+ });
698
+ const queue = messageQueue.get(thread.id);
699
+ if (!queue || queue.length === 0) {
700
+ return;
701
+ }
702
+ const nextMessage = queue.shift();
703
+ if (queue.length === 0) {
704
+ messageQueue.delete(thread.id);
705
+ }
706
+ sessionLogger.log(`[QUEUE] Question shown but queue has messages, processing from ${nextMessage.username}`);
707
+ await sendThreadMessage(thread, `» **${nextMessage.username}:** ${nextMessage.prompt.slice(0, 150)}${nextMessage.prompt.length > 150 ? '...' : ''}`);
708
+ setImmediate(() => {
709
+ void errore
710
+ .tryAsync(async () => {
711
+ return handleOpencodeSession({
712
+ prompt: nextMessage.prompt,
713
+ thread,
714
+ projectDirectory: directory,
715
+ images: nextMessage.images,
716
+ channelId,
717
+ });
718
+ })
719
+ .then(async (result) => {
720
+ if (!(result instanceof Error)) {
721
+ return;
722
+ }
723
+ sessionLogger.error(`[QUEUE] Failed to process queued message:`, result);
724
+ await sendThreadMessage(thread, `✗ Queued message failed: ${result.message.slice(0, 200)}`);
725
+ });
726
+ });
727
+ };
728
+ const handleSessionIdle = (idleSessionId) => {
729
+ if (idleSessionId === session.id) {
730
+ sessionLogger.log(`[SESSION IDLE] Session ${session.id} is idle, aborting`);
731
+ abortController.abort('finished');
732
+ return;
733
+ }
734
+ if (!subtaskSessions.has(idleSessionId)) {
735
+ return;
736
+ }
737
+ const subtask = subtaskSessions.get(idleSessionId);
738
+ sessionLogger.log(`[SUBTASK IDLE] Subtask "${subtask?.label}" completed`);
739
+ subtaskSessions.delete(idleSessionId);
740
+ };
741
+ try {
742
+ for await (const event of events) {
743
+ switch (event.type) {
744
+ case 'message.updated':
745
+ await handleMessageUpdated(event.properties.info);
746
+ break;
747
+ case 'message.part.updated':
748
+ await handlePartUpdated(event.properties.part);
749
+ break;
750
+ case 'session.error':
751
+ sessionLogger.error(`ERROR:`, event.properties);
752
+ await handleSessionError(event.properties);
753
+ break;
754
+ case 'permission.asked':
755
+ await handlePermissionAsked(event.properties);
756
+ break;
757
+ case 'permission.replied':
758
+ handlePermissionReplied(event.properties);
759
+ break;
760
+ case 'question.asked':
761
+ await handleQuestionAsked(event.properties);
762
+ break;
763
+ case 'session.idle':
764
+ handleSessionIdle(event.properties.sessionID);
765
+ break;
766
+ default:
767
+ break;
612
768
  }
613
769
  }
614
770
  }
@@ -621,14 +777,14 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
621
777
  throw e;
622
778
  }
623
779
  finally {
624
- for (const part of currentParts) {
625
- if (!sentPartIds.has(part.id)) {
626
- try {
780
+ abortControllers.delete(session.id);
781
+ const finalMessageId = assistantMessageId;
782
+ if (finalMessageId) {
783
+ const parts = getBufferedParts(finalMessageId);
784
+ for (const part of parts) {
785
+ if (!sentPartIds.has(part.id)) {
627
786
  await sendPartMessage(part);
628
787
  }
629
- catch (error) {
630
- sessionLogger.error(`Failed to send part ${part.id}:`, error);
631
- }
632
788
  }
633
789
  }
634
790
  if (stopTyping) {
@@ -641,12 +797,13 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
641
797
  const modelInfo = usedModel ? ` ⋅ ${usedModel}` : '';
642
798
  const agentInfo = usedAgent && usedAgent.toLowerCase() !== 'build' ? ` ⋅ **${usedAgent}**` : '';
643
799
  let contextInfo = '';
644
- try {
800
+ const contextResult = await errore.tryAsync(async () => {
645
801
  // Fetch final token count from API since message.updated events can arrive
646
802
  // after session.idle due to race conditions in event ordering
647
803
  if (tokensUsedInSession === 0) {
648
804
  const messagesResponse = await getClient().session.messages({
649
805
  path: { id: session.id },
806
+ query: { directory: sdkDirectory },
650
807
  });
651
808
  const messages = messagesResponse.data || [];
652
809
  const lastAssistant = [...messages]
@@ -662,16 +819,16 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
662
819
  tokens.cache.write;
663
820
  }
664
821
  }
665
- const providersResponse = await getClient().provider.list({ query: { directory } });
822
+ const providersResponse = await getClient().provider.list({ query: { directory: sdkDirectory } });
666
823
  const provider = providersResponse.data?.all?.find((p) => p.id === usedProviderID);
667
824
  const model = provider?.models?.[usedModel || ''];
668
825
  if (model?.limit?.context) {
669
826
  const percentage = Math.round((tokensUsedInSession / model.limit.context) * 100);
670
827
  contextInfo = ` ⋅ ${percentage}%`;
671
828
  }
672
- }
673
- catch (e) {
674
- sessionLogger.error('Failed to fetch provider info for context percentage:', e);
829
+ });
830
+ if (contextResult instanceof Error) {
831
+ sessionLogger.error('Failed to fetch provider info for context percentage:', contextResult);
675
832
  }
676
833
  await sendThreadMessage(thread, `_Completed in ${sessionDuration}${contextInfo}_${attachCommand}${modelInfo}${agentInfo}`, { flags: NOTIFY_MESSAGE_FLAGS });
677
834
  sessionLogger.log(`DURATION: Session completed in ${sessionDuration}, port ${port}, model ${usedModel}, tokens ${tokensUsedInSession}`);
@@ -707,15 +864,20 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
707
864
  }
708
865
  }
709
866
  };
710
- try {
711
- const eventHandlerPromise = eventHandler();
867
+ const promptResult = await errore.tryAsync(async () => {
868
+ const newHandlerPromise = eventHandler().finally(() => {
869
+ if (activeEventHandlers.get(thread.id) === newHandlerPromise) {
870
+ activeEventHandlers.delete(thread.id);
871
+ }
872
+ });
873
+ activeEventHandlers.set(thread.id, newHandlerPromise);
874
+ handlerPromise = newHandlerPromise;
712
875
  if (abortController.signal.aborted) {
713
876
  sessionLogger.log(`[DEBOUNCE] Aborted before prompt, exiting`);
714
877
  return;
715
878
  }
716
879
  stopTyping = startTyping();
717
880
  voiceLogger.log(`[PROMPT] Sending prompt to session ${session.id}: "${prompt.slice(0, 100)}${prompt.length > 100 ? '...' : ''}"`);
718
- // append image paths to prompt so ai knows where they are on disk
719
881
  const promptWithImagePaths = (() => {
720
882
  if (images.length === 0) {
721
883
  return prompt;
@@ -730,16 +892,12 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
730
892
  })();
731
893
  const parts = [{ type: 'text', text: promptWithImagePaths }, ...images];
732
894
  sessionLogger.log(`[PROMPT] Parts to send:`, parts.length);
733
- // Get agent preference: session-level overrides channel-level
734
895
  const agentPreference = getSessionAgent(session.id) || (channelId ? getChannelAgent(channelId) : undefined);
735
896
  if (agentPreference) {
736
897
  sessionLogger.log(`[AGENT] Using agent preference: ${agentPreference}`);
737
898
  }
738
- // Get model preference: session-level overrides channel-level
739
- // BUT: if an agent is set, don't pass model param so the agent's model takes effect
740
899
  const modelPreference = getSessionModel(session.id) || (channelId ? getChannelModel(channelId) : undefined);
741
900
  const modelParam = (() => {
742
- // When an agent is set, let the agent's model config take effect
743
901
  if (agentPreference) {
744
902
  sessionLogger.log(`[MODEL] Skipping model param, agent "${agentPreference}" controls model`);
745
903
  return undefined;
@@ -755,8 +913,7 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
755
913
  sessionLogger.log(`[MODEL] Using model preference: ${modelPreference}`);
756
914
  return { providerID, modelID };
757
915
  })();
758
- // Get worktree info if this thread is in a worktree
759
- const worktreeInfo = getThreadWorktree(thread.id);
916
+ // Build worktree info for system message (worktreeInfo was fetched at the start)
760
917
  const worktree = worktreeInfo?.status === 'ready' && worktreeInfo.worktree_directory
761
918
  ? {
762
919
  worktreeDirectory: worktreeInfo.worktree_directory,
@@ -764,10 +921,10 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
764
921
  mainRepoDirectory: worktreeInfo.project_directory,
765
922
  }
766
923
  : undefined;
767
- // Use session.command API for slash commands, session.prompt for regular messages
768
924
  const response = command
769
925
  ? await getClient().session.command({
770
926
  path: { id: session.id },
927
+ query: { directory: sdkDirectory },
771
928
  body: {
772
929
  command: command.name,
773
930
  arguments: command.arguments,
@@ -777,6 +934,7 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
777
934
  })
778
935
  : await getClient().session.prompt({
779
936
  path: { id: session.id },
937
+ query: { directory: sdkDirectory },
780
938
  body: {
781
939
  parts,
782
940
  system: getOpencodeSystemMessage({ sessionId: session.id, channelId, worktree }),
@@ -803,41 +961,50 @@ export async function handleOpencodeSession({ prompt, thread, projectDirectory,
803
961
  abortController.abort('finished');
804
962
  sessionLogger.log(`Successfully sent prompt, got response`);
805
963
  if (originalMessage) {
806
- try {
964
+ const reactionResult = await errore.tryAsync(async () => {
807
965
  await originalMessage.reactions.removeAll();
808
966
  await originalMessage.react('✅');
809
- }
810
- catch (e) {
811
- discordLogger.log(`Could not update reactions:`, e);
967
+ });
968
+ if (reactionResult instanceof Error) {
969
+ discordLogger.log(`Could not update reactions:`, reactionResult);
812
970
  }
813
971
  }
814
972
  return { sessionID: session.id, result: response.data, port };
973
+ });
974
+ if (handlerPromise) {
975
+ await Promise.race([
976
+ handlerPromise,
977
+ new Promise((resolve) => {
978
+ setTimeout(resolve, 1000);
979
+ }),
980
+ ]);
815
981
  }
816
- catch (error) {
817
- if (!isAbortError(error, abortController.signal)) {
818
- sessionLogger.error(`ERROR: Failed to send prompt:`, error);
819
- abortController.abort('error');
820
- if (originalMessage) {
821
- try {
822
- await originalMessage.reactions.removeAll();
823
- await originalMessage.react('❌');
824
- discordLogger.log(`Added error reaction to message`);
825
- }
826
- catch (e) {
827
- discordLogger.log(`Could not update reaction:`, e);
828
- }
829
- }
830
- const errorDisplay = (() => {
831
- if (error instanceof Error) {
832
- const name = error.constructor.name || 'Error';
833
- return `[${name}]\n${error.stack || error.message}`;
834
- }
835
- if (typeof error === 'string') {
836
- return error;
837
- }
838
- return String(error);
839
- })();
840
- await sendThreadMessage(thread, `✗ Unexpected bot Error: ${errorDisplay}`);
982
+ if (!errore.isError(promptResult)) {
983
+ return promptResult;
984
+ }
985
+ const promptError = promptResult instanceof Error ? promptResult : new Error('Unknown error');
986
+ if (isAbortError(promptError, abortController.signal)) {
987
+ return;
988
+ }
989
+ sessionLogger.error(`ERROR: Failed to send prompt:`, promptError);
990
+ abortController.abort('error');
991
+ if (originalMessage) {
992
+ const reactionResult = await errore.tryAsync(async () => {
993
+ await originalMessage.reactions.removeAll();
994
+ await originalMessage.react('❌');
995
+ });
996
+ if (reactionResult instanceof Error) {
997
+ discordLogger.log(`Could not update reaction:`, reactionResult);
998
+ }
999
+ else {
1000
+ discordLogger.log(`Added error reaction to message`);
841
1001
  }
842
1002
  }
1003
+ const errorDisplay = (() => {
1004
+ const promptErrorValue = promptError;
1005
+ const name = promptErrorValue.name || 'Error';
1006
+ const message = promptErrorValue.stack || promptErrorValue.message;
1007
+ return `[${name}]\n${message}`;
1008
+ })();
1009
+ await sendThreadMessage(thread, `✗ Unexpected bot Error: ${errorDisplay}`);
843
1010
  }