minicode-ai 0.13.0 → 0.14.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 (83) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -0
  4. package/cli/args.ts +50 -2
  5. package/cli/commands/acp.ts +18 -3
  6. package/cli/commands/daemon.ts +114 -19
  7. package/cli/commands/exec.ts +95 -7
  8. package/cli/commands/mcp.ts +66 -5
  9. package/cli/commands/memory.ts +46 -14
  10. package/cli/commands.ts +5 -0
  11. package/cli/index.ts +30 -5
  12. package/cli/minicode.js +6 -0
  13. package/cli/setup.ts +365 -24
  14. package/cli/tui.ts +72 -27
  15. package/docs/TERMINAL_CONTRACT.md +91 -24
  16. package/docs/agents.md +2 -2
  17. package/docs/cli.md +1 -0
  18. package/docs/environment.md +1 -0
  19. package/docs/memory-sessions.md +5 -0
  20. package/package.json +3 -2
  21. package/src/app/session.ts +153 -35
  22. package/src/app/tool-layer.ts +67 -61
  23. package/src/daemon/approvals.ts +25 -1
  24. package/src/daemon/client.ts +51 -1
  25. package/src/daemon/control.ts +8 -0
  26. package/src/daemon/protocol.ts +47 -1
  27. package/src/daemon/server.ts +45 -9
  28. package/src/daemon/subscription.ts +25 -1
  29. package/src/daemon/telemetry.ts +4 -0
  30. package/src/hooks/run.ts +5 -1
  31. package/src/mcp/client.ts +349 -90
  32. package/src/mcp/http-transport.ts +7 -0
  33. package/src/mcp/transport.ts +5 -0
  34. package/src/memory/files.ts +69 -3
  35. package/src/memory/vector.ts +556 -160
  36. package/src/policy/approval-binding.ts +199 -0
  37. package/src/policy/context.ts +20 -1
  38. package/src/policy/executor.ts +44 -5
  39. package/src/policy/permission.ts +243 -26
  40. package/src/policy/tool-contract.ts +77 -0
  41. package/src/policy/usage.ts +3 -1
  42. package/src/policy/work-mode.ts +49 -1
  43. package/src/presentation/adapter.ts +157 -7
  44. package/src/presentation/events.ts +173 -1
  45. package/src/presentation/model.ts +37 -0
  46. package/src/presentation/projection.ts +107 -18
  47. package/src/presentation/reducer.ts +134 -10
  48. package/src/sandbox/os.ts +18 -1
  49. package/src/session/persistence.ts +153 -11
  50. package/src/task/store.ts +43 -3
  51. package/src/tools/memory.ts +70 -10
  52. package/src/tools/task.ts +7 -1
  53. package/src/tools/todo.ts +14 -4
  54. package/src/ui/approval/prompt.ts +52 -7
  55. package/src/ui/assistant/simple.ts +160 -57
  56. package/src/ui/contract.ts +46 -0
  57. package/src/ui/footer.ts +14 -5
  58. package/src/ui/i18n/en.ts +9 -0
  59. package/src/ui/i18n/id.ts +9 -0
  60. package/src/ui/render/collapse.ts +24 -52
  61. package/src/ui/render/detail.ts +14 -9
  62. package/src/ui/render/errors.ts +8 -0
  63. package/src/ui/render/reasoning.ts +13 -8
  64. package/src/ui/session-state.ts +243 -0
  65. package/src/ui/tui/app.ts +7 -3
  66. package/src/ui/tui/transcript.ts +271 -30
  67. package/vendor/minicore/src/core/budget.ts +25 -25
  68. package/vendor/minicore/src/core/compact.ts +75 -75
  69. package/vendor/minicore/src/core/errors.ts +59 -59
  70. package/vendor/minicore/src/core/events.ts +73 -73
  71. package/vendor/minicore/src/core/executor.ts +139 -139
  72. package/vendor/minicore/src/core/history.ts +31 -31
  73. package/vendor/minicore/src/core/index.ts +41 -41
  74. package/vendor/minicore/src/core/loop.ts +355 -355
  75. package/vendor/minicore/src/core/permission.ts +22 -22
  76. package/vendor/minicore/src/core/provider.ts +39 -39
  77. package/vendor/minicore/src/core/recovery.ts +35 -35
  78. package/vendor/minicore/src/core/session.ts +327 -327
  79. package/vendor/minicore/src/core/snapshot.ts +146 -146
  80. package/vendor/minicore/src/core/tokens.ts +107 -107
  81. package/vendor/minicore/src/core/tool.ts +115 -115
  82. package/vendor/minicore/src/core/types.ts +50 -50
  83. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
