@@ -92,7 +92,6 @@ import {
9292 appendSessionEventsSinceLastTimestamp ,
9393 getSessionEventSnapshot ,
9494 cancelSessionSleepForThread ,
95- upsertSessionSystemContext ,
9695} from '../database.js'
9796import * as orm from 'drizzle-orm'
9897import * as schema from '../schema.js'
@@ -130,6 +129,8 @@ import {
130129} from './model-utils.js'
131130import {
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