minicode-ai 0.28.0 → 0.30.0

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.
@@ -0,0 +1,397 @@
1
+ import type { Database } from "bun:sqlite"
2
+ import { randomUUID } from "node:crypto"
3
+ import { assertWriterEpochInTxn, openSessionHandle, sessionRowExistsInTxn } from "./schema.ts"
4
+
5
+ export type RunStatus = "CREATED" | "RUNNING" | "COMPLETED" | "INTERRUPTED" | "FAILED"
6
+
7
+ export const RUN_TERMINAL: ReadonlySet<string> = new Set(["COMPLETED", "INTERRUPTED", "FAILED"])
8
+
9
+ export interface RunRow {
10
+ run_id: string
11
+ session_id: string
12
+ thread_id: string
13
+ status: RunStatus
14
+ started_at: number
15
+ ended_at: number | null
16
+ last_persisted_seq: number
17
+ pending_tool_ids: string
18
+ recovery_status: string | null
19
+ takeover_epoch: number | null
20
+ created_at: number
21
+ }
22
+
23
+ const RUN_ID_RE = /^run_[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
24
+
25
+ export function isRunId(value: unknown): value is string {
26
+ return typeof value === "string" && RUN_ID_RE.test(value)
27
+ }
28
+
29
+ export function allocateRunId(): string {
30
+ return `run_${randomUUID()}`
31
+ }
32
+
33
+ export class RunStatusError extends Error {
34
+ readonly code = "RUN_INVALID_TRANSITION"
35
+ constructor(runId: string, from: string, to: string) {
36
+ super(`[run] RUN_INVALID_TRANSITION ${runId}: ${from} → ${to} refused`)
37
+ this.name = "RunStatusError"
38
+ }
39
+ }
40
+
41
+ export class RunTerminalConflictError extends Error {
42
+ readonly code = "RUN_TERMINAL_CONFLICT"
43
+ constructor(runId: string, from: string, to: string) {
44
+ super(
45
+ `[run] RUN_TERMINAL_CONFLICT ${runId}: already terminal ${from}, refusing conflicting ${to} (first terminal wins)`,
46
+ )
47
+ this.name = "RunTerminalConflictError"
48
+ }
49
+ }
50
+
51
+ export class RunRunningExistsError extends Error {
52
+ readonly code = "RUNNING_EXISTS"
53
+ constructor(sessionId: string) {
54
+ super(`[run] RUNNING_EXISTS ${sessionId}: a RUNNING run already holds this session`)
55
+ this.name = "RunRunningExistsError"
56
+ }
57
+ }
58
+
59
+ export class RunCursorError extends Error {
60
+ readonly code: "RUN_CURSOR_BACKWARD" | "RUN_CURSOR_BEYOND_HEAD" | "RUN_CURSOR_FOREIGN"
61
+ constructor(code: RunCursorError["code"], runId: string, detail: string) {
62
+ super(`[run] ${code} ${runId}: ${detail}`)
63
+ this.name = "RunCursorError"
64
+ this.code = code
65
+ }
66
+ }
67
+
68
+ export class RunPendingError extends Error {
69
+ readonly code = "RUN_PENDING_MALFORMED"
70
+ constructor(detail: string) {
71
+ super(`[run] RUN_PENDING_MALFORMED: ${detail}`)
72
+ this.name = "RunPendingError"
73
+ }
74
+ }
75
+
76
+ function rowToRun(row: RunRow): RunRow {
77
+ return { ...row }
78
+ }
79
+
80
+ const RUN_COLUMNS =
81
+ "run_id, session_id, thread_id, status, started_at, ended_at, last_persisted_seq, pending_tool_ids, recovery_status, takeover_epoch, created_at"
82
+
83
+ export function getRun(runId: string, cwd?: string): RunRow | null {
84
+ const db = openSessionHandle(cwd)
85
+ try {
86
+ const row = db
87
+ .prepare(`SELECT ${RUN_COLUMNS} FROM runs WHERE run_id = ?`)
88
+ .get(runId) as RunRow | null
89
+ return row ? rowToRun(row) : null
90
+ } finally {
91
+ db.close()
92
+ }
93
+ }
94
+
95
+ export function listSessionRuns(sessionId: string, cwd?: string): RunRow[] {
96
+ const db = openSessionHandle(cwd)
97
+ try {
98
+ return (
99
+ db
100
+ .prepare(`SELECT ${RUN_COLUMNS} FROM runs WHERE session_id = ? ORDER BY started_at`)
101
+ .all(sessionId) as RunRow[]
102
+ ).map(rowToRun)
103
+ } finally {
104
+ db.close()
105
+ }
106
+ }
107
+
108
+ export function getActiveRun(sessionId: string, cwd?: string): RunRow | null {
109
+ const db = openSessionHandle(cwd)
110
+ try {
111
+ const row = db
112
+ .prepare(
113
+ `SELECT ${RUN_COLUMNS} FROM runs WHERE session_id = ? AND status = 'RUNNING' LIMIT 1`,
114
+ )
115
+ .get(sessionId) as RunRow | null
116
+ return row ? rowToRun(row) : null
117
+ } finally {
118
+ db.close()
119
+ }
120
+ }
121
+
122
+ export function assessRunRecoveryStatus(run: RunRow): "NONE" | "UNKNOWN" {
123
+ if (run.recovery_status === "UNKNOWN") return "UNKNOWN"
124
+ if (run.status === "RUNNING") return "UNKNOWN"
125
+ return "NONE"
126
+ }
127
+
128
+ function validatePendingToolIds(value: unknown): string {
129
+ if (!Array.isArray(value)) throw new RunPendingError("pending_tool_ids must be an array")
130
+ if (value.length > 256) throw new RunPendingError("pending_tool_ids exceeds 256 entries")
131
+ for (const entry of value) {
132
+ if (typeof entry !== "string" || entry.length === 0 || entry.length > 512) {
133
+ throw new RunPendingError("pending_tool_ids entries must be non-empty strings ≤512 chars")
134
+ }
135
+ }
136
+ return JSON.stringify(value)
137
+ }
138
+
139
+ export function createRun(
140
+ sessionId: string,
141
+ threadId: string,
142
+ cwd?: string,
143
+ opts?: { runId?: string; pendingToolIds?: unknown; expectedEpoch?: number },
144
+ ): RunRow {
145
+ const db = openSessionHandle(cwd)
146
+ try {
147
+ return db.transaction(() => {
148
+ if (opts?.expectedEpoch !== undefined)
149
+ assertWriterEpochInTxn(db, sessionId, opts.expectedEpoch)
150
+ if (!sessionRowExistsInTxn(db, sessionId)) throw new Error(`session not found: ${sessionId}`)
151
+ const thread = db
152
+ .prepare("SELECT thread_id FROM threads WHERE session_id = ? AND thread_id = ?")
153
+ .get(sessionId, threadId) as { thread_id: string } | null
154
+ if (!thread) throw new Error(`thread not found: ${sessionId}/${threadId}`)
155
+ const runId = opts?.runId ?? allocateRunId()
156
+ if (!isRunId(runId)) throw new Error(`invalid run id: ${opts?.runId}`)
157
+ const pending =
158
+ opts?.pendingToolIds !== undefined ? validatePendingToolIds(opts.pendingToolIds) : "[]"
159
+ const now = Date.now()
160
+ const headRow = db
161
+ .prepare("SELECT MAX(seq) AS m FROM messages WHERE session_id = ? AND thread_id = ?")
162
+ .get(sessionId, threadId) as { m: number | null } | null
163
+ const head = Math.max(headRow?.m ?? -1, 0)
164
+ const epochRow = db
165
+ .prepare("SELECT writer_epoch AS epoch FROM sessions WHERE id = ?")
166
+ .get(sessionId) as {
167
+ epoch: number
168
+ }
169
+ db.prepare(
170
+ "INSERT INTO runs (run_id, session_id, thread_id, status, started_at, ended_at, last_persisted_seq, pending_tool_ids, recovery_status, takeover_epoch, created_at) VALUES (?, ?, ?, 'CREATED', ?, NULL, ?, ?, 'NONE', ?, ?)",
171
+ ).run(runId, sessionId, threadId, now, head, pending, epochRow.epoch, now)
172
+ return rowToRun({
173
+ run_id: runId,
174
+ session_id: sessionId,
175
+ thread_id: threadId,
176
+ status: "CREATED",
177
+ started_at: now,
178
+ ended_at: null,
179
+ last_persisted_seq: head,
180
+ pending_tool_ids: pending,
181
+ recovery_status: "NONE",
182
+ takeover_epoch: epochRow.epoch,
183
+ created_at: now,
184
+ })
185
+ })()
186
+ } finally {
187
+ db.close()
188
+ }
189
+ }
190
+
191
+ const RUN_EDGES: Record<RunStatus, readonly RunStatus[]> = {
192
+ CREATED: ["RUNNING", "COMPLETED", "INTERRUPTED", "FAILED"],
193
+ RUNNING: ["COMPLETED", "INTERRUPTED", "FAILED"],
194
+ COMPLETED: ["COMPLETED"],
195
+ INTERRUPTED: ["INTERRUPTED"],
196
+ FAILED: ["FAILED"],
197
+ }
198
+
199
+ function isRunningUniquenessViolation(e: unknown): boolean {
200
+ const msg = String((e as Error)?.message ?? e)
201
+ return msg.includes("UNIQUE constraint failed") && msg.includes("runs")
202
+ }
203
+
204
+ export function transitionRun(
205
+ runId: string,
206
+ to: RunStatus,
207
+ cwd?: string,
208
+ opts?: { expectedEpoch?: number; recoveryStatus?: string },
209
+ ): RunRow {
210
+ const db = openSessionHandle(cwd)
211
+ try {
212
+ return db.transaction(() => {
213
+ const row = db
214
+ .prepare(`SELECT ${RUN_COLUMNS} FROM runs WHERE run_id = ?`)
215
+ .get(runId) as RunRow | null
216
+ if (!row) throw new Error(`run not found: ${runId}`)
217
+ if (opts?.expectedEpoch !== undefined)
218
+ assertWriterEpochInTxn(db, row.session_id, opts.expectedEpoch)
219
+ if (RUN_TERMINAL.has(row.status)) {
220
+ if (row.status === to) return rowToRun(row)
221
+ if (RUN_TERMINAL.has(to)) throw new RunTerminalConflictError(runId, row.status, to)
222
+ throw new RunStatusError(runId, row.status, to)
223
+ }
224
+ if (!RUN_EDGES[row.status].includes(to)) throw new RunStatusError(runId, row.status, to)
225
+ const now = Date.now()
226
+ const terminal = RUN_TERMINAL.has(to)
227
+ const recovery = to === "INTERRUPTED" ? (opts?.recoveryStatus ?? "NONE") : "NONE"
228
+ try {
229
+ db.prepare(
230
+ "UPDATE runs SET status = ?, ended_at = ?, recovery_status = ? WHERE run_id = ?",
231
+ ).run(to, terminal ? now : null, recovery, runId)
232
+ } catch (e) {
233
+ if (isRunningUniquenessViolation(e)) throw new RunRunningExistsError(row.session_id)
234
+ throw e
235
+ }
236
+ return rowToRun({
237
+ ...row,
238
+ status: to,
239
+ ended_at: terminal ? now : row.ended_at,
240
+ recovery_status: recovery,
241
+ })
242
+ })()
243
+ } finally {
244
+ db.close()
245
+ }
246
+ }
247
+
248
+ export function completeRun(
249
+ runId: string,
250
+ cwd?: string,
251
+ opts?: { expectedEpoch?: number },
252
+ ): RunRow {
253
+ return transitionRun(runId, "COMPLETED", cwd, opts)
254
+ }
255
+
256
+ export function failRun(runId: string, cwd?: string, opts?: { expectedEpoch?: number }): RunRow {
257
+ return transitionRun(runId, "FAILED", cwd, opts)
258
+ }
259
+
260
+ export function interruptRun(
261
+ runId: string,
262
+ cwd?: string,
263
+ opts?: { expectedEpoch?: number; recoveryStatus?: string },
264
+ ): RunRow {
265
+ return transitionRun(runId, "INTERRUPTED", cwd, opts)
266
+ }
267
+
268
+ export function advanceRunCursorInTxn(
269
+ db: Database,
270
+ runId: string,
271
+ seq: number,
272
+ expectSessionId: string | undefined,
273
+ opts?: { expectedEventId?: string },
274
+ ): RunRow {
275
+ const row = db
276
+ .prepare(`SELECT ${RUN_COLUMNS} FROM runs WHERE run_id = ?`)
277
+ .get(runId) as RunRow | null
278
+ if (!row) throw new Error(`run not found: ${runId}`)
279
+ if (expectSessionId !== undefined && row.session_id !== expectSessionId)
280
+ throw new Error(`run ${runId} does not belong to session ${expectSessionId}`)
281
+ if (RUN_TERMINAL.has(row.status))
282
+ throw new RunStatusError(runId, row.status, `${row.status}+cursor`)
283
+ if (!Number.isInteger(seq) || seq < 0)
284
+ throw new RunCursorError("RUN_CURSOR_BEYOND_HEAD", runId, `invalid seq ${seq}`)
285
+ const target = db
286
+ .prepare(
287
+ "SELECT seq, run_id, event_id FROM messages WHERE session_id = ? AND thread_id = ? AND seq = ?",
288
+ )
289
+ .get(row.session_id, row.thread_id, seq) as {
290
+ seq: number
291
+ run_id: string | null
292
+ event_id: string | null
293
+ } | null
294
+ if (!target)
295
+ throw new RunCursorError("RUN_CURSOR_BEYOND_HEAD", runId, `no durable event at seq ${seq}`)
296
+ if (target.run_id !== null && target.run_id !== runId) {
297
+ throw new RunCursorError(
298
+ "RUN_CURSOR_FOREIGN",
299
+ runId,
300
+ `seq ${seq} belongs to run ${target.run_id}`,
301
+ )
302
+ }
303
+ if (opts?.expectedEventId !== undefined && target.event_id !== opts.expectedEventId) {
304
+ throw new RunCursorError("RUN_CURSOR_FOREIGN", runId, `seq ${seq} event mismatch`)
305
+ }
306
+ if (seq < row.last_persisted_seq) {
307
+ throw new RunCursorError(
308
+ "RUN_CURSOR_BACKWARD",
309
+ runId,
310
+ `${row.last_persisted_seq} → ${seq} refused (no rewind in P2.6)`,
311
+ )
312
+ }
313
+ if (seq === row.last_persisted_seq) return rowToRun(row)
314
+ const upd = db
315
+ .prepare("UPDATE runs SET last_persisted_seq = ? WHERE run_id = ? AND last_persisted_seq = ?")
316
+ .run(seq, runId, row.last_persisted_seq)
317
+ if (upd.changes === 0) {
318
+ const cur = db.prepare("SELECT last_persisted_seq FROM runs WHERE run_id = ?").get(runId) as {
319
+ last_persisted_seq: number
320
+ }
321
+ throw new RunCursorError(
322
+ "RUN_CURSOR_BACKWARD",
323
+ runId,
324
+ `concurrent advance observed (now ${cur.last_persisted_seq})`,
325
+ )
326
+ }
327
+ return rowToRun({ ...row, last_persisted_seq: seq })
328
+ }
329
+
330
+ export function advanceRunCursor(
331
+ runId: string,
332
+ seq: number,
333
+ cwd?: string,
334
+ opts?: { expectedEpoch?: number; expectedEventId?: string },
335
+ ): RunRow {
336
+ const db = openSessionHandle(cwd)
337
+ try {
338
+ return db.transaction(() => {
339
+ if (opts?.expectedEpoch !== undefined) {
340
+ const owner = db.prepare("SELECT session_id FROM runs WHERE run_id = ?").get(runId) as {
341
+ session_id: string
342
+ } | null
343
+ if (!owner) throw new Error(`run not found: ${runId}`)
344
+ assertWriterEpochInTxn(db, owner.session_id, opts.expectedEpoch)
345
+ }
346
+ return advanceRunCursorInTxn(db, runId, seq, undefined, opts)
347
+ })()
348
+ } finally {
349
+ db.close()
350
+ }
351
+ }
352
+
353
+ export function setRunPendingTools(
354
+ runId: string,
355
+ pendingToolIds: unknown,
356
+ cwd?: string,
357
+ opts?: { expectedEpoch?: number },
358
+ ): RunRow {
359
+ const db = openSessionHandle(cwd)
360
+ try {
361
+ return db.transaction(() => {
362
+ const row = db
363
+ .prepare(`SELECT ${RUN_COLUMNS} FROM runs WHERE run_id = ?`)
364
+ .get(runId) as RunRow | null
365
+ if (!row) throw new Error(`run not found: ${runId}`)
366
+ if (opts?.expectedEpoch !== undefined)
367
+ assertWriterEpochInTxn(db, row.session_id, opts.expectedEpoch)
368
+ const pending = validatePendingToolIds(pendingToolIds)
369
+ db.prepare("UPDATE runs SET pending_tool_ids = ? WHERE run_id = ?").run(pending, runId)
370
+ return rowToRun({ ...row, pending_tool_ids: pending })
371
+ })()
372
+ } finally {
373
+ db.close()
374
+ }
375
+ }
376
+
377
+ export function tombstoneDeadRuns(
378
+ sessionId: string,
379
+ cwd?: string,
380
+ opts?: { expectedEpoch?: number },
381
+ ): number {
382
+ const db = openSessionHandle(cwd)
383
+ try {
384
+ return db.transaction(() => {
385
+ if (opts?.expectedEpoch !== undefined)
386
+ assertWriterEpochInTxn(db, sessionId, opts.expectedEpoch)
387
+ const res = db
388
+ .prepare(
389
+ "UPDATE runs SET status = 'INTERRUPTED', recovery_status = 'UNKNOWN' WHERE session_id = ? AND status = 'RUNNING'",
390
+ )
391
+ .run(sessionId)
392
+ return res.changes
393
+ })()
394
+ } finally {
395
+ db.close()
396
+ }
397
+ }