minicode-ai 0.28.0 → 0.30.1

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.
Files changed (41) hide show
  1. package/README.md +1 -1
  2. package/cli/args.ts +93 -70
  3. package/cli/bootstrap/presentation-bridge.ts +383 -0
  4. package/cli/commands/acp.ts +7 -1
  5. package/cli/commands/doctor.ts +7 -3
  6. package/cli/commands/exec.ts +6 -16
  7. package/cli/index.ts +3 -2
  8. package/cli/setup.ts +13 -380
  9. package/cli/tui.ts +3 -4
  10. package/docs/TERMINAL_CONTRACT.md +28 -21
  11. package/docs/UI_RENDER_PIPELINE.md +3 -3
  12. package/docs/architecture.md +14 -29
  13. package/docs/environment.md +1 -1
  14. package/package.json +1 -1
  15. package/src/app/session.ts +201 -53
  16. package/src/app/tool-layer.ts +27 -0
  17. package/src/lib/atomic-write.ts +31 -59
  18. package/src/policy/jail.ts +6 -8
  19. package/src/providers/anthropic.ts +16 -5
  20. package/src/providers/responses.ts +37 -7
  21. package/src/providers/sse-bounds.ts +6 -4
  22. package/src/session/db/runs.ts +397 -0
  23. package/src/session/db/schema.ts +358 -0
  24. package/src/session/persistence.ts +64 -955
  25. package/src/task/db/schema.ts +325 -0
  26. package/src/task/db/types.ts +269 -0
  27. package/src/task/store.ts +74 -986
  28. package/src/ui/assistant/simple.ts +25 -19
  29. package/src/ui/i18n/en.ts +0 -3
  30. package/src/ui/i18n/id.ts +0 -3
  31. package/src/ui/render/logo.ts +15 -18
  32. package/src/ui/render/markdown-layout.ts +293 -0
  33. package/src/ui/render/markdown.ts +36 -44
  34. package/src/ui/render/session-summary.ts +1 -1
  35. package/src/ui/render/table-grid.ts +16 -7
  36. package/src/ui/render/width.ts +71 -18
  37. package/src/ui/render/wrap.ts +39 -22
  38. package/src/ui/session-state.ts +4 -4
  39. package/src/ui/tui/app.ts +15 -36
  40. package/src/ui/tui/transcript.ts +111 -50
  41. package/vendor/minicore/src/providers/openai-compat.ts +7 -0
@@ -2,6 +2,34 @@ import { randomUUID } from "node:crypto"
2
2
  import { chmod, type FileHandle, mkdir, open, rename, unlink } from "node:fs/promises"
3
3
  import { dirname } from "node:path"
4
4
 
5
+ /**
6
+ * Rename atomic dengan backoff EPERM/EBUSY/EACCES sesaat (lock AV/replace window Windows).
7
+ */
8
+ export async function renameWithRetry(
9
+ from: string,
10
+ to: string,
11
+ opts: { maxRetries?: number; renameFn?: (src: string, dst: string) => Promise<void> } = {},
12
+ ): Promise<void> {
13
+ const maxRetries = opts.maxRetries ?? 8
14
+ const doRename = opts.renameFn ?? rename
15
+ let lastErr: unknown
16
+ for (let r = 0; r < maxRetries; r++) {
17
+ try {
18
+ await doRename(from, to)
19
+ return
20
+ } catch (e) {
21
+ const code = (e as NodeJS.ErrnoException).code
22
+ if (code === "EPERM" || code === "EBUSY" || code === "EACCES") {
23
+ lastErr = e
24
+ await new Promise((res) => setTimeout(res, Math.min(10 * 2 ** r, 100)))
25
+ } else {
26
+ throw e
27
+ }
28
+ }
29
+ }
30
+ if (lastErr) throw lastErr
31
+ }
32
+
5
33
  /**
6
34
  * Tulis file secara atomic + tahan hijack:
7
35
  * - nama tmp memakai randomUUID → tidak dapat diprediksi attacker
@@ -11,14 +39,6 @@ import { dirname } from "node:path"
11
39
  * MOVEFILE_REPLACE_EXISTING sehingga menimpa target lama.
12
40
  */
