minicode-ai 0.11.0 → 0.13.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 (221) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -66
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +17 -7
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +54 -18
  184. package/src/ui/i18n/en.ts +62 -6
  185. package/src/ui/i18n/id.ts +62 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +598 -133
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -165
  221. package/docs/USAGE.md +0 -11
package/src/lib/net.ts CHANGED
@@ -7,11 +7,24 @@
7
7
  // socket. Residualnya jujur didokumentasikan di web_fetch (cek dan connect
8
8
  // bisa melihat IP berbeda); yang ditutup di sini adalah cache basi (noCache)
9
9
  // dan kegagalan DNS (strict) — pilih per jalur sesuai risikonya.
10
+ //
11
+ // RESIDUAL anti-SSRF yang SENGAJA TIDAK ditutup (dokumentasi jujur, bukan
12
+ // kelalaian): prefix IPv6 lain yang juga memuat alamat IPv4 tapi tidak
13
+ // menaruhnya di 32 bit terakhir — NAT64 well-known (64:ff9b::/96), 6to4
14
+ // (2002::/16), dan Teredo (2001:0000::/32, IPv4-nya di-obfuscate). Bentuk itu
15
+ // hanya terjangkau bila mesin punya translator/relay NAT64 atau 6to4 — dan
16
+ // memblokir 64:ff9b::/96 sepenuhnya akan mematikan host IPv6-only yang sah di
17
+ // lingkungan NAT64. Yang ditutup: IPv4-mapped (::ffff:0:0/96),
18
+ // IPv4-translated (::ffff:0:0:0/96), dan IPv4-compatible (::/96).
10
19
  import { lookup } from "node:dns/promises"
11
20
 
12
21
  // Host validasi untuk anti-SSRF. Catatan: WHATWG URL sudah menormalisasi host
13
22
  // IPv4 non-dotted (hex 0x7f000001 / desimal 2130706433) menjadi dotted-decimal,
14
23
  // jadi cukup cek bentuk dotted di sini — bypass encoding tertutup oleh parser.
24
+ // CATATAN PENTING: normalisasi itu HANYA berlaku untuk IPv4 telanjang.
25
+ // IPv4-mapped IPv6 (::ffff:a.b.c.d) ditulis parser sebagai HEKSADESIMAL
26
+ // ("::ffff:a9fe:a9fe"), bukan dotted — jadi bentuk dotted SAJA tidak cukup,
27
+ // dan tanpa penanganan extra guard ini lolos ke metadata endpoint IMDS.
15
28
  function isPrivateIPv4(host: string): boolean {
16
29
  const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host)
17
30
  if (!m) return false
@@ -25,13 +38,42 @@ function isPrivateIPv4(host: string): boolean {
25
38
  return false
26
39
  }
27
40
 