package/src/mcp/client.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { createHash } from "node:crypto"
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
3
+ import { dirname, resolve } from "node:path"
2
4
  import type { Tool, ToolContext } from "#minicore"
3
5
  import { LIMITS } from "../constants.ts"
4
6
  import { scrubSecrets } from "../policy/scrub.ts"
@@ -49,49 +51,168 @@ function sortObjectKeys(obj: Record<string, unknown>): Record<string, unknown> {
49
51
  return out
50
52
  }
51
53
 
54
+ /** P2.3: sleep yang dapat dibatalkan oleh signal sesi/koneksi. */
55
+ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
56
+ return new Promise((resolve, reject) => {
57
+ if (signal?.aborted) {
58
+ reject(new Error("aborted"))
59
+ return
60
+ }
61
+ const timer = setTimeout(() => {
62
+ signal?.removeEventListener("abort", onAbort)
63
+ resolve()
64
+ }, ms)
65
+ const onAbort = () => {
66
+ clearTimeout(timer)
67
+ reject(new Error("aborted"))
68
+ }
69
+ signal?.addEventListener("abort", onAbort, { once: true })
70
+ })
71
+ }
72
+
73
+ /**
74
+ * P2.3: klasifikasi recoverable. Auth/schema/protocol TIDAK boleh diulang tanpa
75
+ * batas; kegagalan transport/process boleh. Abort bukan recoverable (berhenti).
76
+ */
77
+ function isRecoverableMcpError(e: Error): boolean {
78
+ const m = `${e.name} ${e.message}`.toLowerCase()
79
+ if (/abort/.test(m)) return false
80
+ if (/schema_drift|mcp_schema_drift/.test(m)) return false
81
+ if (/401|403|unauthor|forbidden|invalid.?token|auth/.test(m)) return false
82
+ if (/protocol|invalid json|invalid params|method not found/.test(m)) return false
83
+ return /exited|econnrefused|econnreset|epipe|closed|transport|fetch failed|network|socket|timeout/.test(
84
+ m,
85
+ )
86
+ }
87
+
52
88
  export class McpSchemaPinRegistry {
53
89
  private readonly pins = new Map<string, string>()
90
+ /**
91
+ * P2.3: pin HARUS bertahan lintas restart. Tanpa persistensi, proses baru
92
+ * mem-pin ulang skema yang sudah berubah dan drift diterima diam-diam.
93
+ * Path null = mode in-memory (unit test / embedding tanpa workspace).
94
+ */
95
+ private path: string | null = null
96
+ private loaded = false
97
+
98
+ /** Arahkan registry ke file pin workspace dan muat isinya sekali. */
99
+ configure(path: string): void {
100
+ if (this.path === path && this.loaded) return
101
+ this.path = path
102
+ this.loaded = false
103
+ this.load()
104
+ }
105
+
106
+ private load(): void {
107
+ if (this.loaded) return
108
+ this.loaded = true
109
+ if (!this.path || !existsSync(this.path)) return
110
+ try {
111
+ const raw = JSON.parse(readFileSync(this.path, "utf8")) as Record<string, unknown>
112
+ for (const [key, value] of Object.entries(raw)) {
113
+ if (typeof value === "string" && /^[0-9a-f]{64}$/.test(value)) this.pins.set(key, value)
114
+ }
115
+ } catch {
116
+ // File rusak = fail-closed: jangan menebak pin dari data parsial.
117
+ }
118
+ }
119
+
120
+ private persist(): void {
121
+ if (!this.path) return
122
+ try {
123
+ mkdirSync(dirname(this.path), { recursive: true })
124
+ const tmp = `${this.path}.tmp`
125
+ const sorted = [...this.pins.entries()].sort(([a], [b]) => a.localeCompare(b))
126
+ writeFileSync(tmp, `${JSON.stringify(Object.fromEntries(sorted), null, 2)}\n`, "utf8")
127
+ renameSync(tmp, this.path)
128
+ } catch {
129
+ // Gagal menulis pin tidak boleh menjatuhkan koneksi; verify tetap
130
+ // memakai pin in-memory untuk proses ini.
131
+ }
132
+ }
133
+
134
+ list(): { serverId: string; toolName: string; hash: string }[] {
135
+ this.load()
136
+ return [...this.pins.entries()]
137
+ .map(([key, hash]) => {
138
+ const i = key.indexOf(":")
139
+ return { serverId: key.slice(0, i), toolName: key.slice(i + 1), hash }
140
+ })
141
+ .sort((a, b) => `${a.serverId}.${a.toolName}`.localeCompare(`${b.serverId}.${b.toolName}`))
142
+ }
54
143
 
55
144
  /** Pin hash skema. Overwrite bila sudah ada? Tidak — pin pertama adalah
56
145
  * otoritas; refresh berikutnya harus lewat `approve`. */
57
146
  pin(serverId: string, toolName: string, hash: string): void {
147
+ this.load()
58
148
  const key = `${serverId}:${toolName}`
59
- if (!this.pins.has(key)) this.pins.set(key, hash)
149
+ if (!this.pins.has(key)) {
150
+ this.pins.set(key, hash)
151
+ this.persist()
152
+ }
60
153
  }
61
154
 
62
155
  /** Approve eksplisit: ganti pin dengan hash baru (persetujuan pengguna). */
63
156
  approveMcpSchemaUpdate(serverId: string, toolName: string, newHash: string): void {
157
+ this.load()
64
158
  this.pins.set(`${serverId}:${toolName}`, newHash)
159
+ this.persist()
65
160
  }
66
161
 
67
162
  /** Verify: hash sama dengan pin → ok; belum ada pin → pin sekarang; beda → drift. */
68
163
  verify(serverId: string, toolName: string, hash: string): "ok" | "pinned" | "drift" {
164
+ this.load()
69
165
  const key = `${serverId}:${toolName}`
70
166
  const pinned = this.pins.get(key)
71
167
  if (pinned === undefined) {
72
168
  this.pins.set(key, hash)
169
+ this.persist()
73
170
  return "pinned"
74
171
  }
75
172
  return pinned === hash ? "ok" : "drift"
76
173
  }
77
174
 
78
175
  getPin(serverId: string, toolName: string): string | undefined {
176
+ this.load()
79
177
  return this.pins.get(`${serverId}:${toolName}`)
80
178
  }
81
179
 
82
- /** Reset seluruh pin (uji hermetik). */
180
+ /** Reset seluruh pin (uji hermetik); file hanya ditulis bila path terpasang. */
83
181
  reset(): void {
84
182
  this.pins.clear()
183
+ this.loaded = true
184
+ this.persist()
85
185
  }
86
186
  }
