minicode-ai 0.9.26

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 (162) hide show
  1. package/CHANGELOG.md +935 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -0
  4. package/cli/args.ts +195 -0
  5. package/cli/auto-update.ts +108 -0
  6. package/cli/commands/auth.ts +166 -0
  7. package/cli/commands/config.ts +382 -0
  8. package/cli/commands/doctor.ts +128 -0
  9. package/cli/commands/exec.ts +179 -0
  10. package/cli/commands/mcp.ts +35 -0
  11. package/cli/commands/memory.ts +107 -0
  12. package/cli/commands/pricing.ts +100 -0
  13. package/cli/commands/providers.ts +162 -0
  14. package/cli/commands/sessions.ts +128 -0
  15. package/cli/commands/skills.ts +61 -0
  16. package/cli/commands/stats.ts +82 -0
  17. package/cli/commands.ts +317 -0
  18. package/cli/index.ts +539 -0
  19. package/cli/model-manager.ts +112 -0
  20. package/cli/provider-manager.ts +111 -0
  21. package/cli/repl.ts +734 -0
  22. package/cli/router.ts +124 -0
  23. package/cli/setup.ts +780 -0
  24. package/cli/wizard.ts +21 -0
  25. package/docs/ARCHITECTURE.html +1222 -0
  26. package/docs/README.md +109 -0
  27. package/docs/architecture.md +44 -0
  28. package/docs/changelog.md +3 -0
  29. package/package.json +91 -0
  30. package/src/agents/pool.ts +43 -0
  31. package/src/app/mentions.ts +50 -0
  32. package/src/app/provider-layer.ts +118 -0
  33. package/src/app/rag-layer.ts +105 -0
  34. package/src/app/session.ts +154 -0
  35. package/src/app/tool-layer.ts +56 -0
  36. package/src/config.ts +372 -0
  37. package/src/constants.ts +119 -0
  38. package/src/hooks/run.ts +89 -0
  39. package/src/lib/atomic-write.ts +88 -0
  40. package/src/lib/db-path.ts +36 -0
  41. package/src/lib/git-hardening.ts +91 -0
  42. package/src/lib/ignore.ts +58 -0
  43. package/src/lib/keystore.ts +202 -0
  44. package/src/lib/net.ts +70 -0
  45. package/src/lib/safe-open.ts +138 -0
  46. package/src/lib/session-id.ts +23 -0
  47. package/src/lib/trash.ts +38 -0
  48. package/src/lib/trusted-exec.ts +81 -0
  49. package/src/lsp/client.ts +395 -0
  50. package/src/mcp/client.ts +400 -0
  51. package/src/mcp/http-transport.ts +344 -0
  52. package/src/mcp/server.ts +538 -0
  53. package/src/mcp/transport.ts +150 -0
  54. package/src/memory/files.ts +159 -0
  55. package/src/memory/vector.ts +775 -0
  56. package/src/policy/allowlist.ts +67 -0
  57. package/src/policy/bash-guard.ts +465 -0
  58. package/src/policy/compaction.ts +271 -0
  59. package/src/policy/context.ts +161 -0
  60. package/src/policy/executor.ts +199 -0
  61. package/src/policy/jail.ts +127 -0
  62. package/src/policy/permission.ts +517 -0
  63. package/src/policy/pricing.ts +336 -0
  64. package/src/policy/ratelimit.ts +54 -0
  65. package/src/policy/sandbox-policy.ts +157 -0
  66. package/src/policy/scrub.ts +138 -0
  67. package/src/policy/update-check.ts +200 -0
  68. package/src/policy/usage.ts +292 -0
  69. package/src/policy/verifier.ts +181 -0
  70. package/src/providers/anthropic.ts +401 -0
  71. package/src/providers/auth-store.ts +139 -0
  72. package/src/providers/build.ts +136 -0
  73. package/src/providers/detect.ts +126 -0
  74. package/src/providers/effort.ts +165 -0
  75. package/src/providers/guards.ts +107 -0
  76. package/src/providers/oauth.ts +326 -0
  77. package/src/providers/presets.ts +122 -0
  78. package/src/providers/provision.ts +298 -0
  79. package/src/providers/responses.ts +371 -0
  80. package/src/providers/router.ts +247 -0
  81. package/src/repo/repomap.ts +470 -0
  82. package/src/sandbox/docker.ts +129 -0
  83. package/src/sandbox/os.ts +193 -0
  84. package/src/session/checkpoint.ts +543 -0
  85. package/src/session/journal.ts +1347 -0
  86. package/src/session/persistence.ts +446 -0
  87. package/src/session/shadow-git.ts +351 -0
  88. package/src/session/turn-marker.ts +118 -0
  89. package/src/skills/loader.ts +117 -0
  90. package/src/telemetry/trace.ts +283 -0
  91. package/src/tools/ask_user.ts +54 -0
  92. package/src/tools/bash.ts +400 -0
  93. package/src/tools/code_run.ts +96 -0
  94. package/src/tools/delete_file.ts +31 -0
  95. package/src/tools/edit.ts +204 -0
  96. package/src/tools/git.ts +301 -0
  97. package/src/tools/glob.ts +90 -0
  98. package/src/tools/grep.ts +281 -0
  99. package/src/tools/hashline.ts +66 -0
  100. package/src/tools/index.ts +103 -0
  101. package/src/tools/lsp.ts +346 -0
  102. package/src/tools/mcp_call.ts +163 -0
  103. package/src/tools/memory.ts +144 -0
  104. package/src/tools/move_file.ts +47 -0
  105. package/src/tools/patch.ts +86 -0
  106. package/src/tools/read_file.ts +130 -0
  107. package/src/tools/read_image.ts +80 -0
  108. package/src/tools/submit_result.ts +49 -0
  109. package/src/tools/task.ts +346 -0
  110. package/src/tools/todo.ts +201 -0
  111. package/src/tools/web_fetch.ts +161 -0
  112. package/src/tools/web_search.ts +156 -0
  113. package/src/tools/write_file.ts +42 -0
  114. package/src/ui/approval/prompt.ts +76 -0
  115. package/src/ui/assistant/simple.ts +568 -0
  116. package/src/ui/assistant/turn-status.ts +303 -0
  117. package/src/ui/contract.ts +55 -0
  118. package/src/ui/footer.ts +105 -0
  119. package/src/ui/input/input.ts +805 -0
  120. package/src/ui/input/prompt-engine.ts +606 -0
  121. package/src/ui/render/collapse.ts +84 -0
  122. package/src/ui/render/detail.ts +24 -0
  123. package/src/ui/render/diff.ts +181 -0
  124. package/src/ui/render/errors.ts +239 -0
  125. package/src/ui/render/format.ts +54 -0
  126. package/src/ui/render/highlight.ts +294 -0
  127. package/src/ui/render/markdown.ts +120 -0
  128. package/src/ui/render/money.ts +12 -0
  129. package/src/ui/render/reasoning.ts +20 -0
  130. package/src/ui/render/sanitize.ts +80 -0
  131. package/src/ui/render/table.ts +88 -0
  132. package/src/ui/render/theme.ts +339 -0
  133. package/src/ui/render/width.ts +256 -0
  134. package/src/ui/render/wrap.ts +120 -0
  135. package/src/ui/runtime/bus-debug.ts +83 -0
  136. package/src/ui/runtime/chrome.ts +301 -0
  137. package/src/ui/runtime/spinner.ts +77 -0
  138. package/src/ui/runtime/statusline.ts +227 -0
  139. package/src/ui/screens/model-manager.ts +434 -0
  140. package/src/ui/screens/overlay.ts +61 -0
  141. package/src/ui/screens/picker.ts +307 -0
  142. package/src/ui/screens/provider-manager.ts +450 -0
  143. package/src/ui/screens/wizard.ts +132 -0
  144. package/vendor/minicore/VENDOR.md +29 -0
  145. package/vendor/minicore/package.json +21 -0
  146. package/vendor/minicore/src/core/budget.ts +26 -0
  147. package/vendor/minicore/src/core/compact.ts +76 -0
  148. package/vendor/minicore/src/core/errors.ts +60 -0
  149. package/vendor/minicore/src/core/events.ts +74 -0
  150. package/vendor/minicore/src/core/executor.ts +139 -0
  151. package/vendor/minicore/src/core/history.ts +32 -0
  152. package/vendor/minicore/src/core/index.ts +42 -0
  153. package/vendor/minicore/src/core/loop.ts +344 -0
  154. package/vendor/minicore/src/core/permission.ts +24 -0
  155. package/vendor/minicore/src/core/provider.ts +39 -0
  156. package/vendor/minicore/src/core/recovery.ts +34 -0
  157. package/vendor/minicore/src/core/session.ts +327 -0
  158. package/vendor/minicore/src/core/snapshot.ts +142 -0
  159. package/vendor/minicore/src/core/tokens.ts +111 -0
  160. package/vendor/minicore/src/core/tool.ts +118 -0
  161. package/vendor/minicore/src/core/types.ts +50 -0
  162. package/vendor/minicore/src/providers/openai-compat.ts +366 -0
