minicode-ai 0.27.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +1 -1
  2. package/cli/args.ts +184 -57
  3. package/cli/bootstrap/presentation-bridge.ts +383 -0
  4. package/cli/commands/acp.ts +45 -29
  5. package/cli/commands/auth.ts +17 -17
  6. package/cli/commands/config.ts +65 -66
  7. package/cli/commands/daemon.ts +44 -16
  8. package/cli/commands/doctor.ts +18 -15
  9. package/cli/commands/exec.ts +41 -89
  10. package/cli/commands/mcp.ts +25 -8
  11. package/cli/commands/memory.ts +16 -24
  12. package/cli/commands/openwork.ts +6 -2
  13. package/cli/commands/pricing.ts +14 -12
  14. package/cli/commands/providers.ts +36 -57
  15. package/cli/commands/sessions.ts +24 -18
  16. package/cli/commands/skills.ts +33 -18
  17. package/cli/commands/stats.ts +15 -30
  18. package/cli/commands.ts +73 -44
  19. package/cli/context-command-run.ts +30 -18
  20. package/cli/index.ts +51 -100
  21. package/cli/model-manager.ts +7 -2
  22. package/cli/provider-manager.ts +33 -18
  23. package/cli/router.ts +41 -12
  24. package/cli/setup.ts +241 -485
  25. package/cli/tui.ts +303 -100
  26. package/docs/TERMINAL_CONTRACT.md +258 -73
  27. package/docs/UI_RENDER_PIPELINE.md +9 -1
  28. package/docs/agents.md +2 -2
  29. package/docs/architecture.md +17 -32
  30. package/docs/choosing-mode.md +7 -9
  31. package/docs/cli.md +3 -5
  32. package/docs/environment.md +1 -2
  33. package/docs/policy-sandbox.md +3 -3
  34. package/docs/repl.md +2 -2
  35. package/docs/tools.md +1 -1
  36. package/package.json +1 -1
  37. package/src/app/mentions.ts +60 -13
  38. package/src/app/rag-layer.ts +17 -20
  39. package/src/app/session.ts +144 -68
  40. package/src/app/tool-layer.ts +38 -16
  41. package/src/config.ts +64 -104
  42. package/src/constants.ts +4 -6
  43. package/src/daemon/capability.ts +8 -1
  44. package/src/daemon/control.ts +3 -2
  45. package/src/daemon/server.ts +57 -0
  46. package/src/hooks/run.ts +73 -41
  47. package/src/lib/atomic-write.ts +31 -59
  48. package/src/lib/db-path.ts +47 -0
  49. package/src/lib/process-tree.ts +62 -0
  50. package/src/lib/public-http.ts +88 -23
  51. package/src/lib/trusted-exec.ts +48 -1
  52. package/src/lsp/client.ts +62 -17
  53. package/src/mcp/client.ts +85 -38
  54. package/src/mcp/http-transport.ts +28 -16
  55. package/src/mcp/transport.ts +42 -6
  56. package/src/memory/files.ts +164 -134
  57. package/src/memory/vector.ts +371 -420
  58. package/src/policy/approval-binding.ts +122 -45
  59. package/src/policy/bash-guard.ts +18 -7
  60. package/src/policy/compaction.ts +51 -18
  61. package/src/policy/context-window.ts +31 -8
  62. package/src/policy/context.ts +62 -36
  63. package/src/policy/executor.ts +17 -7
  64. package/src/policy/jail.ts +6 -8
  65. package/src/policy/microcompact.ts +4 -3
  66. package/src/policy/no-progress.ts +103 -22
  67. package/src/policy/permission.ts +36 -12
  68. package/src/policy/tool-contract.ts +74 -416
  69. package/src/policy/usage.ts +24 -2
  70. package/src/policy/verifier.ts +50 -2
  71. package/src/policy/work-mode.ts +28 -54
  72. package/src/presentation/adapter.ts +24 -16
  73. package/src/providers/anthropic.ts +16 -5
  74. package/src/providers/provision.ts +6 -56
  75. package/src/providers/responses.ts +38 -7
  76. package/src/providers/sse-bounds.ts +6 -4
  77. package/src/runtime/execution-journal.ts +4 -29
  78. package/src/sandbox/docker.ts +58 -34
  79. package/src/sandbox/mask.ts +157 -0
  80. package/src/sandbox/os.ts +107 -73
  81. package/src/session/authority.ts +29 -10
  82. package/src/session/context-projection.ts +6 -5
  83. package/src/session/db/runs.ts +397 -0
  84. package/src/session/db/schema.ts +358 -0
  85. package/src/session/open-work.ts +26 -3
  86. package/src/session/persistence.ts +74 -998
  87. package/src/session/verification.ts +170 -20
  88. package/src/skills/loader.ts +31 -16
  89. package/src/task/db/schema.ts +325 -0
  90. package/src/task/db/types.ts +269 -0
  91. package/src/task/production-scheduler.ts +13 -1
  92. package/src/task/store.ts +92 -1021
  93. package/src/telemetry/trace.ts +27 -0
  94. package/src/tools/ask_user.ts +1 -13
  95. package/src/tools/bash.ts +27 -92
  96. package/src/tools/code_run.ts +1 -1
  97. package/src/tools/context.ts +133 -0
  98. package/src/tools/delete_file.ts +3 -2
  99. package/src/tools/edit.ts +37 -72
  100. package/src/tools/git.ts +86 -9
  101. package/src/tools/glob.ts +26 -51
  102. package/src/tools/grep.ts +67 -57
  103. package/src/tools/hashline.ts +4 -0
  104. package/src/tools/lsp.ts +11 -8
  105. package/src/tools/mcp_call.ts +9 -6
  106. package/src/tools/memory.ts +56 -33
  107. package/src/tools/move_file.ts +36 -10
  108. package/src/tools/patch.ts +13 -21
  109. package/src/tools/read_file.ts +18 -25
  110. package/src/tools/read_image.ts +35 -33
  111. package/src/tools/submit_result.ts +29 -8
  112. package/src/tools/task.ts +74 -17
  113. package/src/tools/todo.ts +181 -74
  114. package/src/tools/web_fetch.ts +42 -2
  115. package/src/tools/web_search.ts +47 -8
  116. package/src/ui/approval/prompt.ts +206 -47
  117. package/src/ui/assistant/turn-status.ts +14 -5
  118. package/src/ui/footer.ts +4 -4
  119. package/src/ui/i18n/en.ts +47 -23
  120. package/src/ui/i18n/id.ts +76 -51
  121. package/src/ui/input/input.ts +4 -3
  122. package/src/ui/input/prompt-engine.ts +35 -5
  123. package/src/ui/render/activity-panel.ts +4 -2
  124. package/src/ui/render/hint.ts +7 -4
  125. package/src/ui/render/list.ts +32 -0
  126. package/src/ui/render/markdown.ts +6 -3
  127. package/src/ui/render/notice.ts +19 -0
  128. package/src/ui/render/table-grid.ts +7 -8
  129. package/src/ui/render/theme.ts +113 -39
  130. package/src/ui/runtime/screen.ts +74 -10
  131. package/src/ui/runtime/spinner.ts +19 -6
  132. package/src/ui/screens/dialog.ts +19 -1
  133. package/src/ui/screens/form.ts +80 -35
  134. package/src/ui/screens/model-manager.ts +82 -61
  135. package/src/ui/screens/output-window.ts +263 -0
  136. package/src/ui/screens/picker.ts +94 -81
  137. package/src/ui/screens/provider-manager.ts +100 -69
  138. package/src/ui/screens/wizard.ts +117 -28
  139. package/src/ui/tui/app.ts +196 -33
  140. package/src/ui/tui/transcript.ts +158 -25
  141. package/vendor/minicore/src/core/executor.ts +2 -0
  142. package/vendor/minicore/src/core/loop.ts +17 -6
  143. package/vendor/minicore/src/core/session.ts +3 -0
  144. package/vendor/minicore/src/core/tool.ts +1 -0
  145. package/vendor/minicore/src/providers/openai-compat.ts +35 -19