87
187
 
88
188
  export const mcpSchemaPinRegistry = new McpSchemaPinRegistry()
89
189
 
90
- export function mcpSchemaDriftError(serverId: string, toolName: string): Error {
190
+ /** Path pin per-workspace; sengaja lokal agar proyek berbeda tak saling percaya. */
191
+ export function mcpSchemaPinPath(cwd?: string): string {
192
+ return resolve(cwd ?? process.cwd(), ".minicode", "mcp-schema-pins.json")
193
+ }
194
+
195
+ /** Muat/arahkan pin ke workspace sebelum connect; idempoten. */
196
+ export function configureMcpSchemaPins(cwd?: string): void {
197
+ mcpSchemaPinRegistry.configure(mcpSchemaPinPath(cwd))
198
+ }
199
+
200
+ export function mcpSchemaDriftError(
201
+ serverId: string,
202
+ toolName: string,
203
+ pinned?: string,
204
+ current?: string,
205
+ ): Error {
206
+ const detail =
207
+ pinned && current
208
+ ? ` pinned=${pinned.slice(0, 12)} current=${current.slice(0, 12)} — run: minicode mcp approve ${serverId}.${toolName} ${current}`
209
+ : ` — run: minicode mcp approve ${serverId}.${toolName} <current-hash>`
91
210
  const e = new Error(
92
- `MCP_SCHEMA_DRIFT_DETECTED: tool "${serverId}.${toolName}" schema changed since pin — approve via approveMcpSchemaUpdate()`,
93
- ) as Error & { code: string }
211
+ `MCP_SCHEMA_DRIFT_DETECTED: tool "${serverId}.${toolName}" schema changed since pin${detail}`,
212
+ ) as Error & { code: string; serverId: string; toolName: string }
94
213
  e.code = "MCP_SCHEMA_DRIFT_DETECTED"
214
+ e.serverId = serverId
215
+ e.toolName = toolName
95
216
  return e
96
217
  }