@@ -0,0 +1,344 @@
1
+ // Transport MCP: Streamable HTTP (spec 2025-03-26) + SSE legacy fallback.
2
+ //
3
+ // Sebelum ini client hanya mendukung stdio, jadi seluruh ekosistem MCP remote
4
+ // tak terjangkau — padahal sisi *server* minicode sudah menyajikan
5
+ // tools/resources/prompts. Asimetri itu yang ditutup di sini.
6
+ //
7
+ // Streamable HTTP singkatnya:
8
+ // - Request : POST <endpoint> dengan body JSON-RPC.
9
+ // - Response : `application/json` (satu balasan) ATAU `text/event-stream`
10
+ // (server boleh mengirim notifikasi lalu balasan).
11
+ // - Sesi : server boleh memberi `Mcp-Session-Id` di respons initialize;
12
+ // header itu harus disertakan di request berikutnya.
13
+ //
14
+ // Keamanan yang diberlakukan di sini (bukan bawaan spec):
15
+ // - Hanya http/https, dan host privat DITOLAK kecuali di-opt-in eksplisit.
16
+ // Server MCP remote yang menunjuk ke 169.254.169.254 atau localhost adalah
17
+ // jalur SSRF klasik; jail-nya memakai penjaga yang sama dengan `web_fetch`.
18
+ // - Header Authorization tidak pernah di-log.
19
+ // - Body respons dibatasi agar server nakal tak bisa membuat OOM.
20
+
21
+ import { LIMITS } from "../constants.ts"
22
+ import { isPrivateHostWithDns } from "../lib/net.ts"
23
+
24
+ /**
25
+ * Kemampuan transport yang dipakai `McpConnection` setelah koneksi terbuka.
26
+ * `connect()` sengaja TIDAK di sini karena bentuknya berbeda antar transport
27
+ * (stdio butuh command/args, HTTP tidak) — pemilihannya ditangani connection.
28
+ */
29
+ export interface McpTransportLike {
30
+ request(
31
+ method: string,
32
+ params?: Record<string, unknown>,
33
+ timeoutMs?: number,
34
+ signal?: AbortSignal,
35
+ ): Promise<unknown>
36
+ notify(method: string, params?: Record<string, unknown>): void
37
+ close(): Promise<void>
38
+ }
39
+
40
+ export interface HttpTransportOptions {
41
+ url: string
42
+ headers?: Record<string, string>
43
+ /** Izinkan host privat (localhost/LAN) — untuk server MCP yang dijalankan sendiri. */
44
+ allowPrivateHost?: boolean
45
+ }
46
+
47
+ interface JsonRpcResponse {
48
+ jsonrpc?: string
49
+ id?: string | number | null
50
+ result?: unknown
51
+ error?: { code?: number; message?: string; data?: unknown }
52
+ }
53
+
54
+ export class McpHttpTransport implements McpTransportLike {
55
+ private seq = 0
56
+ private sessionId: string | null = null
57
+ private closed = false
58
+ private readonly url: URL
59
+ private readonly extraHeaders: Record<string, string>
60
+ private readonly allowPrivate: boolean
61
+ /** Protokol yang dinegosiasikan; dikirim ulang di request berikutnya. */
62
+ private protocolVersion: string | null = null
63
+
64
+ constructor(opts: HttpTransportOptions) {
65
+ let parsed: URL
66
+ try {
67
+ parsed = new URL(opts.url)
68
+ } catch {
69
+ throw new Error(`MCP http: invalid URL: ${opts.url}`)
70
+ }
71
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
72
+ throw new Error(`MCP http: unsupported protocol: ${parsed.protocol}`)
73
+ }
74
+ this.url = parsed
75
+ this.extraHeaders = opts.headers ?? {}
76
+ this.allowPrivate = opts.allowPrivateHost === true
77
+ }
78
+
79
+ async connect(): Promise<void> {
80
+ // Validasi host sebelum request PERTAMA, bukan setelahnya.
81
+ if (!this.allowPrivate && (await isPrivateHostWithDns(this.url.hostname))) {
82
+ throw new Error(
83
+ `MCP http: private host rejected: ${this.url.hostname} (set allowPrivateHost for local servers)`,
84
+ )
85
+ }
86
+ }
87
+
88
+ /** Header dasar; Authorization dari config diteruskan tapi tak pernah di-log. */
89
+ private headers(accept: string): Record<string, string> {
90
+ const h: Record<string, string> = {
91
+ "content-type": "application/json",
92
+ accept,
93
+ ...this.extraHeaders,
94
+ }
95
+ if (this.sessionId) h["mcp-session-id"] = this.sessionId
96
+ if (this.protocolVersion) h["mcp-protocol-version"] = this.protocolVersion
97
+ return h
98
+ }
99
+
100
+ async request(
101
+ method: string,
102
+ params: Record<string, unknown> = {},
103
+ timeoutMs: number = LIMITS.MCP_REQUEST_TIMEOUT_MS,
104
+ signal?: AbortSignal,
105
+ ): Promise<unknown> {
106
+ if (this.closed) throw new Error("MCP http: transport already closed")
107
+ signal?.throwIfAborted()
108
+ // F-21: validasi ulang tiap request (bukan hanya saat connect): sesi MCP
109
+ // berumur panjang dan DNS bisa berubah setelah connect. Cache default
110
+ // (30 dtk) membuat cek ini murah; bukan penutup TOCTOU check-then-connect
111
+ // (itu fundamental, lihat web_fetch), melainkan penutup drift sesi.
112
+ if (!this.allowPrivate && (await isPrivateHostWithDns(this.url.hostname))) {
113
+ throw new Error(`MCP http: private host rejected: ${this.url.hostname}`)
114
+ }
115
+ const id = ++this.seq
116
+ const body = JSON.stringify({ jsonrpc: "2.0", id, method, params })
117
+
118
+ const controller = new AbortController()
119
+ const timer = setTimeout(() => controller.abort(new Error("timeout")), timeoutMs)
120
+ // Pembatalan parent BENAR-BENAR membatalkan fetch HTTP (beda dengan stdio).
121
+ const onAbort = () => controller.abort(signal?.reason ?? new Error("aborted"))
122
+ if (signal?.aborted) controller.abort(signal.reason)
123
+ else signal?.addEventListener("abort", onAbort, { once: true })
124
+ let res: Response
125
+ try {
126
+ res = await fetch(this.url.toString(), {
127
+ method: "POST",
128
+ headers: this.headers("application/json, text/event-stream"),
129
+ body,
130
+ signal: controller.signal,
131
+ redirect: "manual", // redirect ke host lain = permukaan SSRF
132
+ })
133
+ } catch (e) {
134
+ clearTimeout(timer)
135
+ signal?.removeEventListener("abort", onAbort)
136
+ const msg = (e as Error).message
137
+ throw new Error(
138
+ `MCP http: ${method} failed: ${msg === "timeout" ? `timeout ${timeoutMs}ms` : msg}`,
139
+ )
140
+ }
141
+
142
+ try {
143
+ // Sesi dari server: simpan untuk request berikutnya (spec 2025-03-26).
144
+ const sid = res.headers.get("mcp-session-id")
145
+ if (sid) this.sessionId = sid
146
+
147
+ if (res.status >= 300 && res.status < 400) {
148
+ throw new Error(`MCP http: redirect not followed (${res.status}) — check the server URL`)
149
+ }
150
+ if (!res.ok) {
151
+ // F-15 sekelas: snippet error via readCapped (bounded), bukan
152
+ // res.text() mentah yang mem-buffer body utuh sebelum slice.
153
+ const snippet = (await readCapped(res).catch(() => "")).slice(0, 400)
154
+ throw new Error(`MCP http: ${method} → HTTP ${res.status}${snippet ? `: ${snippet}` : ""}`)
155
+ }
156
+
157
+ const ctype = (res.headers.get("content-type") ?? "").toLowerCase()
158
+ const payload = ctype.includes("text/event-stream")
159
+ ? await readSseResponse(res, id)
160
+ : await readJsonResponse(res, id)
161
+
162
+ if (!payload) throw new Error(`MCP http: ${method} returned no response`)
163
+ if (payload.error) {
164
+ throw new Error(
165
+ `MCP http: ${method} → ${payload.error.message ?? JSON.stringify(payload.error)}`,
166
+ )
167
+ }
168
+ // Simpan protokol hasil negosiasi initialize.
169
+ if (method === "initialize") {
170
+ const pv = (payload.result as { protocolVersion?: string } | undefined)?.protocolVersion
171
+ if (typeof pv === "string") this.protocolVersion = pv
172
+ }
173
+ return payload.result
174
+ } finally {
175
+ clearTimeout(timer)
176
+ signal?.removeEventListener("abort", onAbort)
177
+ }
178
+ }
179
+
180
+ notify(method: string, params: Record<string, unknown> = {}): void {
181
+ if (this.closed) return
182
+ // Notifikasi tak punya id dan tak menunggu balasan; kegagalan tidak fatal.
183
+ void fetch(this.url.toString(), {
184
+ method: "POST",
185
+ headers: this.headers("application/json, text/event-stream"),
186
+ body: JSON.stringify({ jsonrpc: "2.0", method, params }),
187
+ redirect: "manual",
188
+ signal: AbortSignal.timeout(LIMITS.MCP_HANDSHAKE_TIMEOUT_MS),
189
+ }).catch(() => {})
190
+ }
191
+
192
+ async close(): Promise<void> {
193
+ if (this.closed) return
194
+ this.closed = true
195
+ // Spec: DELETE mengakhiri sesi. Server yang tak mendukung akan menolak —
196
+ // itu bukan kegagalan bagi kita.
197
+ if (this.sessionId) {
198
+ await fetch(this.url.toString(), {
199
+ method: "DELETE",
200
+ headers: this.headers("application/json"),
201
+ signal: AbortSignal.timeout(LIMITS.MCP_HANDSHAKE_TIMEOUT_MS),
202
+ }).catch(() => {})
203
+ }
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Baca body JSON dengan cap ukuran, lalu cocokkan dengan `id` request.
209
+ *
210
+ * Pencocokan id penting: server yang membalas id lain (atau hanya mengirim
211
+ * notifikasi tanpa id) berarti request kita **tidak** terjawab. Tanpa cek ini,
212
+ * balasan untuk request orang lain — atau notifikasi kosong — akan diterima
213
+ * sebagai hasil, dan `result: undefined` menjalar ke pemanggil sebagai
214
+ * "sukses". Ditemukan oleh experiments/extreme-mcp-adversarial.ts.
215
+ *
216
+ * `expectId` opsional agar helper tetap bisa diuji tanpa konteks request.
217
+ * Diekspor untuk test.
218
+ */
219
+ export async function readJsonResponse(
220
+ res: Response,
221
+ expectId?: string | number,
222
+ ): Promise<JsonRpcResponse | null> {
223
+ const text = await readCapped(res)
224
+ if (!text.trim()) return null
225
+ let parsed: JsonRpcResponse | JsonRpcResponse[]
226
+ try {
227
+ parsed = JSON.parse(text) as JsonRpcResponse | JsonRpcResponse[]
228
+ } catch {
229
+ throw new Error(`MCP http: response is not valid JSON: ${text.slice(0, 200)}`)
230
+ }
231
+ if (parsed === null) return null
232
+ if (expectId !== undefined) return matchResponse(parsed, expectId)
233
+ // Tanpa id yang diharapkan: ambil elemen pertama yang punya result/error.
234
+ if (Array.isArray(parsed)) return parsed.find((p) => p.result !== undefined || p.error) ?? null
235
+ return parsed
236
+ }
237
+
238
+ /**
239
+ * Baca aliran SSE sampai menemukan balasan untuk `id`.
240
+ *
241
+ * Server boleh mengirim notifikasi/progress sebelum balasan; itu dilewati.
242
+ * Diekspor untuk test.
243
+ */
244
+ export async function readSseResponse(
245
+ res: Response,
246
+ id: string | number,
247
+ ): Promise<JsonRpcResponse | null> {
248
+ if (!res.body) return null
249
+ const reader = res.body.getReader()
250
+ const decoder = new TextDecoder()
251
+ let buffer = ""
252
+ let total = 0
253
+ try {
254
+ while (true) {
255
+ const { done, value } = await reader.read()
256
+ if (done) break
257
+ total += value.byteLength
258
+ if (total > LIMITS.MCP_OUTPUT_MAX_CHARS) {
259
+ throw new Error("MCP http: aliran SSE melewati batas ukuran")
260
+ }
261
+ buffer += decoder.decode(value, { stream: true })
262
+
263
+ // Event SSE dipisah baris kosong; tiap event bisa punya beberapa `data:`.
264
+ let sep = findEventBoundary(buffer)
265
+ while (sep !== -1) {
266
+ const rawEvent = buffer.slice(0, sep)
267
+ buffer = buffer.slice(sep).replace(/^(?:\r?\n){1,2}/, "")
268
+ const data = rawEvent
269
+ .split(/\r?\n/)
270
+ .filter((l) => l.startsWith("data:"))
271
+ .map((l) => l.slice(5).trim())
272
+ .join("")
273
+ if (data) {
274
+ let msg: JsonRpcResponse | JsonRpcResponse[]
275
+ try {
276
+ msg = JSON.parse(data)
277
+ } catch {
278
+ sep = findEventBoundary(buffer)
279
+ continue // event bukan JSON → lewati, jangan gagalkan seluruh request
280
+ }
281
+ const found = matchResponse(msg, id)
282
+ if (found) return found
283
+ }
284
+ sep = findEventBoundary(buffer)
285
+ }
286
+ }
287
+ // Aliran berakhir: coba sisa buffer.
288
+ const tail = buffer
289
+ .split(/\r?\n/)
290
+ .filter((l) => l.startsWith("data:"))
291
+ .map((l) => l.slice(5).trim())
292
+ .join("")
293
+ if (tail) {
294
+ try {
295
+ return matchResponse(JSON.parse(tail), id)
296
+ } catch {
297
+ return null
298
+ }
299
+ }
300
+ return null
301
+ } finally {
302
+ reader.releaseLock()
303
+ }
304
+ }
305
+
306
+ function findEventBoundary(buf: string): number {
307
+ const lf = buf.indexOf("\n\n")
308
+ const crlf = buf.indexOf("\r\n\r\n")
309
+ if (lf === -1) return crlf
310
+ if (crlf === -1) return lf
311
+ return Math.min(lf, crlf)
312
+ }
313
+
314
+ function matchResponse(
315
+ msg: JsonRpcResponse | JsonRpcResponse[],
316
+ id: string | number,
317
+ ): JsonRpcResponse | null {
318
+ const list = Array.isArray(msg) ? msg : [msg]
319
+ for (const m of list) {
320
+ // Balasan punya id yang sama; notifikasi tak punya id sama sekali.
321
+ if (m.id === id && (m.result !== undefined || m.error)) return m
322
+ }
323
+ return null
324
+ }
325
+
326
+ async function readCapped(res: Response): Promise<string> {
327
+ if (!res.body) return ""
328
+ const reader = res.body.getReader()
329
+ const decoder = new TextDecoder()
330
+ let out = ""
331
+ try {
332
+ while (true) {
333
+ const { done, value } = await reader.read()
334
+ if (done) break
335
+ out += decoder.decode(value, { stream: true })
336
+ if (out.length > LIMITS.MCP_OUTPUT_MAX_CHARS) {
337
+ throw new Error("MCP http: balasan melewati batas ukuran")
338
+ }
339
+ }
340
+ } finally {
341
+ reader.releaseLock()
342
+ }
343
+ return out
344
+ }