minicode-ai 0.14.0 → 0.14.2

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 (88) hide show
  1. package/README.md +1 -1
  2. package/cli/args.ts +16 -3
  3. package/cli/auto-update.ts +32 -2
  4. package/cli/commands/exec.ts +9 -0
  5. package/cli/index.ts +31 -13
  6. package/cli/setup.ts +31 -19
  7. package/cli/tui.ts +63 -40
  8. package/docs/OUTPUT_PROTOCOL_SPEC.md +6 -0
  9. package/docs/OUTPUT_RENDERING_SPEC.md +28 -4
  10. package/docs/README.md +2 -2
  11. package/docs/TERMINAL_CONTRACT.md +52 -26
  12. package/docs/agents.md +2 -2
  13. package/docs/choosing-mode.md +20 -13
  14. package/docs/cli.md +11 -11
  15. package/docs/environment.md +3 -3
  16. package/docs/getting-started.md +14 -12
  17. package/docs/glossary.md +1 -1
  18. package/docs/mcp-lsp.md +1 -1
  19. package/docs/policy-sandbox.md +7 -1
  20. package/docs/security-model.md +2 -2
  21. package/docs/security.md +7 -1
  22. package/docs/tools.md +4 -4
  23. package/docs/verify-benchmark.md +16 -0
  24. package/package.json +1 -3
  25. package/src/app/mentions.ts +4 -3
  26. package/src/app/session.ts +19 -9
  27. package/src/app/tool-layer.ts +10 -3
  28. package/src/constants.ts +17 -0
  29. package/src/lib/git-hardening.ts +27 -22
  30. package/src/lib/safe-open.ts +73 -19
  31. package/src/lib/trusted-exec.ts +7 -4
  32. package/src/mcp/client.ts +34 -9
  33. package/src/mcp/transport.ts +96 -42
  34. package/src/memory/files.ts +15 -4
  35. package/src/memory/vector.ts +5 -1
  36. package/src/policy/context.ts +21 -13
  37. package/src/policy/permission.ts +75 -16
  38. package/src/policy/tool-contract.ts +21 -10
  39. package/src/policy/update-check.ts +83 -6
  40. package/src/policy/usage.ts +17 -7
  41. package/src/policy/work-mode.ts +51 -17
  42. package/src/presentation/adapter.ts +64 -2
  43. package/src/presentation/events.ts +6 -0
  44. package/src/presentation/model.ts +1 -0
  45. package/src/presentation/projection.ts +2 -0
  46. package/src/presentation/reducer.ts +1 -0
  47. package/src/providers/anthropic.ts +52 -19
  48. package/src/providers/guards.ts +98 -13
  49. package/src/providers/responses.ts +61 -23
  50. package/src/providers/sse-bounds.ts +170 -0
  51. package/src/repo/repomap.ts +10 -11
  52. package/src/runtime/execution-backend.ts +7 -8
  53. package/src/sandbox/docker.ts +113 -9
  54. package/src/session/checkpoint.ts +9 -2
  55. package/src/session/persistence.ts +5 -2
  56. package/src/session/verification.ts +55 -16
  57. package/src/skills/loader.ts +16 -3
  58. package/src/tools/bash.ts +6 -3
  59. package/src/tools/code_run.ts +6 -5
  60. package/src/tools/context.ts +8 -0
  61. package/src/tools/delete_file.ts +2 -1
  62. package/src/tools/edit.ts +2 -1
  63. package/src/tools/git.ts +128 -54
  64. package/src/tools/glob.ts +2 -1
  65. package/src/tools/grep.ts +31 -6
  66. package/src/tools/lsp.ts +5 -4
  67. package/src/tools/mcp_call.ts +3 -1
  68. package/src/tools/memory.ts +175 -180
  69. package/src/tools/move_file.ts +2 -1
  70. package/src/tools/patch.ts +2 -1
  71. package/src/tools/read_file.ts +94 -1
  72. package/src/tools/read_image.ts +2 -1
  73. package/src/tools/task.ts +2 -1
  74. package/src/tools/todo.ts +4 -5
  75. package/src/tools/web_fetch.ts +28 -12
  76. package/src/tools/web_search.ts +28 -9
  77. package/src/tools/write_file.ts +2 -1
  78. package/src/ui/assistant/simple.ts +72 -3
  79. package/src/ui/footer.ts +17 -12
  80. package/src/ui/i18n/en.ts +6 -3
  81. package/src/ui/i18n/id.ts +6 -3
  82. package/src/ui/render/width.ts +107 -79
  83. package/src/ui/runtime/screen.ts +49 -37
  84. package/src/ui/tui/app.ts +261 -209
  85. package/src/ui/tui/transcript.ts +39 -0
  86. package/CHANGELOG.md +0 -1167
  87. package/docs/PLAN_UIUX_V6.md +0 -209
  88. package/docs/changelog.md +0 -3