97
218
 
@@ -144,36 +265,94 @@ export interface McpPromptDef {
144
265
  }
145
266
 
146
267
  const activeConnections = new Map<string, McpConnection>()
268
+ /**
269
+ * P2.3: reference count per server. `closeAll()` dipanggil oleh setiap sesi;
270
+ * tanpa refcount, menutup sesi A mematikan MCP sesi B. Server ditutup hanya
271
+ * saat ref mencapai 0 (atau force saat teardown uji).
272
+ */
273
+ const connectionRefs = new Map<string, number>()
147
274
 
148
275
  class McpConnection {
149
276
  /** Transport konkret; tipe union agar `connect` yang berbeda tetap tersalur. */
150
- private readonly http: McpHttpTransport | null
151
- private readonly stdio: McpTransport | null
277
+ private http: McpHttpTransport | null = null
278
+ private stdio: McpTransport | null = null
152
279
  transport: McpTransportLike
153
280
  tools: McpToolDef[] = []
154
281
  resources: McpResourceDef[] = []
155
282
  prompts: McpPromptDef[] = []
156
283
  ready = false
284
+ /** P2.3: reconnect single-flight + ownership. */
285
+ private reconnectInFlight: Promise<void> | null = null
286
+ private closedByOwner = false
157
287
 
158
288
  constructor(public config: McpServerConfig) {
159
289
  // Transport dipilih dari bentuk config: `url` → HTTP, else stdio.
160
- if (config.url) {
290
+ this.transport = this.buildTransport()
291
+ }
292
+
293
+ private buildTransport(): McpTransportLike {
294
+ if (this.config.url) {
161
295
  this.http = new McpHttpTransport({
162
- url: config.url,
163
- headers: config.headers,
164
- allowPrivateHost: config.allowPrivateHost,
296
+ url: this.config.url,
297
+ headers: this.config.headers,
298
+ allowPrivateHost: this.config.allowPrivateHost,
165
299
  })
166
300
  this.stdio = null
167
- this.transport = this.http
168
- } else {
169
- this.stdio = new McpTransport()
170
- this.http = null
171
- this.transport = this.stdio
301
+ return this.http
172
302
  }
303
+ this.stdio = new McpTransport()
304
+ this.http = null
305
+ return this.stdio
173
306
  }
174
307
 
175
308
  get kind(): "http" | "stdio" {
176
- return this.http ? "http" : "stdio"
309
+ return this.config.url ? "http" : "stdio"
310
+ }
311
+
312
+ /** P2.3: siap dipakai = transport hidup DAN discovery selesai. */
313
+ isAlive(): boolean {
314
+ return !this.closedByOwner && this.ready && !this.transport.isClosed
315
+ }
316
+
317
+ /**
318
+ * Reconnect bounded: hanya untuk kegagalan transport yang recoverable.
319
+ * Single-flight (satu loop per koneksi), abortable, backoff eksponensial +
320
+ * jitter. Setelah connect, discovery dijalankan ulang; pin skema diverifikasi
321
+ * ulang oleh wrapper sebelum tool benar-benar dipanggil (fail-closed).
322
+ */
323
+ async reconnect(signal?: AbortSignal, maxAttempts = 3): Promise<void> {
324
+ if (this.closedByOwner) throw new Error(`MCP server ${this.config.id} is closed`)
325
+ if (this.reconnectInFlight) return this.reconnectInFlight
326
+ const run = (async () => {
327
+ let lastError: Error | null = null
328
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
329
+ signal?.throwIfAborted()
330
+ if (attempt > 0) {
331
+ const backoff = Math.min(2_000, 250 * 2 ** (attempt - 1))
332
+ const jitter = Math.floor(Math.random() * Math.max(1, Math.floor(backoff / 4)))
333
+ await abortableSleep(backoff + jitter, signal)
334
+ }
335
+ try {
336
+ await this.transport.close().catch(() => {})
337
+ this.ready = false
338
+ this.transport = this.buildTransport()
339
+ await this.connect()
340
+ return
341
+ } catch (e) {
342
+ lastError = e as Error
343
+ if (!isRecoverableMcpError(lastError)) throw lastError
344
+ }
345
+ }
346
+ throw new Error(
347
+ `MCP reconnect failed for ${this.config.id} after ${maxAttempts} attempts: ${lastError?.message ?? "unknown"}`,
348
+ )
349
+ })()
350
+ this.reconnectInFlight = run
351
+ try {
352
+ await run
353
+ } finally {
354
+ this.reconnectInFlight = null
355
+ }
177
356
  }
178
357
 
179
358
  async connect(): Promise<void> {
@@ -225,8 +404,9 @@ class McpConnection {
225
404
  }
226
405
  if (!handshakeOk) throw new Error("handshake failed")
227
406
 
228
- const result = (await this.transport.request("tools/list", {})) as Record<string, unknown>
229
- if (result && Array.isArray(result.tools)) this.tools = result.tools as McpToolDef[]
407
+ // P2.3: hormati `nextCursor`. Mengabaikannya membuat server >1 halaman
408
+ // tampil sebagai daftar parsial yang disangka lengkap.
409
+ this.tools = await this.listAll<McpToolDef>("tools/list", "tools")
230
410
 
231
411
  // Resources & prompts bersifat OPSIONAL di spec: banyak server tidak
232
412
  // mengimplementasikannya dan membalas "method not found". Kegagalan di sini
@@ -237,14 +417,36 @@ class McpConnection {
237
417
  this.ready = true
238
418
  }
239
419
 
420
+ /** Baca seluruh halaman `method`; batas 100 halaman mencegah loop server jahat. */
421
+ private async listAll<T>(method: string, key: string): Promise<T[]> {
422
+ const out: T[] = []
423
+ let cursor: string | undefined
424
+ for (let page = 0; page < 100; page++) {
425
+ const res = (await this.transport.request(
426
+ method,
427
+ cursor ? { cursor } : {},
428
+ LIMITS.MCP_HANDSHAKE_TIMEOUT_MS,
429
+ )) as Record<string, unknown> | undefined
430
+ const arr = res?.[key]
431
+ if (Array.isArray(arr)) out.push(...(arr as T[]))
432
+ const next = res?.nextCursor
433
+ if (typeof next !== "string" || next.length === 0) return out
434
+ cursor = next
435
+ }
436
+ throw new Error(`MCP_PAGINATION_LIMIT: ${method} exceeded 100 pages`)
437
+ }
438
+
240
439
  private async listSafely<T>(method: string, key: string): Promise<T[]> {
241
440
  try {
242
- const res = (await this.transport.request(method, {}, LIMITS.MCP_HANDSHAKE_TIMEOUT_MS)) as
243
- | Record<string, unknown>
244
- | undefined
245
- const arr = res?.[key]
246
- return Array.isArray(arr) ? (arr as T[]) : []
247
- } catch {
441
+ return await this.listAll<T>(method, key)
442
+ } catch (e) {
443
+ // "method not found" adalah normal untuk resources/prompts. Batas
444
+ // pagination BUKAN normal: operator harus tahu daftar tidak lengkap.
445
+ if ((e as Error).message.includes("MCP_PAGINATION_LIMIT")) {
446
+ process.stderr.write(
447
+ `[mcp] ${method}: ${(e as Error).message}; list treated as unsupported\n`,
448
+ )
449
+ }
248
450
  return []
249
451
  }
250
452
  }
@@ -332,53 +534,76 @@ class McpConnection {
332
534
  }
333
535
 
334
536
  wrapTools(serverId: string): Tool[] {
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
- })
537
+ return this.tools
538
+ .map((t): Tool | null => {
539
+ // F8.2: pin/verify skema pada setiap discovery. `verify` mem-pin bila
540
+ // pertama kali, dan menolak SELURUH tool server bila ada drift — server
541
+ // yang mengubah skema tanpa persetujuan dianggap tidak tepercaya hingga
542
+ // `approveMcpSchemaUpdate` eksplisit.
543
+ const hash = computeMcpToolSchemaHash(t)
544
+ const v = mcpSchemaPinRegistry.verify(serverId, t.name, hash)
545
+ if (v === "drift") {
546
+ // Fail-closed: tool drift TIDAK diekspos. Sebelumnya tool tetap masuk
547
+ // daftar (baru ditolak saat execute) — model melihat tool yang pasti
548
+ // gagal. Approve eksplisit lewat CLI `mcp approve`.
549
+ process.stderr.write(
550
+ `[mcp] ${serverId}.${t.name} schema drift detected — tool disabled; ${mcpSchemaDriftError(serverId, t.name, mcpSchemaPinRegistry.getPin(serverId, t.name), hash).message}\n`,
551
+ )
552
+ return null
553
+ }
554
+ return {
555
+ name: `${serverId}.${t.name}`,
556
+ description: t.description ?? `MCP tool from ${serverId}`,
557
+ parameters: (t.inputSchema ?? {
558
+ type: "object",
559
+ properties: {},
560
+ additionalProperties: true,
561
+ }) as Tool["parameters"],
562
+ async execute(input: Record<string, unknown>, _ctx: ToolContext): Promise<string> {
563
+ // P2.3: pastikan koneksi hidup; reconnect bounded bila transport
564
+ // mati. Discovery dijalankan ulang, jadi verifikasi memakai definisi
565
+ // tool SAAT INI (bukan `t` hasil discovery lama).
566
+ const conn = await ensureConnection(serverId, _ctx.signal)
567
+ const current = conn.tools.find((x) => x.name === t.name)
568
+ if (!current) throw new Error(`MCP tool ${serverId}.${t.name} missing after reconnect`)
569
+ const hashAtCall = computeMcpToolSchemaHash(current)
570
+ const vAtCall = mcpSchemaPinRegistry.verify(serverId, t.name, hashAtCall)
571
+ if (vAtCall === "drift")
572
+ throw mcpSchemaDriftError(
573
+ serverId,
574
+ t.name,
575
+ mcpSchemaPinRegistry.getPin(serverId, t.name),
576
+ hashAtCall,
577
+ )
578
+ _ctx.signal.throwIfAborted()
579
+ const result = await conn.callTool(t.name, input ?? {}, _ctx.signal)
580
+ const content = extractMcpText(result)
581
+ return capMcpText(content)
582
+ },
583
+ }
584
+ })
585
+ .filter((t): t is Tool => t !== null)
375
586
  }
