minicode-ai 0.14.1 → 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 (79) hide show
  1. package/README.md +1 -1
  2. package/cli/auto-update.ts +32 -2
  3. package/cli/index.ts +10 -2
  4. package/cli/setup.ts +8 -3
  5. package/cli/tui.ts +18 -15
  6. package/docs/OUTPUT_PROTOCOL_SPEC.md +6 -0
  7. package/docs/OUTPUT_RENDERING_SPEC.md +28 -4
  8. package/docs/README.md +2 -2
  9. package/docs/TERMINAL_CONTRACT.md +52 -26
  10. package/docs/getting-started.md +14 -12
  11. package/docs/glossary.md +1 -1
  12. package/docs/mcp-lsp.md +1 -1
  13. package/docs/policy-sandbox.md +7 -1
  14. package/docs/security-model.md +2 -2
  15. package/docs/security.md +7 -1
  16. package/docs/tools.md +4 -4
  17. package/docs/verify-benchmark.md +16 -0
  18. package/package.json +1 -3
  19. package/src/app/mentions.ts +4 -3
  20. package/src/app/session.ts +13 -9
  21. package/src/app/tool-layer.ts +6 -0
  22. package/src/constants.ts +17 -0
  23. package/src/lib/git-hardening.ts +27 -22
  24. package/src/lib/safe-open.ts +73 -19
  25. package/src/lib/trusted-exec.ts +7 -4
  26. package/src/mcp/client.ts +34 -9
  27. package/src/mcp/transport.ts +96 -42
  28. package/src/memory/files.ts +15 -4
  29. package/src/memory/vector.ts +5 -1
  30. package/src/policy/context.ts +21 -13
  31. package/src/policy/tool-contract.ts +4 -10
  32. package/src/policy/update-check.ts +83 -6
  33. package/src/policy/usage.ts +17 -7
  34. package/src/presentation/adapter.ts +64 -2
  35. package/src/presentation/events.ts +6 -0
  36. package/src/presentation/model.ts +1 -0
  37. package/src/presentation/projection.ts +2 -0
  38. package/src/presentation/reducer.ts +1 -0
  39. package/src/providers/anthropic.ts +52 -19
  40. package/src/providers/guards.ts +98 -13
  41. package/src/providers/responses.ts +61 -23
  42. package/src/providers/sse-bounds.ts +170 -0
  43. package/src/repo/repomap.ts +10 -11
  44. package/src/runtime/execution-backend.ts +7 -8
  45. package/src/sandbox/docker.ts +113 -9
  46. package/src/session/checkpoint.ts +9 -2
  47. package/src/session/persistence.ts +5 -2
  48. package/src/session/verification.ts +55 -16
  49. package/src/skills/loader.ts +16 -3
  50. package/src/tools/bash.ts +6 -3
  51. package/src/tools/code_run.ts +6 -5
  52. package/src/tools/context.ts +8 -0
  53. package/src/tools/delete_file.ts +2 -1
  54. package/src/tools/edit.ts +2 -1
  55. package/src/tools/git.ts +128 -54
  56. package/src/tools/glob.ts +2 -1
  57. package/src/tools/grep.ts +31 -6
  58. package/src/tools/lsp.ts +5 -4
  59. package/src/tools/mcp_call.ts +3 -1
  60. package/src/tools/memory.ts +175 -180
  61. package/src/tools/move_file.ts +2 -1
  62. package/src/tools/patch.ts +2 -1
  63. package/src/tools/read_file.ts +94 -1
  64. package/src/tools/read_image.ts +2 -1
  65. package/src/tools/task.ts +2 -1
  66. package/src/tools/todo.ts +4 -5
  67. package/src/tools/web_fetch.ts +28 -12
  68. package/src/tools/web_search.ts +28 -9
  69. package/src/tools/write_file.ts +2 -1
  70. package/src/ui/assistant/simple.ts +72 -3
  71. package/src/ui/i18n/en.ts +3 -0
  72. package/src/ui/i18n/id.ts +3 -0
  73. package/src/ui/render/width.ts +107 -79
  74. package/src/ui/runtime/screen.ts +49 -37
  75. package/src/ui/tui/app.ts +255 -205
  76. package/src/ui/tui/transcript.ts +39 -0
  77. package/CHANGELOG.md +0 -1185
  78. package/docs/PLAN_UIUX_V6.md +0 -209
  79. package/docs/changelog.md +0 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minicode-ai",
