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.
- package/CHANGELOG.md +935 -0
- package/LICENSE +21 -0
- package/README.md +200 -0
- package/cli/args.ts +195 -0
- package/cli/auto-update.ts +108 -0
- package/cli/commands/auth.ts +166 -0
- package/cli/commands/config.ts +382 -0
- package/cli/commands/doctor.ts +128 -0
- package/cli/commands/exec.ts +179 -0
- package/cli/commands/mcp.ts +35 -0
- package/cli/commands/memory.ts +107 -0
- package/cli/commands/pricing.ts +100 -0
- package/cli/commands/providers.ts +162 -0
- package/cli/commands/sessions.ts +128 -0
- package/cli/commands/skills.ts +61 -0
- package/cli/commands/stats.ts +82 -0
- package/cli/commands.ts +317 -0
- package/cli/index.ts +539 -0
- package/cli/model-manager.ts +112 -0
- package/cli/provider-manager.ts +111 -0
- package/cli/repl.ts +734 -0
- package/cli/router.ts +124 -0
- package/cli/setup.ts +780 -0
- package/cli/wizard.ts +21 -0
- package/docs/ARCHITECTURE.html +1222 -0
- package/docs/README.md +109 -0
- package/docs/architecture.md +44 -0
- package/docs/changelog.md +3 -0
- package/package.json +91 -0
- package/src/agents/pool.ts +43 -0
- package/src/app/mentions.ts +50 -0
- package/src/app/provider-layer.ts +118 -0
- package/src/app/rag-layer.ts +105 -0
- package/src/app/session.ts +154 -0
- package/src/app/tool-layer.ts +56 -0
- package/src/config.ts +372 -0
- package/src/constants.ts +119 -0
- package/src/hooks/run.ts +89 -0
- package/src/lib/atomic-write.ts +88 -0
- package/src/lib/db-path.ts +36 -0
- package/src/lib/git-hardening.ts +91 -0
- package/src/lib/ignore.ts +58 -0
- package/src/lib/keystore.ts +202 -0
- package/src/lib/net.ts +70 -0
- package/src/lib/safe-open.ts +138 -0
- package/src/lib/session-id.ts +23 -0
- package/src/lib/trash.ts +38 -0
- package/src/lib/trusted-exec.ts +81 -0
- package/src/lsp/client.ts +395 -0
- package/src/mcp/client.ts +400 -0
- package/src/mcp/http-transport.ts +344 -0
- package/src/mcp/server.ts +538 -0
- package/src/mcp/transport.ts +150 -0
- package/src/memory/files.ts +159 -0
- package/src/memory/vector.ts +775 -0
- package/src/policy/allowlist.ts +67 -0
- package/src/policy/bash-guard.ts +465 -0
- package/src/policy/compaction.ts +271 -0
- package/src/policy/context.ts +161 -0
- package/src/policy/executor.ts +199 -0
- package/src/policy/jail.ts +127 -0
- package/src/policy/permission.ts +517 -0
- package/src/policy/pricing.ts +336 -0
- package/src/policy/ratelimit.ts +54 -0
- package/src/policy/sandbox-policy.ts +157 -0
- package/src/policy/scrub.ts +138 -0
- package/src/policy/update-check.ts +200 -0
- package/src/policy/usage.ts +292 -0
- package/src/policy/verifier.ts +181 -0
- package/src/providers/anthropic.ts +401 -0
- package/src/providers/auth-store.ts +139 -0
- package/src/providers/build.ts +136 -0
- package/src/providers/detect.ts +126 -0
- package/src/providers/effort.ts +165 -0
- package/src/providers/guards.ts +107 -0
- package/src/providers/oauth.ts +326 -0
- package/src/providers/presets.ts +122 -0
- package/src/providers/provision.ts +298 -0
- package/src/providers/responses.ts +371 -0
- package/src/providers/router.ts +247 -0
- package/src/repo/repomap.ts +470 -0
- package/src/sandbox/docker.ts +129 -0
- package/src/sandbox/os.ts +193 -0
- package/src/session/checkpoint.ts +543 -0
- package/src/session/journal.ts +1347 -0
- package/src/session/persistence.ts +446 -0
- package/src/session/shadow-git.ts +351 -0
- package/src/session/turn-marker.ts +118 -0
- package/src/skills/loader.ts +117 -0
- package/src/telemetry/trace.ts +283 -0
- package/src/tools/ask_user.ts +54 -0
- package/src/tools/bash.ts +400 -0
- package/src/tools/code_run.ts +96 -0
- package/src/tools/delete_file.ts +31 -0
- package/src/tools/edit.ts +204 -0
- package/src/tools/git.ts +301 -0
- package/src/tools/glob.ts +90 -0
- package/src/tools/grep.ts +281 -0
- package/src/tools/hashline.ts +66 -0
- package/src/tools/index.ts +103 -0
- package/src/tools/lsp.ts +346 -0
- package/src/tools/mcp_call.ts +163 -0
- package/src/tools/memory.ts +144 -0
- package/src/tools/move_file.ts +47 -0
- package/src/tools/patch.ts +86 -0
- package/src/tools/read_file.ts +130 -0
- package/src/tools/read_image.ts +80 -0
- package/src/tools/submit_result.ts +49 -0
- package/src/tools/task.ts +346 -0
- package/src/tools/todo.ts +201 -0
- package/src/tools/web_fetch.ts +161 -0
- package/src/tools/web_search.ts +156 -0
- package/src/tools/write_file.ts +42 -0
- package/src/ui/approval/prompt.ts +76 -0
- package/src/ui/assistant/simple.ts +568 -0
- package/src/ui/assistant/turn-status.ts +303 -0
- package/src/ui/contract.ts +55 -0
- package/src/ui/footer.ts +105 -0
- package/src/ui/input/input.ts +805 -0
- package/src/ui/input/prompt-engine.ts +606 -0
- package/src/ui/render/collapse.ts +84 -0
- package/src/ui/render/detail.ts +24 -0
- package/src/ui/render/diff.ts +181 -0
- package/src/ui/render/errors.ts +239 -0
- package/src/ui/render/format.ts +54 -0
- package/src/ui/render/highlight.ts +294 -0
- package/src/ui/render/markdown.ts +120 -0
- package/src/ui/render/money.ts +12 -0
- package/src/ui/render/reasoning.ts +20 -0
- package/src/ui/render/sanitize.ts +80 -0
- package/src/ui/render/table.ts +88 -0
- package/src/ui/render/theme.ts +339 -0
- package/src/ui/render/width.ts +256 -0
- package/src/ui/render/wrap.ts +120 -0
- package/src/ui/runtime/bus-debug.ts +83 -0
- package/src/ui/runtime/chrome.ts +301 -0
- package/src/ui/runtime/spinner.ts +77 -0
- package/src/ui/runtime/statusline.ts +227 -0
- package/src/ui/screens/model-manager.ts +434 -0
- package/src/ui/screens/overlay.ts +61 -0
- package/src/ui/screens/picker.ts +307 -0
- package/src/ui/screens/provider-manager.ts +450 -0
- package/src/ui/screens/wizard.ts +132 -0
- package/vendor/minicore/VENDOR.md +29 -0
- package/vendor/minicore/package.json +21 -0
- package/vendor/minicore/src/core/budget.ts +26 -0
- package/vendor/minicore/src/core/compact.ts +76 -0
- package/vendor/minicore/src/core/errors.ts +60 -0
- package/vendor/minicore/src/core/events.ts +74 -0
- package/vendor/minicore/src/core/executor.ts +139 -0
- package/vendor/minicore/src/core/history.ts +32 -0
- package/vendor/minicore/src/core/index.ts +42 -0
- package/vendor/minicore/src/core/loop.ts +344 -0
- package/vendor/minicore/src/core/permission.ts +24 -0
- package/vendor/minicore/src/core/provider.ts +39 -0
- package/vendor/minicore/src/core/recovery.ts +34 -0
- package/vendor/minicore/src/core/session.ts +327 -0
- package/vendor/minicore/src/core/snapshot.ts +142 -0
- package/vendor/minicore/src/core/tokens.ts +111 -0
- package/vendor/minicore/src/core/tool.ts +118 -0
- package/vendor/minicore/src/core/types.ts +50 -0
- 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
|
+
}
|