minicode-ai 0.9.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/CHANGELOG.md +935 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -0
  4. package/cli/args.ts +195 -0
  5. package/cli/auto-update.ts +108 -0
  6. package/cli/commands/auth.ts +166 -0
  7. package/cli/commands/config.ts +382 -0
  8. package/cli/commands/doctor.ts +128 -0
  9. package/cli/commands/exec.ts +179 -0
  10. package/cli/commands/mcp.ts +35 -0
  11. package/cli/commands/memory.ts +107 -0
  12. package/cli/commands/pricing.ts +100 -0
  13. package/cli/commands/providers.ts +162 -0
  14. package/cli/commands/sessions.ts +128 -0
  15. package/cli/commands/skills.ts +61 -0
  16. package/cli/commands/stats.ts +82 -0
  17. package/cli/commands.ts +317 -0
  18. package/cli/index.ts +539 -0
  19. package/cli/model-manager.ts +112 -0
  20. package/cli/provider-manager.ts +111 -0
  21. package/cli/repl.ts +734 -0
  22. package/cli/router.ts +124 -0
  23. package/cli/setup.ts +780 -0
  24. package/cli/wizard.ts +21 -0
  25. package/docs/ARCHITECTURE.html +1222 -0
  26. package/docs/README.md +109 -0
  27. package/docs/architecture.md +44 -0
  28. package/docs/changelog.md +3 -0
  29. package/package.json +91 -0
  30. package/src/agents/pool.ts +43 -0
  31. package/src/app/mentions.ts +50 -0
  32. package/src/app/provider-layer.ts +118 -0
  33. package/src/app/rag-layer.ts +105 -0
  34. package/src/app/session.ts +154 -0
  35. package/src/app/tool-layer.ts +56 -0
  36. package/src/config.ts +372 -0
  37. package/src/constants.ts +119 -0
  38. package/src/hooks/run.ts +89 -0
  39. package/src/lib/atomic-write.ts +88 -0
  40. package/src/lib/db-path.ts +36 -0
  41. package/src/lib/git-hardening.ts +91 -0
  42. package/src/lib/ignore.ts +58 -0
  43. package/src/lib/keystore.ts +202 -0
  44. package/src/lib/net.ts +70 -0
  45. package/src/lib/safe-open.ts +138 -0
  46. package/src/lib/session-id.ts +23 -0
  47. package/src/lib/trash.ts +38 -0
  48. package/src/lib/trusted-exec.ts +81 -0
  49. package/src/lsp/client.ts +395 -0
  50. package/src/mcp/client.ts +400 -0
  51. package/src/mcp/http-transport.ts +344 -0
  52. package/src/mcp/server.ts +538 -0
  53. package/src/mcp/transport.ts +150 -0
  54. package/src/memory/files.ts +159 -0
  55. package/src/memory/vector.ts +775 -0
  56. package/src/policy/allowlist.ts +67 -0
  57. package/src/policy/bash-guard.ts +465 -0
  58. package/src/policy/compaction.ts +271 -0
  59. package/src/policy/context.ts +161 -0
  60. package/src/policy/executor.ts +199 -0
  61. package/src/policy/jail.ts +127 -0
  62. package/src/policy/permission.ts +517 -0
  63. package/src/policy/pricing.ts +336 -0
  64. package/src/policy/ratelimit.ts +54 -0
  65. package/src/policy/sandbox-policy.ts +157 -0
  66. package/src/policy/scrub.ts +138 -0
  67. package/src/policy/update-check.ts +200 -0
  68. package/src/policy/usage.ts +292 -0
  69. package/src/policy/verifier.ts +181 -0
  70. package/src/providers/anthropic.ts +401 -0
  71. package/src/providers/auth-store.ts +139 -0
  72. package/src/providers/build.ts +136 -0
  73. package/src/providers/detect.ts +126 -0
  74. package/src/providers/effort.ts +165 -0
  75. package/src/providers/guards.ts +107 -0
  76. package/src/providers/oauth.ts +326 -0
  77. package/src/providers/presets.ts +122 -0
  78. package/src/providers/provision.ts +298 -0
  79. package/src/providers/responses.ts +371 -0
  80. package/src/providers/router.ts +247 -0
  81. package/src/repo/repomap.ts +470 -0
  82. package/src/sandbox/docker.ts +129 -0
  83. package/src/sandbox/os.ts +193 -0
  84. package/src/session/checkpoint.ts +543 -0
  85. package/src/session/journal.ts +1347 -0
  86. package/src/session/persistence.ts +446 -0
  87. package/src/session/shadow-git.ts +351 -0
  88. package/src/session/turn-marker.ts +118 -0
  89. package/src/skills/loader.ts +117 -0
  90. package/src/telemetry/trace.ts +283 -0
  91. package/src/tools/ask_user.ts +54 -0
  92. package/src/tools/bash.ts +400 -0
  93. package/src/tools/code_run.ts +96 -0
  94. package/src/tools/delete_file.ts +31 -0
  95. package/src/tools/edit.ts +204 -0
  96. package/src/tools/git.ts +301 -0
  97. package/src/tools/glob.ts +90 -0
  98. package/src/tools/grep.ts +281 -0
  99. package/src/tools/hashline.ts +66 -0
  100. package/src/tools/index.ts +103 -0
  101. package/src/tools/lsp.ts +346 -0
  102. package/src/tools/mcp_call.ts +163 -0
  103. package/src/tools/memory.ts +144 -0
  104. package/src/tools/move_file.ts +47 -0
  105. package/src/tools/patch.ts +86 -0
  106. package/src/tools/read_file.ts +130 -0
  107. package/src/tools/read_image.ts +80 -0
  108. package/src/tools/submit_result.ts +49 -0
  109. package/src/tools/task.ts +346 -0
  110. package/src/tools/todo.ts +201 -0
  111. package/src/tools/web_fetch.ts +161 -0
  112. package/src/tools/web_search.ts +156 -0
  113. package/src/tools/write_file.ts +42 -0
  114. package/src/ui/approval/prompt.ts +76 -0
  115. package/src/ui/assistant/simple.ts +568 -0
  116. package/src/ui/assistant/turn-status.ts +303 -0
  117. package/src/ui/contract.ts +55 -0
  118. package/src/ui/footer.ts +105 -0
  119. package/src/ui/input/input.ts +805 -0
  120. package/src/ui/input/prompt-engine.ts +606 -0
  121. package/src/ui/render/collapse.ts +84 -0
  122. package/src/ui/render/detail.ts +24 -0
  123. package/src/ui/render/diff.ts +181 -0
  124. package/src/ui/render/errors.ts +239 -0
  125. package/src/ui/render/format.ts +54 -0
  126. package/src/ui/render/highlight.ts +294 -0
  127. package/src/ui/render/markdown.ts +120 -0
  128. package/src/ui/render/money.ts +12 -0
  129. package/src/ui/render/reasoning.ts +20 -0
  130. package/src/ui/render/sanitize.ts +80 -0
  131. package/src/ui/render/table.ts +88 -0
  132. package/src/ui/render/theme.ts +339 -0
  133. package/src/ui/render/width.ts +256 -0
  134. package/src/ui/render/wrap.ts +120 -0
  135. package/src/ui/runtime/bus-debug.ts +83 -0
  136. package/src/ui/runtime/chrome.ts +301 -0
  137. package/src/ui/runtime/spinner.ts +77 -0
  138. package/src/ui/runtime/statusline.ts +227 -0
  139. package/src/ui/screens/model-manager.ts +434 -0
  140. package/src/ui/screens/overlay.ts +61 -0
  141. package/src/ui/screens/picker.ts +307 -0
  142. package/src/ui/screens/provider-manager.ts +450 -0
  143. package/src/ui/screens/wizard.ts +132 -0
  144. package/vendor/minicore/VENDOR.md +29 -0
  145. package/vendor/minicore/package.json +21 -0
  146. package/vendor/minicore/src/core/budget.ts +26 -0
  147. package/vendor/minicore/src/core/compact.ts +76 -0
  148. package/vendor/minicore/src/core/errors.ts +60 -0
  149. package/vendor/minicore/src/core/events.ts +74 -0
  150. package/vendor/minicore/src/core/executor.ts +139 -0
  151. package/vendor/minicore/src/core/history.ts +32 -0
  152. package/vendor/minicore/src/core/index.ts +42 -0
  153. package/vendor/minicore/src/core/loop.ts +344 -0
  154. package/vendor/minicore/src/core/permission.ts +24 -0
  155. package/vendor/minicore/src/core/provider.ts +39 -0
  156. package/vendor/minicore/src/core/recovery.ts +34 -0
  157. package/vendor/minicore/src/core/session.ts +327 -0
  158. package/vendor/minicore/src/core/snapshot.ts +142 -0
  159. package/vendor/minicore/src/core/tokens.ts +111 -0
  160. package/vendor/minicore/src/core/tool.ts +118 -0
  161. package/vendor/minicore/src/core/types.ts +50 -0
  162. package/vendor/minicore/src/providers/openai-compat.ts +366 -0