41
+ // Ambil alamat IPv4 yang tertanam di 32 bit TERAKHIR sebuah literal IPv6.
42
+ // Dua bentuk: dotted ("169.254.169.254") atau hextet ("a9fe:a9fe", atau
43
+ // "0:a9fe:a9fe" untuk IPv4-translated). Bentuk hextet inilah yang dipakai
44
+ // parser WHATWG, jadi bentuk dotted saja tidak cukup.
45
+ function low32IPv4(tail: string): string | null {
46
+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(tail)) return tail
47
+ const parts = tail.split(":").filter((p) => p.length > 0)
48
+ if (parts.length === 0) return null
49
+ const lo = parts[parts.length - 1]!
50
+ const hi = parts.length >= 2 ? parts[parts.length - 2]! : "0"
51
+ if (!/^[0-9a-f]{1,4}$/.test(hi) || !/^[0-9a-f]{1,4}$/.test(lo)) return null
52
+ const hiN = Number.parseInt(hi, 16)
53
+ const loN = Number.parseInt(lo, 16)
54
+ if (!Number.isFinite(hiN) || !Number.isFinite(loN)) return null
55
+ return [hiN >>> 8, hiN & 0xff, loN >>> 8, loN & 0xff].join(".")
56
+ }
57
+
28
58
  export function isPrivateHost(host: string): boolean {
29
59
  const h = host.toLowerCase().replace(/^\[|\]$/g, "")
30
60
  if (!h) return true
31
61
  if (h === "localhost" || h.endsWith(".localhost")) return true
32
62
  if (h.endsWith(".internal") || h.endsWith(".local")) return true
33
63
  if (h === "::1" || h === "::") return true
34
- if (h.startsWith("::ffff:")) return isPrivateIPv4(h.slice(7)) // IPv4-mapped IPv6
64
+ // IPv4-mapped (::ffff:0:0/96) dan IPv4-translated (::ffff:0:0:0/96): alamat
65
+ // IPv4 ada di 32 bit terakhir. Parser menuliskan ini sebagai heksadesimal,
66
+ // jadi bentuk dotted yang tadinya ditangani TIDAK menangkapnya.
67
+ if (h.startsWith("::ffff:")) {
68
+ const v4 = low32IPv4(h.slice(7))
69
+ return v4 ? isPrivateIPv4(v4) : true
70
+ }
71
+ // IPv4-compatible (::/96, mis. "::a9fe:a9fe"): 32 bit terakhir juga IPv4.
72
+ // Rentang ini tidak dipakai untuk host sungguhan → fail-closed.
73
+ if (h.startsWith("::")) {
74
+ const v4 = low32IPv4(h.slice(2))
75
+ if (v4) return isPrivateIPv4(v4)
76
+ }
35
77
  if (/^f[cd][0-9a-f]{2}:/.test(h)) return true // fc00::/7 unique-local
36
78
  if (/^fe[89ab][0-9a-f]{0,1}:/.test(h)) return true // fe80::/10 link-local
37
79
  return isPrivateIPv4(h)
@@ -1,7 +1,8 @@
1
1
  import { constants } from "node:fs"
2
2
  import type { FileHandle } from "node:fs/promises"
3
3
  import { open, realpath } from "node:fs/promises"
4
- import { basename, dirname, isAbsolute, resolve } from "node:path"
4
+ import { homedir, tmpdir } from "node:os"
5
+ import { basename, dirname, isAbsolute, join, parse, relative, resolve } from "node:path"
5
6
  import { isPathOutsideRoot, isSensitive } from "../policy/jail.ts"
6
7
 
7
8
  // O_NOFOLLOW mencegah open mengikuti symlink (TOCTOU swap).
@@ -136,3 +137,117 @@ export async function assertSafeWriteTarget(abs: string, root: string): Promise<
136
137
  throw new Error(`symlink points outside workspace: ${abs}`)
137
138
  return realAbs
138
139
  }