@@ -1,6 +1,12 @@
1
1
  import { ProviderError } from "#minicore/core/errors.ts"
2
2
  import type { ModelProvider, ProviderEvent, StreamRequest } from "#minicore/core/provider.ts"
3
3
  import { allowedEfforts, thinkingFamily } from "./effort.ts"
4
+ import {
5
+ appendToolArgument,
6
+ boundedSseBody,
7
+ parseProviderToolArguments,
8
+ readProviderErrorBody,
9
+ } from "./sse-bounds.ts"
4
10
 
5
11
  export interface ResponsesConfig {
6
12
  id?: string
@@ -131,7 +137,7 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
131
137
  throw new ProviderError("network", e instanceof Error ? e.message : String(e))
132
138
  }
133
139
  if (!res.ok) {
134
- const txt = await res.text().catch(() => "")
140
+ const txt = await readProviderErrorBody(res).catch(() => "")
135
141
  const retryAfter = res.headers.get("retry-after")
136
142
  if (res.status === 429) {
137
143
  const ms = retryAfter ? Number(retryAfter) * 1000 : undefined
@@ -169,7 +175,8 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
169
175
  }
170
176
  if (!res.body) throw new ProviderError("network", "empty response body")
171
177
  // Simplified SSE: forward text deltas
172
- const reader = res.body.getReader()
178
+ const boundedBody = boundedSseBody(res.body, signal, "Responses")
179
+ const reader = boundedBody.getReader()
173
180
  const decoder = new TextDecoder()
174
181
  let buf = ""
175
182
  // F-01: akumulasi function_call per item (Responses tidak punya delta
@@ -177,16 +184,12 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
177
184
  // response.function_call_arguments.delta lalu item final via
178
185
  // response.output_item.done). Tanpa ini tool yang dideklarasikan di
179
186
  // request tidak pernah dieksekusi — agen tampak selesai padahal buta.
180
- const pendingCalls = new Map<string, { id: string; name: string; args: string }>()
187
+ const pendingCalls = new Map<
188
+ string,
189
+ { id: string; name: string; args: string; argsBytes: number }
190
+ >()
191
+ let pendingToolArgBytes = 0
181
192
  let finished = false
182
- const parseCallArgs = (raw: string): unknown => {
183
- if (!raw) return {}
184
- try {
185
- return JSON.parse(raw)
186
- } catch {
187
- return { raw }
188
- }
189
- }
190
193
  const yieldCall = function* (
191
194
  id: string,
192
195
  name: string,
@@ -197,13 +200,22 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
197
200
  // eksekusi ganda diam-diam — gagal keras sebagai network retryable.
198
201
  throw new ProviderError("network", "tool call after finish")
199
202
  }
200
- yield { type: "tool_call", id: id || name, name, args: parseCallArgs(argsRaw) }
203
+ yield {
204
+ type: "tool_call",
205
+ id: id || name,
206
+ name,
207
+ args: parseProviderToolArguments(argsRaw, "Responses"),
208
+ }
201
209
  }