376
587
 
377
588
  async close(): Promise<void> {
589
+ this.closedByOwner = true
590
+ this.ready = false
378
591
  await this.transport.close()
379
592
  }
380
593
  }
381
594
 
595
+ /**
596
+ * P2.3: ambil koneksi yang SIAP. Bila transport mati, satu reconnect bounded
597
+ * (single-flight) dijalankan; kegagalan non-recoverable dilempar apa adanya.
598
+ */
599
+ async function ensureConnection(serverId: string, signal?: AbortSignal): Promise<McpConnection> {
600
+ const conn = activeConnections.get(serverId)
601
+ if (!conn) throw new Error(`MCP server ${serverId} not connected`)
602
+ if (conn.isAlive()) return conn
603
+ await conn.reconnect(signal)
604
+ return conn
605
+ }
606
+
382
607
  /** Normalisasi konten tool MCP (string | blok {text} campuran) → teks. */
383
608
  export function extractMcpText(result: unknown): string {
384
609
  if (result == null) return ""
@@ -407,16 +632,27 @@ export function capMcpText(content: string): string {
407
632
  : clean
408
633
  }
409
634
 
410
- export async function connectAll(configs: McpServerConfig[]): Promise<Tool[]> {
635
+ export async function connectAll(configs: McpServerConfig[], cwd?: string): Promise<Tool[]> {
636
+ // Pin persisten per workspace: server yang skemanya berubah setelah restart
637
+ // harus terdeteksi, bukan dipin ulang diam-diam.
638
+ configureMcpSchemaPins(cwd)
411
639
  // Paralel: server independen — sequential membuat startup membayar jumlah
412
640
  // timeout handshake (3s/server). Urutan pesan stderr dipertahankan sesuai
413
641
  // config agar log deterministik.
414
642
  const settled = await Promise.allSettled(
415
643
  configs.map(async (cfg) => {
416
- if (activeConnections.has(cfg.id)) return { cfg, conn: null as McpConnection | null }
644
+ const existing = activeConnections.get(cfg.id)
645
+ // P2.3: hanya reuse koneksi yang benar-benar SIAP; koneksi mati diganti
646
+ // agar `connected` tidak pernah berarti "socket ada tapi discovery gagal".
647
+ if (existing?.isAlive()) return { cfg, conn: existing, reused: true }
648
+ if (existing) {
649
+ activeConnections.delete(cfg.id)
650
+ connectionRefs.delete(cfg.id)
651
+ await existing.close().catch(() => {})
652
+ }
417
653
  const conn = new McpConnection(cfg)
418
654
  await conn.connect()
419
- return { cfg, conn }
655
+ return { cfg, conn, reused: false }
420
656
  }),
421
657
  )
422
658
  const allTools: Tool[] = []
@@ -427,25 +663,24 @@ export async function connectAll(configs: McpServerConfig[]): Promise<Tool[]> {
427
663
  process.stderr.write(`[mcp] ${cfg.id} failed: ${(s.reason as Error)?.message ?? s.reason}\n`)
428
664
  continue
429
665
  }
430
- const { cfg, conn } = s.value
431
- if (!conn) {
432
- process.stderr.write(`[mcp] ${cfg.id} already connected\n`)
433
- continue
434
- }
435
- {
436
- const tools = conn.wrapTools(cfg.id)
437
- allTools.push(...tools)
438
- activeConnections.set(cfg.id, conn)
439
- const extra = [
440
- conn.resources.length ? `${conn.resources.length} resources` : "",
441
- conn.prompts.length ? `${conn.prompts.length} prompts` : "",
442
- ]
443
- .filter(Boolean)
444
- .join(", ")
445
- process.stderr.write(
446
- `[mcp] ${cfg.id} connected via ${conn.kind} (${tools.length} tools${extra ? `, ${extra}` : ""})\n`,
447
- )
448
- }
666
+ const { cfg, conn, reused } = s.value
667
+ // P2.3: sesi kedua HARUS mendapat tool dari koneksi yang sudah aktif,
668
+ // bukan daftar kosong. Refcount mencegah closeAll lintas-sesi.
669
+ const tools = conn.wrapTools(cfg.id)
670
+ allTools.push(...tools)
671
+ if (!reused) activeConnections.set(cfg.id, conn)
672
+ connectionRefs.set(cfg.id, (connectionRefs.get(cfg.id) ?? 0) + 1)
673
+ const extra = [
674
+ conn.resources.length ? `${conn.resources.length} resources` : "",
675
+ conn.prompts.length ? `${conn.prompts.length} prompts` : "",
676
+ ]
677
+ .filter(Boolean)
678
+ .join(", ")
679
+ process.stderr.write(
680
+ reused
681
+ ? `[mcp] ${cfg.id} reused existing connection (${tools.length} tools${extra ? `, ${extra}` : ""})\n`
682
+ : `[mcp] ${cfg.id} connected via ${conn.kind} (${tools.length} tools${extra ? `, ${extra}` : ""})\n`,
683
+ )
449
684
  }
450
685
 
451
686
  return allTools
@@ -508,15 +743,39 @@ export function mcpInventory(): {
508
743
  }))