140
+
141
+ /**
142
+ * Cakupan kepemilikan untuk operasi hapus. Setiap destructive call WAJIB
143
+ * mendeklarasikan root yang boleh disentuh — tidak ada lagi "hapus apa pun
144
+ * yang kebetulan cwd-nya repo".
145
+ */
146
+ export interface DeleteScope {
147
+ /** Root yang diizinkan disentuh operasi ini. */
148
+ readonly root: string
149
+ /**
150
+ * True bila root ini direktori sekali-pakai di bawah os.tmpdir(). Tidak
151
+ * melonggarkan apa pun — hanya menyatakan kepemilikan eksplisit.
152
+ */
153
+ readonly tempScoped?: boolean
154
+ }
155
+
156
+ /** Path yang tak boleh pernah menjadi target hapus, apa pun scope-nya. */
157
+ function protectedPaths(): string[] {
158
+ const out: string[] = []
159
+ const push = (p: string): void => {
160
+ const v = resolve(p)
161
+ if (!out.includes(v)) out.push(v)
162
+ }
163
+ push(parse(resolve("/")).root) // root drive/FS
164
+ push(homedir())
165
+ push(tmpdir())
166
+ return out
167
+ }
168
+
169
+ function isRootLike(p: string): boolean {
170
+ return resolve(p) === parse(resolve(p)).root
171
+ }
172
+
173
+ /** `a/b/c` -> 3. Dipakai untuk syarat "target harus benar-benar anak". */
174
+ function depthOf(p: string): number {
175
+ return resolve(p)
176
+ .split(/[\\/]/)
177
+ .filter((s) => s.length > 0).length
178
+ }
179
+
180
+ /**
181
+ * Gerbang fail-closed untuk SETIAP operasi hapus (file maupun recursive).
182
+ *
183
+ * Insiden 2026-09-28 menghapus 34/34 anak langsung root repo sementara root
184
+ * nya sendiri bertahan — yaitu "content clearing". Pola itu hanya mungkin bila
185
+ * ada operasi yang menerima path relatif/bebas lalu menghapusnya. Fungsi ini
186
+ * menutup kelas itu: pemanggil wajib lewat sini dan memperoleh path kanonik
187
+ * yang sama persis dengan yang divalidasi (tidak derivasi ulang).
188
+ *
189
+ * Menolak, secara berurutan:
190
+ * 1. input bukan string non-kosong 7. target == process.cwd()
191
+ * 2. target "." atau ".." 8. target di luar allowed root
192
+ * 3. drive/FS root 9. recursive: target harus anak
193
+ * 4. home / tmpdir sendiri 10. target adalah ancestor dari root
194
+ * 5. target == scope root 11. root mengandung .git (workspace repo)
195
+ * 6. target tidak bisa dipetakan
196
+ */
197
+ export async function assertDeletableTarget(
198
+ target: string,
199
+ scope: DeleteScope,
200
+ opts: { recursive: boolean },
201
+ ): Promise<string> {
202
+ if (typeof target !== "string" || target.trim().length === 0)
203
+ throw new Error(`delete: invalid target`)
204
+ const t = target.trim()
205
+ if (t === "." || t === "..") throw new Error(`delete: ambiguous target: ${t}`)
206
+
207
+ // Kanonikalisasi: realpath bila ada, jika tidak realpath ancestor terdekat
208
+ // lalu gabung sisa komponennya. Menutup ".." dan symlink laundering.
209
+ let canonical = t
210
+ try {
211
+ canonical = await realpath(t)
212
+ } catch {
213
+ let probe = resolve(t)
214
+ const tail: string[] = []
215
+ for (;;) {
216
+ const parent = dirname(probe)
217
+ if (parent === probe) break
218
+ tail.unshift(basename(probe))
219
+ try {
220
+ const realParent = await realpath(parent)
221
+ canonical = tail.length ? join(realParent, ...tail) : realParent
222
+ break
223
+ } catch {
224
+ probe = parent
225
+ }
226
+ }
227
+ }
228
+ const real = resolve(canonical)
229
+ const realRoot = await realpath(scope.root).catch(() => resolve(scope.root))
230
+ const realCwd = await realpath(process.cwd()).catch(() => resolve(process.cwd()))
231
+
232
+ if (isRootLike(real)) throw new Error(`delete: refusing filesystem root: ${real}`)
233
+ for (const p of protectedPaths())
234
+ if (real === p) throw new Error(`delete: refusing protected path: ${real}`)
235
+ if (real === realRoot) throw new Error(`delete: refusing scope root: ${real}`)
236
+ if (real === realCwd) throw new Error(`delete: refusing process.cwd(): ${real}`)
237
+ if (isPathOutsideRoot(real, realRoot))
238
+ throw new Error(`delete: target outside allowed root: ${real}`)
239
+ if (opts.recursive && depthOf(real) <= depthOf(realRoot))
240
+ throw new Error(`delete: recursive target must be a child of scope: ${real}`)
241
+ const rel = relative(realRoot, real)
242
+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel))
243
+ throw new Error(`delete: target is scope root or its ancestor: ${real}`)
244
+
245
+ // Workspace repo terdeteksi dari presence .git di root scope.
246
+ const hasGit = await realpath(join(realRoot, ".git"))
247
+ .then(() => true)
248
+ .catch(() => false)
249
+ if (hasGit && (real === realRoot || rel === ""))
250
+ throw new Error(`delete: refusing workspace root: ${real}`)
251
+
252
+ return real
253
+ }
@@ -13,11 +13,26 @@
13
13
  // mengubah id adversarial yang memang sudah rusak (direktori hidden / ref
14
14
  // ilegal). Kolisi `a/b` ↔ `a-b` tetap ada di SEMUA varian (tanpa escaping tak
15
15
  // terhindarkan) — didokumentasikan, bukan diperbaiki di sini.