210
+ let reachedEof = false
202
211
  try {
203
212
  while (true) {
204
213
  if (signal.aborted) throw new DOMException("Aborted", "AbortError")
205
214
  const { done, value } = await reader.read()
206
- if (done) break
215
+ if (done) {
216
+ reachedEof = true
217
+ break
218
+ }
207
219
  buf += decoder.decode(value, { stream: true })
208
220
  let idx = buf.indexOf("\n")
209
221
  while (idx >= 0) {
@@ -219,20 +231,22 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
219
231
  yield* yieldCall(acc.id, acc.name, acc.args)
220
232
  }
221
233
  pendingCalls.clear()
234
+ pendingToolArgBytes = 0
222
235
  if (!finished) {
223
236
  finished = true
224
237
  yield { type: "finish", reason: "stop" }
225
238
  }
226
239
  return
227
240
  }
228
- // Hanya JSON rusak yang di-skip di sini: error dari yieldCall
229
- // (mis. tool-setelah-finish) HARUS merambat ke kernel, jangan
230
- // sampai tertelan catch di bawah.
241
+ if (!payload) {
242
+ idx = buf.indexOf("\n")
243
+ continue
244
+ }
231
245
  let data: Record<string, unknown>
232
246
  try {
233
247
  data = JSON.parse(payload) as Record<string, unknown>
234
248
  } catch {
235
- continue
249
+ throw new ProviderError("invalid_request", "Responses returned malformed SSE JSON")
236
250
  }
237
251
  // response.completed → simpan id untuk chaining turn berikut.
238
252
  // Format nyata: {type:"response.completed", response:{id:"resp_…"}}.
@@ -300,10 +314,22 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
300
314
  ? item.call_id
301
315
  : `item_${pendingCalls.size}`
302
316
  const cid = typeof item.call_id === "string" && item.call_id ? item.call_id : key
317
+ const prior = pendingCalls.get(key)
318
+ if (prior) pendingToolArgBytes -= prior.argsBytes
319
+ const initialArgs = typeof item.arguments === "string" ? item.arguments : ""
320
+ const boundedArgs = appendToolArgument(
321
+ "",
322
+ 0,
323
+ initialArgs,
324
+ pendingToolArgBytes,
325
+ "Responses",
326
+ )
327
+ pendingToolArgBytes = boundedArgs.pendingBytes
303
328
  pendingCalls.set(key, {
304
329
  id: cid,
305
330
  name: typeof item.name === "string" ? item.name : "",
306
- args: typeof item.arguments === "string" ? item.arguments : "",
331
+ args: boundedArgs.value,
332
+ argsBytes: boundedArgs.bytes,
307
333
  })
308
334
  } else if (dtype === "response.function_call_arguments.delta") {
309
335
  const key =
@@ -311,7 +337,18 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
311
337
  ? data.item_id
312
338
  : ([...pendingCalls.keys()].pop() ?? "")
313
339
  const acc = pendingCalls.get(key)
314
- if (acc && typeof data.delta === "string") acc.args += data.delta
340
+ if (acc && typeof data.delta === "string") {
341
+ const boundedArgs = appendToolArgument(
342
+ acc.args,
343
+ acc.argsBytes,
344
+ data.delta,
345
+ pendingToolArgBytes,
346
+ "Responses",
347
+ )
348
+ acc.args = boundedArgs.value
349
+ acc.argsBytes = boundedArgs.bytes
350
+ pendingToolArgBytes = boundedArgs.pendingBytes
351
+ }
315
352
  } else if (dtype === "response.output_item.done" && item?.type === "function_call") {
316
353
  const key =
317
354
  typeof item.id === "string" && pendingCalls.has(item.id)
@@ -323,6 +360,7 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
323
360
  const argsRaw =
324
361
  (typeof item.arguments === "string" && item.arguments) || acc?.args || ""
325
362
  pendingCalls.delete(key)
363
+ if (acc) pendingToolArgBytes -= acc.argsBytes
326
364
  if (name) yield* yieldCall(id, name, argsRaw)
327
365
  } else if (data.type === "function_call" && typeof data.name === "string") {
328
366
  const id =
@@ -364,16 +402,16 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
364
402
  }
365
403
  }
366
404
  } finally {
405
+ if (!reachedEof) await reader.cancel().catch(() => {})
367
406
  reader.releaseLock()
368
407
  }
369
- // Provider quirky bisa berakhir tanpa finish eksplisit: flush sisa
370
- // function_call yang terakumulasi (argumen parsial → {raw}, ditolak
371
- // validateArgs sebagai observasi error — aman), lalu finish stop agar
372
- // kernel tidak menganggap stream terputus.
408
+ // Gateway yang menyelesaikan stream tanpa output_item.done tetap flush
409
+ // item tertahan; parser sudah membatasi dan memvalidasi JSON argumennya.
373
410
  for (const [, acc] of pendingCalls) {
374
411
  yield* yieldCall(acc.id, acc.name, acc.args)
375
412
  }
376
413
  pendingCalls.clear()
414
+ pendingToolArgBytes = 0
377
415
  if (!finished) yield { type: "finish", reason: "stop" }
378
416
  },
379
417
  }