13
41
  export async function atomicWriteText(path: string, data: string): Promise<void> {
14
- // Direktori induk bisa gagal dibuat: path-nya sudah dipakai FILE biasa,
15
- // salah satu komponennya bukan direktori, atau induknya read-only. Error
16
- // itu adalah AKAR MASALAH. Dulu ia ditelan `.catch(() => {})`, sehingga
17
- // yang sampai ke pemanggil hanya gejala open() berikutnya ("ENOENT: no
18
- // such file or directory") — menyesatkan, karena direktori itu ADA dan
19
- // memang tidak bisa dibuat. Simpan error mkdir; kalau open() juga gagal,
20
- // surface yang sebenarnya dan simpan gejala open() sebagai `cause` supaya
21
- // kedua informasi tetap utuh.
22
42
  let dirErr: NodeJS.ErrnoException | undefined
23
43
  try {
24
44
  await mkdir(dirname(path), { recursive: true, mode: 0o700 })
@@ -32,81 +52,33 @@ export async function atomicWriteText(path: string, data: string): Promise<void>
32
52
  try {
33
53
  fh = await open(tmp, "wx", 0o600)
34
54
  } catch (e) {
35
- // Pembuatan direktori gagal DAN tulisan juga gagal → akar masalahnya
36
- // di direktori, bukan di open(). Jangan biarkan gejala open() menutupi
37
- // penyebab aslinya.
38
55
  if (dirErr) throw Object.assign(dirErr, { cause: e })
39
56
  if ((e as NodeJS.ErrnoException).code === "EEXIST" && attempt === 0) continue
40
57
  throw e
41
58
  }
42
59
  try {
43
- // Bun Windows: `FileHandle.writeFile` kadang nge-hit kWriteMonkeyPatchDefense
44
- // bila `node:fs/promises` ke-import bareng `bun:sqlite` di top-level.
45
- // Fallback ke `Bun.write` (tidak pakai FileHandle) bila kena itu.
46
60
  try {
47
61
  await fh.writeFile(data, "utf8")
48
62
  } catch (e) {
49
63
  const msg = String((e as Error)?.message ?? "")
50
64
  if (msg.includes("kWriteMonkeyPatchDefense") || msg.includes("kWrite")) {
51
65
  await fh.close().catch(() => {})
52
- // Handle sudah ditutup di atas → null-out agar blok `finally` tidak
53
- // memanggil `.close()` pada handle yang sudah tidak ada. Tanpa ini
54
- // `fh.close()` di `finally` melempar TypeError yang menutupi
55
- // penulisan yang justru BERHASIL (file sudah ter-rename, tapi
56
- // pemanggil diberi tahu gagal).
57
66
  fh = undefined
58
67
  await Bun.write(tmp, data)
59
- // re-open untuk sync/chmod path yang sama — atau skip bila Bun.write sudah flush
60
- try {
61
- await chmod(tmp, 0o600).catch(() => {})
62
- } catch {}
63
- let lastErr2: unknown
64
- for (let r = 0; r < 8; r++) {
65
- try {
66
- await rename(tmp, path)
67
- lastErr2 = undefined
68
- break
69
- } catch (ee) {
70
- const code = (ee as NodeJS.ErrnoException).code
71
- if (code === "EPERM" || code === "EBUSY" || code === "EACCES") {
72
- lastErr2 = ee
73
- await new Promise((res) => setTimeout(res, Math.min(10 * 2 ** r, 100)))
74
- } else throw ee
75
- }
76
- }
77
- if (lastErr2) throw lastErr2
68
+ await chmod(tmp, 0o600).catch(() => {})
69
+ await renameWithRetry(tmp, path)
78
70
  return
79
71
  }
80
72
  throw e
81
73
  }
82
74
  await fh.sync().catch(() => {})
83
75
  await chmod(tmp, 0o600).catch(() => {})
84
- // Windows: rename menimpa target yang baru saja ditulis penulis lain
85
- // bisa EPERM/EBUSY/EACCES sesaat (lock AV / replace window) → backoff.
86
- let lastErr: unknown
87
- for (let r = 0; r < 8; r++) {
88
- try {
89
- await rename(tmp, path)
90
- lastErr = undefined
91
- break
92
- } catch (e) {
93
- const code = (e as NodeJS.ErrnoException).code
94
- if (code === "EPERM" || code === "EBUSY" || code === "EACCES") {
95
- lastErr = e
96
- await new Promise((res) => setTimeout(res, Math.min(10 * 2 ** r, 100)))
97
- } else throw e
98
- }
99
- }
100
- if (lastErr) throw lastErr
76
+ await renameWithRetry(tmp, path)
101
77
  return
102
78
  } catch (e) {
103
79
  await unlink(tmp).catch(() => {})
104
80
  throw e
105
81
  } finally {
106
- // `fh` bisa sudah `undefined` di jalur fallback Bun.write di atas
107
- // (handle ditutup manual). Menutup handle yang masih hidup itu aman;
108
- // memanggil `.close()` pada `undefined` melempar TypeError yang
109
- // menutupi penulisan yang justru sudah BERHASIL.
110
82
  if (fh) await fh.close().catch(() => {})
111
83
  }
112
84
  }
@@ -19,16 +19,14 @@ const DOTDOT_SEG_RE = /(?:^|[/\\])\.\.(?:[/\\]|$)/
19
19
  */
20
20
  function cleanPathForMatch(p: string): string {
21
21
  if (!p) return ""
22
- const withoutAds = p.replace(/(:[a-zA-Z0-9_.$-]+)+$/, (m, _g, offset) => {
23
- // Jangan kupas drive letter Windows seperti "C:" di awal path
24
- if (offset === 1 && /^[a-zA-Z]:$/.test(p.slice(0, 2))) return m
25
- return ""
26
- })
27
- return withoutAds
22
+ return p
28
23
  .split(/([/\\]+)/)
29
- .map((seg) => {
24
+ .map((seg, i) => {
30
25
  if (!seg || /^[/\\]+$/.test(seg) || seg === "." || seg === "..") return seg
31
- return seg.replace(/[.\s]+$/, "")
26
+ // Pertahankan drive letter Windows (mis. "C:") di segmen pertama
27
+ const noAds =
28
+ i === 0 && /^[a-zA-Z]:$/.test(seg) ? seg : seg.replace(/(:[a-zA-Z0-9_.$-]+)+$/, "")
29
+ return noAds.replace(/[.\s]+$/, "")
32
30
  })
33
31
  .join("")
34
32
  }
@@ -104,13 +104,24 @@ export function createAnthropicProvider(config: AnthropicConfig): ModelProvider
104
104
  const effectiveMaxTokens = legacyBudget
105
105
  ? Math.max(config.maxTokens ?? 8192, legacyBudget + 1024)
106
106
  : (config.maxTokens ?? 8192)
107
- // Fase 7: cache prefix percakapan (system+tools+histori) — tandai pesan
108
- // stabil terakhir (kedua dari akhir; yang terakhir = pesan user saat ini)
109
- // agar tool result besar ikut ter-cache tiap turn (bukan dikirim ulang).
107
+ // Fase 7: sematkan cache_control pada blok konten stabil terakhir.
110
108
  const messagesPayload = toAnthropicMessages(request.messages)
111
109
  if (enableCache && messagesPayload.length >= 2) {
112
- const lastStable = messagesPayload[messagesPayload.length - 2] as Record<string, unknown>
113
- lastStable.cache_control = { type: "ephemeral" }
110
+ const lastStable = messagesPayload[messagesPayload.length - 2] as {
111
+ role: string
112
+ content: unknown
113
+ }
114
+ if (Array.isArray(lastStable.content) && lastStable.content.length > 0) {
115
+ const lastBlock = lastStable.content[lastStable.content.length - 1] as Record<
116
+ string,
117
+ unknown
118
+ >
119
+ lastBlock.cache_control = { type: "ephemeral" }
120
+ } else if (typeof lastStable.content === "string") {
121
+ lastStable.content = [
122
+ { type: "text", text: lastStable.content, cache_control: { type: "ephemeral" } },
123
+ ]
124
+ }
114
125
  }
115
126
  const body = JSON.stringify({
116
127
  model: request.model ?? config.defaultModel ?? config.models[0],
@@ -254,6 +254,28 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
254
254
  // response.completed → simpan id untuk chaining turn berikut.
255
255
  // Format nyata: {type:"response.completed", response:{id:"resp_…"}}.
256
256
  const dtype = data.type as string | undefined
257
+ if (dtype === "error" || dtype === "response.failed" || data.error) {
258
+ if (prev) lastResponseByModel.delete(modelKey)
259
+ const errRec =
260
+ (data.error as Record<string, unknown> | undefined) ??
261
+ (data.response as { error?: Record<string, unknown> } | undefined)?.error ??
262
+ data
263
+ const msg = String(errRec.message ?? errRec.msg ?? JSON.stringify(errRec))
264
+ const code = String(errRec.code ?? errRec.type ?? "")
265
+ const combined = `${msg} ${code}`
266
+ const cat = /auth|401|403|unauthorized/i.test(combined)
267
+ ? "auth"
268
+ : /quota_exceeded|insufficient_quota|balance/i.test(combined)
269
+ ? "unknown"
270
+ : /rate|429/i.test(combined)
271
+ ? "rate_limit"
272
+ : /context_length|maximum context|prompt is too long|context window/i.test(
273
+ msg,
274
+ )
275
+ ? "context_length_exceeded"
276
+ : "server"
277
+ throw new ProviderError(cat, cat === "unknown" ? `402: ${msg}` : `${cat}: ${msg}`)
278
+ }
257
279
  if (dtype === "response.completed" || dtype === "completed") {
258
280
  const resp = data.response as { id?: unknown; usage?: unknown } | undefined
259
281
  const rid = resp?.id ?? data.id
@@ -391,14 +413,22 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
391
413
  typeof data.arguments === "string" ? data.arguments : "",
392
414
  )
393
415
  }
394
- const isToolEvent =
395
- dtype === "response.output_item.added" ||
396
- dtype === "response.function_call_arguments.delta" ||
397
- dtype === "response.function_call_arguments.done" ||
398
- dtype === "response.output_item.done" ||
399
- dtype === "function_call"
416
+ // Abaikan event lifecycle/summary `.done`/`.added` agar teks utuh di
417
+ // `response.output_text.done` tidak digandakan setelah `.delta`.
418
+ const isNonDeltaEvent =
419
+ typeof dtype === "string" &&
420
+ (dtype.endsWith(".done") ||
421
+ dtype.endsWith(".added") ||
422
+ dtype === "response.created" ||
423
+ dtype === "response.in_progress" ||
424
+ dtype === "response.completed" ||
425
+ dtype === "completed" ||
426
+ dtype === "response.incomplete" ||
427
+ dtype.startsWith("response.function_call") ||
428
+ dtype.startsWith("response.reasoning") ||
429
+ dtype === "function_call")
400
430
  const text =
401
- reasoningText || isToolEvent
431
+ reasoningText || isNonDeltaEvent
402
432
  ? undefined
403
433
  : ((typeof rawDelta === "string" ? rawDelta : undefined) ??
404
434
  drec.text ??
@@ -51,10 +51,7 @@ export function boundedSseBody(
51
51
  if (done) {
52
52
  reachedEof = true
53
53
  if (lineBytes !== 0 || frameBytes !== 0) {
54
- throw new ProviderError(
55
- "invalid_request",
56
- `${provider} returned an incomplete SSE frame`,
57
- )
54
+ throw new ProviderError("network", `${provider} returned an incomplete SSE frame`)
58
55
  }
59
56
  controller.close()
60
57
  release()
@@ -68,6 +65,11 @@ export function boundedSseBody(
68
65
  )
69
66
  }
70
67
  for (const byte of value) {
68
+ if (byte === 0x0d) {
69
+ // CRLF: 0x0D ikut dihitung frameBytes, bukan lineBytes
70
+ frameBytes++
71
+ continue
72
+ }
71
73
  if (byte === 0x0a) {
72
74
  frameBytes++
73
75
  if (frameBytes > maxFrameBytes) {
@@ -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
+ }