@@ -2,6 +2,34 @@ import { randomUUID } from "node:crypto"
2
2
  import { chmod, type FileHandle, mkdir, open, rename, unlink } from "node:fs/promises"
3
3
  import { dirname } from "node:path"
4
4
 
5
+ /**
6
+ * Rename atomic dengan backoff EPERM/EBUSY/EACCES sesaat (lock AV/replace window Windows).
7
+ */
8
+ export async function renameWithRetry(
9
+ from: string,
10
+ to: string,
11
+ opts: { maxRetries?: number; renameFn?: (src: string, dst: string) => Promise<void> } = {},
12
+ ): Promise<void> {
13
+ const maxRetries = opts.maxRetries ?? 8
14
+ const doRename = opts.renameFn ?? rename
15
+ let lastErr: unknown
16
+ for (let r = 0; r < maxRetries; r++) {
17
+ try {
18
+ await doRename(from, to)
19
+ return
20
+ } catch (e) {
21
+ const code = (e as NodeJS.ErrnoException).code
22
+ if (code === "EPERM" || code === "EBUSY" || code === "EACCES") {
23
+ lastErr = e
24
+ await new Promise((res) => setTimeout(res, Math.min(10 * 2 ** r, 100)))
25
+ } else {
26
+ throw e
27
+ }
28
+ }
29
+ }
30
+ if (lastErr) throw lastErr
31
+ }
32
+
5
33
  /**
6
34
  * Tulis file secara atomic + tahan hijack:
7
35
  * - nama tmp memakai randomUUID → tidak dapat diprediksi attacker
@@ -11,14 +39,6 @@ import { dirname } from "node:path"
11
39
  * MOVEFILE_REPLACE_EXISTING sehingga menimpa target lama.
12
40
  */