@@ -0,0 +1,170 @@
1
+ import { Buffer } from "node:buffer"
2
+ import { abortError, ProviderError } from "#minicore/core/errors.ts"
3
+ import { LIMITS } from "../constants.ts"
4
+
5
+ export interface SseBounds {
6
+ maxFrameBytes?: number
7
+ maxTotalBytes?: number
8
+ }
9
+
10
+ export interface ToolArgumentBounds {
11
+ maxArgumentBytes?: number
12
+ maxPendingBytes?: number
13
+ }
14
+
15
+ /** Baca stream per chunk dengan batas byte sebelum parser SSE membangun buffer baris. */
16
+ export function boundedSseBody(
17
+ body: ReadableStream<Uint8Array>,
18
+ signal: AbortSignal,
19
+ provider: string,
20
+ bounds: SseBounds = {},
21
+ ): ReadableStream<Uint8Array> {
22
+ const maxFrameBytes = bounds.maxFrameBytes ?? LIMITS.PROVIDER_SSE_FRAME_MAX_BYTES
23
+ const maxTotalBytes = bounds.maxTotalBytes ?? LIMITS.PROVIDER_SSE_TOTAL_MAX_BYTES
24
+ if (signal.aborted) throw abortError(signal)
25
+ const reader = body.getReader()
26
+ let streamBytes = 0
27
+ let lineBytes = 0
28
+ let frameBytes = 0
29
+ let reachedEof = false
30
+ let released = false
31
+ const release = () => {
32
+ if (released) return
33
+ released = true
34
+ signal.removeEventListener("abort", onAbort)
35
+ reader.releaseLock()
36
+ }
37
+ const onAbort = () => {
38
+ void reader.cancel(signal.reason).catch(() => {})
39
+ }
40
+ signal.addEventListener("abort", onAbort, { once: true })
41
+ const cancelSource = async (reason?: unknown) => {
42
+ if (!reachedEof) await reader.cancel(reason).catch(() => {})
43
+ release()
44
+ }
45
+ return new ReadableStream<Uint8Array>({
46
+ async pull(controller) {
47
+ try {
48
+ if (signal.aborted) throw abortError(signal)
49
+ const { done, value } = await reader.read()
50
+ if (signal.aborted) throw abortError(signal)
51
+ if (done) {
52
+ reachedEof = true
53
+ if (lineBytes !== 0 || frameBytes !== 0) {
54
+ throw new ProviderError(
55
+ "invalid_request",
56
+ `${provider} returned an incomplete SSE frame`,
57
+ )
58
+ }
59
+ controller.close()
60
+ release()
61
+ return
62
+ }
63
+ streamBytes += value.byteLength
64
+ if (streamBytes > maxTotalBytes) {
65
+ throw new ProviderError(
66
+ "invalid_request",
67
+ `${provider} SSE stream exceeds ${maxTotalBytes} bytes`,
68
+ )
69
+ }
70
+ for (const byte of value) {
71
+ if (byte === 0x0a) {
72
+ frameBytes++
73
+ if (frameBytes > maxFrameBytes) {
74
+ throw new ProviderError(
75
+ "invalid_request",
76
+ `${provider} SSE frame exceeds ${maxFrameBytes} bytes`,
77
+ )
78
+ }
79
+ if (lineBytes === 0) frameBytes = 0
80
+ lineBytes = 0
81
+ } else {
82
+ lineBytes++
83
+ frameBytes++
84
+ if (lineBytes > maxFrameBytes || frameBytes > maxFrameBytes) {
85
+ throw new ProviderError(
86
+ "invalid_request",
87
+ `${provider} SSE frame exceeds ${maxFrameBytes} bytes`,
88
+ )
89
+ }
90
+ }
91
+ }
92
+ controller.enqueue(value)
93
+ } catch (error) {
94
+ await cancelSource(error)
95
+ controller.error(error)
96
+ }
97
+ },
98
+ cancel: cancelSource,
99
+ })
100
+ }
101
+
102
+ /** Body error dibaca secukupnya untuk kategori/pesan, lalu sisa stream dibuang. */
103
+ export async function readProviderErrorBody(response: Response): Promise<string> {
104
+ if (!response.body) return ""
105
+ const reader = response.body.getReader()
106
+ const chunks: Uint8Array[] = []
107
+ let size = 0
108
+ let reachedEof = false
109
+ try {
110
+ while (size < LIMITS.PROVIDER_ERROR_BODY_MAX_BYTES) {
111
+ const { done, value } = await reader.read()
112
+ if (done) {
113
+ reachedEof = true
114
+ break
115
+ }
116
+ const remaining = LIMITS.PROVIDER_ERROR_BODY_MAX_BYTES - size
117
+ const part = value.byteLength > remaining ? value.subarray(0, remaining) : value
118
+ chunks.push(part)
119
+ size += part.byteLength
120
+ if (part.byteLength < value.byteLength) break
121
+ }
122
+ return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8")
123
+ } finally {
124
+ if (!reachedEof) await reader.cancel().catch(() => {})
125
+ reader.releaseLock()
126
+ }
127
+ }
128
+
129
+ export function appendToolArgument(
130
+ current: string,
131
+ currentBytes: number,
132
+ delta: string,
133
+ pendingBytes: number,
134
+ provider: string,
135
+ bounds: ToolArgumentBounds = {},
136
+ ): { value: string; bytes: number; pendingBytes: number } {
137
+ const deltaBytes = Buffer.byteLength(delta, "utf8")
138
+ const bytes = currentBytes + deltaBytes
139
+ const nextPendingBytes = pendingBytes + deltaBytes
140
+ const maxArgumentBytes = bounds.maxArgumentBytes ?? LIMITS.PROVIDER_TOOL_ARGS_MAX_BYTES
141
+ const maxPendingBytes = bounds.maxPendingBytes ?? LIMITS.PROVIDER_TOOL_ARGS_PENDING_MAX_BYTES
142
+ if (bytes > maxArgumentBytes) {
143
+ throw new ProviderError(
144
+ "invalid_request",
145
+ `${provider} tool arguments exceed ${maxArgumentBytes} bytes`,
146
+ )
147
+ }
148
+ if (nextPendingBytes > maxPendingBytes) {
149
+ throw new ProviderError(
150
+ "invalid_request",
151
+ `${provider} pending tool arguments exceed ${maxPendingBytes} bytes`,
152
+ )
153
+ }
154
+ return { value: current + delta, bytes, pendingBytes: nextPendingBytes }
155
+ }
156
+
157
+ export function parseProviderToolArguments(raw: string, provider: string): unknown {
158
+ if (Buffer.byteLength(raw, "utf8") > LIMITS.PROVIDER_TOOL_ARGS_MAX_BYTES) {
159
+ throw new ProviderError(
160
+ "invalid_request",
161
+ `${provider} tool arguments exceed ${LIMITS.PROVIDER_TOOL_ARGS_MAX_BYTES} bytes`,
162
+ )
163
+ }
164
+ if (!raw) return {}
165
+ try {
166
+ return JSON.parse(raw)
167
+ } catch {
168
+ throw new ProviderError("invalid_request", `${provider} returned malformed tool arguments`)
169
+ }
170
+ }
@@ -1,13 +1,14 @@
1
1
  import { execFile } from "node:child_process"