3
- "version": "0.14.1",
3
+ "version": "0.14.2",
4
4
  "description": "Coding agent CLI built on the frozen MiniCore runtime — tools, MCP, LSP, sandbox, shadow-git checkpoints",
5
5
  "type": "module",
6
6
  "private": false,
@@ -49,7 +49,6 @@
49
49
  "vendor/minicore/package.json",
50
50
  "vendor/minicore/VENDOR.md",
51
51
  "README.md",
52
- "CHANGELOG.md",
53
52
  "LICENSE",
54
53
  "docs/OUTPUT_ARCHITECTURE_AUDIT.md",
55
54
  "docs/OUTPUT_EVENT_MODEL.md",
@@ -57,7 +56,6 @@
57
56
  "docs/OUTPUT_PROTOCOL_SPEC.md",
58
57
  "docs/OUTPUT_RENDERING_SPEC.md",
59
58
  "docs/OUTPUT_UX_RULES.md",
60
- "docs/PLAN_UIUX_V6.md",
61
59
  "docs/TERMINAL_CONTRACT.md",
62
60
  "docs/agents.md",
63
61
  "docs/architecture.md",
@@ -1,5 +1,6 @@
1
- import { readFile, realpath } from "node:fs/promises"
1
+ import { realpath } from "node:fs/promises"
2
2
  import { isAbsolute, relative, resolve } from "node:path"
3
+ import { safeReadFileCapped } from "../lib/safe-open.ts"
3
4
  import { isPathOutsideRoot, isSensitive } from "../policy/jail.ts"
4
5
 
5
6
  const MAX_INJECT = 2_000