509
744
  }
510
745
 
511
- export async function closeAll(): Promise<void> {
512
- for (const [id, conn] of activeConnections) {
746
+ export async function closeAll(opts: { force?: boolean } = {}): Promise<void> {
747
+ for (const [id, conn] of [...activeConnections]) {
748
+ if (!opts.force) {
749
+ const refs = (connectionRefs.get(id) ?? 1) - 1
750
+ if (refs > 0) {
751
+ connectionRefs.set(id, refs)
752
+ continue
753
+ }
754
+ }
755
+ connectionRefs.delete(id)
756
+ activeConnections.delete(id)
513
757
  try {
514
758
  await conn.close()
515
759
  } catch {}
516
- activeConnections.delete(id)
517
760
  }
518
761
  }
519
762
 
520
763
  export function getMcpServerIds(): string[] {
521
764
  return [...activeConnections.keys()]
522
765
  }
766
+
767
+ /** P2.3: status hidup koneksi (dipakai operator/observability + test). */
768
+ export function mcpConnectionAlive(serverId: string): boolean {
769
+ return activeConnections.get(serverId)?.isAlive() ?? false
770
+ }
771
+
772
+ /**
773
+ * P2.3 seam: matikan transport TANPA menandai koneksi "closed by owner",
774
+ * mensimulasikan server mati/putus. Koneksi tetap terdaftar sehingga pemanggilan
775
+ * berikutnya menempuh jalur reconnect (bukan membuat koneksi kedua).
776
+ */
777
+ export async function simulateMcpTransportFailure(serverId: string): Promise<void> {
778
+ const conn = activeConnections.get(serverId)
779
+ if (!conn) return
780
+ await conn.transport.close().catch(() => {})
781
+ }
@@ -35,6 +35,8 @@ export interface McpTransportLike {
35
35
  ): Promise<unknown>
36
36
  notify(method: string, params?: Record<string, unknown>): void
37
37
  close(): Promise<void>
38
+ /** P2.3: liveness untuk reconnect policy. */
39
+ readonly isClosed: boolean
38
40
  }
39
41
 
40
42
  export interface HttpTransportOptions {
@@ -55,6 +57,11 @@ export class McpHttpTransport implements McpTransportLike {
55
57
  private seq = 0
56
58
  private sessionId: string | null = null
57
59
  private closed = false
60
+
61
+ /** P2.3: liveness untuk reconnect policy. */
62
+ get isClosed(): boolean {
63
+ return this.closed
64
+ }
58
65
  /**
59
66
  * Set bila host TERBUKTI privat (audit F7): egress fire-and-forget
60
67
  * (notify/close) mengikuti keputusan ini supaya tak ada jalur yang
@@ -21,6 +21,11 @@ export class McpTransport {
21
21
  // abort HANYA saat close() — bukan timeout, agar server tidak mati sendiri
22
22
  private killSignal = new AbortController()
23
23
 
24
+ /** P2.3: liveness untuk reconnect policy (bukan sekadar proke ada). */
25
+ get isClosed(): boolean {
26
+ return this.closed || this.proc === null || this.proc.exitCode !== null
27
+ }
28
+
24
29
  async connect(command: string, args: string[], env: Record<string, string> = {}): Promise<void> {
25
30
  if (this.proc) throw new Error("transport already connected")
26
31