minicode-ai 0.27.0 → 0.28.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.
Files changed (135) hide show
  1. package/cli/args.ts +120 -16
  2. package/cli/commands/acp.ts +38 -28
  3. package/cli/commands/auth.ts +17 -17
  4. package/cli/commands/config.ts +65 -66
  5. package/cli/commands/daemon.ts +44 -16
  6. package/cli/commands/doctor.ts +11 -12
  7. package/cli/commands/exec.ts +35 -73
  8. package/cli/commands/mcp.ts +25 -8
  9. package/cli/commands/memory.ts +16 -24
  10. package/cli/commands/openwork.ts +6 -2
  11. package/cli/commands/pricing.ts +14 -12
  12. package/cli/commands/providers.ts +36 -57
  13. package/cli/commands/sessions.ts +24 -18
  14. package/cli/commands/skills.ts +33 -18
  15. package/cli/commands/stats.ts +15 -30
  16. package/cli/commands.ts +73 -44
  17. package/cli/context-command-run.ts +30 -18
  18. package/cli/index.ts +48 -98
  19. package/cli/model-manager.ts +7 -2
  20. package/cli/provider-manager.ts +33 -18
  21. package/cli/router.ts +41 -12
  22. package/cli/setup.ts +246 -123
  23. package/cli/tui.ts +303 -100
  24. package/docs/TERMINAL_CONTRACT.md +254 -69
  25. package/docs/UI_RENDER_PIPELINE.md +9 -1
  26. package/docs/agents.md +2 -2
  27. package/docs/architecture.md +3 -3
  28. package/docs/choosing-mode.md +7 -9
  29. package/docs/cli.md +3 -5
  30. package/docs/environment.md +1 -2
  31. package/docs/policy-sandbox.md +3 -3
  32. package/docs/repl.md +2 -2
  33. package/docs/tools.md +1 -1
  34. package/package.json +1 -1
  35. package/src/app/mentions.ts +60 -13
  36. package/src/app/rag-layer.ts +17 -20
  37. package/src/app/session.ts +119 -66
  38. package/src/app/tool-layer.ts +12 -17
  39. package/src/config.ts +64 -104
  40. package/src/constants.ts +4 -6
  41. package/src/daemon/capability.ts +8 -1
  42. package/src/daemon/control.ts +3 -2
  43. package/src/daemon/server.ts +57 -0
  44. package/src/hooks/run.ts +73 -41
  45. package/src/lib/db-path.ts +47 -0
  46. package/src/lib/process-tree.ts +62 -0
  47. package/src/lib/public-http.ts +88 -23
  48. package/src/lib/trusted-exec.ts +48 -1
  49. package/src/lsp/client.ts +62 -17
  50. package/src/mcp/client.ts +85 -38
  51. package/src/mcp/http-transport.ts +28 -16
  52. package/src/mcp/transport.ts +42 -6
  53. package/src/memory/files.ts +164 -134
  54. package/src/memory/vector.ts +371 -420
  55. package/src/policy/approval-binding.ts +122 -45
  56. package/src/policy/bash-guard.ts +18 -7
  57. package/src/policy/compaction.ts +51 -18
  58. package/src/policy/context-window.ts +31 -8
  59. package/src/policy/context.ts +62 -36
  60. package/src/policy/executor.ts +17 -7
  61. package/src/policy/microcompact.ts +4 -3
  62. package/src/policy/no-progress.ts +103 -22
  63. package/src/policy/permission.ts +36 -12
  64. package/src/policy/tool-contract.ts +74 -416
  65. package/src/policy/usage.ts +24 -2
  66. package/src/policy/verifier.ts +50 -2
  67. package/src/policy/work-mode.ts +28 -54
  68. package/src/presentation/adapter.ts +24 -16
  69. package/src/providers/provision.ts +6 -56
  70. package/src/providers/responses.ts +1 -0
  71. package/src/runtime/execution-journal.ts +4 -29
  72. package/src/sandbox/docker.ts +58 -34
  73. package/src/sandbox/mask.ts +157 -0
  74. package/src/sandbox/os.ts +107 -73
  75. package/src/session/authority.ts +29 -10
  76. package/src/session/context-projection.ts +6 -5
  77. package/src/session/open-work.ts +26 -3
  78. package/src/session/persistence.ts +25 -58
  79. package/src/session/verification.ts +170 -20
  80. package/src/skills/loader.ts +31 -16
  81. package/src/task/production-scheduler.ts +13 -1
  82. package/src/task/store.ts +20 -37
  83. package/src/telemetry/trace.ts +27 -0
  84. package/src/tools/ask_user.ts +1 -13
  85. package/src/tools/bash.ts +27 -92
  86. package/src/tools/code_run.ts +1 -1
  87. package/src/tools/context.ts +133 -0
  88. package/src/tools/delete_file.ts +3 -2
  89. package/src/tools/edit.ts +37 -72
  90. package/src/tools/git.ts +86 -9
  91. package/src/tools/glob.ts +26 -51
  92. package/src/tools/grep.ts +67 -57
  93. package/src/tools/hashline.ts +4 -0
  94. package/src/tools/lsp.ts +11 -8
  95. package/src/tools/mcp_call.ts +9 -6
  96. package/src/tools/memory.ts +56 -33
  97. package/src/tools/move_file.ts +36 -10
  98. package/src/tools/patch.ts +13 -21
  99. package/src/tools/read_file.ts +18 -25
  100. package/src/tools/read_image.ts +35 -33
  101. package/src/tools/submit_result.ts +29 -8
  102. package/src/tools/task.ts +74 -17
  103. package/src/tools/todo.ts +181 -74
  104. package/src/tools/web_fetch.ts +42 -2
  105. package/src/tools/web_search.ts +47 -8
  106. package/src/ui/approval/prompt.ts +206 -47
  107. package/src/ui/assistant/turn-status.ts +14 -5
  108. package/src/ui/footer.ts +4 -4
  109. package/src/ui/i18n/en.ts +47 -23
  110. package/src/ui/i18n/id.ts +76 -51
  111. package/src/ui/input/input.ts +4 -3
  112. package/src/ui/input/prompt-engine.ts +35 -5
  113. package/src/ui/render/activity-panel.ts +4 -2
  114. package/src/ui/render/hint.ts +7 -4
  115. package/src/ui/render/list.ts +32 -0
  116. package/src/ui/render/markdown.ts +6 -3
  117. package/src/ui/render/notice.ts +19 -0
  118. package/src/ui/render/table-grid.ts +7 -8
  119. package/src/ui/render/theme.ts +113 -39
  120. package/src/ui/runtime/screen.ts +74 -10
  121. package/src/ui/runtime/spinner.ts +19 -6
  122. package/src/ui/screens/dialog.ts +19 -1
  123. package/src/ui/screens/form.ts +80 -35
  124. package/src/ui/screens/model-manager.ts +82 -61
  125. package/src/ui/screens/output-window.ts +263 -0
  126. package/src/ui/screens/picker.ts +94 -81
  127. package/src/ui/screens/provider-manager.ts +100 -69
  128. package/src/ui/screens/wizard.ts +117 -28
  129. package/src/ui/tui/app.ts +196 -33
  130. package/src/ui/tui/transcript.ts +154 -25
  131. package/vendor/minicore/src/core/executor.ts +2 -0
  132. package/vendor/minicore/src/core/loop.ts +17 -6
  133. package/vendor/minicore/src/core/session.ts +3 -0
  134. package/vendor/minicore/src/core/tool.ts +1 -0
  135. package/vendor/minicore/src/providers/openai-compat.ts +28 -19