@@ -26,9 +27,9 @@ export async function resolveMentionContent(
26
27
  const [real, realRoot] = await Promise.all([realpath(abs), realpath(cwd)])
27
28
  if (isPathOutsideRoot(real, realRoot) || isSensitive(real))
28
29
  return { ok: false, reason: "rejected (jail)" }
29
- const txt = await readFile(real, "utf8")
30
+ const { text: txt, truncated } = await safeReadFileCapped(real, realRoot, MAX_INJECT)
30
31
  const rel = relative(realRoot, real).replace(/\\/g, "/")
31
- const body = txt.length > MAX_INJECT ? `${txt.slice(0, MAX_INJECT)}\n… (truncated)` : txt
32
+ const body = truncated ? `${txt}\n… (truncated: first ${MAX_INJECT} bytes)` : txt
32
33
  return { ok: true, content: `\n[file: ${rel}]\n${body}\n[/file]\n` }
33
34
  } catch {
34
35
  return { ok: false, reason: "file not found" }
@@ -201,6 +201,8 @@ export async function createMinicodeSession(
201
201
  beforeToolEffect?: (call: { id: string; name: string; args: unknown }) => Promise<void>
202
202
  },
203
203
  ): Promise<Session> {
204
+ // Normalisasi root sekali di composition agar ToolContext selalu memiliki path tepercaya.
205
+ const defaultCwd = resolve(opts.cwd ?? process.cwd())
204
206
  // Fail-closed lebih awal (sebelum provider/system prompt): WorkMode non-
205
207
  // EXECUTE di atas handler terinjeksi belum punya komposisi yang terbukti
206
208
  // aman — jangan pernah membungkus atau melewati policy yang diinjeksi 6S.
@@ -217,14 +219,13 @@ export async function createMinicodeSession(
217
219
  // pembungkus provider supaya transisi runtime `/work-mode` maupun `/mode`
218
220
  // tercermin langsung di StreamRequest.system tanpa mengedit vendor/minicore.
219
221
  const baseSystem = await buildSystemPrompt({
220
- cwd: opts.cwd,
222
+ cwd: defaultCwd,
221
223
  extra: opts.systemExtra ?? "",
222
224
  signal: (opts as unknown as { signal?: AbortSignal }).signal,
223
225
  })
224
226
  const {
225
227
  concurrency,
226
228
  writeConcurrency,
227
- cwd,
228
229
  permissionMode,
229
230
  workMode: _workMode,
230
231
  allowLocalConfig,
@@ -249,8 +250,7 @@ export async function createMinicodeSession(
249
250
  // Dibuat di sini (bukan global) supaya dua sesi dalam satu proses tak
250
251
  // saling memakai bukti persetujuan. Root = cwd sesi (sama dengan yang
251
252
  // dipakai tool untuk resolve path target).
252
- const approvalBindings =
253
- _approvalBindings ?? new ApprovalBindingStore(resolve(cwd ?? process.cwd()))
253
+ const approvalBindings = _approvalBindings ?? new ApprovalBindingStore(defaultCwd)
254
254
  // F-09: sanitasi batas di lapisan app (mencakup pemanggil library langsung,
255
255
  // bukan hanya CLI yang sudah sanitasi di cli/setup.ts + cli/index.ts).
256
256
  // Tanpa ini: timeoutMs NaN/negatif = abort instan; maxSteps 0/negatif =
@@ -297,7 +297,7 @@ export async function createMinicodeSession(
297
297
  workMode: resolvedWorkMode,
298
298
  base: createPermissionHandler({
299
299
  mode: permissionMode ?? "auto",
300
- root: cwd,
300
+ root: defaultCwd,
301
301
  ask,
302
302
  allowLocalConfig,
303
303
  onApprovalEvent,
@@ -306,7 +306,7 @@ export async function createMinicodeSession(
306
306
  // bisa dipakai sebagai bukti di sesi B.
307
307
  approvalBindings,
308
308
  }),
309
- root: cwd,
309
+ root: defaultCwd,
310
310
  })
311
311
  const injected = opts.permissionHandler !== undefined
312
312
  const withMode = permissions as typeof permissions & {
@@ -332,7 +332,7 @@ export async function createMinicodeSession(
332
332
  if (isAllToolsPureRead()) return "explore"
333
333
  return "active"
334
334
  }
335
- const effectiveRoot = cwd ?? process.cwd()
335
+ const effectiveRoot = defaultCwd
336
336
  const detector: NoProgressDetector | null =
337
337
  noProgress === false
338
338
  ? null
@@ -367,7 +367,11 @@ export async function createMinicodeSession(
367
367
  ...permissions,
368
368
  check: async (call, deps) => {
369
369
  const decision = await permissions.check(call, deps)
370
- if (decision !== "allow") return decision
370
+ // Kernel vendored saat ini hanya memblokir literal "deny". Validasi di
371
+ // composition root ini menjaga production dispatch fail-closed tanpa
372
+ // mengubah salinan MiniCore yang wajib disinkronkan dari repo sumber.
373
+ // Handler ASK yang sah tetap menunggu approval lalu mengembalikan allow/deny.
374
+ if (decision !== "allow") return "deny"
371
375
  // Ambil (konsumsi) bukti persetujuan milik call ini — sekali saja.
372
376
  // Diambil SEBELUM await supaya tak ada binding tersisa kalau barrier
373
377
  // memblokir call (tak ada deny lalu tak ada jejak).
@@ -469,7 +473,7 @@ export async function createMinicodeSession(
469
473
  concurrency: safeConcurrency ?? LIMITS.EXECUTOR_CONCURRENCY,
470
474
  writeConcurrency: safeWriteConcurrency ?? LIMITS.EXECUTOR_WRITE_CONCURRENCY,
471
475
  }),
472
- cwd,
476
+ cwd: defaultCwd,
473
477
  ...(turnCount !== undefined ? { turnCount } : {}),
474
478
  ...(stepCount !== undefined ? { stepCount } : {}),
475
479
  })
@@ -13,6 +13,7 @@ import type { CanonicalScope } from "../session/verification.ts"
13
13
  import { createBashJobTools } from "../tools/bash.ts"
14
14
  import { withEvidence } from "../tools/evidence.ts"
15
15
  import { allTools, withMcpTools } from "../tools/index.ts"
16
+ import { createWriteMemoryTool } from "../tools/memory.ts"
16
17
 
17
18
  const errMsg = (e: unknown) => (e instanceof Error ? e.message : String(e))
18
19
 
@@ -78,6 +79,11 @@ export async function setupToolLayer(
78
79
  setPermissionMode?: (pm: string) => void
79
80
  }> {
80
81
  let sessionTools: Tool[] = allTools
82
+ if (jobOwnerSid) {
83
+ sessionTools = sessionTools.map((tool) =>
84
+ tool.name === "write_memory" ? createWriteMemoryTool(jobOwnerSid) : tool,
85
+ )
86
+ }
81
87
  // Harness-P2: scope explore = subset read-only sub-agen (tetap 12 EXPLORE_TOOL_NAMES).
82
88
  if (scope === "explore")
83
89
  sessionTools = allTools.filter((t) => EXPLORE_TOOL_NAMES.includes(t.name))
package/src/constants.ts CHANGED
@@ -14,11 +14,17 @@ export const LIMITS = {
14
14
  BASH_BACKGROUND_MAX_JOBS: 8,
15
15
  BASH_BACKGROUND_MAX_LIFETIME_MS: 3_600_000,
16
16
  DOCKER_OUTPUT_MAX_CHARS: 100_000,
17
+ /** Batas untuk meminta daemon Docker menghapus container yang timeout/abort. */
18
+ DOCKER_CLEANUP_TIMEOUT_MS: 5_000,
17
19
  MCP_OUTPUT_MAX_CHARS: 100_000,
20
+ /** Batas frame JSON-RPC stdio sebelum decode/parse; satu respons tools/list bisa besar. */
21
+ MCP_STDIO_FRAME_MAX_BYTES: 1_048_576,
18
22
  MCP_REQUEST_TIMEOUT_MS: 30_000,
19
23
  TASK_SUB_AGENT_MAX_TOKENS: 2_000,
20
24
  /** Context & memory */
21
25
  SYSTEM_PROMPT_MAX_CHARS: 8_000,
26
+ /** Batas baca per skill sebelum dirender sebagai instruksi pada prompt. */
27
+ SKILL_FILE_MAX_BYTES: 32_000,
22
28
  MEMORY_FILE_MAX_CHARS: 4_000,
23
29
  MEMORY_FILE_MAX_BYTES: 200_000,
24
30
  MEMORY_TRUNCATE_KEEP_BYTES: 150_000,
@@ -85,6 +91,16 @@ export const LIMITS = {
85
91
  /** Investigasi Phase 5: cap reasoning stream (terbukti TANPA cap = akumulasi
86
92
  * tak terbatas — satu-satunya jalur loop `reasoning +=` tanpa batas). */
87
93
  PROVIDER_REASON_MAX_CHARS: 2_000_000,
94
+ /** Frame SSE provider longgar untuk JSON tool besar (write_file menerima 5 MB chars). */
95
+ PROVIDER_SSE_FRAME_MAX_BYTES: 16_777_216,
96
+ /** Batas total satu respons stream provider, termasuk reasoning/tool args. */
97
+ PROVIDER_SSE_TOTAL_MAX_BYTES: 67_108_864,
98
+ /** Argumen tool besar tetap didukung; envelope JSON dapat menggandakan escape chars. */
99
+ PROVIDER_TOOL_ARGS_MAX_BYTES: 12_582_912,
100
+ /** Batas agregat argumen yang masih tertahan dari beberapa tool call. */
101
+ PROVIDER_TOOL_ARGS_PENDING_MAX_BYTES: 25_165_824,
102
+ /** Respons error provider cukup untuk diagnosis tanpa membaca body arbitrer. */
103
+ PROVIDER_ERROR_BODY_MAX_BYTES: 65_536,
88
104
  DOCKER_TIMEOUT_MS: 30_000,
89
105
  DETECT_MODELS_TIMEOUT_MS: 4_000,
90
106
  DETECT_GLOBAL_TIMEOUT_MS: 6_000,
@@ -99,6 +115,7 @@ export const LIMITS = {
99
115
  LSP_INIT_TIMEOUT_MS: 15_000,
100
116
  VERIFY_DEFAULT_TIMEOUT_MS: 30_000,
101
117
  WEB_FETCH_BODY_HARD_CAP_CHARS: 2_000_000,
118
+ WEB_RESPONSE_BODY_HARD_CAP_BYTES: 2_000_000,
102
119
  WEB_FETCH_MAX_REDIRECTS: 5,
103
120
  /** Glob/grep */
104
121
  SEARCH_DEFAULT_LIMIT: 100,
@@ -17,7 +17,7 @@ import { resolveTrustedExecutable } from "./trusted-exec.ts"
17
17
  // index user (LFS/semantik clean milik user, lihat git.ts). Pengecualian:
18
18
  // protokol `filter.<d>.process` diutamakan git di atas clean/smudge, jadi
19
19
  // neutralizer selalu mematikannya (nilai kosong = fallback ke clean/smudge)
20
- // di SEMUA jalur plumbing; jalur user-index hanya diperingatkan, bukan diubah.
20
+ // di SEMUA jalur plumbing; `git_commit` menolak filter sebelum staging.
21
21
 
22
22
  /** Netralisasi universal: tanpa hooks, tanpa fsmonitor, tanpa pager. */
23
23
  export const GIT_SAFE_BASE: readonly string[] = [
@@ -31,7 +31,7 @@ export const GIT_SAFE_BASE: readonly string[] = [
31
31
  /** Netralisasi driver konten untuk diff/log (tanpa eksekusi repo). */
32
32
  export const GIT_NO_DIFF_DRIVERS: readonly string[] = ["--no-ext-diff", "--no-textconv"]
33
33
 
34
- const DRIVER_RE = /^filter\.([A-Za-z0-9_.-]+)\.(?:clean|smudge|process)\b/
34
+ const DRIVER_RE = /^filter\.([A-Za-z0-9_.-]+)\.(clean|smudge|process)$/i
35
35
 
36
36
  export interface FilterDriver {
37
37
  name: string
@@ -42,30 +42,35 @@ export interface FilterDriver {
42
42
 
43
43
  /**
44
44
  * Daftar driver filter yang TERKONFIGURASI di repo (discovery read-only via
45
- * `git config`, tanpa hook/filter/pager). Dipakai neutralizer plumbing DAN
46
- * peringatan jalur user-index (git_commit) agar eksekusi filter repo tidak
47
- * pernah diam-diam.
45
+ * `git config`, tanpa hook/filter/pager). Kegagalan discovery melempar error:
46
+ * pemanggil tidak boleh menganggap ketidakmampuan memeriksa sebagai tidak ada
47
+ * filter. Dipakai neutralizer plumbing dan preflight `git_commit`.
48
48
  */
49
49
  export async function discoverFilterDrivers(cwd: string): Promise<FilterDriver[]> {
50
- try {
51
- const r = spawnSync(
52
- resolveTrustedExecutable("git"),
53
- ["config", "--get-regexp", "^filter\\..*\\.(clean|smudge|process)$"],
54
- { cwd, encoding: "utf8", timeout: 10_000 },
55
- )
56
- if (r.status !== 0 || !r.stdout) return []
57
- const drivers = new Map<string, FilterDriver>()
58
- for (const line of r.stdout.split("\n")) {
59
- const m = DRIVER_RE.exec(line.trim())
60
- if (!m?.[1]) continue
61
- const d = drivers.get(m[1]) ?? { name: m[1], hasProcess: false }
62
- if (line.includes(".process")) d.hasProcess = true
63
- drivers.set(m[1], d)
50
+ const r = spawnSync(
51
+ resolveTrustedExecutable("git"),
52
+ ["config", "--name-only", "--get-regexp", "^filter\\..*\\.(clean|smudge|process)$"],
53
+ { cwd, encoding: "utf8", timeout: 10_000 },
54
+ )
55
+ if (r.error) throw new Error(`unable to inspect Git filter configuration: ${r.error.message}`)
56
+ if (r.status === 1 && !r.stdout?.trim()) return []
57
+ if (r.status !== 0) {
58
+ throw new Error(`unable to inspect Git filter configuration (git exited ${String(r.status)})`)
59
+ }
60
+ if (!r.stdout?.trim()) return []
61
+ const drivers = new Map<string, FilterDriver>()
62
+ for (const line of r.stdout.split("\n")) {
63
+ const key = line.trim()
64
+ if (!key) continue
65
+ const m = DRIVER_RE.exec(key)
66
+ if (!m?.[1] || !m[2]) {
67
+ throw new Error("unable to safely parse Git filter configuration")
64
68
  }
65
- return [...drivers.values()].sort((a, b) => (a.name < b.name ? -1 : 1))
66
- } catch {
67
- return []
69
+ const d = drivers.get(m[1]) ?? { name: m[1], hasProcess: false }
70
+ if (m[2].toLowerCase() === "process") d.hasProcess = true
71
+ drivers.set(m[1], d)
68
72
  }
73
+ return [...drivers.values()].sort((a, b) => (a.name < b.name ? -1 : 1))
69
74
  }
70
75
 
71
76
  /**
@@ -1,13 +1,14 @@
1
1
  import { constants } from "node:fs"
2
2
  import type { FileHandle } from "node:fs/promises"
3
- import { open, realpath } from "node:fs/promises"
3
+ import { open, realpath, stat as statPath } from "node:fs/promises"
4
4
  import { homedir, tmpdir } from "node:os"
5
5
  import { basename, dirname, isAbsolute, join, parse, relative, resolve } from "node:path"
6
6
  import { isPathOutsideRoot, isSensitive } from "../policy/jail.ts"
7
7
 
8
- // O_NOFOLLOW mencegah open mengikuti symlink (TOCTOU swap).
9
- // Di Windows nilai tidak didefinisikan — fallback ke 0 dan pakai dev+ino check.
10
- const O_NOFOLLOW: number = (constants as unknown as { O_NOFOLLOW?: number }).O_NOFOLLOW ?? 0x20000
8
+ // O_NOFOLLOW mencegah open mengikuti symlink pada POSIX. Windows tidak
9
+ // menyediakan flag Node yang setara; semua platform juga membandingkan dev+ino
10
+ // stat sebelum open dengan identitas handle setelah open.
11
+ const O_NOFOLLOW: number = (constants as unknown as { O_NOFOLLOW?: number }).O_NOFOLLOW ?? 0
11
12
  const O_RDONLY = constants.O_RDONLY
12
13
 
13
14
  /**
@@ -39,17 +40,19 @@ export async function resolveSafePath(
39
40
  }
40
41
 
41
42
  /**
42
- * Buka file dengan O_NOFOLLOW pada path yang SUDAH terverifikasi di dalam root.
43
+ * Buka file dengan O_NOFOLLOW pada POSIX dan pemeriksaan identitas handle pada
44
+ * semua platform.
43
45
  *
44
- * Urutan: realpath(abs) → tolak bila di luar root → open(preReal, O_NOFOLLOW).
46
+ * Urutan: realpath + boundary check → stat identitas → realpath ulang +
47
+ * boundary check → open target canonical → fstat dan cocokkan dev+ino.
45
48
  * Membuka hasil resolusi (bukan abs asli) berarti symlink internal tetap bisa
46
- * dibaca (targetnya yang dibuka langsung), sementara swap jadi symlink lain
47
- * sebelum open gagal tutup (ELOOP) — tidak ada konten luar yang terbaca.
49
+ * dibaca. O_NOFOLLOW menutup swap leaf pada POSIX; pencocokan identitas handle
50
+ * menolak target berbeda yang terbuka setelah komponen path berubah, termasuk
51
+ * pada Windows yang tidak memiliki O_NOFOLLOW di API Node.
48
52
  *
49
- * POSIX-only: di Windows konstanta O_NOFOLLOW tidak didefinisikan (Node) dan
50
- * flag diabaikan libuv, sehingga proteksi = pre-check realpath saja (window
51
- * race sama seperti pola lama). Catatan jujur: klaim "0 lolos" hanya sah di
52
- * POSIX — lihat test/tool-toctou.test.ts (skip bila symlink EPERM).
53
+ * File system yang tidak menyediakan inode non-zero ditolak karena identitas
54
+ * handle tidak dapat dibuktikan. Stress test symlink tetap bergantung pada
55
+ * privilege platform; lihat test/tool-toctou.test.ts.
53
56
  */
54
57
  export async function safeOpenRead(
55
58
  abs: string,
@@ -64,31 +67,50 @@ export async function safeOpenRead(
64
67
  // di sini agar semua pembaca via open (read_file/read_image/stat) mewarisinya.
65
68
  if (isSensitive(preReal)) throw new Error(`blocked sensitive file: ${abs}`)
66
69
 
70
+ // Ambil identitas sebelum open, lalu periksa kembali boundary setelah stat.
71
+ // Ini menutup race di mana parent directory berubah menjadi junction/symlink
72
+ // keluar sesudah realpath pertama tetapi sebelum open.
73
+ const expected = await statPath(preReal, { bigint: true })
74
+ const checkedReal = await realpath(preReal)
75
+ if (isPathOutsideRoot(checkedReal, realRoot))
76
+ throw new Error(`symlink points outside workspace: ${abs}`)
77
+ if (isSensitive(checkedReal)) throw new Error(`blocked sensitive file: ${abs}`)
78
+ if (expected.ino === 0n)
79
+ throw new Error(`unable to verify opened file identity on this filesystem: ${abs}`)
80
+
67
81
  // Buka path terverifikasi — bukan abs (yang bisa di-swap setelah realpath).
68
82
  let handle: FileHandle
69
83
  try {
70
- handle = await open(preReal, O_RDONLY | O_NOFOLLOW)
84
+ handle = await open(checkedReal, O_RDONLY | O_NOFOLLOW)
71
85
  } catch (e) {
72
86
  const code = (e as NodeJS.ErrnoException).code
73
87
  if (code === "ELOOP") throw new Error(`symlink swapped during open (O_NOFOLLOW): ${abs}`)
74
- // EINVAL: O_NOFOLLOW tidak didukung → buka biasa (Windows: pre-check saja)
88
+ // EINVAL: O_NOFOLLOW tidak didukung → buka biasa; fstat di bawah tetap
89
+ // memastikan file yang dibuka sama dengan identitas yang sudah diperiksa.
75
90
  if (code === "EINVAL" && O_NOFOLLOW !== 0) {
76
- handle = await open(preReal, O_RDONLY)
91
+ handle = await open(checkedReal, O_RDONLY)
77
92
  } else throw e
78
93
  }
94
+ const opened = await handle.stat({ bigint: true }).catch(async (error: unknown) => {
95
+ await handle.close().catch(() => {})
96
+ throw error
97
+ })
98
+ if (opened.ino === 0n || opened.dev !== expected.dev || opened.ino !== expected.ino) {
99
+ await handle.close().catch(() => {})
100
+ throw new Error(`file changed during safe open; refusing to read unverified target: ${abs}`)
101
+ }
79
102
  // Hardlink ke luar workspace tak terlihat oleh realpath (semua nama setara)
80
103
  // — baca via hardlink = baca konten luar. fstat pada handle yang SUDAH
81
104
  // terbuka: tepat untuk file ini, bebas race dengan swap nama. File normal
82
105
  // nlink=1; tolak sisanya dengan pesan yang bisa ditindaklanjuti.
83
- const st = await handle.stat().catch(() => null)
84
106
  // Hardlink check hanya untuk file regular: direktori punya nlink >= 2
85
107
  // (`.` dan `..`) dan bukan target hardlink — biarkan tool yang menolak
86
108
  // direktori dengan pesan yang user-friendly.
87
- if (st && !st.isDirectory() && st.nlink > 1) {
109
+ if (!opened.isDirectory() && opened.nlink > 1n) {
88
110
  await handle.close().catch(() => {})
89
- throw new Error(`refusing to read file with multiple hardlinks (nlink=${st.nlink}): ${abs}`)
111
+ throw new Error(`refusing to read file with multiple hardlinks (nlink=${opened.nlink}): ${abs}`)
90
112
  }
91
- return { handle, realPath: preReal }
113
+ return { handle, realPath: checkedReal }
92
114
  }
93
115
 
94
116
  export async function safeReadFile(abs: string, root: string): Promise<string> {
@@ -100,6 +122,38 @@ export async function safeReadFile(abs: string, root: string): Promise<string> {
100
122
  }
101
123
  }
102
124
 
125
+ /**
126
+ * Baca file tepercaya dengan batas byte sebelum alokasi tumbuh mengikuti file.
127
+ * Satu byte tambahan membedakan file tepat pada batas dari file yang dipotong.
128
+ */
129
+ export async function safeReadFileCapped(
130
+ abs: string,
131
+ root: string,
132
+ maxBytes: number,
133
+ ): Promise<{ text: string; truncated: boolean }> {
134
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1)
135
+ throw new RangeError("maxBytes must be a positive safe integer")
136
+ const { handle } = await safeOpenRead(abs, root)
137
+ try {
138
+ const st = await handle.stat()
139
+ if (!st.isFile()) throw new Error(`refusing to read non-regular file: ${abs}`)
140
+ const buffer = Buffer.alloc(maxBytes + 1)
141
+ let bytesRead = 0
142
+ while (bytesRead < buffer.length) {
143
+ const result = await handle.read(buffer, bytesRead, buffer.length - bytesRead, bytesRead)
144
+ if (result.bytesRead === 0) break
145
+ bytesRead += result.bytesRead
146
+ }
147
+ const truncated = bytesRead > maxBytes || st.size > maxBytes
148
+ return {
149
+ text: buffer.subarray(0, Math.min(bytesRead, maxBytes)).toString("utf8"),
150
+ truncated,
151
+ }
152
+ } finally {
153
+ await handle.close().catch(() => {})
154
+ }
155
+ }
156
+
103
157
  export async function safeStat(abs: string, root: string) {
104
158
  const { handle } = await safeOpenRead(abs, root)
105
159
  try {
@@ -15,7 +15,9 @@ import { delimiter, isAbsolute, join } from "node:path"
15
15
  // nama telanjang (perilaku lama) supaya kegagalan tetap fail-open seperti
16
16
  // semula, tetapi kasus umum (git terpasang di PATH) jadi aman dari hijack.
17
17
 
18
- const isWin = process.platform === "win32"
18
+ function isWindows(): boolean {
19
+ return process.platform === "win32"
20
+ }
19
21
 
20
22
  function validPathEntries(): string[] {
21
23
  const raw = process.env.PATH ?? process.env.Path ?? ""
@@ -32,7 +34,7 @@ function isExecutableFile(p: string): boolean {
32
34
  try {
33
35
  const st = statSync(p)
34
36
  if (!st.isFile()) return false
35
- if (isWin) return true
37
+ if (isWindows()) return true
36
38
  accessSync(p, constants.X_OK)
37
39
  return true
38
40
  } catch {
@@ -60,14 +62,15 @@ function resolveUncached(name: string): string {
60
62
  // "tools\\run.exe") adalah pilihan eksplisit pemanggil — jangan diubah.
61
63
  if (isAbsolute(name)) return name
62
64
  if (name.includes("/") || name.includes("\\")) return name
63
- const exts = isWin
65
+ const windows = isWindows()
66
+ const exts = windows
64
67
  ? (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
65
68
  .split(";")
66
69
  .map((e) => e.trim())
67
70
  .filter(Boolean)
68
71
  : [""]
69
72
  for (const dir of validPathEntries()) {
70
- if (isWin) {
73
+ if (windows) {
71
74
  for (const ext of exts) {
72
75
  const candidate = join(dir, name.endsWith(ext.toLowerCase()) ? name : name + ext)
73
76
  if (isExecutableFile(candidate)) return candidate
package/src/mcp/client.ts CHANGED
@@ -7,6 +7,22 @@ import { scrubSecrets } from "../policy/scrub.ts"
7
7
  import { McpHttpTransport, type McpTransportLike } from "./http-transport.ts"
8
8
  import { McpTransport } from "./transport.ts"
9
9
 
10
+ /**
11
+ * Transport interruption after a tools/call request can race with remote
12
+ * execution. Callers must not report this as a clean failure or retry blindly.
13
+ */
14
+ export class McpCallOutcomeUnknownError extends Error {
15
+ readonly code = "MCP_CALL_OUTCOME_UNKNOWN"
16
+
17
+ constructor(toolName: string, cause: unknown) {
18
+ const detail = scrubSecrets(cause instanceof Error ? cause.message : String(cause))
19
+ super(
20
+ `MCP tool ${toolName} outcome is unknown: ${detail}. The server may have accepted or completed the operation; inspect remote state before retrying.`,
21
+ )
22
+ this.name = "McpCallOutcomeUnknownError"
23
+ }
24
+ }
25
+
10
26
  // [Fase 8 / 8.2] MCP Schema Fingerprint Pinning.
11
27
  //
12
28
  // Bahaya yang ditutup: server MCP bisa mengubah skema toolnya SETELAH pin
@@ -515,15 +531,24 @@ class McpConnection {
515
531
  args: Record<string, unknown>,
516
532
  signal?: AbortSignal,
517
533
  ): Promise<unknown> {
518
- const result = (await this.transport.request(
519
- "tools/call",
520
- {
521
- name,
522
- arguments: args,
523
- },
524
- undefined,
525
- signal,
526
- )) as Record<string, unknown>
534
+ // Abort before entering transport is known not to have sent a request.
535
+ signal?.throwIfAborted()
536
+ let result: Record<string, unknown>
537
+ try {
538
+ result = (await this.transport.request(
539
+ "tools/call",
540
+ {
541
+ name,
542
+ arguments: args,
543
+ },
544
+ undefined,
545
+ signal,
546
+ )) as Record<string, unknown>
547
+ } catch (error) {
548
+ // Once the transport call begins, timeout/abort/connection failure does
549
+ // not prove the remote server stopped or rolled back the operation.
550
+ throw new McpCallOutcomeUnknownError(name, error)
551
+ }
527
552
  if (result && typeof result.isError === "boolean" && result.isError) {
528
553
  const content = Array.isArray(result.content)
529
554
  ? result.content.map((c: any) => c.text ?? JSON.stringify(c)).join("\n")