2
2
  import { createHash } from "node:crypto"
3
- import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
4
- import { readdir, readFile, stat } from "node:fs/promises"
3
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
4
+ import { readdir } from "node:fs/promises"
5
5
  import { join, relative, resolve } from "node:path"
6
6
  import { fileURLToPath } from "node:url"
7
7
  import { promisify } from "node:util"
8
8
  import { LIMITS, LSP_SYMBOL_KINDS } from "../constants.ts"
9
9
  import { homeDir } from "../lib/db-path.ts"
10
10
  import { GIT_SAFE_BASE } from "../lib/git-hardening.ts"
11
+ import { safeReadFileCapped } from "../lib/safe-open.ts"
11
12
  import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
12
13
  import { isRealPathOutsideRoot } from "../policy/jail.ts"
13
14
 
@@ -233,10 +234,8 @@ async function readSourceContents(
233
234
  for (const f of files) {
234
235
  try {
235
236
  const abs = resolve(cwd, f)
236
- const st = await stat(abs)
237
- if (!st.isFile() || st.size > MAX_FILE_BYTES) continue
238
- const content = await readFile(abs, "utf8")
239
- out.push({ path: f, content })
237
+ const loaded = await safeReadFileCapped(abs, cwd, MAX_FILE_BYTES)
238
+ if (!loaded.truncated) out.push({ path: f, content: loaded.text })
240
239
  } catch {}
241
240
  }
242
241
  return out
@@ -358,15 +357,15 @@ export async function buildRepoMap(
358
357
  // disajikan tanpa baca ulang. Dengan sig isi, cache palsu hanya cocok bila
359
358
  // isinya benar-benar sama — dan bila sama, petanya pun benar. Cache lama
360
359
  // (format mtime) otomatis miss → dibangun ulang sekali, tanpa migrasi.
361
- function signature(files: string[], cwd: string): string {
360
+ async function signature(files: string[], cwd: string): Promise<string> {
362
361
  const h = createHash("sha256")
363
362
  for (const f of files.slice(0, 80)) {
364
363
  try {
365
364
  const abs = resolve(cwd, f)
366
- const st = statSync(abs)
367
- if (!st.isFile() || st.size > MAX_FILE_BYTES) continue
365
+ const loaded = await safeReadFileCapped(abs, cwd, MAX_FILE_BYTES)
366
+ if (loaded.truncated) continue
368
367
  h.update(f)
369
- h.update(readFileSync(abs))
368
+ h.update(loaded.text)
370
369
  } catch {}
371
370
  }
372
371
  return `v2:${h.digest("hex")}`
@@ -412,7 +411,7 @@ export async function loadRepoMap(cwd: string = process.cwd()): Promise<string>
412
411
  const forceRegex = process.env.MINICODE_REPOMAP === "regex"
413
412
  const files = await listSourceFiles(cwd, MAX_FILES)
414
413
  if (files.length === 0) return ""
415
- const sig = signature(files, cwd)
414
+ const sig = await signature(files, cwd)
416
415
  const cp = cachePath(cwd)
417
416
  // Cache hit → langsung pakai (tanpa LSP, cepat)
418
417
  try {
@@ -16,10 +16,9 @@
16
16
  // - Backend tak membuat executionId (M1); handle `be_*` = namespace backend
17
17
  // sendiri, opaque, non-user-controlled, bukan lifecycle authority.
18
18
  // - Opaque handle: caller tak pernah memegang raw ChildProcess.
19
- // - Sandbox shims membungkus runner existing run-to-completion; kill
20
- // preemptif mid-flight = unsupported yang DINYATAKAN (jujur, sesuai evidence
21
- // code_run: abort menghentikan penungguan, container bisa hidup sampai
22
- // timeout runner). Jangan klaim D untuk container.
19
+ // - Sandbox shims membungkus runner existing run-to-completion. Docker runner
20
+ // meminta daemon menghapus container saat timeout; cancel dari backend tetap
21
+ // belum mengirim signal fisik ke runner. Jangan klaim D untuk container.
23
22
  // - MCP/LSP/background-jobs TIDAK dibungkus di sini (lifecycle berbeda:
24
23
  // closeAll/closeAllLsp tetap pemilik; background = tool scope, detached = M7).
25
24
  // - Security parity: spawn SELALU via sanitizeSpawnEnv + resolveTrustedExecutable
@@ -72,7 +71,7 @@ export interface BackendCapability {
72
71
  * - host: killTree grup/taskkill ADA (bash.ts:96-124); tanpa flag CPU/mem/pids;
73
72
  * network hanya guard; FS hanya jail pre-check (TOCTOU terdokumentasi).
74
73
  * - docker: invocation --cpus/--memory/--pids-limit/--network/--read-only ADA
75
- * (docker.ts:58-87); kill eksplisit container TAK ADA (hanya wrapper SIGKILL).
74
+ * (docker.ts:58-87); timeout meminta daemon menjalankan `docker rm --force`.
76
75
  * - bwrap: --unshare-net/--die-with-parent/--cap-drop/bind ADA, tanpa limit
77
76
  * CPU/mem/pids (os.ts:104-135). seatbelt: deny default + deny network* ADA,
78
77
  * policy = restriksi BUKAN kill guarantee (os.ts:91-98).
@@ -109,10 +108,10 @@ export const BACKEND_CAPABILITIES: Record<BackendKind, BackendCapability> = {
109
108
  network: "SUPPORTED",
110
109
  fs: "SUPPORTED",
111
110
  notes: [
112
- "A: timeout wrapper SIGKILL + close observation (docker.ts:116-127).",
111
+ "A: timeout wrapper meminta daemon remove lalu menunggu close Docker CLI (docker.ts).",
113
112
  "B: DELEGATED_TO_RUNTIME — logical stop diputuskan runtime.",
114
- "C: BEST_EFFORT — kill eksplisit container TAK ADA di invocation; hanya wrapper.",
115
- "D: BEST_EFFORT — close wrapper ≠ bukti container mati; jangan klaim D container.",
113
+ "C: BEST_EFFORT — timeout meminta docker rm --force; kegagalan daemon dilaporkan.",
114
+ "D: BEST_EFFORT — permintaan remove bukan bukti fisik mandiri; jangan klaim D container.",
116
115
  "CPU/mem/PID/net/FS: --cpus/--memory/--pids-limit 32/--network none/--read-only+cap-drop+user (docker.ts:58-87).",
117
116
  ],
118
117
  },
@@ -1,4 +1,5 @@
1
1
  import { spawn, spawnSync } from "node:child_process"
2
+ import { randomUUID } from "node:crypto"
2
3
  import { resolve } from "node:path"
3
4
  import { LIMITS } from "../constants.ts"
4
5
  import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
@@ -44,6 +45,45 @@ export interface DockerRunOptions {
44
45
  cpus?: number
45
46
  env?: Record<string, string>
46
47
  timeoutMs?: number
48
+ signal?: AbortSignal
49
+ }
50
+
51
+ let dockerSpawnForTest: typeof spawn | null = null
52
+
53
+ /** Seam untuk mensimulasikan lifecycle Docker tanpa daemon dalam tes. */
54
+ export function setDockerSpawnForTest(spawner: typeof spawn | null): void {
55
+ dockerSpawnForTest = spawner
56
+ }
57
+
58
+ function dockerExecutable(): string {
59
+ return dockerSpawnForTest ? "docker" : resolveTrustedExecutable("docker")
60
+ }
61
+
62
+ function spawnDocker(args: string[], env: NodeJS.ProcessEnv) {
63
+ return (dockerSpawnForTest ?? spawn)(dockerExecutable(), args, {
64
+ stdio: "ignore",
65
+ env,
66
+ })
67
+ }
68
+
69
+ /** Minta daemon menghapus container; timeout membuat kegagalan cleanup eksplisit. */
70
+ function removeContainer(name: string, env: NodeJS.ProcessEnv): Promise<boolean> {
71
+ return new Promise((resolveResult) => {
72
+ let done = false
73
+ const p = spawnDocker(["rm", "--force", name], env)
74
+ const finish = (removed: boolean) => {
75
+ if (done) return
76
+ done = true
77
+ clearTimeout(timer)
78
+ resolveResult(removed)
79
+ }
80
+ const timer = setTimeout(() => {
81
+ p.kill("SIGKILL")
82
+ finish(false)
83
+ }, LIMITS.DOCKER_CLEANUP_TIMEOUT_MS)
84
+ p.on("error", () => finish(false))
85
+ p.on("close", (code) => finish(code === 0))
86
+ })
47
87
  }
48
88
 
49
89
  // Run command di dalam container ephemeral, terisolasi (--network none,
@@ -53,11 +93,17 @@ export function runInDocker(
53
93
  cwd: string,
54
94
  opts: DockerRunOptions = {},
55
95
  ): Promise<{ code: number | null; output: string }> {
96
+ if (opts.signal?.aborted) {
97
+ return Promise.resolve({ code: null, output: "[docker] aborted before container start" })
98
+ }
56
99
  const image = opts.image ?? process.env.MINICODE_SANDBOX_IMAGE ?? "node:22-alpine"
57
100
  const mount = workspaceMount(cwd)
101
+ const containerName = `minicode-${randomUUID()}`
58
102
  const args = [
59
103
  "run",
60
104
  "--rm",
105
+ "--name",
106
+ containerName,
61
107
  "-i",
62
108
  "--read-only",
63
109
  "--cap-drop",
@@ -89,9 +135,10 @@ export function runInDocker(
89
135
  return new Promise((resolveResult) => {
90
136
  // env selalu disanitasi dari hasil merge final — secret (API_KEY/TOKEN/...)
91
137
  // tidak pernah diwarisi container walau caller lupa strip.
92
- const p = spawn(resolveTrustedExecutable("docker"), args, {
138
+ const env = sanitizeSpawnEnv(process.env, opts.env)
139
+ const p = (dockerSpawnForTest ?? spawn)(dockerExecutable(), args, {
93
140
  stdio: ["ignore", "pipe", "pipe"],
94
- env: sanitizeSpawnEnv(process.env, opts.env),
141
+ env,
95
142
  })
96
143
  // Cap buffer saat streaming — output container raksasa tidak menumpuk di RAM.
97
144
  const OUT_CAP = LIMITS.DOCKER_OUTPUT_MAX_CHARS
@@ -113,17 +160,74 @@ export function runInDocker(
113
160
  }
114
161
  p.stdout.on("data", (d) => appendCapped("out", d))
115
162
  p.stderr.on("data", (d) => appendCapped("err", d))
116
- const timeout = opts.timeoutMs ?? LIMITS.DOCKER_TIMEOUT_MS
117
- const t = setTimeout(() => p.kill("SIGKILL"), timeout)
118
- p.on("error", (e) => {
163
+ const timeout =
164
+ typeof opts.timeoutMs === "number" && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
165
+ ? opts.timeoutMs
166
+ : LIMITS.DOCKER_TIMEOUT_MS
167
+ let settled = false
168
+ let closed = false
169
+ let stopReason: "timeout" | "abort" | undefined
170
+ let stopPromise: Promise<boolean> | undefined
171
+ let t: ReturnType<typeof setTimeout>
172
+ const signal = opts.signal
173
+ const finalize = (code: number | null, suffix = "") => {
174
+ if (settled) return
175
+ settled = true
119
176
  clearTimeout(t)
120
- resolveResult({ code: null, output: `[docker] ${e.message}` })
177
+ signal?.removeEventListener("abort", onAbort)
178
+ const marker = truncated ? "\n… [output truncated]" : ""
179
+ const output = (out + (err ? `\n[stderr]\n${err}` : "")).trim() + marker + suffix
180
+ resolveResult({ code, output })
181
+ }
182
+ const requestStop = (reason: "timeout" | "abort") => {
183
+ if (stopReason || settled) return
184
+ stopReason = reason
185
+ clearTimeout(t)
186
+ stopPromise = removeContainer(containerName, env).catch(() => false)
187
+ void stopPromise.then((removed) => {
188
+ if (!closed) p.kill("SIGKILL")
189
+ if (closed) {
190
+ const detail = removed
191
+ ? "daemon container removal confirmed"
192
+ : "daemon cleanup unconfirmed"
193
+ const reasonText = reason === "timeout" ? `timed out after ${timeout}ms` : "aborted"
194
+ finalize(null, `\n[docker] ${reasonText}; ${detail}`)
195
+ }
196
+ })
197
+ }
198
+ const onAbort = () => requestStop("abort")
199
+ t = setTimeout(() => requestStop("timeout"), timeout)
200
+ if (signal) {
201
+ signal.addEventListener("abort", onAbort, { once: true })
202
+ if (signal.aborted) requestStop("abort")
203
+ }
204
+ p.on("error", (e) => {
205
+ closed = true
206
+ if (stopReason) {
207
+ void (stopPromise ?? Promise.resolve(false)).then((removed) => {
208
+ const detail = removed
209
+ ? "daemon container removal confirmed"
210
+ : "daemon cleanup unconfirmed"
211
+ finalize(null, `\n[docker] ${stopReason}; ${detail}`)
212
+ })
213
+ } else {
214
+ finalize(null, `[docker] ${e.message}`)
215
+ }
121
216
  })
122
217
  p.on("close", (code) => {
218
+ closed = true
123
219
  clearTimeout(t)
124
- const marker = truncated ? "\n… [output truncated]" : ""
125
- const output = (out + (err ? `\n[stderr]\n${err}` : "")).trim() + marker
126
- resolveResult({ code, output })
220
+ if (stopReason) {
221
+ void (stopPromise ?? Promise.resolve(false)).then((removed) => {
222
+ const detail = removed
223
+ ? "daemon container removal confirmed"
224
+ : "daemon cleanup unconfirmed"
225
+ const reasonText = stopReason === "timeout" ? `timed out after ${timeout}ms` : "aborted"
226
+ finalize(null, `\n[docker] ${reasonText}; ${detail}`)
227
+ })
228
+ } else {
229
+ finalize(code)
230
+ }
127
231
  })
128
232
  })
129
233
  }
@@ -8,7 +8,7 @@ import { GIT_SAFE_BASE } from "../lib/git-hardening.ts"
8
8
  import { sanitizeSessionPart } from "../lib/session-id.ts"
9
9
  import { isPathOutsideRoot } from "../policy/jail.ts"
10
10
  import { appendUndoMarker, loadJournal } from "./journal.ts"
11
- import { diffTrees, ephemeralTree, restoreTree, snapshotTree } from "./shadow-git.ts"
11
+ import { diffTrees, ephemeralTree, isGitRepo, restoreTree, snapshotTree } from "./shadow-git.ts"
12
12
 
13
13
  /** Alias back-compat: satu-satunya sanitizer kini di lib/session-id.ts (F-17). */
14
14
  export function sanitizeSessionId(id: string): string {
@@ -335,9 +335,16 @@ export async function snapshotWorkspace(
335
335
  export async function beginTurnSnapshot(
336
336
  sessionId: string,
337
337
  cwd: string = process.cwd(),
338
- ): Promise<{ mode: "git"; tree: string } | { mode: "files"; snapshots: FileSnapshot[] }> {
338
+ ): Promise<
339
+ | { mode: "git"; tree: string }
340
+ | { mode: "files"; snapshots: FileSnapshot[] }
341
+ | { mode: "unavailable"; reason: "git-snapshot-failed" }
342
+ > {
339
343
  const shadow = await snapshotTree(cwd, sessionId, "pre")
340
344
  if (shadow) return { mode: "git", tree: shadow.tree }
345
+ // Fallback file snapshot dibatasi 200 path. Memakainya saat repo Git gagal
346
+ // membuat snapshot dapat memberi kesan rollback lengkap padahal parsial.
347
+ if (await isGitRepo(cwd)) return { mode: "unavailable", reason: "git-snapshot-failed" }
341
348
  return { mode: "files", snapshots: await snapshotWorkspace(cwd, LIMITS.WORKSPACE_SNAPSHOT_LIMIT) }
342
349
  }
343
350
 
@@ -739,6 +739,9 @@ function isValidEventShape(value: Record<string, unknown>): boolean {
739
739
  const isStr = (k: string): boolean => typeof value[k] === "string"
740
740
  const isNum = (k: string): boolean => typeof value[k] === "number"
741
741
  const isArr = (k: string): boolean => Array.isArray(value[k])
742
+ const validAttemptId =
743
+ value.attemptId === undefined ||
744
+ (Number.isSafeInteger(value.attemptId) && (value.attemptId as number) > 0)
742
745
  if (!isValidParentLink(value.parentLink)) return false
743
746
  switch (value.type) {
744
747
  case "plan.updated":
@@ -778,7 +781,7 @@ function isValidEventShape(value: Record<string, unknown>): boolean {
778
781
  return true
779
782
  case "model.delta":
780
783
  case "reasoning.delta":
781
- return isStr("delta")
784
+ return isStr("delta") && validAttemptId
782
785
  case "model.completed":
783
786
  case "reasoning.completed":
784
787
  return isStr("text")
@@ -805,7 +808,7 @@ function isValidEventShape(value: Record<string, unknown>): boolean {
805
808
  case "result.produced":
806
809
  return isStr("resultId") && !!value.status
807
810
  case "diagnostic.raised":
808
- return isStr("category") && isStr("message")
811
+ return isStr("category") && isStr("message") && validAttemptId
809
812
  case "consequence.decided":
810
813
  return isStr("verdict") && isStr("failureClass") && isStr("nextAction") && isStr("rationale")
811
814
  case "context.cutoff":