package/src/config.ts CHANGED
@@ -282,6 +282,36 @@ export async function writeConfigAtomic(path: string, cfg: MinicodeConfig): Prom
282
282
  await atomicWriteText(path, JSON.stringify(cfg, null, 2))
283
283
  }
284
284
 
285
+ /** Baca `.minicode/config.json` lokal SAJA tanpa merge global. */
286
+ export async function loadLocalConfigOnly(cwd = process.cwd()): Promise<MinicodeConfig> {
287
+ try {
288
+ const localPath = resolve(cwd, LOCAL)
289
+ const raw = await readFile(localPath, "utf8")
290
+ return normalizeConfig(JSON.parse(raw))
291
+ } catch (e) {
292
+ // SyntaxError selalu ribut; error baca non-ENOENT (EACCES/…) ribut juga —
293
+ // reset diam-diam membuat override lokal "hilang" tanpa jejak.
294
+ const code = (e as NodeJS.ErrnoException)?.code
295
+ if (e instanceof SyntaxError)
296
+ process.stderr.write(
297
+ `[config] invalid JSON in ${resolve(cwd, LOCAL)}: ${(e as Error).message}\n`,
298
+ )
299
+ else if (code !== "ENOENT")
300
+ process.stderr.write(
301
+ `[config] cannot read ${resolve(cwd, LOCAL)} (${code ?? "error"}) — ignoring local\n`,
302
+ )
303
+ return { providers: [] }
304
+ }
305
+ }
306
+
307
+ export async function hasProviderInLocalConfig(
308
+ providerId: string,
309
+ cwd = process.cwd(),
310
+ ): Promise<boolean> {
311
+ const localCfg = await loadLocalConfigOnly(cwd)
312
+ return localCfg.providers.some((p) => p.id === providerId)
313
+ }
314
+
285
315
  export async function loadConfig(
286
316
  cwd = process.cwd(),
287
317
  opts: { allowLocal?: boolean } = {},
@@ -309,24 +339,7 @@ export async function loadConfig(
309
339
  // (--allow-local-config / MINICODE_ALLOW_LOCAL_CONFIG=1); default = global
310
340
  // saja (fail-closed). Tulis eksplisit (--local) tak terpengaruh.
311
341
  if (opts.allowLocal) {
312
- try {
313
- const localPath = resolve(cwd, LOCAL)
314
- const raw = await readFile(localPath, "utf8")
315
- localCfg = normalizeConfig(JSON.parse(raw))
316
- } catch (e) {
317
- // Sama seperti global: SyntaxError selalu ribut; error baca non-ENOENT
318
- // (EACCES/…) ribut juga — reset diam-diam membuat override lokal
319
- // "hilang" tanpa jejak.
320
- const code = (e as NodeJS.ErrnoException)?.code
321
- if (e instanceof SyntaxError)
322
- process.stderr.write(
323
- `[config] invalid JSON in ${resolve(cwd, LOCAL)}: ${(e as Error).message}\n`,
324
- )
325
- else if (code !== "ENOENT")
326
- process.stderr.write(
327
- `[config] cannot read ${resolve(cwd, LOCAL)} (${code ?? "error"}) — ignoring local\n`,
328
- )
329
- }
342
+ localCfg = await loadLocalConfigOnly(cwd)
330
343
  }
331
344
  // generic merge helper — deduplicate DRY
332
345
  function mergeByKey<T>(global: T[], local: T[], keyFn: (v: T) => string): T[] {
@@ -378,17 +391,22 @@ export async function loadLastModel(): Promise<string | undefined> {
378
391
  }
379
392
  }
380
393
 
381
- export async function saveLastModel(id: string): Promise<void> {
394
+ async function updateStateAtomic(mutate: (cur: Record<string, unknown>) => void): Promise<void> {
382
395
  const path = statePath()
383
396
  return withConfigLock(path, async () => {
384
397
  await mkdir(join(homeDir(), ".minicode"), { recursive: true, mode: 0o700 }).catch(() => {})
385
- // Merge (bukan timpa): state.json menampung preferensi lain (lang).
386
- // Timpa utuh menghapusnya diam-diam.
387
398
  let cur: Record<string, unknown> = {}
388
399
  try {
389
400
  cur = JSON.parse(await readFile(path, "utf8")) as Record<string, unknown>
390
401
  } catch {}
391
- await atomicWriteText(path, JSON.stringify({ ...cur, lastModel: id }))
402
+ mutate(cur)
403
+ await atomicWriteText(path, JSON.stringify(cur))
404
+ })
405
+ }
406
+
407
+ export async function saveLastModel(id: string): Promise<void> {
408
+ return updateStateAtomic((cur) => {
409
+ cur.lastModel = id
392
410
  })
393
411
  }
394
412
 
@@ -404,23 +422,16 @@ export async function loadLang(): Promise<"en" | "id" | undefined> {
404
422
  }
405
423
 
406
424
  export async function saveLang(lang: "en" | "id"): Promise<void> {
407
- const path = statePath()
408
- return withConfigLock(path, async () => {
409
- await mkdir(join(homeDir(), ".minicode"), { recursive: true, mode: 0o700 }).catch(() => {})
410
- let cur: Record<string, unknown> = {}
411
- try {
412
- cur = JSON.parse(await readFile(path, "utf8")) as Record<string, unknown>
413
- } catch {}
414
- await atomicWriteText(path, JSON.stringify({ ...cur, lang }))
425
+ return updateStateAtomic((cur) => {
426
+ cur.lang = lang
415
427
  })
416
428
  }
417
429
 
418
- export async function saveMcpServer(
419
- entry: McpServerEntry,
420
- opts: { global?: boolean; cwd?: string } = {},
421
- ) {
422
- if (!entry.id || (!entry.command && !entry.url))
423
- throw new Error("mcp entry needs an id + (command for stdio or url for http)")
430
+ /** Pembaru atomik bersama untuk file config global/lokal dengan proteksi corrupt backup. */
431
+ export async function updateConfigAtomic(
432
+ opts: { global?: boolean; cwd?: string },
433
+ mutate: (cfg: MinicodeConfig) => void,
434
+ ): Promise<void> {
424
435
  const path =
425
436
  (opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
426
437
  return withConfigLock(path, async () => {
@@ -435,46 +446,33 @@ export async function saveMcpServer(
435
446
  await atomicWriteText(backup, raw).catch(() => {})
436
447
  throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
437
448
  }
438
- if ((e as NodeJS.ErrnoException).code === "ENOENT") {
439
- cfg = { providers: [] }
440
- } else if ((e as Error).message?.includes("config corrupt")) {
449
+ if ((e as Error).message?.includes("config corrupt")) throw e
450
+ if ((e as NodeJS.ErrnoException).code && (e as NodeJS.ErrnoException).code !== "ENOENT") {
441
451
  throw e
442
- } else if ((e as NodeJS.ErrnoException).code) {
443
- throw e
444
- } else {
445
- cfg = { providers: [] }
446
452
  }
447
453
  }
454
+ mutate(cfg)
455
+ await writeConfigAtomic(path, cfg)
456
+ })
457
+ }
458
+
459
+ export async function saveMcpServer(
460
+ entry: McpServerEntry,
461
+ opts: { global?: boolean; cwd?: string } = {},
462
+ ) {
463
+ if (!entry.id || (!entry.command && !entry.url))
464
+ throw new Error("mcp entry needs an id + (command for stdio or url for http)")
465
+ return updateConfigAtomic(opts, (cfg) => {
448
466
  cfg.mcpServers ??= []
449
467
  const idx = cfg.mcpServers.findIndex((m) => m.id === entry.id)
450
468
  if (idx >= 0) cfg.mcpServers[idx] = entry
451
469
  else cfg.mcpServers.push(entry)
452
- await writeConfigAtomic(path, cfg)
453
470
  })
454
471
  }
455
472
 
456
473
  export async function removeMcpServer(id: string, opts: { global?: boolean; cwd?: string } = {}) {
457
- const path =
458
- (opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
459
- return withConfigLock(path, async () => {
460
- let cfg: MinicodeConfig = { providers: [] }
461
- let raw = ""
462
- try {
463
- raw = await readFile(path, "utf8")
464
- cfg = normalizeConfig(JSON.parse(raw))
465
- } catch (e) {
466
- if (e instanceof SyntaxError) {
467
- const backup = `${path}.corrupt.${Date.now()}`
468
- await atomicWriteText(backup, raw).catch(() => {})
469
- throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
470
- }
471
- if ((e as NodeJS.ErrnoException).code === "ENOENT") cfg = { providers: [] }
472
- else if ((e as Error).message?.includes("config corrupt")) throw e
473
- else if ((e as NodeJS.ErrnoException).code) throw e
474
- else cfg = { providers: [] }
475
- }
474
+ return updateConfigAtomic(opts, (cfg) => {
476
475
  cfg.mcpServers = (cfg.mcpServers ?? []).filter((m) => m.id !== id)
477
- await writeConfigAtomic(path, cfg)
478
476
  })
479
477
  }
480
478
 
@@ -487,55 +485,17 @@ export async function saveLspServer(
487
485
  opts: { global?: boolean; cwd?: string } = {},
488
486
  ) {
489
487
  if (!entry.ext || !entry.command) throw new Error("lsp ext/command required")
490
- const path =
491
- (opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
492
- return withConfigLock(path, async () => {
493
- let cfg: MinicodeConfig = { providers: [] }
494
- let raw = ""
495
- try {
496
- raw = await readFile(path, "utf8")
497
- cfg = normalizeConfig(JSON.parse(raw))
498
- } catch (e) {
499
- if (e instanceof SyntaxError) {
500
- const backup = `${path}.corrupt.${Date.now()}`
501
- await atomicWriteText(backup, raw).catch(() => {})
502
- throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
503
- }
504
- if ((e as NodeJS.ErrnoException).code === "ENOENT") cfg = { providers: [] }
505
- else if ((e as Error).message?.includes("config corrupt")) throw e
506
- else if ((e as NodeJS.ErrnoException).code) throw e
507
- else cfg = { providers: [] }
508
- }
488
+ return updateConfigAtomic(opts, (cfg) => {
509
489
  cfg.lspServers ??= []
510
490
  const ext = normalizeExt(entry.ext)
511
491
  const idx = cfg.lspServers.findIndex((l) => l.ext.toLowerCase() === ext)
512
492
  if (idx >= 0) cfg.lspServers[idx] = { ...entry, ext }
513
493
  else cfg.lspServers.push({ ...entry, ext })
514
- await writeConfigAtomic(path, cfg)
515
494
  })
516
495
  }
517
496
 
518
497
  export async function removeLspServer(ext: string, opts: { global?: boolean; cwd?: string } = {}) {
519
- const path =
520
- (opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
521
- return withConfigLock(path, async () => {
522
- let cfg: MinicodeConfig = { providers: [] }
523
- let raw = ""
524
- try {
525
- raw = await readFile(path, "utf8")
526
- cfg = normalizeConfig(JSON.parse(raw))
527
- } catch (e) {
528
- if (e instanceof SyntaxError) {
529
- const backup = `${path}.corrupt.${Date.now()}`
530
- await atomicWriteText(backup, raw).catch(() => {})
531
- throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
532
- }
533
- if ((e as NodeJS.ErrnoException).code === "ENOENT") cfg = { providers: [] }
534
- else if ((e as Error).message?.includes("config corrupt")) throw e
535
- else if ((e as NodeJS.ErrnoException).code) throw e
536
- else cfg = { providers: [] }
537
- }
498
+ return updateConfigAtomic(opts, (cfg) => {
538
499
  cfg.lspServers = (cfg.lspServers ?? []).filter((l) => l.ext.toLowerCase() !== normalizeExt(ext))
539
- await writeConfigAtomic(path, cfg)
540
500
  })
541
501
  }
package/src/constants.ts CHANGED
@@ -22,8 +22,10 @@ export const LIMITS = {
22
22
  /** Batas untuk meminta daemon Docker menghapus container yang timeout/abort. */
23
23
  DOCKER_CLEANUP_TIMEOUT_MS: 5_000,
24
24
  MCP_OUTPUT_MAX_CHARS: 100_000,
25
- /** Batas frame JSON-RPC stdio sebelum decode/parse; satu respons tools/list bisa besar. */
25
+ /** Batas frame JSON-RPC stdio default (diuji kontrak); koneksi MCP produksi dapat memberi pagu lebih besar untuk screenshot/DOM. */
26
26
  MCP_STDIO_FRAME_MAX_BYTES: 1_048_576,
27
+ /** Batas respons mentah MCP (HTTP body & stdio koneksi produksi = 8 MiB) agar screenshot/snapshot browser tidak terpotong atau meng-kill server. */
28
+ MCP_HTTP_BODY_MAX_BYTES: 8_388_608,
27
29
  MCP_REQUEST_TIMEOUT_MS: 30_000,
28
30
  TASK_SUB_AGENT_MAX_TOKENS: 2_000,
29
31
  /** Context & memory */
@@ -53,10 +55,6 @@ export const LIMITS = {
53
55
  * angka 0.5 tersebar inline di compaction.ts tanpa nama (magic number). */
54
56
  COMPACTION_SUMMARY_TARGET_RATIO: 0.5,
55
57
  COMPACTION_LLM_TIMEOUT_MS: 10_000,
56
- /** Batas atas cadangan output (framing + respons minimum) saat admission
57
- * request provider: `Math.min(reserve, limit/10)` — cadangan tak naik tanpa
58
- * batas pada jendela raksasa (1M token tetap cukup 256 untuk framing). */
59
- CONTEXT_WINDOW_RESERVE_CAP_TOKENS: 256,
60
58
  /** BATAS ATAS ambang ukuran konteks (estimasi chars/token lokal) untuk
61
59
  * mengklasifikasi 400 `invalid_request` generik sebagai
62
60
  * `context_length_exceeded` alih-alih mati fatal. Di bawah ambang ini, 400
@@ -195,7 +193,7 @@ export const LIMITS = {
195
193
  DETECT_MODELS_TIMEOUT_MS: 4_000,
196
194
  DETECT_GLOBAL_TIMEOUT_MS: 6_000,
197
195
  DETECT_ATTEMPT_TIMEOUT_MS: 2_500,
198
- MCP_HANDSHAKE_TIMEOUT_MS: 3_000,
196
+ MCP_HANDSHAKE_TIMEOUT_MS: 15_000,
199
197
  /** OAuth device flow: request pendek, tapi poll bisa berlangsung menit. */
200
198
  OAUTH_REQUEST_TIMEOUT_MS: 15_000,
201
199
  /** Pricing dari models.dev — cache agar tidak menembak jaringan tiap run. */
@@ -107,7 +107,14 @@ export function verifyCapability(
107
107
  } catch {
108
108
  return { ok: false, reason: "MALFORMED" }
109
109
  }
110
- if (payload?.v !== 1 || !Array.isArray(payload.scopes)) return { ok: false, reason: "MALFORMED" }
110
+ if (
111
+ payload?.v !== 1 ||
112
+ !Array.isArray(payload.scopes) ||
113
+ typeof payload.n !== "string" ||
114
+ payload.n.length === 0 ||
115
+ typeof payload.who !== "string"
116
+ )
117
+ return { ok: false, reason: "MALFORMED" }
111
118
  if (payload.inc !== opts.incarnation) return { ok: false, reason: "STALE_INCARNATION" }
112
119
  const now = opts.now ?? Date.now()
113
120
  if (typeof payload.exp !== "number" || payload.exp <= now) return { ok: false, reason: "EXPIRED" }
@@ -22,7 +22,7 @@ export interface HostedSessionInfo {
22
22
  runStatus: string | null
23
23
  presentationHead: number
24
24
  /** P0.2 (Q5): WorkMode efektif sesi yang di-host (bila diketahui host). */
25
- workMode?: "DISCUSS" | "PLAN" | "BUILD"
25
+ workMode?: "DISCUSS" | "BUILD"
26
26
  /**
27
27
  * P2.3: hasil recovery run terakhir yang durable (mis. UNKNOWN setelah
28
28
  * restart). Operator dapat membedakan LIVE vs reconstructed/interrupted
@@ -273,6 +273,7 @@ function runOp(op: ControlOp, req: ControlRequest, deps: ControlDeps): ControlOu
273
273
  }
274
274
 
275
275
  case "approval.decide": {
276
+ if (!sid) return refuse("SESSION_MISMATCH", "args.sid wajib diisi")
276
277
  const approvalId = typeof args.approvalId === "string" ? args.approvalId : ""
277
278
  const decisionRaw = typeof args.decision === "string" ? args.decision : ""
278
279
  if (!approvalId) return refuse("SESSION_MISMATCH", "args.approvalId wajib diisi")
@@ -282,7 +283,7 @@ function runOp(op: ControlOp, req: ControlRequest, deps: ControlDeps): ControlOu
282
283
  // [RC-2] Cek kepemilikan session SEBELUM mutasi DB: baca baris tanpa menulis,
283
284
  // tolak mismatch SESSION_MISMATCH tanpa membangunkan waiter/mengubah state.
284
285
  const existing = deps.approvals.read(approvalId)
285
- if (sid && existing && existing.sid !== sid) {
286
+ if (existing && existing.sid !== sid) {
286
287
  // Approval milik sesi lain: menolaknya menggagalkan keputusan yang
287
288
  // sebenarnya valid, jadi jangan — laporkan kecocokan yang salah saja.
288
289
  return refuse("SESSION_MISMATCH", "approval bukan milik sesi yang disebut", {
@@ -72,6 +72,10 @@ export interface DaemonServerDeps {
72
72
  maxQueuePerSubscription?: number
73
73
  /** Seam uji: batas antrean per identitas konsumen logis (lihat host). */
74
74
  maxQueuePerConsumer?: (consumerId: string) => number | undefined
75
+ /** Batas koneksi pra-handshake bersamaan (anti-slowloris). Default 32. */
76
+ maxPendingHandshakes?: number
77
+ /** Batas waktu menunggu `hello` setelah TCP tersambung. Default 5000 ms. */
78
+ preAuthTimeoutMs?: number
75
79
  /** Dipanggil saat daemon menerima koneksi (diagnostik). */
76
80
  onConnection?: (info: { remote: string; consumer: string }) => void
77
81
  }
@@ -81,6 +85,7 @@ interface Conn {
81
85
  socket: Socket
82
86
  decoder: FrameDecoder
83
87
  state: "new" | "ready"
88
+ authTimer: ReturnType<typeof setTimeout> | null
84
89
  /**
85
90
  * Identitas logis (dari capability `who`) untuk offset durable, idempotensi,
86
91
  * dan label wire. Stabil lintas reconnect.
@@ -106,12 +111,15 @@ let connSeq = 0
106
111
  // kendali). Scope live = identitas logis + id koneksi, sehingga dua koneksi
107
112
  // konsumen yang sama tidak pernah berbagi kunci langganan.
108
113
  const CONSUMER_SCOPE_SEP = String.fromCharCode(1)
114
+ const DEFAULT_MAX_PENDING_HANDSHAKES = 32
115
+ const DEFAULT_PRE_AUTH_TIMEOUT_MS = 5_000
109
116
 
110
117
  export class DaemonServer {
111
118
  readonly #deps: DaemonServerDeps
112
119
  readonly #subs: SubscriptionRegistry
113
120
  readonly #conns = new Map<number, Conn>()
114
121
  readonly #liveUnsub = new Map<string, () => void>()
122
+ readonly #revokedNonces = new Map<string, number>()
115
123
  #server: Server | null = null
116
124
  #port = 0
117
125
  #closing = false
@@ -154,12 +162,26 @@ export class DaemonServer {
154
162
  }
155
163
 
156
164
  #onConnection(socket: Socket): void {
165
+ const maxPending = this.#deps.maxPendingHandshakes ?? DEFAULT_MAX_PENDING_HANDSHAKES
166
+ let pendingCount = 0
167
+ for (const c of this.#conns.values()) {
168
+ if (!c.closed && c.state === "new") pendingCount++
169
+ }
170
+ if (pendingCount >= maxPending) {
171
+ this.#deps.telemetry.inc("connections.rejected")
172
+ try {
173
+ socket.destroy()
174
+ } catch {}
175
+ return
176
+ }
157
177
  this.#deps.telemetry.inc("connections.opened")
178
+ const preAuthMs = this.#deps.preAuthTimeoutMs ?? DEFAULT_PRE_AUTH_TIMEOUT_MS
158
179
  const conn: Conn = {
159
180
  id: ++connSeq,
160
181
  socket,
161
182
  decoder: new FrameDecoder(),
162
183
  state: "new",
184
+ authTimer: null,
163
185
  consumerId: null,
164
186
  subscriptionScope: null,
165
187
  scopes: [],
@@ -167,6 +189,13 @@ export class DaemonServer {
167
189
  paused: false,
168
190
  closed: false,
169
191
  }
192
+ conn.authTimer = setTimeout(() => {
193
+ if (conn.closed || conn.state !== "new") return
194
+ this.#deps.telemetry.inc("connections.rejected")
195
+ this.#sendError(conn, "PROTOCOL_ERROR", "timeout menunggu handshake hello")
196
+ this.#halt(conn, "PROTOCOL_ERROR")
197
+ }, preAuthMs)
198
+ conn.authTimer.unref?.()
170
199
  this.#conns.set(conn.id, conn)
171
200
 
172
201
  socket.on("data", (chunk: Buffer) => {
@@ -197,6 +226,10 @@ export class DaemonServer {
197
226
  #teardown(conn: Conn): void {
198
227
  if (conn.closed) return
199
228
  conn.closed = true
229
+ if (conn.authTimer) {
230
+ clearTimeout(conn.authTimer)
231
+ conn.authTimer = null
232
+ }
200
233
  this.#deps.telemetry.inc("connections.closed")
201
234
  // Tutup HANYA langganan milik koneksi ini. Memakai consumerId logis di sini
202
235
  // akan ikut memutus koneksi lain yang memakai identitas konsumen sama.
@@ -330,6 +363,17 @@ export class DaemonServer {
330
363
  return
331
364
  }
332
365
  const payload: CapabilityPayload = check.payload
366
+ this.#pruneRevoked(Date.now())
367
+ if (this.#revokedNonces.has(payload.n)) {
368
+ this.#deps.telemetry.inc("connections.rejected")
369
+ this.#sendError(conn, "INVALID_CAPABILITY", "capability telah dicabut")
370
+ this.#teardown(conn)
371
+ return
372
+ }
373
+ if (conn.authTimer) {
374
+ clearTimeout(conn.authTimer)
375
+ conn.authTimer = null
376
+ }
333
377
  conn.state = "ready"
334
378
  conn.scopes = payload.scopes
335
379
  conn.consumerId = sanitizeLabel(payload.who, 120) || `consumer-${conn.id}`
@@ -653,6 +697,19 @@ export class DaemonServer {
653
697
  })
654
698
  }
655
699
 
700
+ /** Cabut nonce capability yang bocor sebelum masa berlaku `exp` habis. */
701
+ revokeCapabilityNonce(nonce: string, expMs = Date.now() + 24 * 60 * 60 * 1000): void {
702
+ if (!nonce) return
703
+ this.#pruneRevoked(Date.now())
704
+ this.#revokedNonces.set(nonce, expMs)
705
+ }
706
+
707
+ #pruneRevoked(now: number): void {
708
+ for (const [n, exp] of this.#revokedNonces) {
709
+ if (exp <= now) this.#revokedNonces.delete(n)
710
+ }
711
+ }
712
+
656
713
  get startedAt(): number {
657
714
  return this.#startedAt
658
715
  }
package/src/hooks/run.ts CHANGED
@@ -2,6 +2,8 @@ import { spawn } from "node:child_process"
2
2
  import { existsSync, readdirSync } from "node:fs"
3
3
  import { homedir } from "node:os"
4
4
  import { join, resolve } from "node:path"
5
+ import { killProcessTree, signalProcessGroupGraceful } from "../lib/process-tree.ts"
6
+ import { isRealPathOutsideRoot } from "../policy/jail.ts"
5
7
  import { sanitizeSpawnEnv } from "../policy/scrub.ts"
6
8
 
7
9
  export interface RunHookCtx {
@@ -11,6 +13,11 @@ export interface RunHookCtx {
11
13
  result?: unknown
12
14
  }
13
15
 
16
+ export interface RunHooksOptions {
17
+ /** Izinkan hook lokal `<cwd>/.minicode/hooks` (hanya bila `--allow-local-config`). */
18
+ allowLocal?: boolean
19
+ }
20
+
14
21
  /**
15
22
  * Guard mode untuk hooks (audit #10 P1): hooks berjalan di luar permission
16
23
  * system — di mode tanpa-eksekusi (plan/readonly) hook TETAP mengeksekusi
@@ -23,32 +30,44 @@ export interface RunHookCtx {
23
30
  * tulis/eksekusi). Pemanggil legacy tanpa workMode memakai keputusan murni
24
31
  * permission mode (default undefined = perilaku lama).
25
32
  */
26
- export function shouldRunHooks(
27
- permissionMode: string,
28
- workMode?: "DISCUSS" | "PLAN" | "EXECUTE",
29
- ): boolean {
30
- // P0.2 (Q3): hooks berjalan di luar permission system dengan akses penuh
31
- // Node.js/filesystem/jaringan, sehingga DILARANG di DISCUSS maupun PLAN
32
- // untuk seluruh PermissionMode. Hanya WorkMode EXECUTE (atau pemanggil
33
- // legacy tanpa argumen workMode) yang boleh menjalankan hooks.
33
+ export function shouldRunHooks(permissionMode: string, workMode?: "DISCUSS" | "EXECUTE"): boolean {
34
+ // Hooks berjalan di luar permission system dengan akses penuh Node.js/FS/jaringan,
35
+ // sehingga DILARANG di DISCUSS untuk seluruh PermissionMode. Hanya WorkMode EXECUTE
36
+ // (atau pemanggil legacy tanpa argumen workMode) yang boleh menjalankan hooks.
34
37
  if (workMode !== undefined && workMode !== "EXECUTE") return false
35
38
  return permissionMode !== "plan" && permissionMode !== "readonly"
36
39
  }
37
40
 
38
- // 6.4 — hooks global opt-in: ~/.minicode/hooks/{pre,post}*.js dan
39
- // .minicode/hooks/{pre,post}*.js. Berjalan sebagai node script terpisah
40
- // dengan konteks di env MINICODE_HOOK_CTX (JSON). Opt-in via MINICODE_HOOKS=1
41
- // supaya tidak mengubah perilaku default (aman, tanpa efek samping).
42
- export function findRunHooks(cwd?: string): { pre: string[]; post: string[] } {
43
- const dirs: string[] = [join(homedir(), ".minicode", "hooks")]
44
- if (cwd) dirs.push(resolve(cwd, ".minicode", "hooks"))
41
+ // 6.4 — hooks global opt-in: ~/.minicode/hooks/{pre,post}*.js, dan lokal
42
+ // .minicode/hooks/{pre,post}*.js (fail-closed: lokal butuh allowLocal=true
43
+ // agar menyalakan MINICODE_HOOKS=1 global tak mengeksekusi JS repo asing).
44
+ // Berjalan sebagai node script terpisah dengan konteks di env MINICODE_HOOK_CTX.
45
+ export function findRunHooks(
46
+ cwd?: string,
47
+ opts: RunHooksOptions = {},
48
+ ): { pre: string[]; post: string[] } {
49
+ const dirs: { dir: string; jail: boolean }[] = [
50
+ { dir: join(homedir(), ".minicode", "hooks"), jail: false },
51
+ ]
52
+ if (cwd && opts.allowLocal === true) {
53
+ dirs.push({ dir: resolve(cwd, ".minicode", "hooks"), jail: true })
54
+ }
45
55
  const out = { pre: [] as string[], post: [] as string[] }
46
- for (const dir of dirs) {
56
+ for (const { dir, jail } of dirs) {
47
57
  if (!existsSync(dir)) continue
48
- for (const f of readdirSync(dir)) {
58
+ let entries: string[]
59
+ try {
60
+ entries = readdirSync(dir)
61
+ } catch {
62
+ continue
63
+ }
64
+ for (const f of entries) {
49
65
  if (!f.endsWith(".js")) continue
50
- if (f.includes("pre")) out.pre.push(join(dir, f))
51
- else if (f.includes("post")) out.post.push(join(dir, f))
66
+ const full = join(dir, f)
67
+ // Symlink di dalam .minicode/hooks tak boleh lolos keluar direktori hook.
68
+ if (jail && isRealPathOutsideRoot(full, dir)) continue
69
+ if (f.startsWith("pre")) out.pre.push(full)
70
+ else if (f.startsWith("post")) out.post.push(full)
52
71
  }
53
72
  }
54
73
  return out
@@ -58,15 +77,15 @@ export async function runRunHooks(
58
77
  phase: "pre" | "post",
59
78
  ctx: RunHookCtx,
60
79
  signal?: AbortSignal,
80
+ opts: RunHooksOptions = {},
61
81
  ): Promise<void> {
62
82
  if (process.env.MINICODE_HOOKS !== "1") return
63
- // Hook = arbitrary Node.js di luar permission system (berjalan di SEMUA
64
- // mode bila opt-in) — karenanya: tanpa secret di env (baca dari berkas bila
65
- // perlu), dan hormati pembatalan sesi (lewati sisa hook bila aborted).
66
- // MINICODE_HOOK_CTX sendiri memuat prompt user apa adanya — prompt yang
67
- // ditempeli kredensial akan terlihat hook; itu inheren dari desain.
83
+ // Hook = arbitrary Node.js di luar permission system (berjalan di EXECUTE
84
+ // bila opt-in) — karenanya: tanpa secret di env (baca dari berkas bila
85
+ // perlu), hormati pembatalan sesi secara instan, dan tree-kill saat timeout.
68
86
  if (signal?.aborted) return
69
- const hooks = findRunHooks(ctx.cwd)
87
+ const hooks = findRunHooks(ctx.cwd, opts)
88
+ const baseKillEnv = sanitizeSpawnEnv(process.env)
70
89
  for (const file of hooks[phase]) {
71
90
  if (signal?.aborted) return
72
91
  // Audit #10 P2 observability: hook adalah eksekusi di luar permission
@@ -79,25 +98,38 @@ export async function runRunHooks(
79
98
  const p = spawn(process.execPath, [file], {
80
99
  env: sanitizeSpawnEnv(process.env, { MINICODE_HOOK_CTX: JSON.stringify(ctx) }),
81
100
  stdio: "ignore",
101
+ detached: process.platform !== "win32",
82
102
  })
83
- const timer = setTimeout(() => {
84
- try {
85
- p.kill("SIGTERM")
86
- setTimeout(() => {
87
- try {
88
- p.kill("SIGKILL")
89
- } catch {}
90
- }, 1000)
91
- } catch {}
92
- }, 5000)
93
- p.on("error", () => {
103
+ let settled = false
104
+ let killTimer: ReturnType<typeof setTimeout> | undefined
105
+ const cleanup = (): void => {
106
+ if (settled) return
107
+ settled = true
94
108
  clearTimeout(timer)
109
+ if (killTimer) clearTimeout(killTimer)
110
+ signal?.removeEventListener("abort", onAbort)
95
111
  res()
96
- })
97
- p.on("exit", () => {
98
- clearTimeout(timer)
99
- res()
100
- })
112
+ }
113
+ const terminateHook = (): void => {
114
+ if (settled) return
115
+ if (process.platform === "win32") {
116
+ killProcessTree(p, { env: baseKillEnv })
117
+ return
118
+ }
119
+ signalProcessGroupGraceful(p.pid, p)
120
+ killTimer = setTimeout(() => {
121
+ killProcessTree(p, { env: baseKillEnv })
122
+ }, 1000)
123
+ killTimer.unref?.()
124
+ }
125
+ const onAbort = (): void => {
126
+ killProcessTree(p, { env: baseKillEnv })
127
+ }
128
+ const timer = setTimeout(terminateHook, 5000)
129
+ signal?.addEventListener("abort", onAbort, { once: true })
130
+ if (signal?.aborted) onAbort()
131
+ p.on("error", cleanup)
132
+ p.on("close", cleanup)
101
133
  })
102
134
  }
103
135
  }
@@ -60,3 +60,50 @@ export function resolveLocalDbPath(filename: string, cwd?: string): string {
60
60
  } catch {}
61
61
  return join(dir, filename)
62
62
  }
63
+
64
+ const SQLITE_CONTENTION_RE =
65
+ /SQLITE_BUSY|database is locked|database table is locked|SQLITE_LOCKED|SQLITE_PROTOCOL|SQLITE_IOERR_TRUNCATE|SQLITE_IOERR_SHMOPEN|SQLITE_IOERR_LOCK|disk I\/O error/i
66
+
67
+ /** Predikat kontensi SQLite transien lintas-proses (aman di-retry; bukan korupsi/constraint). */
68
+ export function isSqliteContention(e: unknown): boolean {
69
+ const code = (e as { code?: unknown } | null)?.code
70
+ if (typeof code === "string" && SQLITE_CONTENTION_RE.test(code)) return true
71
+ const msg = e instanceof Error ? String(e.message ?? e) : String(e)
72
+ return SQLITE_CONTENTION_RE.test(msg)
73
+ }
74
+
75
+ export function withSqliteBusyRetrySync<T>(
76
+ fn: () => T,
77
+ opts: {
78
+ attempts?: number
79
+ backoffMs?: number
80
+ jitterMaxMs?: number
81
+ deterministicJitter?: boolean
82
+ onGiveUp?: (last: unknown, attempts: number) => void
83
+ } = {},
84
+ ): T | null {
85
+ const attempts = opts.attempts ?? 8
86
+ const backoffMs = opts.backoffMs ?? 15
87
+ const jitterMax = opts.jitterMaxMs ?? 0
88
+ let last: unknown
89
+ for (let i = 0; i < attempts; i++) {
90
+ try {
91
+ return fn()
92
+ } catch (e) {
93
+ if (!isSqliteContention(e)) throw e
94
+ last = e
95
+ if (i + 1 >= attempts) break
96
+ const base = backoffMs * 2 ** i
97
+ const jitter = opts.deterministicJitter
98
+ ? i === 0
99
+ ? 0
100
+ : (i * 7919 + 3) % Math.max(1, Math.floor(base * 0.2))
101
+ : jitterMax > 0
102
+ ? Math.floor(Math.random() * jitterMax)
103
+ : 0
104
+ Bun.sleepSync(base + jitter)
105
+ }
106
+ }
107
+ opts.onGiveUp?.(last, attempts)
108
+ return null
109
+ }