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,538 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto"
|
|
2
|
+
import { createInterface } from "node:readline"
|
|
3
|
+
import type { ExecutorDeps, Tool, ToolContext } from "#minicore"
|
|
4
|
+
import { scrubSecrets } from "../policy/scrub.ts"
|
|
5
|
+
import {
|
|
6
|
+
appendMutationIntent,
|
|
7
|
+
appendMutationTerminal,
|
|
8
|
+
finalizeJournal,
|
|
9
|
+
hashArgs,
|
|
10
|
+
isMutationTool,
|
|
11
|
+
verifyPaths,
|
|
12
|
+
} from "../session/journal.ts"
|
|
13
|
+
import { allTools } from "../tools/index.ts"
|
|
14
|
+
import { todoSession } from "../tools/todo.ts"
|
|
15
|
+
import { capMcpText } from "./client.ts"
|
|
16
|
+
|
|
17
|
+
export interface McpServeOptions {
|
|
18
|
+
allowAll?: boolean
|
|
19
|
+
allTools?: boolean
|
|
20
|
+
root?: string
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// tool internal minicode — tidak relevan/berbahaya jika dipanggil dari agent eksternal
|
|
24
|
+
// write_memory/forget_memory juga di-exclude biar AI luar tidak polusi vector.db global
|
|
25
|
+
const INTERNAL_TOOLS = new Set([
|
|
26
|
+
"delegate_task",
|
|
27
|
+
"mcp_call",
|
|
28
|
+
"mcp_list",
|
|
29
|
+
"write_memory",
|
|
30
|
+
"forget_memory",
|
|
31
|
+
])
|
|
32
|
+
|
|
33
|
+
const SERVER_INFO = { name: "minicode", version: "0.1.0" }
|
|
34
|
+
const PROTOCOL_VERSION = "2026-07-28"
|
|
35
|
+
|
|
36
|
+
interface JsonRpcMsg {
|
|
37
|
+
jsonrpc?: string
|
|
38
|
+
id?: string | number | null
|
|
39
|
+
method?: string
|
|
40
|
+
params?: Record<string, unknown>
|
|
41
|
+
result?: unknown
|
|
42
|
+
error?: unknown
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function send(msg: JsonRpcMsg) {
|
|
46
|
+
process.stdout.write(`${JSON.stringify(msg)}\n`)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function reply(id: string | number, result: unknown) {
|
|
50
|
+
send({ jsonrpc: "2.0", id, result })
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function replyError(id: string | number | null | undefined, code: number, message: string) {
|
|
54
|
+
if (id === undefined) return // notification → no response
|
|
55
|
+
send({ jsonrpc: "2.0", id, error: { code, message } }) // null id valid utk parse error
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const CODE_METHOD_NOT_FOUND = -32601
|
|
59
|
+
const CODE_INVALID_PARAMS = -32602
|
|
60
|
+
const CODE_INTERNAL = -32603
|
|
61
|
+
|
|
62
|
+
export function selectTools(opts: McpServeOptions): Tool[] {
|
|
63
|
+
const base = opts.allTools ? allTools : allTools.filter((t) => !INTERNAL_TOOLS.has(t.name))
|
|
64
|
+
const seen = new Set<string>()
|
|
65
|
+
return base.filter((t) => (seen.has(t.name) ? false : (seen.add(t.name), true)))
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function invokeTool(
|
|
69
|
+
tool: Tool,
|
|
70
|
+
args: Record<string, unknown>,
|
|
71
|
+
opts: McpServeOptions,
|
|
72
|
+
signal: AbortSignal,
|
|
73
|
+
journal: { session: string; root: string },
|
|
74
|
+
/** Kunci bukti dedup `req:<id>:<argsHash>` (dibuat pemanggil dari argumen
|
|
75
|
+
* mentah) — ditulis apa adanya ke outcome.note + flag dedup. */
|
|
76
|
+
noteKey?: string,
|
|
77
|
+
): Promise<{ content: { type: string; text: string }[]; isError: boolean }> {
|
|
78
|
+
const root = journal.root
|
|
79
|
+
// validateArgs KERNEL (bukan validasi ad-hoc): argumen invalid ditolak
|
|
80
|
+
// SEBELUM permission/execute — sama seperti jalur REPL. Tanpa ini argumen
|
|
81
|
+
// mentah mencapai execute (temuan audit #05: crash/perilaku indefinisi).
|
|
82
|
+
const { validateArgs } = await import("#minicore")
|
|
83
|
+
const parsed = validateArgs(tool.parameters, args ?? {})
|
|
84
|
+
if (!parsed.ok) {
|
|
85
|
+
return {
|
|
86
|
+
content: [{ type: "text", text: `[invalid arguments] ${tool.name}: ${parsed.message}` }],
|
|
87
|
+
isError: true,
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const validArgs = parsed.value as Record<string, unknown>
|
|
91
|
+
// permission check — sandbox tetap aktif walau dipanggil dari luar.
|
|
92
|
+
// SELALU jalan (bahkan allowAll): gerbang jail universal + bash-guard
|
|
93
|
+
// hidup di DALAM check(), sebelum dispatch mode. Melewatkan check() sama
|
|
94
|
+
// sekali (kode lama saat allowAll) berarti TANPA jail — temuan P0 audit #05.
|
|
95
|
+
// allowAll hanya memilih MODE, bukan menonaktifkan pemeriksaan.
|
|
96
|
+
{
|
|
97
|
+
const { createPermissionHandler } = await import("../policy/permission.ts")
|
|
98
|
+
const perms = createPermissionHandler({
|
|
99
|
+
mode: opts.allowAll ? "allow-all" : "auto",
|
|
100
|
+
root: opts.root,
|
|
101
|
+
})
|
|
102
|
+
const toolCall = { id: randomUUID(), name: tool.name, args: validArgs }
|
|
103
|
+
const { createEventBus, createToolRegistry } = await import("#minicore")
|
|
104
|
+
const deps: ExecutorDeps = {
|
|
105
|
+
registry: createToolRegistry([]),
|
|
106
|
+
permissions: perms,
|
|
107
|
+
events: createEventBus(),
|
|
108
|
+
signal,
|
|
109
|
+
state: { history: [], turnCount: 0, stepCount: 0 },
|
|
110
|
+
maxResultTokens: 4096,
|
|
111
|
+
}
|
|
112
|
+
const decision = await perms.check(toolCall, deps)
|
|
113
|
+
if (decision !== "allow") {
|
|
114
|
+
return {
|
|
115
|
+
content: [
|
|
116
|
+
{ type: "text", text: `[denied] ${tool.name} blocked by minicode permission policy` },
|
|
117
|
+
],
|
|
118
|
+
isError: true,
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Journal mutation (kelas mutasi + unknown fail-closed, F-14): intent →
|
|
124
|
+
// terminal. Server mode tak punya turn/session kernel, jadi sesi jurnal
|
|
125
|
+
// tetap "mcp-server".
|
|
126
|
+
const mutating = isMutationTool(tool.name)
|
|
127
|
+
let intent: { id: string; seq: number } | null = null
|
|
128
|
+
if (mutating) {
|
|
129
|
+
intent = await appendMutationIntent({
|
|
130
|
+
session: journal.session,
|
|
131
|
+
tool: tool.name,
|
|
132
|
+
cwd: root,
|
|
133
|
+
paths: verifyPaths(tool.name, validArgs, root),
|
|
134
|
+
argsHash: hashArgs(validArgs),
|
|
135
|
+
// Kunci idempotency sejak intent (audit #08): crash di tengah eksekusi
|
|
136
|
+
// (tanpa terminal) tetap terdeteksi sebagai unknown, bukan fresh.
|
|
137
|
+
...(noteKey ? { note: noteKey } : {}),
|
|
138
|
+
})
|
|
139
|
+
}
|
|
140
|
+
const ctx: ToolContext = {
|
|
141
|
+
signal,
|
|
142
|
+
state: { history: [], turnCount: 0, stepCount: 0 },
|
|
143
|
+
emit: () => {},
|
|
144
|
+
// P0 audit #05: root eksekusi HARUS sama dengan root jail permission.
|
|
145
|
+
// Sebelumnya ctx tanpa cwd → tool jatuh ke process.cwd() sementara jail
|
|
146
|
+
// memakai opts.root — divergensi jail-vs-eksekusi bila --cwd dipakai.
|
|
147
|
+
cwd: root,
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
const out = await tool.execute(validArgs, ctx)
|
|
151
|
+
const text =
|
|
152
|
+
typeof out === "string" ? out : out instanceof Uint8Array ? "(binary)" : JSON.stringify(out)
|
|
153
|
+
if (intent) {
|
|
154
|
+
await appendMutationTerminal(
|
|
155
|
+
journal.session,
|
|
156
|
+
root,
|
|
157
|
+
intent.id,
|
|
158
|
+
intent.seq,
|
|
159
|
+
tool.name,
|
|
160
|
+
"committed",
|
|
161
|
+
{
|
|
162
|
+
note: noteKey,
|
|
163
|
+
},
|
|
164
|
+
undefined,
|
|
165
|
+
{ dedup: true },
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
// capMcpText scrub + cap + tandai dalam satu langkah (tanpa double-scrub).
|
|
169
|
+
return {
|
|
170
|
+
content: [{ type: "text", text: capMcpText(text) }],
|
|
171
|
+
isError: false,
|
|
172
|
+
}
|
|
173
|
+
} catch (e) {
|
|
174
|
+
if (intent) {
|
|
175
|
+
await appendMutationTerminal(
|
|
176
|
+
journal.session,
|
|
177
|
+
root,
|
|
178
|
+
intent.id,
|
|
179
|
+
intent.seq,
|
|
180
|
+
tool.name,
|
|
181
|
+
"failed",
|
|
182
|
+
{
|
|
183
|
+
note: noteKey,
|
|
184
|
+
},
|
|
185
|
+
undefined,
|
|
186
|
+
{ dedup: true },
|
|
187
|
+
)
|
|
188
|
+
}
|
|
189
|
+
throw e
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export async function serveMcp(opts: McpServeOptions = {}): Promise<void> {
|
|
194
|
+
const tools = selectTools(opts)
|
|
195
|
+
const byName = new Map(tools.map((t) => [t.name, t]))
|
|
196
|
+
const shutdown = new AbortController()
|
|
197
|
+
// Root tunggal: jail permission, cwd eksekusi, dan jurnal memakai nilai
|
|
198
|
+
// yang sama (audit #05: divergensi ketiganya = jail bypass).
|
|
199
|
+
const root = opts.root ?? process.cwd()
|
|
200
|
+
const JOURNAL_SESSION = "mcp-server"
|
|
201
|
+
|
|
202
|
+
// todoSession global dipakai tool todo_*; di proses serve khusus, skop ke
|
|
203
|
+
// sesi server agar tak mencemari/membaca state sesi lain (P2 isolation).
|
|
204
|
+
// Default "default" bila serve dipakai sebagai library tanpa setup root.
|
|
205
|
+
const prevTodo = todoSession.id
|
|
206
|
+
const prevTodoCwd = todoSession.cwd
|
|
207
|
+
todoSession.id = "mcp-server"
|
|
208
|
+
todoSession.cwd = root
|
|
209
|
+
|
|
210
|
+
// Idempotency request (audit #05 P0, diperkuat #08 P0): retry client
|
|
211
|
+
// (atau crash-restart) tak boleh mengeksekusi ulang mutasi non-idempoten
|
|
212
|
+
// secara buta.
|
|
213
|
+
// - In-flight (promise map): duplikat konkuren menunggu hasil yang SAMA
|
|
214
|
+
// (satu eksekusi). Dihapus setelah reply.
|
|
215
|
+
// - Completed (cache FIFO 100): replay hasil persis tanpa eksekusi ulang.
|
|
216
|
+
// - Restart/crash (cache hilang): bukti jurnal durable → error eksplisit
|
|
217
|
+
// (BUKAN sukses palsu, BUKAN eksekusi ulang buta). Hasil tak disimpan di
|
|
218
|
+
// jurnal (aturan no-content), jadi retry pasca-restart harus pakai id
|
|
219
|
+
// BARU setelah verifikasi manual.
|
|
220
|
+
// - Kunci bukti = id + hash argumen (audit #08): id sama + argumen SAMA =
|
|
221
|
+
// retry operasi sama (tahan); id sama + argumen BEDA = operasi baru
|
|
222
|
+
// (client reconnect me-reset seq — BOLEH jalan). Tanpa hash, salah satu
|
|
223
|
+
// sisi pasti salah: tahan-semua merusak reconnect sah, jalan-semua
|
|
224
|
+
// menduplikasi retry. Terminal bukti ditandai dedup agar selamat dari
|
|
225
|
+
// sweep finalize (tanpa ini buktinya rutin terhapus dan retry
|
|
226
|
+
// pasca-restart dieksekusi ulang buta — reproducer: note hilang
|
|
227
|
+
// setelah finalize+sweep).
|
|
228
|
+
const inflight = new Map<
|
|
229
|
+
string,
|
|
230
|
+
Promise<{ content: { type: string; text: string }[]; isError: boolean }>
|
|
231
|
+
>()
|
|
232
|
+
const completedCache = new Map<
|
|
233
|
+
string,
|
|
234
|
+
{ content: { type: string; text: string }[]; isError: boolean }
|
|
235
|
+
>()
|
|
236
|
+
const COMPLETED_CACHE_MAX = 100
|
|
237
|
+
const rememberCompleted = (
|
|
238
|
+
key: string,
|
|
239
|
+
result: { content: { type: string; text: string }[]; isError: boolean },
|
|
240
|
+
): void => {
|
|
241
|
+
completedCache.set(key, result)
|
|
242
|
+
if (completedCache.size > COMPLETED_CACHE_MAX) {
|
|
243
|
+
const oldest = completedCache.keys().next()
|
|
244
|
+
if (!oldest.done) completedCache.delete(oldest.value)
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
// Bukti durable mutasi terdahulu untuk (id, argumen) ini: "committed" |
|
|
248
|
+
// "failed" | "pending" (ambigu) | null (tak ada bukti). Tanpa bukti =
|
|
249
|
+
// fresh request. Cocok PERSIS pada note `req:<id>:<argsHash>`; note legacy
|
|
250
|
+
// `req:<id>` (pra-hash) dicocok id-mentah secara konservatif; note ber-hash
|
|
251
|
+
// lain = operasi beda (reconnect sah) → lewati, jangan vonis.
|
|
252
|
+
const journalEvidence = async (
|
|
253
|
+
idKey: string,
|
|
254
|
+
noteKey: string,
|
|
255
|
+
): Promise<"committed" | "failed" | "pending" | null> => {
|
|
256
|
+
try {
|
|
257
|
+
const { loadJournal } = await import("../session/journal.ts")
|
|
258
|
+
const { records } = await loadJournal(JOURNAL_SESSION, root)
|
|
259
|
+
let seen: "committed" | "failed" | "pending" | null = null
|
|
260
|
+
for (const r of records) {
|
|
261
|
+
const n = r.outcome?.note
|
|
262
|
+
if (typeof n !== "string") continue
|
|
263
|
+
if (n !== noteKey && n !== idKey) continue
|
|
264
|
+
if (r.state === "committed" || r.state === "failed") return r.state
|
|
265
|
+
seen = "pending"
|
|
266
|
+
}
|
|
267
|
+
return seen
|
|
268
|
+
} catch {
|
|
269
|
+
return null
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
// Abort per-request (notifications/cancelled): dibedakan dari shutdown
|
|
273
|
+
// global. Tanpa ini request panjang tak bisa dibatalkan individual.
|
|
274
|
+
const reqControllers = new Map<string, AbortController>()
|
|
275
|
+
// Batas konkurensi: tanpa batas, client lokal nakal bisa menumpuk request
|
|
276
|
+
// tak terbatas (tiap handle jalan bebas). 32 longgar untuk pemakaian sah.
|
|
277
|
+
const INFLIGHT_MAX = 32
|
|
278
|
+
const linkedSignal = (reqCtrl: AbortController): AbortSignal =>
|
|
279
|
+
AbortSignal.any([shutdown.signal, reqCtrl.signal])
|
|
280
|
+
|
|
281
|
+
process.stderr.write(
|
|
282
|
+
`[mcp-server] ready — ${tools.length} tools (${opts.allTools ? "all" : "curated"}${opts.allowAll ? ", allow-all" : ""})\n`,
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
const rl = createInterface({ input: process.stdin })
|
|
286
|
+
rl.on("line", (line) => {
|
|
287
|
+
if (!line.trim()) return
|
|
288
|
+
let msg: JsonRpcMsg
|
|
289
|
+
try {
|
|
290
|
+
msg = JSON.parse(line)
|
|
291
|
+
} catch {
|
|
292
|
+
// per JSON-RPC spec: parse error wajib dibalas dengan id:null
|
|
293
|
+
send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } })
|
|
294
|
+
return
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
void handle(msg).catch((e) => {
|
|
298
|
+
if (msg.id !== undefined && msg.id !== null)
|
|
299
|
+
replyError(msg.id, CODE_INTERNAL, String((e as Error).message ?? e))
|
|
300
|
+
})
|
|
301
|
+
})
|
|
302
|
+
|
|
303
|
+
async function handle(msg: JsonRpcMsg): Promise<void> {
|
|
304
|
+
const method = msg.method ?? ""
|
|
305
|
+
// per JSON-RPC: pesan tanpa id = notification → JANGAN dibalas apa pun.
|
|
306
|
+
// Pengecualian: notifications/cancelled MEMBUTUHKAN params.requestId
|
|
307
|
+
// untuk abort per-request — tangani di sini sebelum early-return.
|
|
308
|
+
if (method === "notifications/cancelled") {
|
|
309
|
+
const rid = (msg.params as { requestId?: unknown } | undefined)?.requestId
|
|
310
|
+
if (rid !== undefined && rid !== null) {
|
|
311
|
+
reqControllers.get(`req:${JSON.stringify(rid)}`)?.abort()
|
|
312
|
+
}
|
|
313
|
+
return
|
|
314
|
+
}
|
|
315
|
+
if (msg.id === undefined || msg.id === null) {
|
|
316
|
+
if (!method.startsWith("notifications/") && method !== "initialized") {
|
|
317
|
+
process.stderr.write(`[mcp-server] ignored id-less non-notification: ${method}\n`)
|
|
318
|
+
}
|
|
319
|
+
return
|
|
320
|
+
}
|
|
321
|
+
switch (method) {
|
|
322
|
+
case "server/discover":
|
|
323
|
+
reply(msg.id!, {
|
|
324
|
+
supportedVersions: [PROTOCOL_VERSION],
|
|
325
|
+
capabilities: { tools: {}, resources: {}, prompts: {} },
|
|
326
|
+
serverInfo: SERVER_INFO,
|
|
327
|
+
})
|
|
328
|
+
return
|
|
329
|
+
|
|
330
|
+
case "initialize":
|
|
331
|
+
reply(msg.id!, {
|
|
332
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
333
|
+
capabilities: { tools: {}, resources: {}, prompts: {} },
|
|
334
|
+
serverInfo: SERVER_INFO,
|
|
335
|
+
})
|
|
336
|
+
return
|
|
337
|
+
|
|
338
|
+
case "initialized":
|
|
339
|
+
case "notifications/initialized":
|
|
340
|
+
// Notifikasi murni (tanpa id) sudah kembali di pintu handle; yang
|
|
341
|
+
// sampai sini membawa id → balas kosong agar client tak menggantung.
|
|
342
|
+
reply(msg.id!, {})
|
|
343
|
+
return
|
|
344
|
+
|
|
345
|
+
case "ping":
|
|
346
|
+
reply(msg.id!, {})
|
|
347
|
+
return
|
|
348
|
+
|
|
349
|
+
case "tools/list":
|
|
350
|
+
reply(msg.id!, {
|
|
351
|
+
tools: tools.map((t) => ({
|
|
352
|
+
name: t.name,
|
|
353
|
+
description: t.description,
|
|
354
|
+
inputSchema: t.parameters,
|
|
355
|
+
})),
|
|
356
|
+
})
|
|
357
|
+
return
|
|
358
|
+
|
|
359
|
+
case "resources/list":
|
|
360
|
+
reply(msg.id!, { resources: [] })
|
|
361
|
+
return
|
|
362
|
+
|
|
363
|
+
case "resources/read": {
|
|
364
|
+
replyError(msg.id, CODE_INVALID_PARAMS, "no resources exposed")
|
|
365
|
+
return
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
case "prompts/list":
|
|
369
|
+
reply(msg.id!, { prompts: [] })
|
|
370
|
+
return
|
|
371
|
+
|
|
372
|
+
case "prompts/get": {
|
|
373
|
+
replyError(msg.id, CODE_INVALID_PARAMS, "no prompts exposed")
|
|
374
|
+
return
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
case "tools/call": {
|
|
378
|
+
const params = (msg.params ?? {}) as { name?: string; arguments?: Record<string, unknown> }
|
|
379
|
+
const name = params.name ?? ""
|
|
380
|
+
const tool = byName.get(name)
|
|
381
|
+
if (!tool) {
|
|
382
|
+
replyError(msg.id, CODE_INVALID_PARAMS, `unknown tool: ${name}`)
|
|
383
|
+
return
|
|
384
|
+
}
|
|
385
|
+
// Kunci idempotency = id JSON-RPC apa adanya (string/number beda).
|
|
386
|
+
const idKey = `req:${JSON.stringify(msg.id)}`
|
|
387
|
+
// Kunci bukti durable = id + hash argumen MENTAH (pre-validasi):
|
|
388
|
+
// retry operasi sama cocok persis; id sama + argumen beda (client
|
|
389
|
+
// reconnect me-reset seq) = operasi baru. Hash mentah (bukan hasil
|
|
390
|
+
// validasi) agar raceCheck dan invokeTool memakai nilai identik.
|
|
391
|
+
const noteKey = `${idKey}:${hashArgs(params.arguments ?? {})}`
|
|
392
|
+
// Cek sinkron dulu (fast path); cek ULANG setelah await di bawah
|
|
393
|
+
// karena dua handler konkuren bisa sama-sama melewati titik ini
|
|
394
|
+
// sebelum salah satunya mendaftarkan inflight (TOCTOU → eksekusi
|
|
395
|
+
// ganda — persis yang dicegah; lihat re-check sesudah evidence).
|
|
396
|
+
const raceCheck = async (): Promise<
|
|
397
|
+
| {
|
|
398
|
+
kind: "reply"
|
|
399
|
+
result: { content: { type: string; text: string }[]; isError: boolean }
|
|
400
|
+
}
|
|
401
|
+
| { kind: "replyError"; code: number; message: string }
|
|
402
|
+
| { kind: "proceed" }
|
|
403
|
+
> => {
|
|
404
|
+
const ongoing = inflight.get(idKey)
|
|
405
|
+
if (ongoing) {
|
|
406
|
+
try {
|
|
407
|
+
return { kind: "reply", result: await ongoing }
|
|
408
|
+
} catch (e) {
|
|
409
|
+
return {
|
|
410
|
+
kind: "reply",
|
|
411
|
+
result: {
|
|
412
|
+
content: [
|
|
413
|
+
{ type: "text", text: `[error] ${scrubSecrets((e as Error).message ?? e)}` },
|
|
414
|
+
],
|
|
415
|
+
isError: true,
|
|
416
|
+
},
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
// 2. Hasil selesai (proses ini): replay persis, tanpa eksekusi ulang.
|
|
421
|
+
const cached = completedCache.get(idKey)
|
|
422
|
+
if (cached) return { kind: "reply", result: cached }
|
|
423
|
+
// 3. Bukti durable (restart/crash di tengah): jangan eksekusi ulang
|
|
424
|
+
// buta dan jangan klaim sukses palsu — error eksplisit per status.
|
|
425
|
+
const evidence = await journalEvidence(idKey, noteKey)
|
|
426
|
+
if (evidence === "committed") {
|
|
427
|
+
return {
|
|
428
|
+
kind: "replyError",
|
|
429
|
+
code: CODE_INTERNAL,
|
|
430
|
+
message: `duplicate request id: already executed successfully — result not retained, verify state before retrying with a new id`,
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (evidence === "failed") {
|
|
434
|
+
return {
|
|
435
|
+
kind: "replyError",
|
|
436
|
+
code: CODE_INTERNAL,
|
|
437
|
+
message: `duplicate request id: previous attempt failed — inspect state, then retry with a new id`,
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
if (evidence === "pending") {
|
|
441
|
+
return {
|
|
442
|
+
kind: "replyError",
|
|
443
|
+
code: CODE_INTERNAL,
|
|
444
|
+
message: `duplicate request id: previous attempt status unknown (interrupted) — verify state before retrying with a new id`,
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
// Re-check pasca-await: pemenang balapan sudah mendaftar sementara
|
|
448
|
+
// kita menunggu evidence. Tanpa ini dua duplikat konkuren lolos
|
|
449
|
+
// berdua (reproducer: dua tools/call id sama back-to-back).
|
|
450
|
+
const ongoing2 = inflight.get(idKey)
|
|
451
|
+
if (ongoing2) {
|
|
452
|
+
try {
|
|
453
|
+
return { kind: "reply", result: await ongoing2 }
|
|
454
|
+
} catch (e) {
|
|
455
|
+
return {
|
|
456
|
+
kind: "reply",
|
|
457
|
+
result: {
|
|
458
|
+
content: [
|
|
459
|
+
{ type: "text", text: `[error] ${scrubSecrets((e as Error).message ?? e)}` },
|
|
460
|
+
],
|
|
461
|
+
isError: true,
|
|
462
|
+
},
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
return { kind: "proceed" }
|
|
467
|
+
}
|
|
468
|
+
const gated = await raceCheck()
|
|
469
|
+
if (gated.kind === "reply") {
|
|
470
|
+
reply(msg.id!, gated.result)
|
|
471
|
+
return
|
|
472
|
+
}
|
|
473
|
+
if (gated.kind === "replyError") {
|
|
474
|
+
replyError(msg.id, gated.code, gated.message)
|
|
475
|
+
return
|
|
476
|
+
}
|
|
477
|
+
if (inflight.size >= INFLIGHT_MAX) {
|
|
478
|
+
replyError(msg.id, CODE_INTERNAL, "server busy: too many in-flight requests")
|
|
479
|
+
return
|
|
480
|
+
}
|
|
481
|
+
const reqCtrl = new AbortController()
|
|
482
|
+
const link = () => reqCtrl.abort()
|
|
483
|
+
shutdown.signal.addEventListener("abort", link, { once: true })
|
|
484
|
+
reqControllers.set(idKey, reqCtrl)
|
|
485
|
+
const run = (async () => {
|
|
486
|
+
try {
|
|
487
|
+
return await invokeTool(
|
|
488
|
+
tool,
|
|
489
|
+
params.arguments ?? {},
|
|
490
|
+
opts,
|
|
491
|
+
linkedSignal(reqCtrl),
|
|
492
|
+
{ session: JOURNAL_SESSION, root },
|
|
493
|
+
noteKey,
|
|
494
|
+
)
|
|
495
|
+
} finally {
|
|
496
|
+
shutdown.signal.removeEventListener("abort", link)
|
|
497
|
+
reqControllers.delete(idKey)
|
|
498
|
+
}
|
|
499
|
+
})()
|
|
500
|
+
inflight.set(idKey, run)
|
|
501
|
+
try {
|
|
502
|
+
const result = await run
|
|
503
|
+
rememberCompleted(idKey, result)
|
|
504
|
+
reply(msg.id!, result)
|
|
505
|
+
} catch (e) {
|
|
506
|
+
reply(msg.id!, {
|
|
507
|
+
content: [{ type: "text", text: `[error] ${scrubSecrets((e as Error).message ?? e)}` }],
|
|
508
|
+
isError: true,
|
|
509
|
+
})
|
|
510
|
+
} finally {
|
|
511
|
+
inflight.delete(idKey)
|
|
512
|
+
// Finalize jurnal per panggilan (tak ada turn/persist di mode ini):
|
|
513
|
+
// sweep hanya membuang yang finalized — best-effort, tak blokir reply.
|
|
514
|
+
void finalizeJournal(JOURNAL_SESSION, root).catch(() => {})
|
|
515
|
+
}
|
|
516
|
+
return
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
default:
|
|
520
|
+
if (method.startsWith("notifications/")) return
|
|
521
|
+
replyError(msg.id, CODE_METHOD_NOT_FOUND, `method not found: ${method}`)
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// stdin close → shutdown bersih
|
|
526
|
+
await new Promise<void>((resolve) => {
|
|
527
|
+
rl.on("close", resolve)
|
|
528
|
+
for (const sig of ["SIGINT", "SIGTERM"] as const) {
|
|
529
|
+
process.once(sig, () => {
|
|
530
|
+
shutdown.abort()
|
|
531
|
+
resolve()
|
|
532
|
+
})
|
|
533
|
+
}
|
|
534
|
+
})
|
|
535
|
+
rl.close()
|
|
536
|
+
todoSession.id = prevTodo
|
|
537
|
+
todoSession.cwd = prevTodoCwd
|
|
538
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { type ChildProcess, spawn } from "node:child_process"
|
|
2
|
+
import { createInterface } from "node:readline"
|
|
3
|
+
import { LIMITS } from "../constants.ts"
|
|
4
|
+
import { sanitizeSpawnEnv } from "../policy/scrub.ts"
|
|
5
|
+
|
|
6
|
+
export class McpTransport {
|
|
7
|
+
private proc: ChildProcess | null = null
|
|
8
|
+
private rl: ReturnType<typeof createInterface> | null = null
|
|
9
|
+
private pending = new Map<
|
|
10
|
+
string | number,
|
|
11
|
+
{
|
|
12
|
+
resolve: (v: unknown) => void
|
|
13
|
+
reject: (e: Error) => void
|
|
14
|
+
timer: ReturnType<typeof setTimeout>
|
|
15
|
+
}
|
|
16
|
+
>()
|
|
17
|
+
private seq = 0
|
|
18
|
+
private closed = false
|
|
19
|
+
// abort HANYA saat close() — bukan timeout, agar server tidak mati sendiri
|
|
20
|
+
private killSignal = new AbortController()
|
|
21
|
+
|
|
22
|
+
async connect(command: string, args: string[], env: Record<string, string> = {}): Promise<void> {
|
|
23
|
+
if (this.proc) throw new Error("transport already connected")
|
|
24
|
+
|
|
25
|
+
this.proc = spawn(command, args, {
|
|
26
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
27
|
+
// env kredensial di-strip; env eksplisit config server menang setelahnya
|
|
28
|
+
env: sanitizeSpawnEnv(process.env, env),
|
|
29
|
+
signal: this.killSignal.signal,
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
this.proc.on("error", (err) => this.failAll(err))
|
|
33
|
+
this.proc.on("exit", (code) => {
|
|
34
|
+
if (!this.closed) this.failAll(new Error(`MCP server exited with code ${code}`))
|
|
35
|
+
})
|
|
36
|
+
this.proc.stderr?.on("data", (d: Buffer) =>
|
|
37
|
+
process.stderr.write(`[mcp:${command}] ${d.toString().trim()}\n`),
|
|
38
|
+
)
|
|
39
|
+
// ensure previous rl closed if reconnecting (defensive)
|
|
40
|
+
if (this.rl)
|
|
41
|
+
try {
|
|
42
|
+
this.rl.close()
|
|
43
|
+
} catch {}
|
|
44
|
+
|
|
45
|
+
this.rl = createInterface({ input: this.proc.stdout! })
|
|
46
|
+
this.rl.on("line", (line) => {
|
|
47
|
+
if (!line.trim()) return
|
|
48
|
+
try {
|
|
49
|
+
const msg = JSON.parse(line)
|
|
50
|
+
if (msg.id != null && this.pending.has(msg.id)) {
|
|
51
|
+
const p = this.pending.get(msg.id)!
|
|
52
|
+
clearTimeout(p.timer)
|
|
53
|
+
this.pending.delete(msg.id)
|
|
54
|
+
if (msg.error) p.reject(new Error(msg.error.message || JSON.stringify(msg.error)))
|
|
55
|
+
else p.resolve(msg.result)
|
|
56
|
+
}
|
|
57
|
+
} catch (e) {
|
|
58
|
+
process.stderr.write(`[mcp] ignoring invalid JSON from server: ${(e as Error).message}\n`)
|
|
59
|
+
}
|
|
60
|
+
})
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async request(
|
|
64
|
+
method: string,
|
|
65
|
+
params: Record<string, unknown> = {},
|
|
66
|
+
timeoutMs: number = LIMITS.MCP_REQUEST_TIMEOUT_MS,
|
|
67
|
+
signal?: AbortSignal,
|
|
68
|
+
): Promise<unknown> {
|
|
69
|
+
// Batal sebelum tulis: jangan kirim request ke server yang sudah tak ditunggu.
|
|
70
|
+
signal?.throwIfAborted()
|
|
71
|
+
const id = ++this.seq
|
|
72
|
+
this.write({ jsonrpc: "2.0", id, method, params })
|
|
73
|
+
return new Promise((resolve, reject) => {
|
|
74
|
+
const timer = setTimeout(() => {
|
|
75
|
+
this.pending.delete(id)
|
|
76
|
+
reject(new Error(`MCP request ${method} timed out after ${timeoutMs}ms`))
|
|
77
|
+
}, timeoutMs)
|
|
78
|
+
const entry = { resolve, reject, timer }
|
|
79
|
+
this.pending.set(id, entry)
|
|
80
|
+
// stdio JSON-RPC tak punya pembatalan di-kabel: abort hanya menghentikan
|
|
81
|
+
// PENUNGGUAN di sisi kita (server child tetap hidup sampai close/timeout
|
|
82
|
+
// dan efek yang sudah terjadi di server TIDAK dibatalkan).
|
|
83
|
+
signal?.addEventListener(
|
|
84
|
+
"abort",
|
|
85
|
+
() => {
|
|
86
|
+
if (!this.pending.has(id)) return
|
|
87
|
+
this.pending.delete(id)
|
|
88
|
+
clearTimeout(timer)
|
|
89
|
+
reject(
|
|
90
|
+
signal.reason instanceof Error
|
|
91
|
+
? signal.reason
|
|
92
|
+
: new Error(`MCP request ${method} aborted`),
|
|
93
|
+
)
|
|
94
|
+
},
|
|
95
|
+
{ once: true },
|
|
96
|
+
)
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
notify(method: string, params: Record<string, unknown> = {}) {
|
|
101
|
+
this.write({ jsonrpc: "2.0", method, params })
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async close(): Promise<void> {
|
|
105
|
+
if (this.closed) return
|
|
106
|
+
this.closed = true
|
|
107
|
+
this.failAll(new Error("transport closed"))
|
|
108
|
+
if (this.rl) this.rl.close()
|
|
109
|
+
try {
|
|
110
|
+
this.proc?.stdin?.end()
|
|
111
|
+
} catch {}
|
|
112
|
+
this.killSignal.abort()
|
|
113
|
+
if (this.proc) {
|
|
114
|
+
await new Promise<void>((r) => {
|
|
115
|
+
const p = this.proc!
|
|
116
|
+
const t = setTimeout(() => {
|
|
117
|
+
try {
|
|
118
|
+
p.kill("SIGKILL")
|
|
119
|
+
} catch {}
|
|
120
|
+
r()
|
|
121
|
+
}, 2_000)
|
|
122
|
+
p.once("exit", () => {
|
|
123
|
+
clearTimeout(t)
|
|
124
|
+
r()
|
|
125
|
+
})
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
this.proc = null
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
private write(msg: unknown) {
|
|
132
|
+
if (!this.proc?.stdin) throw new Error("transport not connected")
|
|
133
|
+
let line: string
|
|
134
|
+
try {
|
|
135
|
+
line = `${JSON.stringify(msg)}\n`
|
|
136
|
+
} catch {
|
|
137
|
+
throw new Error("circular JSON in MCP message")
|
|
138
|
+
}
|
|
139
|
+
const ok = this.proc.stdin.write(line)
|
|
140
|
+
if (!ok) this.proc.stdin.once("drain", () => {})
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private failAll(err: Error) {
|
|
144
|
+
for (const p of this.pending.values()) {
|
|
145
|
+
clearTimeout(p.timer)
|
|
146
|
+
p.reject(err)
|
|
147
|
+
}
|
|
148
|
+
this.pending.clear()
|
|
149
|
+
}
|
|
150
|
+
}
|