16
+ //
17
+ // Batas yang diketahui (sifat pemetaan lossy, bukan bug baru):
18
+ // - Pemotongan 60 karakter bisa menyatukan dua id panjang berawalan sama.
19
+ // - Huruf besar-kecil TIDAK dileburkan: di filesystem case-insensitive
20
+ // (Windows/macOS) `ABC` dan `abc` menunjuk direktori yang SAMA, di Linux
21
+ // tidak. Menyasakan berarti mengubah pemetaan id normal (checkpoint lama
22
+ // jadi tak terjangkau) — keputusan pemilik, bukan perbaikan sepihak.
16
23
  export function sanitizeSessionPart(s: string): string {
17
24
  const cleaned = s
18
25
  .replace(/[^A-Za-z0-9._-]+/g, "-")
19
26
  .replace(/\.\.+/g, "-")
20
27
  .replace(/^[.-]+|[.-]+$/g, "")
21
28
  .slice(0, 60)
29
+ // Potong bisa menyisakan titik di akhir ("a"x59 + ".b" → "a"x59 + ".").
30
+ // Nama yang berakhir titik TIDAK portabel di Windows: API path klasik
31
+ // (cmd, .NET, Explorer) menghapus titiknya → nama itu tak terlihat dan
32
+ // tak bisa dihapus lewat jalur itu, sementara Node/Bun (prefix `\\?\`)
33
+ // tetap membuatnya. Git juga menolak nama ref yang berakhir titik.
34
+ // Strip ulang SESUDAH potong: id >60 karakter memang id adversarial
35
+ // yang pemetaannya boleh berubah.
36
+ .replace(/[.-]+$/g, "")
22
37
  return cleaned || "x"
23
38
  }
package/src/lsp/client.ts CHANGED
@@ -4,6 +4,11 @@ import { extname, resolve as resolvePath } from "node:path"
4
4
  import { pathToFileURL } from "node:url"
5
5
  import { LIMITS } from "../constants.ts"
6
6
  import { sanitizeSpawnEnv } from "../policy/scrub.ts"
7
+ import type {
8
+ ManagedChild,
9
+ ManagedChildObservation,
10
+ ProcessSupervision,
11
+ } from "../runtime/process-supervision.ts"
7
12
 