@@ -0,0 +1,401 @@
1
+ import { Buffer } from "node:buffer"
2
+ import { ProviderError } from "#minicore/core/errors.ts"
3
+ import type { ModelProvider, ProviderEvent, StreamRequest } from "#minicore/core/provider.ts"
4
+ import type { ToolSchema } from "#minicore/core/tool.ts"
5
+ import type { Content, Message } from "#minicore/core/types.ts"
6
+ import { LIMITS } from "../constants.ts"
7
+ import { thinkingFamily } from "./effort.ts"
8
+
9
+ export interface AnthropicConfig {
10
+ id?: string
11
+ apiKey: string
12
+ baseUrl?: string // default https://api.anthropic.com
13
+ models: readonly string[]
14
+ defaultModel?: string
15
+ maxTokens?: number
16
+ enablePromptCaching?: boolean
17
+ /** Budget tokens for extended thinking — yields reasoning via extension event. */
18
+ thinking?: number
19
+ /**
20
+ * Knob generik — dipetakan per MODEL per request: Claude ≤4.5 → budget
21
+ * legacy; Claude ≥4.6/5 (adaptive) → thinking adaptive + output effort;
22
+ * lainnya → diabaikan (default vendor). Menang atas `thinking` numerik.
23
+ */
24
+ reasoningEffort?: string
25
+ }
26
+
27
+ /** low/medium/high → budget token thinking legacy. Diekspor untuk test. */
28
+ export function mapReasoningToThinking(effort?: string): number | undefined {
29
+ return effort === "high" ? 4096 : effort === "medium" ? 2048 : effort === "low" ? 1024 : undefined
30
+ }
31
+
32
+ interface AnthropicRaw {
33
+ type?: string
34
+ delta?: {
35
+ type?: string
36
+ text?: string
37
+ partial_json?: string
38
+ thinking?: string
39
+ stop_reason?: string
40
+ }
41
+ usage?: {
42
+ input_tokens?: number
43
+ output_tokens?: number
44
+ cache_read_input_tokens?: number
45
+ cache_creation_input_tokens?: number
46
+ }
47
+ message?: {
48
+ usage?: {
49
+ input_tokens?: number
50
+ output_tokens?: number
51
+ cache_read_input_tokens?: number
52
+ cache_creation_input_tokens?: number
53
+ }
54
+ }
55
+ index?: number
56
+ content_block?: { type?: string; id?: string; name?: string }
57
+ }
58
+
59
+ export function createAnthropicProvider(config: AnthropicConfig): ModelProvider {
60
+ // Normalisasi baseUrl: bila sudah berakhir /v1, jangan dobel (/v1/v1/messages).
61
+ const baseUrl = (config.baseUrl ?? "https://api.anthropic.com")
62
+ .replace(/\/+$/, "")
63
+ .replace(/\/v1$/, "")
64
+ const endpoint = `${baseUrl}/v1/messages`
65
+ const enableCache = config.enablePromptCaching !== false
66
+
67
+ // brand `kind` dipakai router agar tahu konten Uint8Array ditangani native
68
+ const provider: ModelProvider & { kind: "anthropic" } = {
69
+ id: config.id ?? "anthropic",
70
+ models: config.models,
71
+ kind: "anthropic",
72
+ async *stream(request: StreamRequest, signal: AbortSignal): AsyncIterable<ProviderEvent> {
73
+ // System prompt with optional ephemeral cache control for 90% cost savings on long runs
74
+ const systemPayload = request.system
75
+ ? enableCache
76
+ ? [{ type: "text", text: request.system, cache_control: { type: "ephemeral" } }]
77
+ : request.system
78
+ : undefined
79
+
80
+ const toolsPayload = request.tools?.length
81
+ ? toAnthropicTools(request.tools, enableCache)
82
+ : undefined
83
+
84
+ // Thinking per model: legacy budget (≤4.5), adaptive (≥4.6/5), atau
85
+ // omit (lainnya + default). `thinking` numerik = back-compat eksplisit.
86
+ const model = request.model ?? config.defaultModel ?? config.models[0]
87
+ const family = thinkingFamily(model ?? "")
88
+ const effortBudget =
89
+ config.reasoningEffort && family === "claude-legacy"
90
+ ? mapReasoningToThinking(config.reasoningEffort)
91
+ : undefined
92
+ const adaptiveEffort =
93
+ config.reasoningEffort && family === "claude-adaptive" ? config.reasoningEffort : undefined
94
+ const legacyBudget = effortBudget ?? config.thinking
95
+ const effectiveMaxTokens = legacyBudget
96
+ ? Math.max(config.maxTokens ?? 8192, legacyBudget + 1024)
97
+ : (config.maxTokens ?? 8192)
98
+ const body = JSON.stringify({
99
+ model: request.model ?? config.defaultModel ?? config.models[0],
100
+ max_tokens: effectiveMaxTokens,
101
+ system: systemPayload,
102
+ messages: toAnthropicMessages(request.messages),
103
+ tools: toolsPayload,
104
+ ...(legacyBudget ? { thinking: { type: "enabled", budget_tokens: legacyBudget } } : {}),
105
+ // Adaptive: tanpa budget & tanpa beta thinking (dikelola model);
106
+ // depth dikendalikan output_config.effort (low/medium/high).
107
+ ...(adaptiveEffort
108
+ ? { thinking: { type: "adaptive" }, output_config: { effort: adaptiveEffort } }
109
+ : {}),
110
+ stream: true,
111
+ })
112
+
113
+ // Beta thinking hanya untuk mode legacy (adaptive tak butuh header).
114
+ const betaThinking = legacyBudget ? ", thinking-2024-12-16" : ""
115
+ const headers: Record<string, string> = {
116
+ "content-type": "application/json",
117
+ "x-api-key": config.apiKey,
118
+ "anthropic-version": "2023-06-01",
119
+ "anthropic-beta": `prompt-caching-2024-07-31${betaThinking}`,
120
+ accept: "text/event-stream",
121
+ }
122
+
123
+ let response: Response
124
+ try {
125
+ response = await fetch(endpoint, { method: "POST", headers, body, signal })
126
+ } catch (e) {
127
+ if ((e as Error).name === "AbortError") throw e
128
+ throw new ProviderError("network", (e as Error).message)
129
+ }
130
+ if (!response.ok) {
131
+ const txt = await response.text().catch(() => "")
132
+ throw toAnthropicError(response.status, txt, response.headers)
133
+ }
134
+ if (!response.body) throw new ProviderError("network", "empty response body")
135
+
136
+ // buffer for tool inputs across deltas — per-stream (was global, now isolated)
137
+ const pendingTools = new Map<number, { id: string; name: string; args: string }>()
138
+
139
+ // Anthropic SSE: event: ...\ndata: {...}
140
+ let currentEvent = ""
141
+ for await (const chunk of sseAnthropic(response.body, signal)) {
142
+ if (chunk.event) currentEvent = chunk.event
143
+ const data = chunk.data
144
+ if (!data) continue
145
+ // handle different event types
146
+ const raw = data as AnthropicRaw
147
+ if (currentEvent === "content_block_delta") {
148
+ const delta = raw.delta
149
+ if (delta?.type === "text_delta" && typeof delta.text === "string") {
150
+ yield { type: "text", text: delta.text }
151
+ }
152
+ } else if (currentEvent === "message_delta") {
153
+ const d = raw.delta
154
+ const stop = d?.stop_reason
155
+ if (stop) {
156
+ if (stop === "tool_use") yield { type: "finish", reason: "tool_calls" }
157
+ else if (stop === "max_tokens") {
158
+ yield {
159
+ type: "extension",
160
+ kind: "warning",
161
+ data: { text: "⚠ response truncated: hit max_tokens — raise via config maxTokens" },
162
+ }
163
+ yield { type: "finish", reason: "length" }
164
+ } else yield { type: "finish", reason: "stop" }
165
+ }
166
+ // Anthropic also sends usage in message_delta
167
+ const usage = raw.usage ?? (d as unknown as { usage?: AnthropicRaw["usage"] })?.usage
168
+ if (usage && (usage.input_tokens != null || usage.output_tokens != null)) {
169
+ yield {
170
+ type: "extension",
171
+ kind: "usage",
172
+ data: {
173
+ inputTokens: usage.input_tokens,
174
+ outputTokens: usage.output_tokens,
175
+ cacheReadTokens: usage.cache_read_input_tokens,
176
+ cacheWriteTokens: usage.cache_creation_input_tokens,
177
+ cacheIncluded: true,
178
+ },
179
+ }
180
+ }
181
+ } else if (raw.type === "message_start") {
182
+ const usage = raw.message?.usage
183
+ if (usage) {
184
+ yield {
185
+ type: "extension",
186
+ kind: "usage",
187
+ data: {
188
+ inputTokens: usage.input_tokens,
189
+ outputTokens: usage.output_tokens,
190
+ cacheReadTokens: usage.cache_read_input_tokens,
191
+ cacheWriteTokens: usage.cache_creation_input_tokens,
192
+ cacheIncluded: true,
193
+ },
194
+ }
195
+ }
196
+ }
197
+ // content_block_start for tool_use
198
+ if (raw.type === "content_block_start") {
199
+ const block = raw.content_block
200
+ if (block?.type === "tool_use") {
201
+ pendingTools.set(raw.index ?? 0, { id: block.id!, name: block.name!, args: "" })
202
+ }
203
+ }
204
+ if (raw.type === "content_block_delta") {
205
+ const d = raw.delta
206
+ if (d?.type === "input_json_delta") {
207
+ const idx = raw.index ?? 0
208
+ const p = pendingTools.get(idx)
209
+ if (p) p.args += d.partial_json ?? ""
210
+ }
211
+ if (d?.type === "thinking_delta" && typeof d.thinking === "string") {
212
+ yield { type: "extension", kind: "reasoning", data: { text: d.thinking } }
213
+ }
214
+ }
215
+ if (raw.type === "content_block_stop") {
216
+ const idx = raw.index ?? 0
217
+ const p = pendingTools.get(idx)
218
+ if (p) {
219
+ let args: unknown = p.args
220
+ try {
221
+ args = p.args ? JSON.parse(p.args) : {}
222
+ } catch {
223
+ args = { raw: p.args }
224
+ }
225
+ yield { type: "tool_call", id: p.id, name: p.name, args }
226
+ pendingTools.delete(idx)
227
+ }
228
+ }
229
+ }
230
+ },
231
+ }
232
+ return provider
233
+ }
234
+
235
+ // Deteksi tipe gambar dari magic bytes — tool result biner yang jelas gambar
236
+ // dikirim sebagai blok image (media_type benar), selain itu fallback base64.
237
+ function sniffImageMime(b: Uint8Array): string | null {
238
+ if (b.length >= 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47)
239
+ return "image/png"
240
+ if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return "image/jpeg"
241
+ if (b.length >= 6 && b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46) return "image/gif"
242
+ if (b.length >= 12 && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50)
243
+ return "image/webp"
244
+ return null
245
+ }
246
+
247
+ function toAnthropicMessages(messages: readonly Message[]): unknown[] {
248
+ const out: unknown[] = []
249
+ let toolGroup:
250
+ | { type: "tool_result"; tool_use_id: string; content: unknown; is_error?: boolean }[]
251
+ | null = null
252
+ const flushToolGroup = () => {
253
+ if (toolGroup) {
254
+ out.push({ role: "user", content: toolGroup })
255
+ toolGroup = null
256
+ }
257
+ }
258
+
259
+ for (const m of messages) {
260
+ if (m.role === "user") {
261
+ flushToolGroup()
262
+ out.push({ role: "user", content: toContent(m.content) })
263
+ } else if (m.role === "assistant") {
264
+ flushToolGroup()
265
+ const content: unknown[] = []
266
+ if (typeof m.content === "string" && m.content)
267
+ content.push({ type: "text", text: m.content })
268
+ else if (Array.isArray(m.content))
269
+ for (const p of m.content)
270
+ if (p.type === "text") content.push({ type: "text", text: p.text })
271
+ for (const tc of m.toolCalls ?? []) {
272
+ content.push({ type: "tool_use", id: tc.id, name: tc.name, input: tc.args })
273
+ }
274
+ out.push({
275
+ role: "assistant",
276
+ content: content.length ? content : [{ type: "text", text: "" }],
277
+ })
278
+ } else {
279
+ const c = m as unknown as { toolCallId: string; content: unknown; isError?: boolean }
280
+ let entryContent: unknown
281
+ if (typeof c.content === "string") {
282
+ entryContent = c.content
283
+ } else if (c.content instanceof Uint8Array) {
284
+ // biner dari tool: bila jelas gambar → blok image base64 (spec Anthropic);
285
+ // selain itu kirim base64 string seperti sebelumnya.
286
+ const mime = sniffImageMime(c.content)
287
+ const b64 = Buffer.from(c.content).toString("base64")
288
+ entryContent = mime
289
+ ? [{ type: "image", source: { type: "base64", media_type: mime, data: b64 } }]
290
+ : b64
291
+ } else {
292
+ entryContent = JSON.stringify(c.content)
293
+ }
294
+ toolGroup ??= []
295
+ const entry: {
296
+ type: "tool_result"
297
+ tool_use_id: string
298
+ content: unknown
299
+ is_error?: boolean
300
+ } = { type: "tool_result", tool_use_id: c.toolCallId, content: entryContent }
301
+ if (c.isError) entry.is_error = true
302
+ toolGroup.push(entry)
303
+ }
304
+ }
305
+ flushToolGroup()
306
+ return out
307
+ }
308
+
309
+ function toContent(content: Content): unknown {
310
+ if (typeof content === "string") return content
311
+ return (
312
+ content as readonly { type: string; text?: string; data?: Uint8Array; mime?: string }[]
313
+ ).map((p) =>
314
+ p.type === "text"
315
+ ? { type: "text", text: p.text }
316
+ : {
317
+ type: "image",
318
+ source: {
319
+ type: "base64",
320
+ media_type: p.mime,
321
+ data: Buffer.from(p.data as Uint8Array).toString("base64"),
322
+ },
323
+ },
324
+ )
325
+ }
326
+
327
+ function toAnthropicTools(tools: readonly ToolSchema[], enableCache: boolean = true): unknown[] {
328
+ return tools.map((t, idx) => {
329
+ const isLast = idx === tools.length - 1
330
+ return {
331
+ name: t.name,
332
+ description: t.description,
333
+ input_schema: t.parameters,
334
+ ...(enableCache && isLast ? { cache_control: { type: "ephemeral" } } : {}),
335
+ }
336
+ })
337
+ }
338
+
339
+ function toAnthropicError(status: number, body: string, headers: Headers): ProviderError {
340
+ const detail = body.slice(0, 500)
341
+ const retryAfter = headers.get("retry-after")
342
+ if (status === 429) {
343
+ const ms = retryAfter ? Number(retryAfter) * 1000 : undefined
344
+ return new ProviderError(
345
+ "rate_limit",
346
+ `rate limited (${status}): ${detail}`,
347
+ Number.isFinite(ms) ? Math.min(ms!, LIMITS.RETRY_AFTER_MAX_MS) : undefined,
348
+ )
349
+ }
350
+ if (status === 401 || status === 403)
351
+ return new ProviderError("auth", `auth failed (${status}): ${detail}`)
352
+ if (status === 400 || status === 422) {
353
+ const isCtx =
354
+ body.toLowerCase().includes("maximum context") ||
355
+ body.toLowerCase().includes("prompt is too long")
356
+ return new ProviderError(
357
+ isCtx ? "context_length_exceeded" : "invalid_request",
358
+ `${status}: ${detail}`,
359
+ )
360
+ }
361
+ if (status >= 500) return new ProviderError("server", `server error (${status}): ${detail}`)
362
+ return new ProviderError("unknown", `${status}: ${detail}`)
363
+ }
364
+
365
+ async function* sseAnthropic(
366
+ body: ReadableStream<Uint8Array>,
367
+ signal: AbortSignal,
368
+ ): AsyncGenerator<{ event: string; data: unknown }> {
369
+ const reader = body.getReader()
370
+ const decoder = new TextDecoder()
371
+ let buffer = ""
372
+ let evt = ""
373
+ try {
374
+ while (true) {
375
+ if (signal.aborted) throw new DOMException("Aborted", "AbortError")
376
+ const { done, value } = await reader.read()
377
+ if (done) break
378
+ buffer += decoder.decode(value, { stream: true })
379
+ let idx = buffer.indexOf("\n")
380
+ while (idx >= 0) {
381
+ const line = buffer.slice(0, idx).replace(/\r$/, "")
382
+ buffer = buffer.slice(idx + 1)
383
+ if (line.startsWith("event:")) evt = line.slice(6).trim()
384
+ else if (line.startsWith("data:")) {
385
+ const payload = line.slice(5).trim()
386
+ if (payload) {
387
+ try {
388
+ const data = JSON.parse(payload)
389
+ yield { event: evt, data }
390
+ } catch {}
391
+ }
392
+ } else if (line === "") {
393
+ evt = ""
394
+ }
395
+ idx = buffer.indexOf("\n")
396
+ }
397
+ }
398
+ } finally {
399
+ reader.releaseLock()
400
+ }
401
+ }
@@ -0,0 +1,139 @@
1
+ // Penyimpanan kredensial OAuth, terpisah dari config.json.
2
+ //
3
+ // Kenapa terpisah? `config.json` sering dibagikan / di-commit ke repo
4
+ // (`.minicode/config.json` lokal), sementara token OAuth adalah rahasia
5
+ // berumur pendek yang tak boleh ikut. Berkas ini selalu global
6
+ // (`~/.minicode/auth.json`), chmod 600, dan tak pernah dibaca dari cwd.
7
+ //
8
+ // Refresh token disimpan karena itu inti dari nilai OAuth: user login sekali,
9
+ // lalu access token diperbarui otomatis tanpa interaksi.
10
+
11
+ import { readFile } from "node:fs/promises"
12
+ import { homedir } from "node:os"
13
+ import { join } from "node:path"
14
+ import { atomicWriteText } from "../lib/atomic-write.ts"
15
+
16
+ export interface AuthCredentials {
17
+ /** Tipe kredensial; `oauth` = punya refresh flow. */
18
+ type: "oauth"
19
+ accessToken: string
20
+ refreshToken?: string
21
+ /** Epoch ms kedaluwarsa access token. */
22
+ expiresAt?: number
23
+ /** Scope yang diberikan server (informasional). */
24
+ scope?: string
25
+ /** Endpoint token untuk refresh — disimpan agar tak perlu hard-code ulang. */
26
+ tokenUrl?: string
27
+ clientId?: string
28
+ }
29
+
30
+ export interface AuthStore {
31
+ /** key = provider id (mis. "qwen", "anthropic"). */
32
+ [providerId: string]: AuthCredentials
33
+ }
34
+
35
+ const AUTH_PATH = join(homedir(), ".minicode", "auth.json")
36
+
37
+ export function authFilePath(): string {
38
+ return AUTH_PATH
39
+ }
40
+
41
+ // Kunci in-process per berkas (audit #09 P1): saveAuth/removeAuth adalah
42
+ // baca-modifikasi-tulis; dua refresh paralel (dua provider kedaluwarsa
43
+ // bersamaan) tanpa ini last-wins dan menelan kredensial segar salah satu —
44
+ // reproducer: 2× refresh konkuren → satu tetap OLD. Lintas proses tetap
45
+ // last-wins (terdokumentasi, tanpa CAS) — pola sama dengan withConfigLock.
46
+ const authLocks = new Map<string, Promise<void>>()
47
+
48
+ async function withAuthLock<T>(path: string, fn: () => Promise<T>): Promise<T> {
49
+ const prev = authLocks.get(path) ?? Promise.resolve()
50
+ let release!: () => void
51
+ const next = new Promise<void>((res) => (release = res))
52
+ authLocks.set(
53
+ path,
54
+ prev.then(() => next),
55
+ )
56
+ await prev
57
+ try {
58
+ return await fn()
59
+ } finally {
60
+ release()
61
+ if (authLocks.get(path) === next) authLocks.delete(path)
62
+ }
63
+ }
64
+
65
+ export async function loadAuthStore(): Promise<AuthStore> {
66
+ try {
67
+ const raw = await readFile(AUTH_PATH, "utf8")
68
+ const parsed = JSON.parse(raw) as unknown
69
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {}
70
+ const out: AuthStore = {}
71
+ for (const [id, v] of Object.entries(parsed as Record<string, unknown>)) {
72
+ const c = v as Partial<AuthCredentials>
73
+ // Entri tanpa accessToken tak berguna; buang daripada menyebarkan
74
+ // undefined ke header Authorization.
75
+ if (c && c.type === "oauth" && typeof c.accessToken === "string" && c.accessToken) {
76
+ out[id] = {
77
+ type: "oauth",
78
+ accessToken: c.accessToken,
79
+ ...(typeof c.refreshToken === "string" ? { refreshToken: c.refreshToken } : {}),
80
+ ...(typeof c.expiresAt === "number" ? { expiresAt: c.expiresAt } : {}),
81
+ ...(typeof c.scope === "string" ? { scope: c.scope } : {}),
82
+ ...(typeof c.tokenUrl === "string" ? { tokenUrl: c.tokenUrl } : {}),
83
+ ...(typeof c.clientId === "string" ? { clientId: c.clientId } : {}),
84
+ }
85
+ }
86
+ }
87
+ return out
88
+ } catch {
89
+ // Tidak ada file / JSON rusak = belum login. Bukan kondisi error.
90
+ return {}
91
+ }
92
+ }
93
+
94
+ export async function saveAuth(providerId: string, creds: AuthCredentials): Promise<void> {
95
+ return withAuthLock(AUTH_PATH, async () => {
96
+ const store = await loadAuthStore()
97
+ store[providerId] = creds
98
+ // atomicWriteText sudah chmod 600 + O_EXCL tmp; tak perlu perlakuan khusus.
99
+ await atomicWriteText(AUTH_PATH, JSON.stringify(store, null, 2))
100
+ })
101
+ }
102
+
103
+ export async function removeAuth(providerId: string): Promise<boolean> {
104
+ return withAuthLock(AUTH_PATH, async () => {
105
+ const store = await loadAuthStore()
106
+ if (!store[providerId]) return false
107
+ delete store[providerId]
108
+ await atomicWriteText(AUTH_PATH, JSON.stringify(store, null, 2))
109
+ return true
110
+ })
111
+ }
112
+
113
+ export async function getAuth(providerId: string): Promise<AuthCredentials | undefined> {
114
+ return (await loadAuthStore())[providerId]
115
+ }
116
+
117
+ /** Daftar provider yang punya kredensial (untuk `minicode auth status`). */
118
+ export async function listAuth(): Promise<
119
+ { providerId: string; expiresAt?: number; expired: boolean; hasRefresh: boolean }[]
120
+ > {
121
+ const store = await loadAuthStore()
122
+ return Object.entries(store).map(([providerId, c]) => ({
123
+ providerId,
124
+ ...(c.expiresAt ? { expiresAt: c.expiresAt } : {}),
125
+ expired: isExpired(c),
126
+ hasRefresh: Boolean(c.refreshToken),
127
+ }))
128
+ }
129
+
130
+ /**
131
+ * Kedaluwarsa dengan margin 60 detik.
132
+ *
133
+ * Margin penting: token yang kedaluwarsa 5 detik setelah kita memeriksanya akan
134
+ * gagal di tengah request. Lebih baik refresh sedikit lebih awal.
135
+ */
136
+ export function isExpired(creds: AuthCredentials, nowMs: number = Date.now()): boolean {
137
+ if (!creds.expiresAt) return false // tanpa info kedaluwarsa: anggap masih valid
138
+ return creds.expiresAt - 60_000 <= nowMs
139
+ }
@@ -0,0 +1,136 @@
1
+ import { randomUUID } from "node:crypto"
2
+ import type { ModelProvider } from "#minicore/core/provider.ts"
3
+ import { createOpenAICompatProvider } from "#minicore/providers/openai-compat.ts"
4
+ import type { MinicodeConfig } from "../config.ts"
5
+ import { createAnthropicProvider } from "./anthropic.ts"
6
+ import { allowedEfforts, thinkingFamily, withEffortFallback } from "./effort.ts"
7
+ import { withStreamGuards } from "./guards.ts"
8
+ import { getValidAccessToken } from "./oauth.ts"
9
+ import { createResponsesProvider } from "./responses.ts"
10
+
11
+ // Satu-satunya tempat membangun daftar provider dari config (hybrid anthropic/openai-compat).
12
+ // Dipakai CLI, sub-agent (task.ts), dan MCP server agar logika tidak terduplikasi.
13
+ // PENTING: id identitas provider WAJIB diteruskan — kalau tidak, router byId
14
+ // memetakan semua provider ke id generik "openai-compat" (provider terakhir menang).
15
+ // Thinking effort: default universal = omit (tanpa param). Knob hanya dikirim
16
+ // ke keluarga terbukti (OpenAI reasoning, Claude legacy/adaptive); jalur
17
+ // openai-compat yang campur dibungkus fail-soft (strip saat 400/500).
18
+ // Diekspor agar teruji tanpa membangun provider sungguhan.
19
+ export { mapReasoningToThinking } from "./anthropic.ts"
20
+
21
+ export function buildProviderList(cfg: MinicodeConfig): ModelProvider[] {
22
+ const out: ModelProvider[] = []
23
+ for (const p of cfg.providers) {
24
+ if (p.providerHint === "responses") {
25
+ out.push(
26
+ // F-11/F-16: guard stream (timeout + text-cap) di satu titik bangun —
27
+ // berlaku untuk semua adapter termasuk vendor yang tak boleh disentuh.
28
+ withStreamGuards(
29
+ createResponsesProvider({
30
+ id: p.id,
31
+ baseUrl: p.baseUrl,
32
+ apiKey: p.apiKey,
33
+ models: p.models,
34
+ defaultModel: p.models[0],
35
+ ...(p.reasoningEffort ? { reasoningEffort: p.reasoningEffort } : {}),
36
+ }),
37
+ ),
38
+ )
39
+ } else if (p.providerHint === "anthropic" || p.baseUrl.includes("anthropic")) {
40
+ // String effort diteruskan mentah; adapter memilih bentuk wire per
41
+ // MODEL per request (legacy budget vs adaptive vs omit).
42
+ out.push(
43
+ withStreamGuards(
44
+ createAnthropicProvider({
45
+ id: p.id,
46
+ apiKey: p.apiKey,
47
+ baseUrl: p.baseUrl,
48
+ models: p.models,
49
+ defaultModel: p.models[0],
50
+ ...(p.reasoningEffort ? { reasoningEffort: p.reasoningEffort } : {}),
51
+ }) as unknown as ModelProvider,
52
+ ),
53
+ )
54
+ } else {
55
+ const isZen =
56
+ p.baseUrl.includes("opencode.ai/zen") || p.id.includes("opencode") || p.id.includes("zen")
57
+ const zenHeaders = isZen ? { "x-opencode-session": randomUUID() } : undefined
58
+ const base = {
59
+ id: p.id,
60
+ baseUrl: p.baseUrl,
61
+ apiKey: p.apiKey,
62
+ models: p.models,
63
+ defaultModel: p.models[0],
64
+ ...(zenHeaders ? { headers: zenHeaders } : {}),
65
+ }
66
+ // Jalur openai-compat melayani semua keluarga (DeepSeek, free-tier,
67
+ // custom gateway) — effort hanya untuk model reasoning yang levelnya
68
+ // didukung; sisanya langsung tanpa effort + fail-soft bila ditolak.
69
+ if (!p.reasoningEffort) {
70
+ out.push(withStreamGuards(createOpenAICompatProvider(base)))
71
+ continue
72
+ }
73
+ const effort = p.reasoningEffort
74
+ out.push(
75
+ withStreamGuards(
76
+ withEffortFallback(
77
+ createOpenAICompatProvider({ ...base, reasoningEffort: effort }),
78
+ createOpenAICompatProvider(base),
79
+ {
80
+ providerId: p.id,
81
+ effort,
82
+ shouldSend: (model: string): boolean => {
83
+ if (thinkingFamily(model) !== "openai-reasoning") return false
84
+ return allowedEfforts(model).includes(effort as "low" | "medium" | "high")
85
+ },
86
+ },
87
+ ),
88
+ ),
89
+ )
90
+ }
91
+ }
92
+ return out
93
+ }
94
+
95
+ /**
96
+ * Versi async: provider ber-`auth: "oauth"` mendapat access token segar dari
97
+ * `~/.minicode/auth.json` (di-refresh bila perlu) alih-alih `apiKey` di config.
98
+ *
99
+ * Dipisah dari `buildProviderList` agar jalur sinkron yang sudah ada tidak
100
+ * berubah perilaku, dan agar pemanggil yang tak peduli OAuth tak jadi async.
101
+ * Provider OAuth yang belum login dibuang dengan peringatan — lebih baik hilang
102
+ * dari daftar daripada mengirim header Authorization tanpa token.
103
+ */
104
+ export async function buildProviderListAsync(cfg: MinicodeConfig): Promise<ModelProvider[]> {
105
+ const { getSecret } = await import("../lib/keystore.ts")
106
+ const resolved: MinicodeConfig = { ...cfg, providers: [] }
107
+ for (const p of cfg.providers) {
108
+ if (p.auth !== "oauth") {
109
+ // Referensi keystore (`keystore:<nama>`) di-resolve ke secret OS di
110
+ // sini (lapisan provisioning) — config.ts tetap IO murni. Gagal =
111
+ // skip dengan peringatan, sama seperti OAuth yang belum login.
112
+ if (p.apiKey.startsWith("keystore:")) {
113
+ const secret = await getSecret(p.apiKey.slice("keystore:".length)).catch(() => null)
114
+ if (!secret) {
115
+ process.stderr.write(
116
+ `[auth] provider "${p.id}" keystore entry missing/unreadable — skipped. Run: minicode config set-key ${p.id}\n`,
117
+ )
118
+ continue
119
+ }
120
+ resolved.providers.push({ ...p, apiKey: secret })
121
+ continue
122
+ }
123
+ resolved.providers.push(p)
124
+ continue
125
+ }
126
+ const token = await getValidAccessToken(p.id)
127
+ if (!token) {
128
+ process.stderr.write(
129
+ `[auth] provider "${p.id}" uses OAuth but is not logged in (or refresh failed) — skipped. Run: minicode auth login ${p.id}\n`,
130
+ )
131
+ continue
132
+ }
133
+ resolved.providers.push({ ...p, apiKey: token })
134
+ }
135
+ return buildProviderList(resolved)
136
+ }