13
41
  export async function atomicWriteText(path: string, data: string): Promise<void> {
14
- // Direktori induk bisa gagal dibuat: path-nya sudah dipakai FILE biasa,
15
- // salah satu komponennya bukan direktori, atau induknya read-only. Error
16
- // itu adalah AKAR MASALAH. Dulu ia ditelan `.catch(() => {})`, sehingga
17
- // yang sampai ke pemanggil hanya gejala open() berikutnya ("ENOENT: no
18
- // such file or directory") — menyesatkan, karena direktori itu ADA dan
19
- // memang tidak bisa dibuat. Simpan error mkdir; kalau open() juga gagal,
20
- // surface yang sebenarnya dan simpan gejala open() sebagai `cause` supaya
21
- // kedua informasi tetap utuh.
22
42
  let dirErr: NodeJS.ErrnoException | undefined
23
43
  try {
24
44
  await mkdir(dirname(path), { recursive: true, mode: 0o700 })
@@ -32,81 +52,33 @@ export async function atomicWriteText(path: string, data: string): Promise<void>
32
52
  try {
33
53
  fh = await open(tmp, "wx", 0o600)
34
54
  } catch (e) {
35
- // Pembuatan direktori gagal DAN tulisan juga gagal → akar masalahnya
36
- // di direktori, bukan di open(). Jangan biarkan gejala open() menutupi
37
- // penyebab aslinya.
38
55
  if (dirErr) throw Object.assign(dirErr, { cause: e })
39
56
  if ((e as NodeJS.ErrnoException).code === "EEXIST" && attempt === 0) continue
40
57
  throw e
41
58
  }
42
59
  try {
43
- // Bun Windows: `FileHandle.writeFile` kadang nge-hit kWriteMonkeyPatchDefense
44
- // bila `node:fs/promises` ke-import bareng `bun:sqlite` di top-level.
45
- // Fallback ke `Bun.write` (tidak pakai FileHandle) bila kena itu.
46
60
  try {
47
61
  await fh.writeFile(data, "utf8")
48
62
  } catch (e) {
49
63
  const msg = String((e as Error)?.message ?? "")
50
64
  if (msg.includes("kWriteMonkeyPatchDefense") || msg.includes("kWrite")) {
51
65
  await fh.close().catch(() => {})
52
- // Handle sudah ditutup di atas → null-out agar blok `finally` tidak
53
- // memanggil `.close()` pada handle yang sudah tidak ada. Tanpa ini
54
- // `fh.close()` di `finally` melempar TypeError yang menutupi
55
- // penulisan yang justru BERHASIL (file sudah ter-rename, tapi
56
- // pemanggil diberi tahu gagal).
57
66
  fh = undefined
58
67
  await Bun.write(tmp, data)
59
- // re-open untuk sync/chmod path yang sama — atau skip bila Bun.write sudah flush
60
- try {
61
- await chmod(tmp, 0o600).catch(() => {})
62
- } catch {}
63
- let lastErr2: unknown
64
- for (let r = 0; r < 8; r++) {
65
- try {
66
- await rename(tmp, path)
67
- lastErr2 = undefined
68
- break
69
- } catch (ee) {
70
- const code = (ee as NodeJS.ErrnoException).code
71
- if (code === "EPERM" || code === "EBUSY" || code === "EACCES") {
72
- lastErr2 = ee
73
- await new Promise((res) => setTimeout(res, Math.min(10 * 2 ** r, 100)))
74
- } else throw ee
75
- }
76
- }
77
- if (lastErr2) throw lastErr2
68
+ await chmod(tmp, 0o600).catch(() => {})
69
+ await renameWithRetry(tmp, path)
78
70
  return
79
71
  }
80
72
  throw e
81
73
  }
82
74
  await fh.sync().catch(() => {})
83
75
  await chmod(tmp, 0o600).catch(() => {})
84
- // Windows: rename menimpa target yang baru saja ditulis penulis lain
85
- // bisa EPERM/EBUSY/EACCES sesaat (lock AV / replace window) → backoff.
86
- let lastErr: unknown
87
- for (let r = 0; r < 8; r++) {
88
- try {
89
- await rename(tmp, path)
90
- lastErr = undefined
91
- break
92
- } catch (e) {
93
- const code = (e as NodeJS.ErrnoException).code
94
- if (code === "EPERM" || code === "EBUSY" || code === "EACCES") {
95
- lastErr = e
96
- await new Promise((res) => setTimeout(res, Math.min(10 * 2 ** r, 100)))
97
- } else throw e
98
- }
99
- }
100
- if (lastErr) throw lastErr
76
+ await renameWithRetry(tmp, path)
101
77
  return
102
78
  } catch (e) {
103
79
  await unlink(tmp).catch(() => {})
104
80
  throw e
105
81
  } finally {
106
- // `fh` bisa sudah `undefined` di jalur fallback Bun.write di atas
107
- // (handle ditutup manual). Menutup handle yang masih hidup itu aman;
108
- // memanggil `.close()` pada `undefined` melempar TypeError yang
109
- // menutupi penulisan yang justru sudah BERHASIL.
110
82
  if (fh) await fh.close().catch(() => {})
111
83
  }
112
84
  }
@@ -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
+ }
@@ -0,0 +1,62 @@
1
+ import { type ChildProcess, type spawn, spawnSync } from "node:child_process"
2
+ import { resolveTrustedExecutable } from "./trusted-exec.ts"
3
+
4
+ /** Kirim sinyal ke grup proses POSIX (`-pid`, butuh `detached: true`). */
5
+ export function signalProcessGroup(p: Pick<ChildProcess, "pid">, signal: NodeJS.Signals): boolean {
6
+ if (process.platform === "win32" || p.pid === undefined) return false
7
+ try {
8
+ process.kill(-p.pid, signal)
9
+ return true
10
+ } catch {
11
+ return false
12
+ }
13
+ }
14
+
15
+ /** Eskalasi sopan POSIX: SIGTERM ke process group, fallback ke proses tunggal. */
16
+ export function signalProcessGroupGraceful(
17
+ pid: number | undefined,
18
+ fallback: { kill: (signal?: NodeJS.Signals | number) => boolean },
19
+ opts: {
20
+ platform?: NodeJS.Platform
21
+ killGroup?: (pid: number, signal: NodeJS.Signals) => boolean
22
+ } = {},
23
+ ): "group" | "fallback" {
24
+ const platform = opts.platform ?? process.platform
25
+ if (platform !== "win32" && typeof pid === "number" && pid > 0) {
26
+ const killGroup =
27
+ opts.killGroup ??
28
+ ((target: number, signal: NodeJS.Signals): boolean => process.kill(target, signal))
29
+ try {
30
+ if (killGroup(-pid, "SIGTERM")) return "group"
31
+ } catch {}
32
+ }
33
+ try {
34
+ fallback.kill("SIGTERM")
35
+ } catch {}
36
+ return "fallback"
37
+ }
38
+
39
+ /** Hentikan proses beserta subtree: Windows `taskkill /T /F`, POSIX SIGKILL `-pid`. */
40
+ export function killProcessTree(
41
+ p: ReturnType<typeof spawn>,
42
+ opts: { env?: NodeJS.ProcessEnv } = {},
43
+ ): void {
44
+ try {
45
+ if (process.platform === "win32" && p.pid !== undefined) {
46
+ const r = spawnSync(
47
+ resolveTrustedExecutable("taskkill"),
48
+ ["/pid", String(p.pid), "/T", "/F"],
49
+ {
50
+ stdio: "ignore",
51
+ ...(opts.env ? { env: opts.env } : {}),
52
+ },
53
+ )
54
+ if (r.status === 0) return
55
+ } else if (signalProcessGroup(p, "SIGKILL")) {
56
+ return
57
+ }
58
+ } catch {}
59
+ try {
60
+ p.kill("SIGKILL")
61
+ } catch {}
62
+ }
@@ -6,22 +6,34 @@ import { pipeline, Readable } from "node:stream"
6
6
  import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib"
