Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
/**
* Dispatcher — handles `WorkerOp` requests received over the message port.
*
* Lives in its own file (separate from `dbWorker.ts`) so tests can drive it
* directly with an in-memory Database and stubbed statements, without the
* worker_threads boilerplate.
*/
import type { Database } from 'better-sqlite3'
import { PreparedStatements, prepareStatements } from '../statements'
import { withBusyRetry } from './busyRetry'
import type {
LoadAllPendingApprovalsRow,
ModelSelectionWriteOutcome,
PendingApprovalRow,
PersistedSession,
PersistedSessionMessagePage,
PersistedSessionSummary,
ReapedSession,
SessionRow,
WorkerOp,
} from './protocol'
export interface DispatcherDeps {
db: Database
statements: PreparedStatements
}
export function createDispatcher(db: Database): DispatcherDeps {
return { db, statements: prepareStatements(db) }
}
function updateSessionSummaryAfterInsert(
statements: PreparedStatements,
message: {
session_id: string
role: string
tool_calls: string | null
timestamp: number
turn_number: number | null
}
): void {
statements.updateSessionSummaryAfterInsert.run({
id: message.session_id,
timestamp: message.timestamp,
turn_number: message.turn_number,
visible_message_delta:
message.role === 'user' || (message.role === 'assistant' && message.tool_calls === null)
? 1
: 0,
})
}
/**
* Strict ISO 8601 — `YYYY-MM-DD` optionally followed by `THH:MM[:SS[.sss]]`
* and a `Z`/`±HH:MM` offset. Rejects bare numeric strings ("1000000") that
* `Date.parse` would otherwise happily interpret as a four-digit year. The
* dispatcher is the last line of defense before raw SQL, so we fail hard
* here rather than at the REST/tool layer (which has its own checks).
*/
const ISO_8601_RE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2})?)?$/
export function parseIsoSinceOrThrow(raw: unknown): number | null {
if (raw === undefined || raw === null) return null
if (typeof raw !== 'string' || raw.length === 0) return null
if (!ISO_8601_RE.test(raw)) {
const err: Error & { code?: string } = new Error(
`fts_search_messages: invalid 'since' value: ${JSON.stringify(raw)} (expected ISO 8601 datetime)`
)
err.code = 'INVALID_ARGUMENT'
throw err
}
const ms = Date.parse(raw)
if (!Number.isFinite(ms)) {
const err: Error & { code?: string } = new Error(
`fts_search_messages: unparseable 'since' value: ${JSON.stringify(raw)}`
)
err.code = 'INVALID_ARGUMENT'
throw err
}
return ms / 1000
}
/**
* Execute a single worker op. Throws on unknown op kinds. Write ops are
* wrapped in `withBusyRetry`; reads run directly (`better-sqlite3` reads
* don't hit `SQLITE_BUSY` in WAL mode unless someone forced `journal_mode`
* back to `delete`).
*
* B4 fix — `dispatch` is now async because `withBusyRetry` is async. The
* inner SQL work (`tx.immediate()`) is still synchronous, so two concurrent
* `dispatch()` invocations cannot interleave SQL — they only interleave
* during the inter-retry sleep. The per-session FIFO chain in
* `PersistQueue.enqueueAsync` keeps ordering correct cross-message.
*/
export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unknown> {
const { db, statements: s } = deps
switch (op.kind) {
case 'ping':
return { pong: true }
case 'insert_session':
return withBusyRetry(() => {
const tx = db.transaction((row: SessionRow) => {
s.insertSession.run({
id: row.id,
session_key: row.session_key,
source: row.source,
user_id: row.user_id ?? null,
team_id: row.team_id ?? null,
channel_type: row.channel_type ?? null,
channel_id: row.channel_id ?? null,
thread_id: row.thread_id ?? null,
model: row.model ?? null,
model_selections: row.model_selections ?? null,
system_prompt_stable_hash: row.system_prompt_stable_hash ?? null,
parent_session_id: row.parent_session_id ?? null,
started_at: row.started_at,
last_activity_at: row.last_activity_at ?? row.started_at,
turn_count: row.turn_count ?? 0,
ended_at: row.ended_at ?? null,
end_reason: row.end_reason ?? null,
message_count: row.message_count ?? 0,
tool_call_count: row.tool_call_count ?? 0,
input_tokens: row.input_tokens ?? 0,
output_tokens: row.output_tokens ?? 0,
cache_read_tokens: row.cache_read_tokens ?? 0,
cache_write_tokens: row.cache_write_tokens ?? 0,
cache_tokens_reported: row.cache_tokens_reported ?? 0,
title: row.title ?? null,
state: row.state ?? 'idle',
active_task_id: row.active_task_id ?? null,
active_trace_context: row.active_trace_context ?? null,
})
})
tx.immediate(op.payload)
return { ok: true }
})
case 'update_session_state':
return withBusyRetry(() => {
const tx = db.transaction(() => {
// active_task_id: a string sets it; null/undefined pass NULL to the
// COALESCE (keeps current). The explicit clear below handles null.
s.updateSessionState.run({
id: op.sessionId,
state: op.state,
ended_at: op.endedAt ?? null,
end_reason: op.endReason ?? null,
active_task_id: op.activeTaskId ?? null,
active_trace_context: op.activeTraceContext ?? null,
clear_active_trace_context: op.activeTraceContext === null ? 1 : 0,
})
// D.1 — null means "clear". COALESCE can't clear, so run the
// dedicated statement in the SAME transaction (atomic with the state
// change — no window where state=idle but active_task_id is stale).
if (op.activeTaskId === null) {
s.clearSessionActiveTask.run({ id: op.sessionId })
}
})
tx.immediate()
return { ok: true }
})
case 'reap_processing_sessions': {
// D.2 — at boot, every session left in 'processing' has no live reporter
// (it died with the previous pod). Transition each to 'idle', clear its
// active_task_id, and append a synthetic error message to the open turn
// so the chat is usable again and the desktop sees the interruption.
//
// Chunked (security P0-3): a spam of processing sessions must not block
// boot in one giant transaction. One transaction per chunk; the SELECT
// runs inside it and sees committed state, so the loop terminates once
// no 'processing' rows remain.
const chunkSize = op.chunkSize ?? 500
const nowMs = op.nowEpoch
const reaped: ReapedSession[] = []
for (;;) {
const chunkReaped = await withBusyRetry(() => {
const tx = db.transaction(() => {
const sessions = s.selectProcessingSessions.all({ limit: chunkSize }) as Array<{
id: string
session_key: string
active_task_id: string | null
user_id: string | null
channel_type: string | null
channel_id: string | null
thread_id: string | null
}>
const out: ReapedSession[] = []
for (const sess of sessions) {
const agg = s.selectSessionMaxOrdinalTurn.get({ session_id: sess.id }) as {
max_ordinal: number
max_turn: number | null
}
// Synthetic assistant message on the open turn. The marker lives
// in content_parts JSON (machine-detectable) while finish_reason
// stays a conventional 'error' (cross-ref D.2 P3 — no overload of
// finish_reason, no non-existent error_code column).
s.insertMessage.run({
session_id: sess.id,
ordinal: agg.max_ordinal + 1,
role: 'assistant',
content: '[Task interrupted by server restart]',
content_parts: JSON.stringify({
kind: 'system_error',
error_code: 'POD_RESTART_DURING_EXECUTION',
synthetic: true,
}),
tool_call_id: null,
tool_calls: null,
tool_name: null,
timestamp: nowMs / 1000,
token_count: null,
finish_reason: 'error',
spillover_ref: null,
is_error: 1,
turn_number: agg.max_turn,
input_tokens: null,
output_tokens: null,
cache_read_tokens: null,
cache_write_tokens: null,
})
updateSessionSummaryAfterInsert(s, {
session_id: sess.id,
role: 'assistant',
tool_calls: null,
timestamp: nowMs / 1000,
turn_number: agg.max_turn,
})
s.updateSessionState.run({
id: sess.id,
state: 'idle',
ended_at: null,
end_reason: null,
active_task_id: null,
active_trace_context: null,
clear_active_trace_context: 1,
})
s.clearSessionActiveTask.run({ id: sess.id })
out.push({
sessionId: sess.id,
sessionKey: sess.session_key,
userId: sess.user_id,
channelType: sess.channel_type,
channelId: sess.channel_id,
threadId: sess.thread_id,
activeTaskId: sess.active_task_id,
reapedAt: nowMs,
})
}
return out
})
return tx.immediate()
})
if (chunkReaped.length === 0) break
reaped.push(...chunkReaped)
}
return reaped
}
case 'reap_awaiting_approval_sessions': {
// D.8 (F7) / S1 — at boot, transition stuck 'awaiting_approval' sessions to
// 'idle', delete the stale approval row(s), clear active_task_id, and append
// a synthetic error message so the chat is usable again and the desktop sees
// the interruption.
//
// Two modes, selected by op.includeLive:
// - includeLive=false (D.8 default): reap only sessions whose approval can
// no longer resolve (all pending_approvals expired, or the row was already
// swept leaving an orphan). Synthetic msg: APPROVAL_EXPIRED_DURING_DOWNTIME.
// - includeLive=true (S1, explicit operator recovery): reap EVERY
// 'awaiting_approval' session, live or expired. Normal boot keeps this
// false because live approval executors are reconstructed below.
//
// Runs at PHASE 1b (before approval rehydration) so loadAllPendingApprovals
// never re-hydrates an approval we just deleted. Chunked like D.2 so a
// backlog can't stall boot; the SELECT runs inside the tx and sees
// committed state, so the loop terminates once no eligible rows remain.
const chunkSize = op.chunkSize ?? 500
const nowMs = op.nowEpoch
const nowEpochSeconds = op.nowEpoch / 1000 // pending_approvals.expires_at is REAL seconds
const includeLive = op.includeLive ?? false
const syntheticContent = includeLive
? '[Approval interrupted by server restart]'
: '[Approval expired during server downtime]'
const syntheticErrorCode = includeLive
? 'APPROVAL_INTERRUPTED_BY_RESTART'
: 'APPROVAL_EXPIRED_DURING_DOWNTIME'
const reaped: ReapedSession[] = []
for (;;) {
const chunkReaped = await withBusyRetry(() => {
const tx = db.transaction(() => {
// The inverse orphan case is a pending row whose parent session is
// no longer awaiting the same task (for example, cancellation made
// the session idle but a transient SQLite failure left the delete
// behind). Prune those rows in the same transaction as the session
// reconciliation so PHASE 2 can only observe a coherent pair.
s.deleteUnrehydratablePendingApprovals.run()
const sessions = (
includeLive
? s.selectAwaitingApprovalSessions.all({ limit: chunkSize })
: s.selectExpiredAwaitingApprovalSessions.all({
now_epoch_seconds: nowEpochSeconds,
limit: chunkSize,
})
) as Array<{
id: string
session_key: string
active_task_id: string | null
user_id: string | null
channel_type: string | null
channel_id: string | null
thread_id: string | null
}>
const out: ReapedSession[] = []
for (const sess of sessions) {
const agg = s.selectSessionMaxOrdinalTurn.get({ session_id: sess.id }) as {
max_ordinal: number
max_turn: number | null
}
s.insertMessage.run({
session_id: sess.id,
ordinal: agg.max_ordinal + 1,
role: 'assistant',
content: syntheticContent,
content_parts: JSON.stringify({
kind: 'system_error',
error_code: syntheticErrorCode,
synthetic: true,
}),
tool_call_id: null,
tool_calls: null,
tool_name: null,
timestamp: nowMs / 1000,
token_count: null,
finish_reason: 'error',
spillover_ref: null,
is_error: 1,
turn_number: agg.max_turn,
input_tokens: null,
output_tokens: null,
cache_read_tokens: null,
cache_write_tokens: null,
})
updateSessionSummaryAfterInsert(s, {
session_id: sess.id,
role: 'assistant',
tool_calls: null,
timestamp: nowMs / 1000,
turn_number: agg.max_turn,
})
// Resolve the (expired) approval row(s) atomically with the state
// flip so PHASE 2's load_all_pending_approvals can't resurrect them.
// No-op for the orphan case (row already gone).
s.deletePendingApprovalsBySession.run({ session_id: sess.id })
s.updateSessionState.run({
id: sess.id,
state: 'idle',
ended_at: null,
end_reason: null,
active_task_id: null,
active_trace_context: null,
clear_active_trace_context: 1,
})
s.clearSessionActiveTask.run({ id: sess.id })
out.push({
sessionId: sess.id,
sessionKey: sess.session_key,
userId: sess.user_id,
channelType: sess.channel_type,
channelId: sess.channel_id,
threadId: sess.thread_id,
activeTaskId: sess.active_task_id,
reapedAt: nowMs,
})
}
return out
})
return tx.immediate()
})
if (chunkReaped.length === 0) break
reaped.push(...chunkReaped)
}
return reaped
}
case 'update_session_counters':
return withBusyRetry(() => {
const tx = db.transaction(() => {
s.updateSessionCounters.run({
id: op.sessionId,
message_count_delta: op.counters.messageCountDelta ?? 0,
tool_call_count_delta: op.counters.toolCallCountDelta ?? 0,
input_tokens_delta: op.counters.inputTokensDelta ?? 0,
output_tokens_delta: op.counters.outputTokensDelta ?? 0,
cache_read_tokens_delta: op.counters.cacheReadTokensDelta ?? 0,
cache_write_tokens_delta: op.counters.cacheWriteTokensDelta ?? 0,
cache_reported: op.counters.cacheReported ? 1 : 0,
})
})
tx.immediate()
return { ok: true }
})
case 'update_session_prompt_stable_hash':
return withBusyRetry(() => {
const tx = db.transaction(() => {
s.updateSessionPromptStableHash.run({
id: op.sessionId,
system_prompt_stable_hash: op.stableHash,
})
})
tx.immediate()
return { ok: true }
})
case 'update_session_model_selections':
return withBusyRetry(() => {
// #654 — compare-and-swap on `model_selection_revision`.
//
// Read-then-write inside ONE IMMEDIATE transaction. The worker is a
// single writer, but another replica may hold the same row, and
// `.immediate()` takes the write lock before the read, so no other
// process can commit between the check and the update.
//
// A missing row throws instead of acking: reporting `applied` for a
// selection that never reached disk would recreate exactly the
// fire-and-forget lie this change removes.
const tx = db.transaction((): ModelSelectionWriteOutcome => {
const row = s.selectSessionModelSelectionRevision.get({ id: op.sessionId }) as
{ model_selection_revision: number; model_selections: string | null } | undefined
if (!row) {
const err: Error & { code?: string } = new Error(
`update_session_model_selections: no session row for id=${op.sessionId}`
)
err.code = 'MODEL_SELECTION_SESSION_NOT_FOUND'
throw err
}
const current = row.model_selection_revision
if (
!Number.isSafeInteger(current) ||
current < 0 ||
current === Number.MAX_SAFE_INTEGER
) {
throw new Error('Invalid persisted model selection revision')
}
let modelSelections: Record<string, string>
try {
const parsed: unknown =
row.model_selections === null ? {} : JSON.parse(row.model_selections)
if (
!parsed ||
typeof parsed !== 'object' ||
Array.isArray(parsed) ||
Object.values(parsed).some(value => typeof value !== 'string')
)
throw new Error()
modelSelections = { ...parsed } as Record<string, string>
} catch {
throw new Error('Invalid persisted model selections')
}
if (op.expectedRevision !== undefined && op.expectedRevision !== current) {
return {
applied: false,
reason: 'model_selection_conflict',
modelSelectionRevision: current,
modelSelections,
}
}
const next = current + 1
// Merge the one requested provider in the durable row, never a stale
// full map from another replica's RAM (including legacy writes).
modelSelections = { ...modelSelections, [op.provider]: op.model }
s.updateSessionModelSelections.run({
id: op.sessionId,
model_selections: JSON.stringify(modelSelections),
model_selection_revision: next,
})
return { applied: true, modelSelectionRevision: next, modelSelections }
})
return tx.immediate()
})
case 'update_session_title':
// Spec 15 Fase B — unconditional overwrite (rename wins over the auto-title).
return withBusyRetry(() => {
const tx = db.transaction(() => {
s.updateSessionTitle.run({ id: op.sessionId, title: op.title })
})
tx.immediate()
return { ok: true }
})
case 'insert_message':
return withBusyRetry(() => {
const tx = db.transaction(() => {
s.insertMessage.run({
session_id: op.payload.session_id,
ordinal: op.payload.ordinal,
role: op.payload.role,
content: op.payload.content,
content_parts: op.payload.content_parts,
tool_call_id: op.payload.tool_call_id,
tool_calls: op.payload.tool_calls,
tool_name: op.payload.tool_name,
timestamp: op.payload.timestamp,
token_count: op.payload.token_count,
finish_reason: op.payload.finish_reason,
spillover_ref: op.payload.spillover_ref,
is_error: op.payload.is_error,
turn_number: op.payload.turn_number,
// Named-param bind requires every key present; default to NULL for
// callers that don't stamp per-turn usage (migration 005).
input_tokens: op.payload.input_tokens ?? null,
output_tokens: op.payload.output_tokens ?? null,
cache_read_tokens: op.payload.cache_read_tokens ?? null,
cache_write_tokens: op.payload.cache_write_tokens ?? null,
})
updateSessionSummaryAfterInsert(s, op.payload)
s.updateSessionCounters.run({
id: op.payload.session_id,
message_count_delta: 0,
tool_call_count_delta: op.payload.role === 'assistant' && op.payload.tool_calls ? 1 : 0,
input_tokens_delta: 0,
output_tokens_delta: 0,
cache_read_tokens_delta: 0,
cache_write_tokens_delta: 0,
cache_reported: 0,
})
})
tx.immediate()
return { ok: true }
})
case 'persist_turn_boundary':
// D3 (stateless-agents) — boundary message + session-state flip in ONE
// transaction. Mirrors the exact row/counter shape of `insert_message`
// plus the state semantics of `update_session_state` so a crash between
// the two writes is impossible by construction.
return withBusyRetry(() => {
const tx = db.transaction(() => {
s.insertMessage.run({
session_id: op.message.session_id,
ordinal: op.message.ordinal,
role: op.message.role,
content: op.message.content,
content_parts: op.message.content_parts,
tool_call_id: op.message.tool_call_id,
tool_calls: op.message.tool_calls,
tool_name: op.message.tool_name,
timestamp: op.message.timestamp,
token_count: op.message.token_count,
finish_reason: op.message.finish_reason,
spillover_ref: op.message.spillover_ref,
is_error: op.message.is_error,
turn_number: op.message.turn_number,
input_tokens: op.message.input_tokens ?? null,
output_tokens: op.message.output_tokens ?? null,
cache_read_tokens: op.message.cache_read_tokens ?? null,
cache_write_tokens: op.message.cache_write_tokens ?? null,
})
updateSessionSummaryAfterInsert(s, op.message)
s.updateSessionCounters.run({
id: op.message.session_id,
message_count_delta: 0,
tool_call_count_delta: op.message.role === 'assistant' && op.message.tool_calls ? 1 : 0,
input_tokens_delta: 0,
output_tokens_delta: 0,
cache_read_tokens_delta: 0,
cache_write_tokens_delta: 0,
cache_reported: 0,
})
s.updateSessionState.run({
id: op.sessionId,
state: op.state,
ended_at: null,
end_reason: null,
active_task_id: op.activeTaskId ?? null,
active_trace_context: op.activeTraceContext ?? null,
clear_active_trace_context: op.activeTraceContext === null ? 1 : 0,
})
// null means "clear" — COALESCE can't, so run the dedicated
// statement in the SAME transaction (see 'update_session_state').
if (op.activeTaskId === null) {
s.clearSessionActiveTask.run({ id: op.sessionId })
}
// Auto-title (spec 15) — turn 1 only carries a title. COALESCE inside
// the statement makes a retried turn 1 idempotent and preserves a
// rename. Run in the SAME transaction as the boundary message.
if (op.title !== undefined) {
s.setSessionTitleIfAbsent.run({ id: op.sessionId, title: op.title })
}
})
tx.immediate()
return { ok: true }
})
case 'replace_messages':
return withBusyRetry(() => {
const tx = db.transaction(() => {
s.deleteMessagesBySession.run(op.sessionId)
for (const m of op.messages) {
s.insertMessage.run({
session_id: m.session_id,
ordinal: m.ordinal,
role: m.role,
content: m.content,
content_parts: m.content_parts,
tool_call_id: m.tool_call_id,
tool_calls: m.tool_calls,
tool_name: m.tool_name,
timestamp: m.timestamp,
token_count: m.token_count,
finish_reason: m.finish_reason,
spillover_ref: m.spillover_ref,
is_error: m.is_error,
turn_number: m.turn_number,
input_tokens: m.input_tokens ?? null,
output_tokens: m.output_tokens ?? null,
cache_read_tokens: m.cache_read_tokens ?? null,
cache_write_tokens: m.cache_write_tokens ?? null,
})
}
s.recomputeSessionMessageSummary.run({ id: op.sessionId })
})
tx.immediate()
return { ok: true, count: op.messages.length }
})
case 'insert_pending_approval':
return withBusyRetry(() => {
const tx = db.transaction((row: PendingApprovalRow) => {
let sourceMessage = row.source_message
if (op.replaceRequestId) {
const previous = db
.prepare('SELECT * FROM pending_approvals WHERE request_id = ?')
.get(op.replaceRequestId) as PendingApprovalRow | undefined
if (
!previous ||
previous.session_id !== row.session_id ||
previous.task_id !== row.task_id ||
previous.task_budget !== 'legacy'
) {
throw new Error('Approval renewal binding mismatch')
}
sourceMessage = previous.source_message
db.prepare('DELETE FROM pending_approvals WHERE request_id = ?').run(
op.replaceRequestId
)
}
s.insertPendingApproval.run({
...row,
source_message: sourceMessage,
task_budget: row.task_budget ?? null,
// Legacy protocol payloads may omit this field. SQL NULL keeps
// that unknown consent scope exact when the approval rehydrates.
authorization_scope: row.authorization_scope ?? null,
})
if (op.markAwaitingApproval)
db.prepare('UPDATE sessions SET state = ? WHERE id = ?').run(
'awaiting_approval',
row.session_id
)
})
tx.immediate(op.payload)
return { ok: true }
})
case 'delete_pending_approval':
return withBusyRetry(() => {
const tx = db.transaction(() => {
s.deletePendingApproval.run(op.requestId)
})
tx.immediate()
return { ok: true }
})
case 'load_active_session': {
const sessionRow = s.selectSessionBySessionKey.get(op.sessionKey) as SessionRow | undefined
if (!sessionRow) return null
const messageRows = s.selectMessagesBySession.all(sessionRow.id)
const pendingRow = s.selectPendingApprovalBySession.get(sessionRow.id)
const persisted: PersistedSession = {
session: sessionRow,
messages: messageRows as PersistedSession['messages'],
pending_approval: (pendingRow ?? null) as PersistedSession['pending_approval'],
}
return persisted
}
case 'load_session_message_page': {
const sessionRow = s.selectSessionBySessionKey.get(op.sessionKey) as SessionRow | undefined
if (!sessionRow) return null
const limit =
op.limit === undefined ? -1 : Number.isInteger(op.limit) && op.limit > 0 ? op.limit : 0
const messageRows =
op.afterTurn !== undefined
? s.selectMessagesBySessionTurnsAfter.all({
session_id: sessionRow.id,
after_turn: op.afterTurn,
limit,
})
: op.beforeTurn !== undefined
? s.selectMessagesBySessionTurnsBefore.all({
session_id: sessionRow.id,
before_turn: op.beforeTurn,
limit,
})
: s.selectMessagesBySessionNewestTurns.all({
session_id: sessionRow.id,
limit,
})
const bounds = s.selectSessionTurnBounds.get({ session_id: sessionRow.id }) as
| {
first_turn_number: number | null
last_turn_number: number | null
}
| undefined
const pendingRow = s.selectPendingApprovalBySession.get(sessionRow.id) as
PendingApprovalRow | undefined
return {
session: sessionRow,
messages: messageRows as PersistedSessionMessagePage['messages'],
pending_approval: pendingRow
? {
request_id: pendingRow.request_id,
tool_name: pendingRow.tool_name,
reason: pendingRow.reason,
mcp_server_name: pendingRow.mcp_server_name,
}
: null,
total_turns: sessionRow.turn_count ?? 0,
first_turn_number: bounds?.first_turn_number ?? null,
last_turn_number: bounds?.last_turn_number ?? null,
last_activity_at: sessionRow.last_activity_at ?? sessionRow.started_at,
} satisfies PersistedSessionMessagePage
}
case 'list_sessions_by_prefix': {
const pattern = `${op.sessionKeyPrefix}%`
const sessionRows = s.selectSessionsByPrefix.all(pattern) as SessionRow[]
const result: PersistedSession[] = []
for (const row of sessionRows) {
const messageRows = s.selectMessagesBySession.all(row.id)
const pendingRow = s.selectPendingApprovalBySession.get(row.id)
result.push({
session: row,
messages: messageRows as PersistedSession['messages'],
pending_approval: (pendingRow ?? null) as PersistedSession['pending_approval'],
})
}
return result
}
case 'list_session_summaries_by_prefix': {
const prefixStart = op.sessionKeyPrefix
const prefixCharacters = Array.from(op.sessionKeyPrefix)
const finalCodePoint = prefixCharacters.at(-1)?.codePointAt(0)
if (finalCodePoint === undefined || finalCodePoint >= 0x10ffff) {
throw new Error('Session key prefix must have a finite lexicographic upper bound')
}
const prefixEnd = `${prefixCharacters
.slice(0, -1)
.join('')}${String.fromCodePoint(finalCodePoint + 1)}`
const agentScoped = op.agentScoped === true
const limit =
op.limit === undefined ? -1 : Number.isInteger(op.limit) && op.limit > 0 ? op.limit : 0
const rows = s.selectSessionSummariesByPrefix.all({
prefix_start: prefixStart,
prefix_end: prefixEnd,
user_id: op.userId,
agent_scoped: agentScoped ? 1 : 0,
limit,
cursor_updated_at: op.cursorUpdatedAt ?? null,
cursor_key: op.cursorKey ?? null,
}) as Array<
SessionRow & {
summary_last_activity_at: number
summary_turn_count: number
pending_request_id: string | null
pending_tool_name: string | null
pending_reason: string | null
pending_mcp_server_name: string | null
}
>
return rows.map(row => {
const {
summary_last_activity_at,
summary_turn_count,
pending_request_id,
pending_tool_name,
pending_reason,
pending_mcp_server_name,
...session
} = row
return {
session: session as SessionRow,
last_activity_at: summary_last_activity_at,
turn_count: summary_turn_count,
pending_approval:
pending_request_id && pending_tool_name
? {
request_id: pending_request_id,
tool_name: pending_tool_name,
reason: pending_reason,
mcp_server_name: pending_mcp_server_name,
}
: null,
} satisfies PersistedSessionSummary
})
}
case 'load_all_pending_approvals': {
const rows = s.selectPendingApprovalsAll.all() as Array<
PendingApprovalRow & {
session_key: string
session_user_id: string | null
session_channel_type: string | null
session_channel_id: string | null
session_thread_id: string | null
}
>
const out: LoadAllPendingApprovalsRow[] = []
for (const row of rows) {
const {
session_key,
session_user_id,
session_channel_type,
session_channel_id,
session_thread_id,
...approval
} = row
out.push({
approval: approval as PendingApprovalRow,
session_key,
ownership: {
user_id: session_user_id,
channel_type: session_channel_type,
channel_id: session_channel_id,
thread_id: session_thread_id,
},
})
}
return out
}
case 'sweep_expired':
return withBusyRetry(() => {
const tx = db.transaction(() => {
const expiredApprovals = s.sweepExpiredApprovals.run(op.nowEpoch)
const expiredSessions = s.sweepEndedSessions.run(op.nowEpoch - op.ttlSeconds)
return {
approvals_removed: expiredApprovals.changes,
sessions_removed: expiredSessions.changes,
}
})
return tx.immediate()
})
case 'fts_search': {
const rows = op.userId
? s.ftsSearchByUser.all({ query: op.query, limit: op.limit, user_id: op.userId })
: s.ftsSearch.all({ query: op.query, limit: op.limit })
return rows
}
case 'fts_search_messages': {
// T3.1 — `since` is propagated as a SQLite REAL (UNIX seconds) so the
// comparison with `m.timestamp` (stored as REAL too) is a direct numeric
// compare instead of lexical text. The handler converts ISO strings.
//
// B11 fix: `Date.parse` accepts numeric strings like "1000000" and
// interprets them as a year — silently dropping a meaningful filter.
// Reject anything that doesn't look like ISO 8601 BEFORE parsing so the
// caller sees a hard error instead of a phantom result set.
const sinceEpoch = parseIsoSinceOrThrow(op.since)
const rows = s.ftsSearchMessages.all({
query: op.query,
user_id: op.userId,
channel_type: op.channelType ?? null,
since: sinceEpoch,
limit: op.limit,
})
return rows
}
case 'sweep_closed_sessions':
// SQLite reads LIMIT 0 as "delete nothing" and a negative LIMIT as "no
// limit"; either would break the bounded-batch contract silently.
if (!Number.isSafeInteger(op.limit) || op.limit <= 0) {
throw new Error('sweep_closed_sessions: limit must be a positive integer')
}
return withBusyRetry(() => {
const tx = db.transaction(() => {
const params = { cutoff: op.cutoffEpoch, limit: op.limit }
const deletedMessages = s.sweepClosedSessionMessages.run(params).changes
const deletedSessions =
deletedMessages === 0 ? s.sweepClosedSessionsEmpty.run(params).changes : 0
return { deleted_messages: deletedMessages, deleted_sessions: deletedSessions }
})
return tx.immediate()
})
case 'integrity_check': {
const row = s.integrityCheck.get() as { integrity_check?: string } | undefined
return { ok: row?.integrity_check === 'ok', detail: row?.integrity_check ?? 'unknown' }
}
case 'checkpoint': {
const result = db.pragma('wal_checkpoint(PASSIVE)')
return result
}
case 'shutdown':
// Closing happens in the worker entry; dispatcher just returns ack.
return { ok: true }
default: {
const exhaustive: never = op
throw new Error(`Unknown op kind: ${JSON.stringify(exhaustive)}`)
}
}
}