minicode-ai 0.28.0 → 0.30.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.
@@ -180,6 +180,14 @@ export function createRecoveryLedger(now: () => number = Date.now): RecoveryLedg
180
180
  export const cappedRecovery = {
181
181
  onError(error: ProviderError, attempt: number): RecoveryAction {
182
182
  const category = error.category
183
+ // 402 / kuota habis tidak akan sembuh dengan retry — fail-fast.
184
+ if (
185
+ category === "unknown" &&
186
+ (/\b402\b/.test(error.message) ||
187
+ /quota_exceeded|insufficient_quota|exceeded its quota/i.test(error.message))
188
+ ) {
189
+ return { type: "throw" }
190
+ }
183
191
  const ra = error.retryAfterMs
184
192
  const saneRetryAfter =
185
193
  ra != null && Number.isFinite(ra) && ra >= 0
@@ -401,6 +409,9 @@ export async function createMinicodeSession(
401
409
  * ini perilaku identik seperti sebelumnya.
402
410
  */
403
411
  beforeToolEffect?: (call: { id: string; name: string; args: unknown }) => Promise<void>
412
+ /** Tool tak-tersedia yang skemanya disembunyikan pada request wire LLM
413
+ * (tidak mengubah registry `tools`/permission kanonik). */
414
+ hiddenWireTools?: ReadonlySet<string>
404
415
  },
405
416
  ): Promise<Session> {
406
417
  // Normalisasi root sekali di composition agar ToolContext selalu memiliki path tepercaya.
@@ -450,6 +461,7 @@ export async function createMinicodeSession(
450
461
  noProgress,
451
462
  onNoProgress,
452
463
  approvalBindings: _approvalBindings,
464
+ hiddenWireTools,
453
465
  ...rest
454
466
  } = opts
455
467
  if (!provider) throw new Error("createMinicodeSession: provider is required")
@@ -848,7 +860,11 @@ export async function createMinicodeSession(
848
860
  let calibration = calibrationFor(estimatorModel)
849
861
  let estimator = (text: string) => preciseEstimator(estimatorModel, text)
850
862
  let admittedFactor = calibration.snapshot().factor
851
- const tools = req.tools ?? []
863
+ const rawTools = req.tools ?? []
864
+ const tools =
865
+ hiddenWireTools && hiddenWireTools.size > 0
866
+ ? rawTools.filter((t) => !hiddenWireTools.has(t.name))
867
+ : rawTools
852
868
  const localInputTokens =
853
869
  estimateMessages(req.messages, minicodeEstimator) +
854
870
  estimateSystem(system, minicodeEstimator) +
@@ -926,7 +942,14 @@ export async function createMinicodeSession(
926
942
  throw error
927
943
  }
928
944
 
929
- for await (const event of provider.stream({ ...req, system }, requestController.signal)) {
945
+ for await (const event of provider.stream(
946
+ {
947
+ ...req,
948
+ system,
949
+ ...(hiddenWireTools && hiddenWireTools.size > 0 ? { tools } : {}),
950
+ },
951
+ requestController.signal,
952
+ )) {
930
953
  if (event.type === "extension" && event.kind === "effective-model") {
931
954
  const effective = event.data as { effective?: unknown; provider?: unknown } | undefined
932
955
  if (
@@ -18,6 +18,33 @@ const errMsg = (e: unknown) => (e instanceof Error ? e.message : String(e))
18
18
 
19
19
  export type ToolScope = "full" | "explore"
20
20
 
21
+ const MCP_WIRE_TOOLS = ["mcp_list", "mcp_call", "mcp_read", "mcp_prompt"] as const
22
+ const LSP_WIRE_TOOLS = [
23
+ "lsp_diagnostics",
24
+ "lsp_definition",
25
+ "lsp_references",
26
+ "lsp_hover",
27
+ "lsp_symbols",
28
+ "lsp_workspace_symbols",
29
+ ] as const
30
+
31
+ /**
32
+ * Daftar tool yang skemanya aman disembunyikan dari wire API ketika kapabilitas
33
+ * runtime-nya tidak aktif (MCP/LSP kosong, sandbox none, atau non-interaktif),
34
+ * agar token prompt awal hemat tanpa mengubah registry izin/WorkMode kanonik.
35
+ */
36
+ export function computeUnavailableWireTools(
37
+ cfg: Pick<MinicodeConfig, "mcpServers" | "lspServers">,
38
+ opts: { sandboxMode?: string; interactiveAsk?: boolean } = {},
39
+ ): Set<string> {
40
+ const hidden = new Set<string>()
41
+ if (!cfg.mcpServers?.length) for (const n of MCP_WIRE_TOOLS) hidden.add(n)
42
+ if (!cfg.lspServers?.length) for (const n of LSP_WIRE_TOOLS) hidden.add(n)
43
+ if (!opts.sandboxMode || opts.sandboxMode === "none") hidden.add("code_run")
44
+ if (opts.interactiveAsk === false) hidden.add("ask_user")
45
+ return hidden
46
+ }
47
+
21
48
  // WorkMode ceiling (DISCUSS menyatukan diskusi + perencanaan; EXECUTE = BUILD).
22
49
  // Invariant INV-WM1 & #7: WorkMode TIDAK PERNAH memperluas akses; `visible`
23
50
  // diselaraskan penuh dengan `callable` di handler:
@@ -2,6 +2,34 @@ import { randomUUID } from "node:crypto"
2
2
  import { chmod, type FileHandle, mkdir, open, rename, unlink } from "node:fs/promises"
3
3
  import { dirname } from "node:path"
4
4
 
5
+ /**
6
+ * Rename atomic dengan backoff EPERM/EBUSY/EACCES sesaat (lock AV/replace window Windows).
7
+ */
8
+ export async function renameWithRetry(
9
+ from: string,
10
+ to: string,
11
+ opts: { maxRetries?: number; renameFn?: (src: string, dst: string) => Promise<void> } = {},
12
+ ): Promise<void> {
13
+ const maxRetries = opts.maxRetries ?? 8
14
+ const doRename = opts.renameFn ?? rename
15
+ let lastErr: unknown
16
+ for (let r = 0; r < maxRetries; r++) {
17
+ try {
18
+ await doRename(from, to)
19
+ return
20
+ } catch (e) {
21
+ const code = (e as NodeJS.ErrnoException).code
22
+ if (code === "EPERM" || code === "EBUSY" || code === "EACCES") {
23
+ lastErr = e
24
+ await new Promise((res) => setTimeout(res, Math.min(10 * 2 ** r, 100)))
25
+ } else {
26
+ throw e
27
+ }
28
+ }
29
+ }
30
+ if (lastErr) throw lastErr
31
+ }
32
+
5
33
  /**
6
34
  * Tulis file secara atomic + tahan hijack:
7
35
  * - nama tmp memakai randomUUID → tidak dapat diprediksi attacker
@@ -11,14 +39,6 @@ import { dirname } from "node:path"
11
39
  * MOVEFILE_REPLACE_EXISTING sehingga menimpa target lama.
12
40
  */
13
41
  export async function atomicWriteText(path: string, data: string): Promise<void> {
14
- // Direktori induk bisa gagal dibuat: path-nya sudah dipakai FILE biasa,
15
- // salah satu komponennya bukan direktori, atau induknya read-only. Error
16
- // itu adalah AKAR MASALAH. Dulu ia ditelan `.catch(() => {})`, sehingga
17
- // yang sampai ke pemanggil hanya gejala open() berikutnya ("ENOENT: no
18
- // such file or directory") — menyesatkan, karena direktori itu ADA dan
19
- // memang tidak bisa dibuat. Simpan error mkdir; kalau open() juga gagal,
20
- // surface yang sebenarnya dan simpan gejala open() sebagai `cause` supaya
21
- // kedua informasi tetap utuh.
22
42
  let dirErr: NodeJS.ErrnoException | undefined
23
43
  try {
24
44
  await mkdir(dirname(path), { recursive: true, mode: 0o700 })
@@ -32,81 +52,33 @@ export async function atomicWriteText(path: string, data: string): Promise<void>
32
52
  try {
33
53
  fh = await open(tmp, "wx", 0o600)
34
54
  } catch (e) {
35
- // Pembuatan direktori gagal DAN tulisan juga gagal → akar masalahnya
36
- // di direktori, bukan di open(). Jangan biarkan gejala open() menutupi
37
- // penyebab aslinya.
38
55
  if (dirErr) throw Object.assign(dirErr, { cause: e })
39
56
  if ((e as NodeJS.ErrnoException).code === "EEXIST" && attempt === 0) continue
40
57
  throw e
41
58
  }
42
59
  try {
43
- // Bun Windows: `FileHandle.writeFile` kadang nge-hit kWriteMonkeyPatchDefense
44
- // bila `node:fs/promises` ke-import bareng `bun:sqlite` di top-level.
45
- // Fallback ke `Bun.write` (tidak pakai FileHandle) bila kena itu.
46
60
  try {
47
61
  await fh.writeFile(data, "utf8")
48
62
  } catch (e) {
49
63
  const msg = String((e as Error)?.message ?? "")
50
64
  if (msg.includes("kWriteMonkeyPatchDefense") || msg.includes("kWrite")) {
51
65
  await fh.close().catch(() => {})
52
- // Handle sudah ditutup di atas → null-out agar blok `finally` tidak
53
- // memanggil `.close()` pada handle yang sudah tidak ada. Tanpa ini
54
- // `fh.close()` di `finally` melempar TypeError yang menutupi
55
- // penulisan yang justru BERHASIL (file sudah ter-rename, tapi
56
- // pemanggil diberi tahu gagal).
57
66
  fh = undefined
58
67
  await Bun.write(tmp, data)
59
- // re-open untuk sync/chmod path yang sama — atau skip bila Bun.write sudah flush
60
- try {
61
- await chmod(tmp, 0o600).catch(() => {})
62
- } catch {}
63
- let lastErr2: unknown
64
- for (let r = 0; r < 8; r++) {
65
- try {
66
- await rename(tmp, path)
67
- lastErr2 = undefined
68
- break
69
- } catch (ee) {
70
- const code = (ee as NodeJS.ErrnoException).code
71
- if (code === "EPERM" || code === "EBUSY" || code === "EACCES") {
72
- lastErr2 = ee
73
- await new Promise((res) => setTimeout(res, Math.min(10 * 2 ** r, 100)))
74
- } else throw ee
75
- }
76
- }
77
- if (lastErr2) throw lastErr2
68
+ await chmod(tmp, 0o600).catch(() => {})
69
+ await renameWithRetry(tmp, path)
78
70
  return
79
71
  }
80
72
  throw e
81
73
  }
82
74
  await fh.sync().catch(() => {})
83
75
  await chmod(tmp, 0o600).catch(() => {})
84
- // Windows: rename menimpa target yang baru saja ditulis penulis lain
85
- // bisa EPERM/EBUSY/EACCES sesaat (lock AV / replace window) → backoff.
86
- let lastErr: unknown
87
- for (let r = 0; r < 8; r++) {
88
- try {
89
- await rename(tmp, path)
90
- lastErr = undefined
91
- break
92
- } catch (e) {
93
- const code = (e as NodeJS.ErrnoException).code
94
- if (code === "EPERM" || code === "EBUSY" || code === "EACCES") {
95
- lastErr = e
96
- await new Promise((res) => setTimeout(res, Math.min(10 * 2 ** r, 100)))
97
- } else throw e
98
- }
99
- }
100
- if (lastErr) throw lastErr
76
+ await renameWithRetry(tmp, path)
101
77
  return
102
78
  } catch (e) {
103
79
  await unlink(tmp).catch(() => {})
104
80
  throw e
105
81
  } finally {
106
- // `fh` bisa sudah `undefined` di jalur fallback Bun.write di atas
107
- // (handle ditutup manual). Menutup handle yang masih hidup itu aman;
108
- // memanggil `.close()` pada `undefined` melempar TypeError yang
109
- // menutupi penulisan yang justru sudah BERHASIL.
110
82
  if (fh) await fh.close().catch(() => {})
111
83
  }
112
84
  }
@@ -19,16 +19,14 @@ const DOTDOT_SEG_RE = /(?:^|[/\\])\.\.(?:[/\\]|$)/
19
19
  */
20
20
  function cleanPathForMatch(p: string): string {
21
21
  if (!p) return ""
22
- const withoutAds = p.replace(/(:[a-zA-Z0-9_.$-]+)+$/, (m, _g, offset) => {
23
- // Jangan kupas drive letter Windows seperti "C:" di awal path
24
- if (offset === 1 && /^[a-zA-Z]:$/.test(p.slice(0, 2))) return m
25
- return ""
26
- })
27
- return withoutAds
22
+ return p
28
23
  .split(/([/\\]+)/)
29
- .map((seg) => {
24
+ .map((seg, i) => {
30
25
  if (!seg || /^[/\\]+$/.test(seg) || seg === "." || seg === "..") return seg
31
- return seg.replace(/[.\s]+$/, "")
26
+ // Pertahankan drive letter Windows (mis. "C:") di segmen pertama
27
+ const noAds =
28
+ i === 0 && /^[a-zA-Z]:$/.test(seg) ? seg : seg.replace(/(:[a-zA-Z0-9_.$-]+)+$/, "")
29
+ return noAds.replace(/[.\s]+$/, "")
32
30
  })
33
31
  .join("")
34
32
  }
@@ -104,13 +104,24 @@ export function createAnthropicProvider(config: AnthropicConfig): ModelProvider
104
104
  const effectiveMaxTokens = legacyBudget
105
105
  ? Math.max(config.maxTokens ?? 8192, legacyBudget + 1024)
106
106
  : (config.maxTokens ?? 8192)
107
- // Fase 7: cache prefix percakapan (system+tools+histori) — tandai pesan
108
- // stabil terakhir (kedua dari akhir; yang terakhir = pesan user saat ini)
109
- // agar tool result besar ikut ter-cache tiap turn (bukan dikirim ulang).
107
+ // Fase 7: sematkan cache_control pada blok konten stabil terakhir.
110
108
  const messagesPayload = toAnthropicMessages(request.messages)
111
109
  if (enableCache && messagesPayload.length >= 2) {
112
- const lastStable = messagesPayload[messagesPayload.length - 2] as Record<string, unknown>
113
- lastStable.cache_control = { type: "ephemeral" }
110
+ const lastStable = messagesPayload[messagesPayload.length - 2] as {
111
+ role: string
112
+ content: unknown
113
+ }
114
+ if (Array.isArray(lastStable.content) && lastStable.content.length > 0) {
115
+ const lastBlock = lastStable.content[lastStable.content.length - 1] as Record<
116
+ string,
117
+ unknown
118
+ >
119
+ lastBlock.cache_control = { type: "ephemeral" }
120
+ } else if (typeof lastStable.content === "string") {
121
+ lastStable.content = [
122
+ { type: "text", text: lastStable.content, cache_control: { type: "ephemeral" } },
123
+ ]
124
+ }
114
125
  }
115
126
  const body = JSON.stringify({
116
127
  model: request.model ?? config.defaultModel ?? config.models[0],
@@ -254,6 +254,28 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
254
254
  // response.completed → simpan id untuk chaining turn berikut.
255
255
  // Format nyata: {type:"response.completed", response:{id:"resp_…"}}.
256
256
  const dtype = data.type as string | undefined
257
+ if (dtype === "error" || dtype === "response.failed" || data.error) {
258
+ if (prev) lastResponseByModel.delete(modelKey)
259
+ const errRec =
260
+ (data.error as Record<string, unknown> | undefined) ??
261
+ (data.response as { error?: Record<string, unknown> } | undefined)?.error ??
262
+ data
263
+ const msg = String(errRec.message ?? errRec.msg ?? JSON.stringify(errRec))
264
+ const code = String(errRec.code ?? errRec.type ?? "")
265
+ const combined = `${msg} ${code}`
266
+ const cat = /auth|401|403|unauthorized/i.test(combined)
267
+ ? "auth"
268
+ : /quota_exceeded|insufficient_quota|balance/i.test(combined)
269
+ ? "unknown"
270
+ : /rate|429/i.test(combined)
271
+ ? "rate_limit"
272
+ : /context_length|maximum context|prompt is too long|context window/i.test(
273
+ msg,
274
+ )
275
+ ? "context_length_exceeded"
276
+ : "server"
277
+ throw new ProviderError(cat, cat === "unknown" ? `402: ${msg}` : `${cat}: ${msg}`)
278
+ }
257
279
  if (dtype === "response.completed" || dtype === "completed") {
258
280
  const resp = data.response as { id?: unknown; usage?: unknown } | undefined
259
281
  const rid = resp?.id ?? data.id
@@ -391,14 +413,22 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
391
413
  typeof data.arguments === "string" ? data.arguments : "",
392
414
  )
393
415
  }
394
- const isToolEvent =
395
- dtype === "response.output_item.added" ||
396
- dtype === "response.function_call_arguments.delta" ||
397
- dtype === "response.function_call_arguments.done" ||
398
- dtype === "response.output_item.done" ||
399
- dtype === "function_call"
416
+ // Abaikan event lifecycle/summary `.done`/`.added` agar teks utuh di
417
+ // `response.output_text.done` tidak digandakan setelah `.delta`.
418
+ const isNonDeltaEvent =
419
+ typeof dtype === "string" &&
420
+ (dtype.endsWith(".done") ||
421
+ dtype.endsWith(".added") ||
422
+ dtype === "response.created" ||
423
+ dtype === "response.in_progress" ||
424
+ dtype === "response.completed" ||
425
+ dtype === "completed" ||
426
+ dtype === "response.incomplete" ||
427
+ dtype.startsWith("response.function_call") ||
428
+ dtype.startsWith("response.reasoning") ||
429
+ dtype === "function_call")
400
430
  const text =
401
- reasoningText || isToolEvent
431
+ reasoningText || isNonDeltaEvent
402
432
  ? undefined
403
433
  : ((typeof rawDelta === "string" ? rawDelta : undefined) ??
404
434
  drec.text ??
@@ -51,10 +51,7 @@ export function boundedSseBody(
51
51
  if (done) {
52
52
  reachedEof = true
53
53
  if (lineBytes !== 0 || frameBytes !== 0) {
54
- throw new ProviderError(
55
- "invalid_request",
56
- `${provider} returned an incomplete SSE frame`,
57
- )
54
+ throw new ProviderError("network", `${provider} returned an incomplete SSE frame`)
58
55
  }
59
56
  controller.close()
60
57
  release()
@@ -68,6 +65,11 @@ export function boundedSseBody(
68
65
  )
69
66
  }
70
67
  for (const byte of value) {
68
+ if (byte === 0x0d) {
69
+ // CRLF: 0x0D ikut dihitung frameBytes, bukan lineBytes
70
+ frameBytes++
71
+ continue
72
+ }
71
73
  if (byte === 0x0a) {
72
74
  frameBytes++
73
75
  if (frameBytes > maxFrameBytes) {