Skip to content

Commit 4eadc97

Browse files
committed
Store Kimaki system instructions through native OpenCode session entries.
Write the session-stable Kimaki prompt to instruction entry kimaki before chat or command dispatch. Stop submission when preparation fails and avoid repeating the write within one runtime. Remove the SQLite context table definition, query helpers, and plugin-side prompt reconstruction. Keep dynamic context hooks separate. Cover the instruction key and published 256 KiB payload limit. Preserve notes about pending per-input model selection support in anomalyco/opencode#48356. Related to #220. Session: ses_f73cb3f4dffeM3OEPTncCzysNU
1 parent 1eefe63 commit 4eadc97

8 files changed

Lines changed: 111 additions & 168 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
'kimaki': patch
3+
---
4+
5+
Inject the Kimaki system prompt through OpenCode v2 `session.instructions.entry.put`.
6+
7+
v2 `session.prompt` and `session.command` have no `system` field. Kimaki now writes the full session-stable prompt as instruction entry `kimaki` after session create. Chat, slash commands, tools, and compaction all see it. The sqlite `session_system_contexts` side channel and the plugin rebuild of that prompt are gone.
8+
9+
Kimaki now uses published OpenCode **2.0.2** (`@opencode/cli`, `@opencode/client`, `@opencode/plugin`) so the instruction-entry size limit is 256 KiB.

‎cli/src/database.ts‎

Lines changed: 0 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1428,60 +1428,6 @@ export async function deleteStaleForumSyncConfigs({ appId, forumChannelId, outpu
14281428
))
14291429
}
14301430

1431-
export type SessionSystemContextPayload = {
1432-
channelId?: string
1433-
guildId?: string
1434-
threadId?: string
1435-
channelTopic?: string
1436-
agents?: Array<{ name: string; description?: string }>
1437-
userId?: string
1438-
parentSessionId?: string
1439-
scheduledTask?: {
1440-
taskId?: number
1441-
scheduleKind: 'at' | 'cron'
1442-
cronExpr?: string | null
1443-
timezone?: string | null
1444-
}
1445-
dataDir?: string
1446-
critiqueEnabled?: boolean
1447-
}
1448-
1449-
export async function upsertSessionSystemContext({
1450-
sessionId,
1451-
payload,
1452-
}: {
1453-
sessionId: string
1454-
payload: SessionSystemContextPayload
1455-
}) {
1456-
const db = await getDb()
1457-
const encoded = JSON.stringify(payload)
1458-
await db.insert(schema.session_system_contexts)
1459-
.values({ session_id: sessionId, payload: encoded })
1460-
.onConflictDoUpdate({
1461-
target: schema.session_system_contexts.session_id,
1462-
set: { payload: encoded, updated_at: new Date() },
1463-
})
1464-
}
1465-
1466-
export async function getSessionSystemContext(sessionId: string) {
1467-
const db = await getDb()
1468-
const row = await db.query.session_system_contexts.findFirst({
1469-
where: { session_id: sessionId },
1470-
})
1471-
if (!row) return null
1472-
try {
1473-
return JSON.parse(row.payload) as SessionSystemContextPayload
1474-
} catch (cause) {
1475-
return new Error('Invalid session system context payload', { cause })
1476-
}
1477-
}
1478-
1479-
export async function deleteSessionSystemContext(sessionId: string) {
1480-
const db = await getDb()
1481-
await db.delete(schema.session_system_contexts)
1482-
.where(orm.eq(schema.session_system_contexts.session_id, sessionId))
1483-
}
1484-
14851431
export async function createIpcRequest({ type, sessionId, threadId, payload }: { type: IpcRequestType; sessionId: string; threadId: string; payload: string }) {
14861432
const db = await getDb()
14871433
const [row] = await db.insert(schema.ipc_requests).values({ type, session_id: sessionId, thread_id: threadId, payload }).returning()

‎cli/src/kimaki-opencode-plugin/index.ts‎

Lines changed: 0 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,8 @@ import dedent from 'string-dedent'
1111
import type {
1212
createIpcRequest,
1313
getIpcRequestById,
14-
getSessionSystemContext,
1514
getThreadIdBySessionId,
1615
upsertSessionSleep,
17-
deleteSessionSystemContext,
1816
} from '../database.ts'
1917
import type { setDataDir } from '../config.ts'
2018
import type { setPluginLogFilePath } from '../plugin-logger.ts'
@@ -47,8 +45,6 @@ type DatabaseModule = {
4745
createIpcRequest: typeof createIpcRequest
4846
getIpcRequestById: typeof getIpcRequestById
4947
upsertSessionSleep: typeof upsertSessionSleep
50-
getSessionSystemContext: typeof getSessionSystemContext
51-
deleteSessionSystemContext: typeof deleteSessionSystemContext
5248
}
5349

5450
type TaskScheduleModule = {
@@ -309,60 +305,13 @@ export default Plugin.define({
309305
})) {
310306
if (event.type !== 'session.deleted') continue
311307
sessions.delete(event.data.sessionID)
312-
const database = await loadDatabaseModule()
313-
await database.deleteSessionSystemContext(event.data.sessionID)
314308
}
315309
} catch {
316310
// aborted on plugin unload
317311
}
318312
})()
319313