7
7
  import { isPrivateHost } from "./net.ts"
8
8
 
9
- /** Resolve once and pass only validated addresses to the socket lookup.
9
+ export interface PinnedRequestInit {
10
+ signal: AbortSignal
11
+ headers: Record<string, string>
12
+ method?: "GET" | "POST" | "DELETE"
13
+ body?: string
14
+ /** Izinkan host privat (khusus MCP lokal yang di-opt-in eksplisit); IP tetap di-pin ke socket. */
15
+ allowPrivateHost?: boolean
16
+ }
17
+
18
+ /**
19
+ * Resolve once and pass only validated addresses to the socket lookup.
10
20
  * The original URL retains HTTP Host and HTTPS certificate/SNI validation.
11
- * No proxy, connection pool, or automatic redirect can bypass this lookup. */
12
- export async function fetchPublicUrl(
13
- url: URL,
14
- init: { signal: AbortSignal; headers: Record<string, string> },
15
- ): Promise<Response> {
21
+ * No proxy, connection pool, or automatic redirect can bypass this lookup.
22
+ */
23
+ export async function fetchPinnedUrl(url: URL, init: PinnedRequestInit): Promise<Response> {
16
24
  init.signal.throwIfAborted()
17
25
  if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("disallowed protocol")
26
+ const allowPrivate = init.allowPrivateHost === true
18
27
  const hostname = url.hostname.replace(/^\[|\]$/g, "")
19
- if (isPrivateHost(hostname)) throw new Error(`blocked private host: ${hostname}`)
28
+ if (!allowPrivate && isPrivateHost(hostname)) {
29
+ throw new Error(`blocked private host: ${hostname}`)
30
+ }
20
31
  const family = isIP(hostname)
21
32
  let addresses: { address: string; family: number }[]
22
33
  if (family) addresses = [{ address: hostname, family }]
23
34
  else {
24
- const signal = AbortSignal.any([init.signal, AbortSignal.timeout(1000)])
35
+ // 4000ms memberi ruang untuk DNS dingin/VPN/Windows tanpa mengorbankan batas 10s web_fetch.
36
+ const signal = AbortSignal.any([init.signal, AbortSignal.timeout(4000)])
25
37
  let onAbort!: () => void
26
38
  try {
27
39
  addresses = await Promise.race([
@@ -41,7 +53,9 @@ export async function fetchPublicUrl(
41
53
  }
42
54
  if (
43
55
  !addresses.length ||
44
- addresses.some((entry) => !isIP(entry.address) || isPrivateHost(entry.address))
56
+ addresses.some(
57
+ (entry) => !isIP(entry.address) || (!allowPrivate && isPrivateHost(entry.address)),
58
+ )
45
59
  ) {
46
60
  throw new Error(`blocked private host: ${hostname}`)
47
61
  }
@@ -49,17 +63,60 @@ export async function fetchPublicUrl(
49
63
  const target = new URL(url)
50
64
  target.username = ""
51
65
  target.password = ""
66
+ const method = init.method ?? "GET"
67
+ const headers: Record<string, string> = { ...init.headers }
68
+ const payload = init.body !== undefined ? Buffer.from(init.body, "utf8") : undefined
69
+ if (payload && !Object.keys(headers).some((k) => k.toLowerCase() === "content-length")) {
70
+ headers["content-length"] = String(payload.byteLength)
71
+ }
72
+
73
+ // Untuk HTTP polos (tanpa TLS SNI), pin IP tervalidasi langsung ke hostname URL + header Host
74
+ // lewat fetch native (redirect: "manual"). Ini menutup DNS rebinding sekaligus menghindari
75
+ // bug UAF callback custom `lookup` pada `node:http` di Bun Windows saat koneksi/abort bertubi-tubi.
76
+ if (target.protocol === "http:") {
77
+ const pinned = new URL(target)
78
+ const entry = addresses[0]!
79
+ pinned.hostname = entry.family === 6 ? `[${entry.address}]` : entry.address
80
+ if (!Object.keys(headers).some((k) => k.toLowerCase() === "host")) {
81
+ headers.host = target.host
82
+ }
83
+ try {
84
+ const res = await fetch(pinned, {
85
+ method,
86
+ headers,
87
+ ...(init.body !== undefined ? { body: init.body } : {}),
88
+ signal: init.signal,
89
+ redirect: "manual",
90
+ })
91
+ if (res.status < 200 || res.status > 599) {
92
+ throw new Error(`invalid HTTP status: ${res.status}`)
93
+ }
94
+ return res
95
+ } catch (err) {
96
+ if (init.signal.aborted && init.signal.reason !== undefined) {
97
+ throw init.signal.reason
98
+ }
99
+ throw err
100
+ }
101
+ }
102
+
52
103
  return new Promise<Response>((resolve, reject) => {
104
+ const rejectWithAbort = (err: unknown): void => {
105
+ if (init.signal.aborted && init.signal.reason !== undefined) {
106
+ reject(init.signal.reason)
107
+ return
108
+ }
109
+ reject(err)
110
+ }
53
111
  const request = target.protocol === "https:" ? https.request : http.request
54
112
  const req = request(
55
113
  target,
56
114
  {
57
- method: "GET",
58
- headers: init.headers,
115
+ method,
116
+ headers,
59
117
  signal: init.signal,
60
118
  agent: false,
61
119
  lookup: (_host, options, callback) => {
62
- // Both Node and Bun may request all addresses for family autoselection.
63
120
  if ((options as { all?: boolean }).all) {
64
121
  callback(null, addresses as never)
65
122
  } else {
@@ -71,22 +128,22 @@ export async function fetchPublicUrl(
71
128
  (res) => {
72
129
  let body: Readable = res
73
130
  try {
74
- const headers = new Headers()
131
+ const resHeaders = new Headers()
75
132
  for (let i = 0; i < res.rawHeaders.length; i += 2) {
76
- headers.append(res.rawHeaders[i]!, res.rawHeaders[i + 1]!)
133
+ resHeaders.append(res.rawHeaders[i]!, res.rawHeaders[i + 1]!)
77
134
  }
78
135
  const status = res.statusCode ?? 502
79
136
  if (status < 200 || status > 599) throw new Error(`invalid HTTP status: ${status}`)
80
137
  const noBody = status === 204 || status === 205 || status === 304
81
138
  if (noBody) res.resume()
82
139
  else {
83
- const encodings = (headers.get("content-encoding") ?? "")
140
+ const encodings = (resHeaders.get("content-encoding") ?? "")
84
141
  .split(",")
85
142
  .map((s) => s.trim().toLowerCase())
86
143
  .filter((s) => s && s !== "identity")
87
144
  for (const encoding of encodings.reverse()) {
88
145
  const decoder =
89
- encoding === "gzip"
146
+ encoding === "gzip" || encoding === "x-gzip"
90
147
  ? createGunzip()
91
148
  : encoding === "deflate"
92
149
  ? createInflate()
@@ -98,8 +155,8 @@ export async function fetchPublicUrl(
98
155
  body = decoder
99
156
  }
100
157
  if (encodings.length) {
101
- headers.delete("content-encoding")
102
- headers.delete("content-length")
158
+ resHeaders.delete("content-encoding")
159
+ resHeaders.delete("content-length")
103
160
  }
104
161
  }
105
162
  resolve(
@@ -108,21 +165,29 @@ export async function fetchPublicUrl(
108
165
  {
109
166
  status,
110
167
  statusText: res.statusMessage,
111
- headers,
168
+ headers: resHeaders,
112
169
  },
113
170
  ),
114
171
  )
115
172
  } catch (error) {
116
173
  body.destroy()
117
174
  res.destroy()
118
- reject(error)
175
+ rejectWithAbort(error)
119
176
  }
120
177
  },
121
178
  )
122
- req.once("error", reject)
123
- req.end()
179
+ req.once("error", rejectWithAbort)
180
+ if (payload) req.end(payload)
181
+ else req.end()
124
182
  })
125
183
  }
126
184
 
185
+ export async function fetchPublicUrl(
186
+ url: URL,
187
+ init: { signal: AbortSignal; headers: Record<string, string> },
188
+ ): Promise<Response> {
189
+ return fetchPinnedUrl(url, { ...init, method: "GET", allowPrivateHost: false })
190
+ }
191
+
127
192
  // A module boundary for transport-level tests without opening real network sockets.
128
- export const publicHttp = { fetch: fetchPublicUrl }
193
+ export const publicHttp = { fetch: fetchPublicUrl, request: fetchPinnedUrl }
@@ -53,7 +53,9 @@ export function resolveTrustedExecutable(name: string): string {
53
53
  const cached = cache.get(name)
54
54
  if (cached) return cached
55
55
  const resolved = resolveUncached(name)
56
- cache.set(name, resolved)
56
+ // Jangan pernah men-cache kegagalan resolusi (nama telanjang): bila PATH
57
+ // baru diisi belakangan, pemanggilan ulang harus tetap bisa menemukan biner absolut.
58
+ if (isAbsolute(resolved)) cache.set(name, resolved)
57
59
  return resolved
58
60
  }
59
61
 
@@ -85,3 +87,48 @@ function resolveUncached(name: string): string {
85
87
  }
86
88
  return name
87
89
  }
90
+
91
+ function quoteWinCmdArg(arg: string): string {
92
+ if (/[\r\n\0]/.test(arg)) {
93
+ throw new Error("trusted-exec: unsafe control character in cmd.exe shim argument")
94
+ }
95
+ if (/^[A-Za-z0-9_./:=+-]+$/.test(arg)) return arg
96
+ // Pisahkan di `%` agar `cmd.exe` tidak melakukan ekspansi `%VAR%` di dalam
97
+ // tanda kutip ganda: tiap potongan aman dikutip, `%` disisip di luar kutip
98
+ // sebagai `^%` tanpa menghasilkan `""` berurutan yang dibaca MSVCRT sebagai `"`.
99
+ const quoteSegment = (seg: string): string =>
100
+ seg === "" ? "" : `"${seg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"`
101
+ if (arg.includes("%")) {
102
+ const out = arg
103
+ .split("%")
104
+ .map((part) => quoteSegment(part))
105
+ .join("^%")
106
+ return out || '""'
107
+ }
108
+ return `"${arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"`
109
+ }
110
+
111
+ /**
112
+ * Siapkan target `spawn()` lintas-OS yang aman dari hijack CWD sekaligus
113
+ * mampu menjalankan shim `.cmd`/`.bat` di Windows (Node/Bun menolak spawn
114
+ * langsung `.cmd` dengan EINVAL tanpa shell).
115
+ */
116
+ export function resolveSpawnTarget(
117
+ command: string,
118
+ args: readonly string[],
119
+ opts: { platform?: NodeJS.Platform; resolveExec?: (name: string) => string } = {},
120
+ ): { command: string; args: string[]; windowsVerbatimArguments?: boolean } {
121
+ const resolveExec = opts.resolveExec ?? resolveTrustedExecutable
122
+ const resolved = resolveExec(command)
123
+ const platform = opts.platform ?? process.platform
124
+ if (platform === "win32" && /\.(?:cmd|bat)$/i.test(resolved)) {
125
+ const comspec = resolveExec(process.env.ComSpec || "cmd.exe")
126
+ const line = [resolved, ...args].map(quoteWinCmdArg).join(" ")
127
+ return {
128
+ command: comspec,
129
+ args: ["/d", "/s", "/c", `"${line}"`],
130
+ windowsVerbatimArguments: true,
131
+ }
132
+ }
133
+ return { command: resolved, args: [...args] }
134
+ }
package/src/lsp/client.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { Buffer } from "node:buffer"
2
- import { type ChildProcess, spawn } from "node:child_process"
2
+ import { type ChildProcess, spawn, spawnSync } from "node:child_process"
3
3
  import { extname, resolve as resolvePath } from "node:path"
4
4
  import { pathToFileURL } from "node:url"
5
5
  import { LIMITS } from "../constants.ts"
6
+ import { resolveSpawnTarget, resolveTrustedExecutable } from "../lib/trusted-exec.ts"
6
7
  import { sanitizeSpawnEnv } from "../policy/scrub.ts"
7
8
  import type {
8
9
  ManagedChild,
@@ -91,6 +92,7 @@ class LspConnection {
91
92
  private stopping = false
92
93
  /** [P13.2] root workspace — dipakai lagi saat restart. */
93
94
  private rootPath = ""
95
+ private winCmdTree = false
94
96
 
95
97
  constructor(public entry: LspServerEntry) {}
96
98
 
@@ -110,11 +112,14 @@ class LspConnection {
110
112
  this.rootPath = rootPath
111
113
  this.stopping = false
112
114
  this.killSignal = new AbortController()
113
- this.proc = spawn(this.entry.command, this.entry.args, {
115
+ const target = resolveSpawnTarget(this.entry.command, this.entry.args)
116
+ this.winCmdTree = target.windowsVerbatimArguments === true
117
+ this.proc = spawn(target.command, target.args, {
114
118
  stdio: ["pipe", "pipe", "pipe"],
115
119
  // env kredensial di-strip; env eksplisit config server menang setelahnya
116
120
  env: sanitizeSpawnEnv(process.env, this.entry.env),
117
121
  signal: this.killSignal.signal,
122
+ ...(target.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
118
123
  })
119
124
  this.proc.on("error", (err) => this.failAll(err))
120
125
  // [P13.2] Tulis ke server yang sudah mati menghasilkan EPIPE. Itu kondisi
@@ -331,20 +336,35 @@ class LspConnection {
331
336
  try {
332
337
  this.proc.stdin?.end()
333
338
  } catch {}
339
+ const p = this.proc
340
+ if (
341
+ this.winCmdTree &&
342
+ process.platform === "win32" &&
343
+ p.pid !== undefined &&
344
+ p.exitCode === null
345
+ ) {
346
+ try {
347
+ spawnSync(resolveTrustedExecutable("taskkill"), ["/pid", String(p.pid), "/T", "/F"], {
348
+ stdio: "ignore",
349
+ env: sanitizeSpawnEnv(process.env),
350
+ })
351
+ } catch {}
352
+ }
334
353
  this.killSignal.abort()
335
- await new Promise<void>((r) => {
336
- const p = this.proc!
337
- const t = setTimeout(() => {
338
- try {
339
- p.kill("SIGKILL")
340
- } catch {}
341
- r()
342
- }, 2_000)
343
- p.once("exit", () => {
344
- clearTimeout(t)
345
- r()
354
+ if (p.exitCode === null && p.signalCode === null) {
355
+ await new Promise<void>((r) => {
356
+ const t = setTimeout(() => {
357
+ try {
358
+ p.kill("SIGKILL")
359
+ } catch {}
360
+ r()
361
+ }, 2_000)
362
+ p.once("exit", () => {
363
+ clearTimeout(t)
364
+ r()
365
+ })
346
366
  })
347
- })
367
+ }
348
368
  this.proc = null
349
369
  this.started = false
350
370
  this.starting = undefined
@@ -457,9 +477,34 @@ export function findSymbolPosition(
457
477
  symbol: string,
458
478
  ): LspPositionResult["position"] | null {
459
479
  const escaped = symbol.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
460
- // prefer word-boundary match to avoid hitting comments/import substrings; fallback to plain indexOf
461
- const re = new RegExp(`\\b${escaped}\\b`)
462
- const m = re.exec(text)
480
+ const wordRe = new RegExp(`\\b${escaped}\\b`, "g")
481
+ const declRe = new RegExp(
482
+ `^\\s*(?:export\\s+)?(?:default\\s+)?(?:async\\s+)?(?:(?:function|class|interface|type|enum|const|let|var|def|fn|struct|impl|trait)\\s+|(?:public|private|protected|static|readonly|override|pub(?:\\([^)]*\\))?)\\s+)*${escaped}\\b`,
483
+ )
484
+ const isCommentLine = (trimmed: string): boolean =>
485
+ trimmed.startsWith("//") ||
486
+ trimmed.startsWith("/*") ||
487
+ trimmed.startsWith("*") ||
488
+ trimmed.startsWith("#")
489
+
490
+ // Prioritaskan baris deklarasi non-komentar, lalu kemunculan word-boundary
491
+ // non-komentar pertama, baru fallback ke pencarian umum agar tidak nyasar
492
+ // ke komentar atau import statement di atas file.
493
+ const lines = text.split("\n")
494
+ let firstNonComment: LspPositionResult["position"] | null = null
495
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
496
+ const line = lines[lineIdx]!
497
+ const trimmed = line.trimStart()
498
+ if (isCommentLine(trimmed) || trimmed.startsWith("import ")) continue
499
+ wordRe.lastIndex = 0
500
+ const m = wordRe.exec(line)
501
+ if (!m) continue
502
+ if (!firstNonComment) firstNonComment = { line: lineIdx, character: m.index }
503
+ if (declRe.test(line)) return { line: lineIdx, character: m.index }
504
+ }
505
+ if (firstNonComment) return firstNonComment
506
+
507
+ const m = new RegExp(`\\b${escaped}\\b`).exec(text)
463
508
  const idx = m?.index ?? text.indexOf(symbol)
464
509
  if (idx === -1) return null
465
510
  const before = text.slice(0, idx).split("\n")