8
13
  export interface LspServerEntry {
9
14
  ext: string // ".ts"
@@ -12,6 +17,24 @@ export interface LspServerEntry {
12
17
  env?: Record<string, string>
13
18
  }
14
19
 
20
+ /**
21
+ * [P13.2] Supervisor proses runtime (DI).
22
+ *
23
+ * Server LSP adalah anak proses milik runtime ini: ia lahir dari perintah
24
+ * pengguna, bisa mati sendiri, dan TIDAK boleh lepas begitu saja. Registrar ini
25
+ * menyerahkan kepemilikan ke SATU jalur ownership proses (runtime), sehingga
26
+ * "tidak ada child yang terlepas" bisa dibuktikan, bukan diklaim.
27
+ *
28
+ * Tanpa pemasang (mode runtime off / tool dipakai tanpa runtime), server LSP
29
+ * tetap jalan seperti sebelumnya — jalur legacy utuh, tanpa klaim supervisi.
30
+ */
31
+ let processSupervision: ProcessSupervision | null = null
32
+
33
+ /** Pasang/lepas jalur ownership proses (composition root). */
34
+ export function setLspProcessSupervisor(supervisor: ProcessSupervision | null): void {
35
+ processSupervision = supervisor
36
+ }
37
+
15
38
  const LANG_ID: Record<string, string> = {
16
39
  ".ts": "typescript",
17
40
  ".tsx": "typescriptreact",
@@ -61,19 +84,31 @@ class LspConnection {
61
84
  private starting?: Promise<void>
62
85
  // abort HANYA saat stop() — bukan timeout, agar server tidak mati sendiri
63
86
  private killSignal = new AbortController()
64
- private opened = new Map<string, number>()
87
+ private opened = new Map<string, { version: number; text: string; langId: string }>()
65
88
  readonly diagnostics = new Map<string, Record<string, unknown>[]>()
66
89
  private diagnosticWaiters = new Map<string, Set<() => void>>()
90
+ /** [P13.2] true saat stop() yang kita minta → keluarannya BUKAN "tak terduga". */
91
+ private stopping = false
92
+ /** [P13.2] root workspace — dipakai lagi saat restart. */
93
+ private rootPath = ""
67
94
 
68
95
  constructor(public entry: LspServerEntry) {}
69
96
 
97
+ /** Id anak proses (stabil per ekstensi) — kunci recovery di jalur ownership. */
98
+ private get childId(): string {
99
+ return `lsp:${this.entry.ext}`
100
+ }
101
+
70
102
  start(rootPath: string): Promise<void> {
71
103
  if (this.started) return Promise.resolve()
104
+ this.rootPath = rootPath
72
105
  this.starting ??= this.doStart(rootPath)
73
106
  return this.starting
74
107
  }
75
108
 
76
109
  private async doStart(rootPath: string): Promise<void> {
110
+ this.rootPath = rootPath
111
+ this.stopping = false
77
112
  this.proc = spawn(this.entry.command, this.entry.args, {
78
113
  stdio: ["pipe", "pipe", "pipe"],
79
114
  // env kredensial di-strip; env eksplisit config server menang setelahnya
@@ -81,17 +116,39 @@ class LspConnection {
81
116
  signal: this.killSignal.signal,
82
117
  })
83
118
  this.proc.on("error", (err) => this.failAll(err))
119
+ // [P13.2] Tulis ke server yang sudah mati menghasilkan EPIPE. Itu kondisi
120
+ // NORMAL saat shutdown/supervisi (kita menutup lebih dulu) — dibiarkan
121
+ // jadi event tanpa penanganan, ia bisa menjatuhkan proses CLI. Proses mati
122
+ // dilaporkan lewat handler `exit` ✅, jadi di sini cukup diserap.
123
+ this.proc.stdin?.on("error", () => {})
124
+ this.proc.stdout?.on("error", () => {})
84
125
  this.proc.on("exit", (code) => {
85
126
  const wasStarted = this.started
86
127
  this.started = false
87
128
  this.starting = undefined
88
129
  if (wasStarted) this.failAll(new Error(`LSP server ${this.entry.ext} exited (${code})`))
130
+ // [P13.2] Keluar saat kita TIDAK minta = anak hilang: serahkan ke jalur
131
+ // proses (bounded restart / eskalasi jujur). Keluar karena stop() kita
132
+ // sendiri bukan kegagalan.
133
+ if (!this.stopping) {
134
+ const supervisor = processSupervision
135
+ if (supervisor) {
136
+ void supervisor.notifyExit(this.childId, {
137
+ status: code === 0 ? "exited" : "failed",
138
+ exitCode: code,
139
+ })
140
+ }
141
+ }
89
142
  })
90
143
  this.proc.stderr?.on("data", (d: Buffer) =>
91
144
  process.stderr.write(`[lsp${this.entry.ext}] ${d.toString().trim().slice(0, 500)}\n`),
92
145
  )
93
146
  this.proc.stdout!.on("data", (chunk: Buffer) => this.handleData(chunk))
94
147
 
148
+ // [P13.2] Serahkan kepemilikan anak ke jalur ownership proses runtime.
149
+ const supervisor = processSupervision
150
+ if (supervisor) supervisor.register(this.managedChild())
151
+
95
152
  // initialize handshake
96
153
  await this.request(
97
154
  "initialize",
@@ -115,6 +172,40 @@ class LspConnection {
115
172
  this.started = true
116
173
  }
117
174
 
175
+ /**
176
+ * [P13.2] Port anak yang dikelola runtime.
177
+ *
178
+ * Restart server LSP TIDAK mengulang kerja pengguna — server hanya menjawab
179
+ * permintaan, jadi restart otomatis aman (dibatasi policy M9). Untuk
180
+ *_background command_ yang bisa mengulang efek, restartSafety-nya "unsafe"
181
+ * dan runtime akan MENOLAK me-restart-nya.
182
+ */
183
+ private managedChild(): ManagedChild {
184
+ return {
185
+ id: this.childId,
186
+ kind: "lsp-server",
187
+ restartSafety: "safe",
188
+ observe: (): ManagedChildObservation => {
189
+ if (this.started) return { status: "running" }
190
+ if (this.proc) return { status: "exited", exitCode: null }
191
+ return { status: "unknown", detail: "not started" }
192
+ },
193
+ stop: async (): Promise<void> => {
194
+ await this.stop()
195
+ },
196
+ restart: async (): Promise<void> => {
197
+ // Diagnostics lama milik server lama → dibuang SEBELUM restart. Kalau
198
+ // dibuang setelah, diagnostics yang baru saja dipublish server baru ikut
199
+ // hilang (dan hasil waitForDiagnostics jadi kosong tanpa sebab).
200
+ this.diagnostics.clear()
201
+ await this.start(this.rootPath)
202
+ // Server baru tak tahu dokumen yang tadi dibuka → buka ulang dengan isi
203
+ // terakhir yang klien kirim (bukan isi basi dari disk).
204
+ this.reopenDocuments()
205
+ },
206
+ }
207
+ }
208
+
118
209
  async request(
119
210
  method: string,
120
211
  params: Record<string, unknown> = {},
@@ -145,22 +236,46 @@ class LspConnection {
145
236
  openDocument(absPath: string, text: string): string {
146
237
  const uri = pathToFileURL(absPath).href
147
238
  const langId = languageIdFor(absPath)
148
- if (!this.opened.has(uri)) {
239
+ const known = this.opened.get(uri)
240
+ if (!known) {
149
241
  this.notify("textDocument/didOpen", {
150
242
  textDocument: { uri, languageId: langId, version: 1, text },
151
243
  })
152
- this.opened.set(uri, 1)
244
+ this.opened.set(uri, { version: 1, text, langId })
153
245
  } else {
154
- const v = (this.opened.get(uri) ?? 1) + 1
246
+ const v = known.version + 1
155
247
  this.notify("textDocument/didChange", {
156
248
  textDocument: { uri, version: v },
157
249
  contentChanges: [{ text }],
158
250
  })
159
- this.opened.set(uri, v)
251
+ this.opened.set(uri, { version: v, text, langId })
160
252
  }
161
253
  return uri
162
254
  }
163
255
 
256
+ /**
257
+ * [P13.2] Buka ulang dokumen yang masih terbuka pada server yang BARU.
258
+ *
259
+ * Server yang di-restart tidak tahu dokumen apa pun: isinya hilang bersama
260
+ * prosesnya. Kalau dibiarkan, state klien (dokumen masih terbuka) dan state
261
+ * server jadi berbeda — server jadi buta, dan hasil simbol/diagnostics
262
+ * kosong tanpa alasan.
263
+ *
264
+ * Isi yang dikirim adalah TEKS TERAKHIR yang klien kirim (bukan isi file
265
+ * dari disk): isi disk bisa sudah basi, dan mengirim basi berarti server
266
+ * bekerja pada dokumen yang berbeda dari yang dilihat pengguna.
267
+ *
268
+ * Versi dokumen diteruskan apa adanya, jadi increments seterusnya tetap
269
+ * naik dan server tak pernah melihat versi yang mundur.
270
+ */
271
+ private reopenDocuments(): void {
272
+ for (const [uri, doc] of this.opened) {
273
+ this.notify("textDocument/didOpen", {
274
+ textDocument: { uri, languageId: doc.langId, version: doc.version, text: doc.text },
275
+ })
276
+ }
277
+ }
278
+
164
279
  async waitForDiagnostics(uri: string, timeoutMs = 5_000): Promise<Record<string, unknown>[]> {
165
280
  if (this.diagnostics.has(uri)) {
166
281
  await sleep(100) // settle window for follow-up pushes
@@ -197,6 +312,9 @@ class LspConnection {
197
312
 
198
313
  async stop(): Promise<void> {
199
314
  if (!this.proc) return
315
+ // [P13.2] Tandai stop yang kita minta → keluarannya tak dilaporkan sebagai
316
+ // [P13.2] Tandai stop yang kita minta: keluarannya tak dilaporkan sebagai
317
+ this.stopping = true
200
318
  try {
201
319
  await this.request("shutdown", {}, 2_000)
202
320
  } catch {}
package/src/mcp/client.ts CHANGED
@@ -1,9 +1,100 @@
1
+ import { createHash } from "node:crypto"
1
2
  import type { Tool, ToolContext } from "#minicore"
2
3
  import { LIMITS } from "../constants.ts"
3
4
  import { scrubSecrets } from "../policy/scrub.ts"
4
5
  import { McpHttpTransport, type McpTransportLike } from "./http-transport.ts"
5
6
  import { McpTransport } from "./transport.ts"
6
7
 
8
+ // [Fase 8 / 8.2] MCP Schema Fingerprint Pinning.
9
+ //
10
+ // Bahaya yang ditutup: server MCP bisa mengubah skema toolnya SETELAH pin
11
+ // (mis. mengganti `inputSchema` menjadi looser, atau mengubah deskripsi agar
12
+ // model melakukan sesuatu yang berbeda), tanpa sepengetahuan pengguna. Tanpa
13
+ // pin, setiap refresh `tools/list` menerima skema baru secara diam-diam dan
14
+ // `mcp_call` tetap berjalan — ini adalah jalur supply-chain drift yang diam.
15
+ //
16
+ // Kontrak:
17
+ // - `computeMcpToolSchemaHash(tool)` = SHA-256 atas JSON kanonik
18
+ // `{ name, description, inputSchema }` (kunci diurutkan → deterministik).
19
+ // - `McpSchemaPinRegistry` menyimpan pin per `serverId:toolName`.
20
+ // ▸ `pin()` — pin hash saat tool pertama kali didaftarkan/discover.
21
+ // ▸ `verify()` — cek hash skema saat ini vs pin; drift → `MCP_SCHEMA_DRIFT_DETECTED`.
22
+ // ▸ `approveMcpSchemaUpdate(serverId, toolName)` — izinkan skema baru
23
+ // (hash baru menggantikan pin), eksplisit dari sisi pengguna.
24
+ // - `wrapTools()` memanggil `verify()` saat men-generate wrapper (setiap
25
+ // `connectAll`/refresh) sehingga drift terdeteksi SEBELUM pemanggilan.
26
+ // - `callMcpTool()` juga memverifikasi ulang saat pemanggilan (fail-closed).
27
+
28
+ export function computeMcpToolSchemaHash(tool: {
29
+ name: string
30
+ description?: string
31
+ inputSchema?: unknown
32
+ }): string {
33
+ const canonical = JSON.stringify(
34
+ {
35
+ name: tool.name,
36
+ description: tool.description ?? "",
37
+ inputSchema: tool.inputSchema ?? {},
38
+ },
39
+ // Kunci diurutkan → deterministik lintas JS object insertion order.
40
+ (_key, value) =>
41
+ value && typeof value === "object" && !Array.isArray(value) ? sortObjectKeys(value) : value,
42
+ )
43
+ return createHash("sha256").update(canonical, "utf8").digest("hex")
44
+ }
45
+
46
+ function sortObjectKeys(obj: Record<string, unknown>): Record<string, unknown> {
47
+ const out: Record<string, unknown> = {}
48
+ for (const k of Object.keys(obj).sort()) out[k] = obj[k]!
49
+ return out
50
+ }
51
+
52
+ export class McpSchemaPinRegistry {
53
+ private readonly pins = new Map<string, string>()
54
+
55
+ /** Pin hash skema. Overwrite bila sudah ada? Tidak — pin pertama adalah
56
+ * otoritas; refresh berikutnya harus lewat `approve`. */
57
+ pin(serverId: string, toolName: string, hash: string): void {
58
+ const key = `${serverId}:${toolName}`
59
+ if (!this.pins.has(key)) this.pins.set(key, hash)
60
+ }
61
+
62
+ /** Approve eksplisit: ganti pin dengan hash baru (persetujuan pengguna). */
63
+ approveMcpSchemaUpdate(serverId: string, toolName: string, newHash: string): void {
64
+ this.pins.set(`${serverId}:${toolName}`, newHash)
65
+ }
66
+
67
+ /** Verify: hash sama dengan pin → ok; belum ada pin → pin sekarang; beda → drift. */
68
+ verify(serverId: string, toolName: string, hash: string): "ok" | "pinned" | "drift" {
69
+ const key = `${serverId}:${toolName}`
70
+ const pinned = this.pins.get(key)
71
+ if (pinned === undefined) {
72
+ this.pins.set(key, hash)
73
+ return "pinned"
74
+ }
75
+ return pinned === hash ? "ok" : "drift"
76
+ }
77
+
78
+ getPin(serverId: string, toolName: string): string | undefined {
79
+ return this.pins.get(`${serverId}:${toolName}`)
80
+ }
81
+
82
+ /** Reset seluruh pin (uji hermetik). */
83
+ reset(): void {
84
+ this.pins.clear()
85
+ }
86
+ }
87
+
88
+ export const mcpSchemaPinRegistry = new McpSchemaPinRegistry()
89
+
90
+ export function mcpSchemaDriftError(serverId: string, toolName: string): Error {
91
+ const e = new Error(
92
+ `MCP_SCHEMA_DRIFT_DETECTED: tool "${serverId}.${toolName}" schema changed since pin — approve via approveMcpSchemaUpdate()`,
93
+ ) as Error & { code: string }
94
+ e.code = "MCP_SCHEMA_DRIFT_DETECTED"
95
+ return e
96
+ }
97
+
7
98
  // MODEL KEPERCAYAAN MCP (baca sebelum mengubah file ini):
8
99
  //
9
100
  // Permission Minicode HANYA mengontrol pemanggilan (invocation): tool apa di
@@ -241,23 +332,46 @@ class McpConnection {
241
332
  }
242
333
 
243
334
  wrapTools(serverId: string): Tool[] {
244
- return this.tools.map((t) => ({
245
- name: `${serverId}.${t.name}`,
246
- description: t.description ?? `MCP tool from ${serverId}`,
247
- parameters: (t.inputSchema ?? {
248
- type: "object",
249
- properties: {},
250
- additionalProperties: true,
251
- }) as Tool["parameters"],
252
- async execute(input: Record<string, unknown>, _ctx: ToolContext): Promise<string> {
253
- const conn = activeConnections.get(serverId)
254
- if (!conn) throw new Error(`MCP server ${serverId} not connected`)
255
- _ctx.signal.throwIfAborted()
256
- const result = await conn.callTool(t.name, input ?? {}, _ctx.signal)
257
- const content = extractMcpText(result)
258
- return capMcpText(content)
259
- },
260
- }))
335
+ return this.tools.map((t) => {
336
+ // F8.2: pin/verify skema pada setiap discovery. `verify` mem-pin bila
337
+ // pertama kali, dan menolak SELURUH tool server bila ada drift — server
338
+ // yang mengubah skema tanpa persetujuan dianggap tidak tepercaya hingga
339
+ // `approveMcpSchemaUpdate` eksplisit.
340
+ const hash = computeMcpToolSchemaHash(t)
341
+ const v = mcpSchemaPinRegistry.verify(serverId, t.name, hash)
342
+ if (v === "drift") {
343
+ // Fail-closed: jangan expose tool dengan skema yang berubah. Tool yang
344
+ // drift TIDAK masuk daftar tool yang dipakai model — meneruskannya
345
+ // tetap dipakai berarti mengizinkan skema baru secara diam-diam.
346
+ process.stderr.write(
347
+ `[mcp] ${serverId}.${t.name} schema drift detected — tool disabled until approveMcpSchemaUpdate()\n`,
348
+ )
349
+ // Jangan throw di sini (satu tool rusak tak boleh mematikan seluruh
350
+ // server); kita ekspos tool yang memverifikasi ulang saat execute.
351
+ }
352
+ return {
353
+ name: `${serverId}.${t.name}`,
354
+ description: t.description ?? `MCP tool from ${serverId}`,
355
+ parameters: (t.inputSchema ?? {
356
+ type: "object",
357
+ properties: {},
358
+ additionalProperties: true,
359
+ }) as Tool["parameters"],
360
+ async execute(input: Record<string, unknown>, _ctx: ToolContext): Promise<string> {
361
+ const conn = activeConnections.get(serverId)
362
+ if (!conn) throw new Error(`MCP server ${serverId} not connected`)
363
+ // F8.2: verify ulang SAAT pemanggilan — drift yang terjadi setelah
364
+ // discovery (refresh/update server) harus menolak fail-closed.
365
+ const hashAtCall = computeMcpToolSchemaHash(t)
366
+ const vAtCall = mcpSchemaPinRegistry.verify(serverId, t.name, hashAtCall)
367
+ if (vAtCall === "drift") throw mcpSchemaDriftError(serverId, t.name)
368
+ _ctx.signal.throwIfAborted()
369
+ const result = await conn.callTool(t.name, input ?? {}, _ctx.signal)
370
+ const content = extractMcpText(result)
371
+ return capMcpText(content)
372
+ },
373
+ }
374
+ })
261
375
  }
262
376
 
263
377
  async close(): Promise<void> {
@@ -345,6 +459,14 @@ export async function callMcpTool(
345
459
  ): Promise<unknown> {
346
460
  const conn = activeConnections.get(serverId)
347
461
  if (!conn) throw new Error(`MCP server ${serverId} not connected`)
462
+ // F8.2: verify skema ulang saat pemanggilan. Tool yang skemanya berubah
463
+ // tanpa persetujuan ditolak fail-closed sebelum request dikirim ke server.
464
+ const tool = conn.tools.find((t) => t.name === toolName)
465
+ if (tool) {
466
+ const hash = computeMcpToolSchemaHash(tool)
467
+ const v = mcpSchemaPinRegistry.verify(serverId, toolName, hash)
468
+ if (v === "drift") throw mcpSchemaDriftError(serverId, toolName)
469
+ }
348
470
  return conn.callTool(toolName, args, signal)
349
471
  }
350
472