320314
await ctx.session.hook('context', async (event) => {
321-
const { getOpencodeSystemMessage } = (await import(
322-
siblingModuleHref('system-message')
323-
)) as {
324-
getOpencodeSystemMessage: (input: {
325-
sessionId: string
326-
channelId?: string
327-
guildId?: string
328-
threadId?: string
329-
channelTopic?: string
330-
agents?: Array<{ name: string; description?: string }>
331-
userId?: string
332-
parentSessionId?: string
333-
scheduledTask?: {
334-
taskId?: number
335-
scheduleKind: 'at' | 'cron'
336-
cronExpr?: string | null
337-
timezone?: string | null
338-
}
339-
dataDir?: string
340-
critiqueEnabled?: boolean
341-
}) => string
342-
}
343-
const database = await loadDatabaseModule()
344-
const stored = await database.getSessionSystemContext(event.sessionID)
345-
if (stored instanceof Error) {
346-
logger.warn('session system context read failed', stored)
347-
}
348-
const context = stored instanceof Error || stored === null ? undefined : stored
349-
pushSystemText(
350-
event,
351-
getOpencodeSystemMessage({
352-
sessionId: event.sessionID,
353-
channelId: context?.channelId,
354-
guildId: context?.guildId,
355-
threadId: context?.threadId,
356-
channelTopic: context?.channelTopic,
357-
agents: context?.agents,
358-
userId: context?.userId,
359-
parentSessionId: context?.parentSessionId,
360-
scheduledTask: context?.scheduledTask,
361-
dataDir: context?.dataDir || process.env.KIMAKI_DATA_DIR,
362-
critiqueEnabled: context?.critiqueEnabled,
363-
}),
364-
)
365-
366315
const state = getContextSession(event.sessionID)
367316
const userText = latestUserText(event.messages)
368317
if (userText.includes(TUTORIAL_WELCOME_TEXT)) {

‎cli/src/schema.sql‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -195,12 +195,6 @@ CREATE TABLE IF NOT EXISTS `session_start_sources` (
195195
CONSTRAINT `fk_session_start_sources_scheduled_task_id_scheduled_tasks_id_fk` FOREIGN KEY (`scheduled_task_id`) REFERENCES `scheduled_tasks`(`id`) ON UPDATE CASCADE ON DELETE SET NULL
196196
);
197197

198-
CREATE TABLE IF NOT EXISTS `session_system_contexts` (
199-
`session_id` text PRIMARY KEY,
200-
`payload` text NOT NULL,
201-
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP NOT NULL
202-
);
203-
204198
CREATE TABLE IF NOT EXISTS `thread_sessions` (
205199
`thread_id` text PRIMARY KEY,
206200
`session_id` text NOT NULL,

‎cli/src/schema.ts‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -277,12 +277,6 @@ export const session_sleeps = sqliteCore.sqliteTable('session_sleeps', {
277277
sqliteCore.index('session_sleeps_status_wake_at_idx').on(table.status, table.wake_at),
278278
])
279279

280-
export const session_system_contexts = sqliteCore.sqliteTable('session_system_contexts', {
281-
session_id: sqliteCore.text('session_id').primaryKey().notNull(),
282-
payload: sqliteCore.text('payload').notNull(),
283-
updated_at: datetime('updated_at').notNull().default(orm.sql`CURRENT_TIMESTAMP`).$onUpdate(() => new Date()),
284-
})
285-
286280
export const ipc_requests = sqliteCore.sqliteTable('ipc_requests', {
287281
id: sqliteCore.text('id').primaryKey().notNull().$defaultFn(() => crypto.randomUUID()),
288282
type: sqliteCore.text('type', { enum: ['file_upload', 'action_buttons'] }).notNull(),
@@ -321,7 +315,6 @@ export const relations = defineRelations({
321315
session_start_sources,
322316
forum_sync_configs,
323317
session_sleeps,
324-
session_system_contexts,
325318
ipc_requests,
326319
}, (r) => ({
327320
thread_sessions: {

‎cli/src/session-handler/thread-session-runtime.ts‎

Lines changed: 66 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,6 @@ import {
9292
appendSessionEventsSinceLastTimestamp,
9393
getSessionEventSnapshot,
9494
cancelSessionSleepForThread,
95-
upsertSessionSystemContext,
9695
} from '../database.js'
9796
import * as orm from 'drizzle-orm'
9897
import * as schema from '../schema.js'
@@ -130,6 +129,8 @@ import {
130129
} from './model-utils.js'
131130
import {
132131
getOpencodePromptContext,
132+
getOpencodeSystemMessage,
133+
KIMAKI_INSTRUCTION_ENTRY_KEY,
133134
type AgentInfo,
134135
type RepliedMessageContext,
135136
type WorktreeInfo,
@@ -3875,10 +3876,17 @@ export class ThreadSessionRuntime {
38753876
}
38763877
const resolvedAgent = agentResult.agentPreference
38773878
const availableAgents = agentResult.agents
3878-
await this.persistSessionSystemContext({
3879+
const systemWriteResult = await this.persistSessionSystemInstructions({
3880+
client: getClient(),
38793881
sessionId: session.id,
38803882
agents: availableAgents,
38813883
})
3884+
if (systemWriteResult instanceof Error) {
3885+
await cleanupOnError(
3886+
`✗ Failed to prepare session system prompt: ${systemWriteResult.message}`,
3887+
)
3888+
return
3889+
}
38823890
releaseCurrentThreadIngress()
38833891

38843892
await this.persistIngressVariant({
@@ -4028,6 +4036,7 @@ export class ThreadSessionRuntime {
40284036
...images,
40294037
]
40304038

4039+
// TODO(anomalyco/opencode#48356): Pass agent/model/variant on prompt instead of switching session-wide selection here.
40314040
if (resolvedAgent) {
40324041
await getClient().session.switchAgent({
40334042
sessionID: session.id,
@@ -4933,10 +4942,6 @@ export class ThreadSessionRuntime {
49334942
}
49344943
const earlyAgentPreference = earlyAgentResult.agentPreference
49354944
const earlyAvailableAgents = earlyAgentResult.agents
4936-
await this.persistSessionSystemContext({
4937-
sessionId: session.id,
4938-
agents: earlyAvailableAgents,
4939-
})
49404945

49414946
await this.persistIngressVariant({
49424947
sessionId: session.id,
@@ -5073,6 +5078,31 @@ export class ThreadSessionRuntime {
50735078
}
50745079
return fetched.topic?.trim() || undefined
50755080
})()
5081+
const systemWriteResult = await this.persistSessionSystemInstructions({
5082+
client: getClient(),
5083+
sessionId: session.id,
5084+
agents: earlyAvailableAgents,
5085+
channelTopic,
5086+
})
5087+
if (systemWriteResult instanceof Error) {
5088+
logger.error(
5089+
`[DISPATCH] Failed to persist system instructions for session ${session.id}: ${systemWriteResult.message}`,
5090+
)
5091+
void notifyError(
5092+
systemWriteResult,
5093+
'Failed to persist system instructions before prompt',
5094+
)
5095+
this.stopTyping()
5096+
await sendThreadMessage(
5097+
this.thread,
5098+
`✗ Failed to prepare session system prompt: ${systemWriteResult.message}`,
5099+
{ flags: NOTIFY_MESSAGE_FLAGS },
5100+
)
5101+
await this.dispatchAction(() => {
5102+
return this.tryDrainQueue({ showIndicator: true })
5103+
})
5104+
return
5105+
}
50765106
const worktreeChanged = this.consumeWorktreePromptChange(worktree)
50775107
const syntheticContext = getOpencodePromptContext({
50785108
sessionId: session.id,
@@ -5137,27 +5167,6 @@ export class ThreadSessionRuntime {
51375167
threadName: this.thread.name || undefined,
51385168
repliedMessage: input.repliedMessage,
51395169
})
5140-
const systemWriteResult = await this.persistSessionSystemContext({
5141-
sessionId: session.id,
5142-
agents: earlyAvailableAgents,
5143-
channelTopic,
5144-
})
5145-
if (systemWriteResult instanceof Error) {
5146-
logger.error(
5147-
`[DISPATCH] Failed to persist system context for command session ${session.id}: ${systemWriteResult.message}`,
5148-
)
5149-
void notifyError(
5150-
systemWriteResult,
5151-
'Failed to persist system context before session.command',
5152-
)
5153-
this.stopTyping()
5154-
await sendThreadMessage(
5155-
this.thread,
5156-
`✗ Failed to prepare command system prompt: ${systemWriteResult.message}`,
5157-
{ flags: NOTIFY_MESSAGE_FLAGS },
5158-
)
5159-
return false
5160-
}
51615170
const commandResponse = await getClient().session.command(
51625171
{
51635172
sessionID: session.id,
@@ -5253,6 +5262,7 @@ export class ThreadSessionRuntime {
52535262
.filter((part) => part.type === 'text')
52545263
.map((part) => part.text)
52555264
.join('\n')
5265+
// TODO(anomalyco/opencode#48356): Share prompt-option submission with direct ingress once selection is bound to queued input.
52565266
const promptResponse = await getClient().session.prompt({
52575267
sessionID: session.id,
52585268
text: promptText,
@@ -5288,6 +5298,9 @@ export class ThreadSessionRuntime {
52885298
// ── Session Ensure ──────────────────────────────────────────
52895299
// Creates or reuses the OpenCode session for this thread.
52905300

5301+
/** Session IDs that already have the Kimaki instruction entry. */
5302+
private sessionSystemInstructionsWritten = new Set<string>()
5303+
52915304
/** Cached per-session scheduled task info for the system message. */
52925305
private scheduledTaskContextCache = new Map<
52935306
string,
@@ -5334,45 +5347,52 @@ export class ThreadSessionRuntime {
53345347
return context
53355348
}
53365349

5337-
private async persistSessionSystemContext({
5350+
private async persistSessionSystemInstructions({
5351+
client,
53385352
sessionId,
53395353
agents,
53405354
channelTopic,
53415355
}: {
5356+
client: OpencodeClient
53425357
sessionId: string
53435358
agents: AgentInfo[]
53445359
channelTopic?: string
53455360
}) {
5361+
if (this.sessionSystemInstructionsWritten.has(sessionId)) return null
53465362
const topic = channelTopic ?? await (async () => {
53475363
if (this.thread.parent?.type === ChannelType.GuildText) {
53485364
return this.thread.parent.topic?.trim() || undefined
53495365
}
53505366
return undefined
53515367
})()
5352-
const result = await upsertSessionSystemContext({
5368+
const value = getOpencodeSystemMessage({
53535369
sessionId,
5354-
payload: {
5355-
channelId: this.channelId,
5356-
guildId: this.thread.guildId,
5357-
threadId: this.thread.id,
5358-
channelTopic: topic,
5359-
agents,
5360-
userId: this.state?.sessionUserId,
5361-
parentSessionId: this.state?.parentSessionId,
5362-
scheduledTask: await this.resolveScheduledTaskContext(sessionId),
5363-
dataDir: getDataDir(),
5364-
critiqueEnabled: store.getState().critiqueEnabled,
5365-
},
5366-
}).catch((cause) => {
5367-
return cause instanceof Error
5368-
? cause
5369-
: new Error(String(cause), { cause })
5370+
channelId: this.channelId,
5371+
guildId: this.thread.guildId,
5372+
threadId: this.thread.id,
5373+
channelTopic: topic,
5374+
agents,
5375+
userId: this.state?.sessionUserId,
5376+
parentSessionId: this.state?.parentSessionId,
5377+
scheduledTask: await this.resolveScheduledTaskContext(sessionId),
5378+
dataDir: getDataDir(),
5379+
critiqueEnabled: store.getState().critiqueEnabled,
53705380
})
5381+
const result = await client.session.instructions.entry.put({
5382+
sessionID: sessionId,
5383+
key: KIMAKI_INSTRUCTION_ENTRY_KEY,
5384+
value,
5385+
}).catch((cause) => new OpenCodeSdkError({
5386+
operation: 'session.instructions.entry.put',
5387+
cause,
5388+
}))
53715389
if (result instanceof Error) {
53725390
logger.warn(
5373-
`[SYSTEM CONTEXT] Failed to persist for session ${sessionId}: ${result.message}`,
5391+
`[SYSTEM INSTRUCTIONS] Failed to persist for session ${sessionId}: ${result.message}`,
53745392
)
5393+
return result
53755394
}
5395+
this.sessionSystemInstructionsWritten.add(sessionId)
53765396
return result
53775397
}
53785398

0 commit comments

Comments
 (0)