kimaki 0.4.94 → 0.4.96
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.
- package/dist/anthropic-auth-plugin.js +23 -18
- package/dist/discord-utils.js +5 -2
- package/dist/session-handler/thread-session-runtime.js +18 -1
- package/dist/system-prompt-drift-plugin.js +12 -4
- package/dist/utils.js +5 -1
- package/package.json +2 -2
- package/src/anthropic-auth-plugin.ts +23 -17
- package/src/discord-utils.ts +19 -17
- package/src/session-handler/thread-session-runtime.ts +21 -1
- package/src/system-prompt-drift-plugin.ts +31 -11
- package/src/utils.ts +5 -1
|
@@ -430,15 +430,25 @@ function buildAuthorizeHandler(mode) {
|
|
|
430
430
|
function toClaudeCodeToolName(name) {
|
|
431
431
|
return OPENCODE_TO_CLAUDE_CODE_TOOL_NAME[name.toLowerCase()] ?? name;
|
|
432
432
|
}
|
|
433
|
-
function sanitizeSystemText(text) {
|
|
434
|
-
|
|
433
|
+
function sanitizeSystemText(text, onError) {
|
|
434
|
+
const startIdx = text.indexOf(OPENCODE_IDENTITY);
|
|
435
|
+
if (startIdx === -1)
|
|
436
|
+
return text;
|
|
437
|
+
const codeRefsMarker = '# Code References';
|
|
438
|
+
const endIdx = text.indexOf(codeRefsMarker, startIdx);
|
|
439
|
+
if (endIdx === -1) {
|
|
440
|
+
onError?.(`sanitizeSystemText: could not find '# Code References' after OpenCode identity`);
|
|
441
|
+
return text;
|
|
442
|
+
}
|
|
443
|
+
// Remove everything from the OpenCode identity up to (but not including) '# Code References'
|
|
444
|
+
return text.slice(0, startIdx) + text.slice(endIdx);
|
|
435
445
|
}
|
|
436
|
-
function prependClaudeCodeIdentity(system) {
|
|
446
|
+
function prependClaudeCodeIdentity(system, onError) {
|
|
437
447
|
const identityBlock = { type: 'text', text: CLAUDE_CODE_IDENTITY };
|
|
438
448
|
if (typeof system === 'undefined')
|
|
439
449
|
return [identityBlock];
|
|
440
450
|
if (typeof system === 'string') {
|
|
441
|
-
const sanitized = sanitizeSystemText(system);
|
|
451
|
+
const sanitized = sanitizeSystemText(system, onError);
|
|
442
452
|
if (sanitized === CLAUDE_CODE_IDENTITY)
|
|
443
453
|
return [identityBlock];
|
|
444
454
|
return [identityBlock, { type: 'text', text: sanitized }];
|
|
@@ -447,11 +457,11 @@ function prependClaudeCodeIdentity(system) {
|
|
|
447
457
|
return [identityBlock, system];
|
|
448
458
|
const sanitized = system.map((item) => {
|
|
449
459
|
if (typeof item === 'string')
|
|
450
|
-
return { type: 'text', text: sanitizeSystemText(item) };
|
|
460
|
+
return { type: 'text', text: sanitizeSystemText(item, onError) };
|
|
451
461
|
if (item && typeof item === 'object' && item.type === 'text') {
|
|
452
462
|
const text = item.text;
|
|
453
463
|
if (typeof text === 'string') {
|
|
454
|
-
return { ...item, text: sanitizeSystemText(text) };
|
|
464
|
+
return { ...item, text: sanitizeSystemText(text, onError) };
|
|
455
465
|
}
|
|
456
466
|
}
|
|
457
467
|
return item;
|
|
@@ -465,7 +475,7 @@ function prependClaudeCodeIdentity(system) {
|
|
|
465
475
|
}
|
|
466
476
|
return [identityBlock, ...sanitized];
|
|
467
477
|
}
|
|
468
|
-
function rewriteRequestPayload(body) {
|
|
478
|
+
function rewriteRequestPayload(body, onError) {
|
|
469
479
|
if (!body)
|
|
470
480
|
return { body, modelId: undefined, reverseToolNameMap: new Map() };
|
|
471
481
|
try {
|
|
@@ -486,7 +496,7 @@ function rewriteRequestPayload(body) {
|
|
|
486
496
|
});
|
|
487
497
|
}
|
|
488
498
|
// Rename system prompt
|
|
489
|
-
payload.system = prependClaudeCodeIdentity(payload.system);
|
|
499
|
+
payload.system = prependClaudeCodeIdentity(payload.system, onError);
|
|
490
500
|
// Rename tool_choice
|
|
491
501
|
if (payload.tool_choice &&
|
|
492
502
|
typeof payload.tool_choice === 'object' &&
|
|
@@ -627,15 +637,6 @@ async function getFreshOAuth(getAuth, client) {
|
|
|
627
637
|
// --- Plugin export ---
|
|
628
638
|
const AnthropicAuthPlugin = async ({ client }) => {
|
|
629
639
|
return {
|
|
630
|
-
"experimental.chat.system.transform": async (input, output) => {
|
|
631
|
-
if (input.model.providerID !== ('anthropic'))
|
|
632
|
-
return;
|
|
633
|
-
const opencodePromptPart = output.system.findIndex(x => x?.includes('https://github.com/anomalyco/opencode'));
|
|
634
|
-
// Remove the OpenCode system prompt part if present
|
|
635
|
-
if (opencodePromptPart !== -1) {
|
|
636
|
-
output.system.splice(opencodePromptPart, 1);
|
|
637
|
-
}
|
|
638
|
-
},
|
|
639
640
|
auth: {
|
|
640
641
|
provider: 'anthropic',
|
|
641
642
|
async loader(getAuth, provider) {
|
|
@@ -667,7 +668,11 @@ const AnthropicAuthPlugin = async ({ client }) => {
|
|
|
667
668
|
.text()
|
|
668
669
|
.catch(() => undefined)
|
|
669
670
|
: undefined;
|
|
670
|
-
const rewritten = rewriteRequestPayload(originalBody)
|
|
671
|
+
const rewritten = rewriteRequestPayload(originalBody, (msg) => {
|
|
672
|
+
client.tui.showToast({
|
|
673
|
+
body: { message: msg, variant: 'error' },
|
|
674
|
+
}).catch(() => { });
|
|
675
|
+
});
|
|
671
676
|
const headers = new Headers(init?.headers);
|
|
672
677
|
if (input instanceof Request) {
|
|
673
678
|
input.headers.forEach((v, k) => {
|
package/dist/discord-utils.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
// Discord-specific utility functions.
|
|
2
2
|
// Handles markdown splitting for Discord's 2000-char limit, code block escaping,
|
|
3
3
|
// thread message sending, and channel metadata extraction from topic tags.
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
// Use namespace import for CJS interop — discord.js is CJS and its named
|
|
5
|
+
// exports aren't detectable by all ESM loaders (e.g. tsx/esbuild) because
|
|
6
|
+
// discord.js uses tslib's __exportStar which is opaque to static analysis.
|
|
7
|
+
import * as discord from 'discord.js';
|
|
8
|
+
const { ChannelType, GuildMember, MessageFlags, PermissionsBitField, REST, Routes } = discord;
|
|
6
9
|
import { discordApiUrl } from './discord-urls.js';
|
|
7
10
|
import { Lexer } from 'marked';
|
|
8
11
|
import { splitTablesFromMarkdown } from './format-tables.js';
|
|
@@ -40,6 +40,14 @@ import { extractLeadingOpencodeCommand } from '../opencode-command-detection.js'
|
|
|
40
40
|
const logger = createLogger(LogPrefix.SESSION);
|
|
41
41
|
const discordLogger = createLogger(LogPrefix.DISCORD);
|
|
42
42
|
const DETERMINISTIC_CONTEXT_LIMIT = 100_000;
|
|
43
|
+
const TOAST_SESSION_ID_REGEX = /\b(ses_[A-Za-z0-9]+)\b\s*$/u;
|
|
44
|
+
function extractToastSessionId({ message }) {
|
|
45
|
+
const match = message.match(TOAST_SESSION_ID_REGEX);
|
|
46
|
+
return match?.[1];
|
|
47
|
+
}
|
|
48
|
+
function stripToastSessionId({ message }) {
|
|
49
|
+
return message.replace(TOAST_SESSION_ID_REGEX, '').trimEnd();
|
|
50
|
+
}
|
|
43
51
|
const shouldLogSessionEvents = process.env['KIMAKI_LOG_SESSION_EVENTS'] === '1' ||
|
|
44
52
|
process.env['KIMAKI_VITEST'] === '1';
|
|
45
53
|
// ── Registry ─────────────────────────────────────────────────────
|
|
@@ -943,6 +951,9 @@ export class ThreadSessionRuntime {
|
|
|
943
951
|
}
|
|
944
952
|
const sessionId = this.state?.sessionId;
|
|
945
953
|
const eventSessionId = getOpencodeEventSessionId(event);
|
|
954
|
+
const toastSessionId = event.type === 'tui.toast.show'
|
|
955
|
+
? extractToastSessionId({ message: event.properties.message })
|
|
956
|
+
: undefined;
|
|
946
957
|
if (shouldLogSessionEvents) {
|
|
947
958
|
const eventDetails = (() => {
|
|
948
959
|
if (event.type === 'session.error') {
|
|
@@ -970,6 +981,7 @@ export class ThreadSessionRuntime {
|
|
|
970
981
|
logger.log(`[EVENT] type=${event.type} eventSessionId=${eventSessionId || 'none'} activeSessionId=${sessionId || 'none'} ${this.formatRunStateForLog()}${eventDetails}`);
|
|
971
982
|
}
|
|
972
983
|
const isGlobalEvent = event.type === 'tui.toast.show';
|
|
984
|
+
const isScopedToastEvent = Boolean(toastSessionId);
|
|
973
985
|
// Drop events that don't match current session (stale events from
|
|
974
986
|
// previous sessions), unless it's a global event or a subtask session.
|
|
975
987
|
if (!isGlobalEvent && eventSessionId && eventSessionId !== sessionId) {
|
|
@@ -977,6 +989,11 @@ export class ThreadSessionRuntime {
|
|
|
977
989
|
return; // stale event from previous session
|
|
978
990
|
}
|
|
979
991
|
}
|
|
992
|
+
if (isScopedToastEvent && toastSessionId !== sessionId) {
|
|
993
|
+
if (!this.getSubtaskInfoForSession(toastSessionId)) {
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
996
|
+
}
|
|
980
997
|
if (isOpencodeSessionEventLogEnabled()) {
|
|
981
998
|
const eventLogResult = await appendOpencodeSessionEventLog({
|
|
982
999
|
threadId: this.threadId,
|
|
@@ -2023,7 +2040,7 @@ export class ThreadSessionRuntime {
|
|
|
2023
2040
|
if (properties.variant === 'warning') {
|
|
2024
2041
|
return;
|
|
2025
2042
|
}
|
|
2026
|
-
const toastMessage = properties.message.trim();
|
|
2043
|
+
const toastMessage = stripToastSessionId({ message: properties.message }).trim();
|
|
2027
2044
|
if (!toastMessage) {
|
|
2028
2045
|
return;
|
|
2029
2046
|
}
|
|
@@ -11,12 +11,16 @@ import { createPluginLogger, formatPluginErrorWithStack, setPluginLogFilePath }
|
|
|
11
11
|
import { initSentry, notifyError } from './sentry.js';
|
|
12
12
|
import { abbreviatePath } from './utils.js';
|
|
13
13
|
const logger = createPluginLogger('OPENCODE');
|
|
14
|
+
const TOAST_SESSION_MARKER_SEPARATOR = ' ';
|
|
14
15
|
function getSystemPromptDiffDir({ dataDir }) {
|
|
15
16
|
return path.join(dataDir, 'system-prompt-diffs');
|
|
16
17
|
}
|
|
17
18
|
function normalizeSystemPrompt({ system }) {
|
|
18
19
|
return system.join('\n');
|
|
19
20
|
}
|
|
21
|
+
function appendToastSessionMarker({ message, sessionId, }) {
|
|
22
|
+
return `${message}${TOAST_SESSION_MARKER_SEPARATOR}${sessionId}`;
|
|
23
|
+
}
|
|
20
24
|
function buildTurnContext({ input, directory, }) {
|
|
21
25
|
const model = input.model
|
|
22
26
|
? `${input.model.providerID}/${input.model.modelID}${input.variant ? `:${input.variant}` : ''}`
|
|
@@ -66,7 +70,7 @@ function writeSystemPromptDiffFile({ dataDir, sessionId, beforePrompt, afterProm
|
|
|
66
70
|
const timestamp = new Date().toISOString().replaceAll(':', '-');
|
|
67
71
|
const sessionDir = path.join(getSystemPromptDiffDir({ dataDir }), sessionId);
|
|
68
72
|
const filePath = path.join(sessionDir, `${timestamp}.diff`);
|
|
69
|
-
const latestPromptPath = path.join(sessionDir, `${
|
|
73
|
+
const latestPromptPath = path.join(sessionDir, `${timestamp}.md`);
|
|
70
74
|
const fileContent = [
|
|
71
75
|
`Session: ${sessionId}`,
|
|
72
76
|
`Created: ${new Date().toISOString()}`,
|
|
@@ -84,6 +88,7 @@ function writeSystemPromptDiffFile({ dataDir, sessionId, beforePrompt, afterProm
|
|
|
84
88
|
additions: diff.additions,
|
|
85
89
|
deletions: diff.deletions,
|
|
86
90
|
filePath,
|
|
91
|
+
latestPromptPath,
|
|
87
92
|
};
|
|
88
93
|
},
|
|
89
94
|
catch: (error) => {
|
|
@@ -154,9 +159,12 @@ async function handleSystemTransform({ input, output, sessions, dataDir, client,
|
|
|
154
159
|
body: {
|
|
155
160
|
variant: 'info',
|
|
156
161
|
title: 'Context cache discarded',
|
|
157
|
-
message:
|
|
158
|
-
|
|
159
|
-
|
|
162
|
+
message: appendToastSessionMarker({
|
|
163
|
+
sessionId,
|
|
164
|
+
message: `system prompt changed since the previous message (+${diffFileResult.additions} / -${diffFileResult.deletions}). ` +
|
|
165
|
+
`Diff: \`${abbreviatePath(diffFileResult.filePath)}\`. ` +
|
|
166
|
+
`Latest prompt: \`${abbreviatePath(diffFileResult.latestPromptPath)}\``,
|
|
167
|
+
}),
|
|
160
168
|
},
|
|
161
169
|
});
|
|
162
170
|
}
|
package/dist/utils.js
CHANGED
|
@@ -2,7 +2,11 @@
|
|
|
2
2
|
// Includes Discord OAuth URL generation, array deduplication,
|
|
3
3
|
// abort error detection, and date/time formatting helpers.
|
|
4
4
|
import os from 'node:os';
|
|
5
|
-
import
|
|
5
|
+
// Use namespace import for CJS interop — discord.js is CJS and its named
|
|
6
|
+
// exports aren't detectable by all ESM loaders (e.g. tsx/esbuild) because
|
|
7
|
+
// discord.js uses tslib's __exportStar which is opaque to static analysis.
|
|
8
|
+
import * as discord from 'discord.js';
|
|
9
|
+
const { PermissionsBitField } = discord;
|
|
6
10
|
import * as errore from 'errore';
|
|
7
11
|
export function generateBotInstallUrl({ clientId, permissions = [
|
|
8
12
|
PermissionsBitField.Flags.ViewChannel,
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "kimaki",
|
|
3
3
|
"module": "index.ts",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"version": "0.4.
|
|
5
|
+
"version": "0.4.96",
|
|
6
6
|
"repository": "https://github.com/remorses/kimaki",
|
|
7
7
|
"bin": "bin.js",
|
|
8
8
|
"files": [
|
|
@@ -26,8 +26,8 @@
|
|
|
26
26
|
"tsx": "^4.20.5",
|
|
27
27
|
"undici": "^8.0.2",
|
|
28
28
|
"opencode-cached-provider": "^0.0.1",
|
|
29
|
-
"db": "^0.0.0",
|
|
30
29
|
"discord-digital-twin": "^0.1.0",
|
|
30
|
+
"db": "^0.0.0",
|
|
31
31
|
"opencode-deterministic-provider": "^0.0.1"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
@@ -528,17 +528,26 @@ function toClaudeCodeToolName(name: string) {
|
|
|
528
528
|
return OPENCODE_TO_CLAUDE_CODE_TOOL_NAME[name.toLowerCase()] ?? name
|
|
529
529
|
}
|
|
530
530
|
|
|
531
|
-
function sanitizeSystemText(text: string) {
|
|
532
|
-
|
|
531
|
+
function sanitizeSystemText(text: string, onError?: (msg: string) => void) {
|
|
532
|
+
const startIdx = text.indexOf(OPENCODE_IDENTITY)
|
|
533
|
+
if (startIdx === -1) return text
|
|
534
|
+
const codeRefsMarker = '# Code References'
|
|
535
|
+
const endIdx = text.indexOf(codeRefsMarker, startIdx)
|
|
536
|
+
if (endIdx === -1) {
|
|
537
|
+
onError?.(`sanitizeSystemText: could not find '# Code References' after OpenCode identity`)
|
|
538
|
+
return text
|
|
539
|
+
}
|
|
540
|
+
// Remove everything from the OpenCode identity up to (but not including) '# Code References'
|
|
541
|
+
return text.slice(0, startIdx) + text.slice(endIdx)
|
|
533
542
|
}
|
|
534
543
|
|
|
535
|
-
function prependClaudeCodeIdentity(system: unknown) {
|
|
544
|
+
function prependClaudeCodeIdentity(system: unknown, onError?: (msg: string) => void) {
|
|
536
545
|
const identityBlock = { type: 'text', text: CLAUDE_CODE_IDENTITY }
|
|
537
546
|
|
|
538
547
|
if (typeof system === 'undefined') return [identityBlock]
|
|
539
548
|
|
|
540
549
|
if (typeof system === 'string') {
|
|
541
|
-
const sanitized = sanitizeSystemText(system)
|
|
550
|
+
const sanitized = sanitizeSystemText(system, onError)
|
|
542
551
|
if (sanitized === CLAUDE_CODE_IDENTITY) return [identityBlock]
|
|
543
552
|
return [identityBlock, { type: 'text', text: sanitized }]
|
|
544
553
|
}
|
|
@@ -546,11 +555,11 @@ function prependClaudeCodeIdentity(system: unknown) {
|
|
|
546
555
|
if (!Array.isArray(system)) return [identityBlock, system]
|
|
547
556
|
|
|
548
557
|
const sanitized = system.map((item) => {
|
|
549
|
-
if (typeof item === 'string') return { type: 'text', text: sanitizeSystemText(item) }
|
|
558
|
+
if (typeof item === 'string') return { type: 'text', text: sanitizeSystemText(item, onError) }
|
|
550
559
|
if (item && typeof item === 'object' && (item as { type?: unknown }).type === 'text') {
|
|
551
560
|
const text = (item as { text?: unknown }).text
|
|
552
561
|
if (typeof text === 'string') {
|
|
553
|
-
return { ...(item as Record<string, unknown>), text: sanitizeSystemText(text) }
|
|
562
|
+
return { ...(item as Record<string, unknown>), text: sanitizeSystemText(text, onError) }
|
|
554
563
|
}
|
|
555
564
|
}
|
|
556
565
|
return item
|
|
@@ -568,7 +577,7 @@ function prependClaudeCodeIdentity(system: unknown) {
|
|
|
568
577
|
return [identityBlock, ...sanitized]
|
|
569
578
|
}
|
|
570
579
|
|
|
571
|
-
function rewriteRequestPayload(body: string | undefined) {
|
|
580
|
+
function rewriteRequestPayload(body: string | undefined, onError?: (msg: string) => void) {
|
|
572
581
|
if (!body) return { body, modelId: undefined, reverseToolNameMap: new Map<string, string>() }
|
|
573
582
|
|
|
574
583
|
try {
|
|
@@ -589,7 +598,7 @@ function rewriteRequestPayload(body: string | undefined) {
|
|
|
589
598
|
}
|
|
590
599
|
|
|
591
600
|
// Rename system prompt
|
|
592
|
-
payload.system = prependClaudeCodeIdentity(payload.system)
|
|
601
|
+
payload.system = prependClaudeCodeIdentity(payload.system, onError)
|
|
593
602
|
|
|
594
603
|
// Rename tool_choice
|
|
595
604
|
if (
|
|
@@ -743,14 +752,6 @@ async function getFreshOAuth(
|
|
|
743
752
|
|
|
744
753
|
const AnthropicAuthPlugin: Plugin = async ({ client }) => {
|
|
745
754
|
return {
|
|
746
|
-
"experimental.chat.system.transform": async (input, output) => {
|
|
747
|
-
if (input.model.providerID !== ('anthropic')) return
|
|
748
|
-
const opencodePromptPart = output.system.findIndex(x => x?.includes('https://github.com/anomalyco/opencode'))
|
|
749
|
-
// Remove the OpenCode system prompt part if present
|
|
750
|
-
if (opencodePromptPart !== -1) {
|
|
751
|
-
output.system.splice(opencodePromptPart, 1)
|
|
752
|
-
}
|
|
753
|
-
},
|
|
754
755
|
auth: {
|
|
755
756
|
provider: 'anthropic',
|
|
756
757
|
async loader(
|
|
@@ -787,7 +788,11 @@ const AnthropicAuthPlugin: Plugin = async ({ client }) => {
|
|
|
787
788
|
.catch(() => undefined)
|
|
788
789
|
: undefined
|
|
789
790
|
|
|
790
|
-
const rewritten = rewriteRequestPayload(originalBody)
|
|
791
|
+
const rewritten = rewriteRequestPayload(originalBody, (msg) => {
|
|
792
|
+
client.tui.showToast({
|
|
793
|
+
body: { message: msg, variant: 'error' },
|
|
794
|
+
}).catch(() => {})
|
|
795
|
+
})
|
|
791
796
|
const headers = new Headers(init?.headers)
|
|
792
797
|
if (input instanceof Request) {
|
|
793
798
|
input.headers.forEach((v, k) => {
|
|
@@ -837,6 +842,7 @@ const AnthropicAuthPlugin: Plugin = async ({ client }) => {
|
|
|
837
842
|
message: `Switching from account ${rotated.fromLabel} to account ${rotated.toLabel}`,
|
|
838
843
|
variant: 'info',
|
|
839
844
|
},
|
|
845
|
+
|
|
840
846
|
}).catch(() => {})
|
|
841
847
|
const retryAuth = await getFreshOAuth(getAuth, client)
|
|
842
848
|
if (retryAuth) {
|
package/src/discord-utils.ts
CHANGED
|
@@ -2,19 +2,21 @@
|
|
|
2
2
|
// Handles markdown splitting for Discord's 2000-char limit, code block escaping,
|
|
3
3
|
// thread message sending, and channel metadata extraction from topic tags.
|
|
4
4
|
|
|
5
|
-
import
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
5
|
+
// Use namespace import for CJS interop — discord.js is CJS and its named
|
|
6
|
+
// exports aren't detectable by all ESM loaders (e.g. tsx/esbuild) because
|
|
7
|
+
// discord.js uses tslib's __exportStar which is opaque to static analysis.
|
|
8
|
+
import * as discord from 'discord.js'
|
|
9
|
+
import type {
|
|
10
|
+
APIInteractionGuildMember,
|
|
11
|
+
AutocompleteInteraction,
|
|
12
|
+
GuildMember as GuildMemberType,
|
|
13
|
+
Guild,
|
|
14
|
+
Message,
|
|
15
|
+
REST as RESTType,
|
|
16
|
+
TextChannel,
|
|
17
|
+
ThreadChannel,
|
|
16
18
|
} from 'discord.js'
|
|
17
|
-
|
|
19
|
+
const { ChannelType, GuildMember, MessageFlags, PermissionsBitField, REST, Routes } = discord
|
|
18
20
|
import type { OpencodeClient } from '@opencode-ai/sdk/v2'
|
|
19
21
|
import { discordApiUrl } from './discord-urls.js'
|
|
20
22
|
import { Lexer } from 'marked'
|
|
@@ -37,7 +39,7 @@ const discordLogger = createLogger(LogPrefix.DISCORD)
|
|
|
37
39
|
* Returns false if member is null or has the "no-kimaki" role (overrides all).
|
|
38
40
|
*/
|
|
39
41
|
export function hasKimakiBotPermission(
|
|
40
|
-
member:
|
|
42
|
+
member: GuildMemberType | APIInteractionGuildMember | null,
|
|
41
43
|
guild?: Guild | null,
|
|
42
44
|
): boolean {
|
|
43
45
|
if (!member) {
|
|
@@ -61,7 +63,7 @@ export function hasKimakiBotPermission(
|
|
|
61
63
|
}
|
|
62
64
|
|
|
63
65
|
function hasRoleByName(
|
|
64
|
-
member:
|
|
66
|
+
member: GuildMemberType | APIInteractionGuildMember,
|
|
65
67
|
roleName: string,
|
|
66
68
|
guild?: Guild | null,
|
|
67
69
|
): boolean {
|
|
@@ -89,7 +91,7 @@ function hasRoleByName(
|
|
|
89
91
|
* Check if the member has the "no-kimaki" role that blocks bot access.
|
|
90
92
|
* Separate from hasKimakiBotPermission so callers can show a specific error message.
|
|
91
93
|
*/
|
|
92
|
-
export function hasNoKimakiRole(member:
|
|
94
|
+
export function hasNoKimakiRole(member: GuildMemberType | null): boolean {
|
|
93
95
|
if (!member?.roles?.cache) {
|
|
94
96
|
return false
|
|
95
97
|
}
|
|
@@ -108,7 +110,7 @@ export async function reactToThread({
|
|
|
108
110
|
channelId,
|
|
109
111
|
emoji,
|
|
110
112
|
}: {
|
|
111
|
-
rest:
|
|
113
|
+
rest: RESTType
|
|
112
114
|
threadId: string
|
|
113
115
|
/** Parent channel ID where the thread starter message lives.
|
|
114
116
|
* If not provided, fetches the thread info from Discord API to resolve it. */
|
|
@@ -169,7 +171,7 @@ export async function archiveThread({
|
|
|
169
171
|
client,
|
|
170
172
|
archiveDelay = 0,
|
|
171
173
|
}: {
|
|
172
|
-
rest:
|
|
174
|
+
rest: RESTType
|
|
173
175
|
threadId: string
|
|
174
176
|
parentChannelId?: string
|
|
175
177
|
sessionId?: string
|
|
@@ -137,6 +137,17 @@ import { extractLeadingOpencodeCommand } from '../opencode-command-detection.js'
|
|
|
137
137
|
const logger = createLogger(LogPrefix.SESSION)
|
|
138
138
|
const discordLogger = createLogger(LogPrefix.DISCORD)
|
|
139
139
|
const DETERMINISTIC_CONTEXT_LIMIT = 100_000
|
|
140
|
+
const TOAST_SESSION_ID_REGEX = /\b(ses_[A-Za-z0-9]+)\b\s*$/u
|
|
141
|
+
|
|
142
|
+
function extractToastSessionId({ message }: { message: string }): string | undefined {
|
|
143
|
+
const match = message.match(TOAST_SESSION_ID_REGEX)
|
|
144
|
+
return match?.[1]
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function stripToastSessionId({ message }: { message: string }): string {
|
|
148
|
+
return message.replace(TOAST_SESSION_ID_REGEX, '').trimEnd()
|
|
149
|
+
}
|
|
150
|
+
|
|
140
151
|
const shouldLogSessionEvents =
|
|
141
152
|
process.env['KIMAKI_LOG_SESSION_EVENTS'] === '1' ||
|
|
142
153
|
process.env['KIMAKI_VITEST'] === '1'
|
|
@@ -1381,6 +1392,9 @@ export class ThreadSessionRuntime {
|
|
|
1381
1392
|
const sessionId = this.state?.sessionId
|
|
1382
1393
|
|
|
1383
1394
|
const eventSessionId = getOpencodeEventSessionId(event)
|
|
1395
|
+
const toastSessionId = event.type === 'tui.toast.show'
|
|
1396
|
+
? extractToastSessionId({ message: event.properties.message })
|
|
1397
|
+
: undefined
|
|
1384
1398
|
|
|
1385
1399
|
if (shouldLogSessionEvents) {
|
|
1386
1400
|
const eventDetails = (() => {
|
|
@@ -1412,6 +1426,7 @@ export class ThreadSessionRuntime {
|
|
|
1412
1426
|
}
|
|
1413
1427
|
|
|
1414
1428
|
const isGlobalEvent = event.type === 'tui.toast.show'
|
|
1429
|
+
const isScopedToastEvent = Boolean(toastSessionId)
|
|
1415
1430
|
|
|
1416
1431
|
// Drop events that don't match current session (stale events from
|
|
1417
1432
|
// previous sessions), unless it's a global event or a subtask session.
|
|
@@ -1420,6 +1435,11 @@ export class ThreadSessionRuntime {
|
|
|
1420
1435
|
return // stale event from previous session
|
|
1421
1436
|
}
|
|
1422
1437
|
}
|
|
1438
|
+
if (isScopedToastEvent && toastSessionId !== sessionId) {
|
|
1439
|
+
if (!this.getSubtaskInfoForSession(toastSessionId!)) {
|
|
1440
|
+
return
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1423
1443
|
|
|
1424
1444
|
if (isOpencodeSessionEventLogEnabled()) {
|
|
1425
1445
|
const eventLogResult = await appendOpencodeSessionEventLog({
|
|
@@ -2763,7 +2783,7 @@ export class ThreadSessionRuntime {
|
|
|
2763
2783
|
if (properties.variant === 'warning') {
|
|
2764
2784
|
return
|
|
2765
2785
|
}
|
|
2766
|
-
const toastMessage = properties.message.trim()
|
|
2786
|
+
const toastMessage = stripToastSessionId({ message: properties.message }).trim()
|
|
2767
2787
|
if (!toastMessage) {
|
|
2768
2788
|
return
|
|
2769
2789
|
}
|
|
@@ -14,6 +14,7 @@ import { initSentry, notifyError } from './sentry.js'
|
|
|
14
14
|
import { abbreviatePath } from './utils.js'
|
|
15
15
|
|
|
16
16
|
const logger = createPluginLogger('OPENCODE')
|
|
17
|
+
const TOAST_SESSION_MARKER_SEPARATOR = ' '
|
|
17
18
|
|
|
18
19
|
type PluginHooks = Awaited<ReturnType<Plugin>>
|
|
19
20
|
type SystemTransformHook = NonNullable<PluginHooks['experimental.chat.system.transform']>
|
|
@@ -54,6 +55,16 @@ function normalizeSystemPrompt({ system }: { system: string[] }): string {
|
|
|
54
55
|
return system.join('\n')
|
|
55
56
|
}
|
|
56
57
|
|
|
58
|
+
function appendToastSessionMarker({
|
|
59
|
+
message,
|
|
60
|
+
sessionId,
|
|
61
|
+
}: {
|
|
62
|
+
message: string
|
|
63
|
+
sessionId: string
|
|
64
|
+
}): string {
|
|
65
|
+
return `${message}${TOAST_SESSION_MARKER_SEPARATOR}${sessionId}`
|
|
66
|
+
}
|
|
67
|
+
|
|
57
68
|
function buildTurnContext({
|
|
58
69
|
input,
|
|
59
70
|
directory,
|
|
@@ -131,7 +142,12 @@ function writeSystemPromptDiffFile({
|
|
|
131
142
|
sessionId: string
|
|
132
143
|
beforePrompt: string
|
|
133
144
|
afterPrompt: string
|
|
134
|
-
}): Error | {
|
|
145
|
+
}): Error | {
|
|
146
|
+
additions: number
|
|
147
|
+
deletions: number
|
|
148
|
+
filePath: string
|
|
149
|
+
latestPromptPath: string
|
|
150
|
+
} {
|
|
135
151
|
const diff = buildPatch({
|
|
136
152
|
beforeText: beforePrompt,
|
|
137
153
|
afterText: afterPrompt,
|
|
@@ -141,7 +157,7 @@ function writeSystemPromptDiffFile({
|
|
|
141
157
|
const timestamp = new Date().toISOString().replaceAll(':', '-')
|
|
142
158
|
const sessionDir = path.join(getSystemPromptDiffDir({ dataDir }), sessionId)
|
|
143
159
|
const filePath = path.join(sessionDir, `${timestamp}.diff`)
|
|
144
|
-
const latestPromptPath = path.join(sessionDir, `${
|
|
160
|
+
const latestPromptPath = path.join(sessionDir, `${timestamp}.md`)
|
|
145
161
|
const fileContent = [
|
|
146
162
|
`Session: ${sessionId}`,
|
|
147
163
|
`Created: ${new Date().toISOString()}`,
|
|
@@ -156,11 +172,12 @@ function writeSystemPromptDiffFile({
|
|
|
156
172
|
fs.mkdirSync(sessionDir, { recursive: true })
|
|
157
173
|
fs.writeFileSync(filePath, fileContent)
|
|
158
174
|
// fs.writeFileSync(latestPromptPath, afterPrompt)
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
175
|
+
return {
|
|
176
|
+
additions: diff.additions,
|
|
177
|
+
deletions: diff.deletions,
|
|
178
|
+
filePath,
|
|
179
|
+
latestPromptPath,
|
|
180
|
+
}
|
|
164
181
|
},
|
|
165
182
|
catch: (error) => {
|
|
166
183
|
return new Error('Failed to write system prompt diff file', { cause: error })
|
|
@@ -257,10 +274,13 @@ async function handleSystemTransform({
|
|
|
257
274
|
body: {
|
|
258
275
|
variant: 'info',
|
|
259
276
|
title: 'Context cache discarded',
|
|
260
|
-
message:
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
`
|
|
277
|
+
message: appendToastSessionMarker({
|
|
278
|
+
sessionId,
|
|
279
|
+
message:
|
|
280
|
+
`system prompt changed since the previous message (+${diffFileResult.additions} / -${diffFileResult.deletions}). ` +
|
|
281
|
+
`Diff: \`${abbreviatePath(diffFileResult.filePath)}\`. ` +
|
|
282
|
+
`Latest prompt: \`${abbreviatePath(diffFileResult.latestPromptPath)}\``,
|
|
283
|
+
}),
|
|
264
284
|
},
|
|
265
285
|
})
|
|
266
286
|
}
|
package/src/utils.ts
CHANGED
|
@@ -3,7 +3,11 @@
|
|
|
3
3
|
// abort error detection, and date/time formatting helpers.
|
|
4
4
|
|
|
5
5
|
import os from 'node:os'
|
|
6
|
-
import
|
|
6
|
+
// Use namespace import for CJS interop — discord.js is CJS and its named
|
|
7
|
+
// exports aren't detectable by all ESM loaders (e.g. tsx/esbuild) because
|
|
8
|
+
// discord.js uses tslib's __exportStar which is opaque to static analysis.
|
|
9
|
+
import * as discord from 'discord.js'
|
|
10
|
+
const { PermissionsBitField } = discord
|
|
7
11
|
import type { BotMode } from './database.js'
|
|
8
12
|
import * as errore from 'errore'
|
|
9
13
|
|