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,298 @@
|
|
|
1
|
+
// Provisioning provider: deteksi model, simpan/hapus/sinkron entri provider.
|
|
2
|
+
// Dipisah dari src/config.ts supaya lapisan config murni IO (baca/tulis/validasi
|
|
3
|
+
// berkas) dan tidak bergantung ke providers/ — arah dependensi jadi satu arah:
|
|
4
|
+
// providers → config.
|
|
5
|
+
import { readFile } from "node:fs/promises"
|
|
6
|
+
import { resolve } from "node:path"
|
|
7
|
+
import {
|
|
8
|
+
globalConfigPath,
|
|
9
|
+
LOCAL,
|
|
10
|
+
loadConfig,
|
|
11
|
+
type MinicodeConfig,
|
|
12
|
+
normalizeConfig,
|
|
13
|
+
type ProviderEntry,
|
|
14
|
+
withConfigLock,
|
|
15
|
+
writeConfigAtomic,
|
|
16
|
+
} from "../config.ts"
|
|
17
|
+
import { atomicWriteText } from "../lib/atomic-write.ts"
|
|
18
|
+
import { getSecret } from "../lib/keystore.ts"
|
|
19
|
+
import { clearDetectCache, type DetectResult, detectModels } from "./detect.ts"
|
|
20
|
+
import { GATEWAY_PRESETS } from "./presets.ts"
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Selesaikan apiKey untuk deteksi model: referensi `keystore:<nama>` menjadi
|
|
24
|
+
* secret OS, sisanya lewat apa adanya. Return null bila entri keystore
|
|
25
|
+
* hilang/tak terbaca — pemanggil harus mencatat failed yang actionable,
|
|
26
|
+
* JANGAN mengirim literal "keystore:..." sebagai Bearer (401 diam-diam).
|
|
27
|
+
*/
|
|
28
|
+
export async function resolveDetectApiKey(apiKey: string): Promise<string | null> {
|
|
29
|
+
if (!apiKey.startsWith("keystore:")) return apiKey
|
|
30
|
+
return getSecret(apiKey.slice("keystore:".length)).catch(() => null)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function saveProvider(
|
|
34
|
+
entry: ProviderEntry,
|
|
35
|
+
opts: { global?: boolean; cwd?: string } = {},
|
|
36
|
+
) {
|
|
37
|
+
// Provider OAuth sengaja TIDAK butuh apiKey: tokennya hidup di auth.json.
|
|
38
|
+
const needsKey = entry.auth !== "oauth"
|
|
39
|
+
if (!entry.id || !entry.baseUrl || (needsKey && !entry.apiKey))
|
|
40
|
+
throw new Error("provider id/baseUrl/apiKey required")
|
|
41
|
+
// A provider may temporarily have no models: `/model` can remove the last
|
|
42
|
+
// entry before `/sync` discovers a new one.
|
|
43
|
+
const path =
|
|
44
|
+
(opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
|
|
45
|
+
// Kunci per-path SAMA dengan saveMcpServer/saveLspServer (audit #07):
|
|
46
|
+
// tanpa ini baca-modifikasi-tulis paralel last-wins dan menelan entri.
|
|
47
|
+
return withConfigLock(path, async () => {
|
|
48
|
+
let cfg: MinicodeConfig = { providers: [] }
|
|
49
|
+
try {
|
|
50
|
+
cfg = normalizeConfig(JSON.parse(await readFile(path, "utf8")))
|
|
51
|
+
} catch (e) {
|
|
52
|
+
// Audit #08 P1: reset diam-diam saat berkas korup MENGHAPUS semua
|
|
53
|
+
// provider + MCP/LSP/verify/allowlist lain saat tulis berikutnya.
|
|
54
|
+
// ENOENT (belum ada file) = mulai kosong; korup = backup + gagal keras
|
|
55
|
+
// seperti saveMcpServer; error lain (EACCES/…) = teruskan, jangan timpa.
|
|
56
|
+
if (e instanceof SyntaxError) {
|
|
57
|
+
const raw = await readFile(path, "utf8").catch(() => "")
|
|
58
|
+
const backup = `${path}.corrupt.${Date.now()}`
|
|
59
|
+
await atomicWriteText(backup, raw).catch(() => {})
|
|
60
|
+
throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
|
|
61
|
+
}
|
|
62
|
+
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e
|
|
63
|
+
}
|
|
64
|
+
const idx = cfg.providers.findIndex((p) => p.id === entry.id)
|
|
65
|
+
if (idx >= 0) cfg.providers[idx] = entry
|
|
66
|
+
else cfg.providers.push(entry)
|
|
67
|
+
await writeConfigAtomic(path, cfg)
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// 5.1 — id ramah: pakai id preset (openrouter/deepseek/generic/...) atau slug
|
|
72
|
+
// baseUrl; dedupe dengan indeks numerik, BUKAN hash acak.
|
|
73
|
+
export function deriveProviderId(baseUrl: string, existingIds: string[], id?: string): string {
|
|
74
|
+
let baseId: string
|
|
75
|
+
if (id) {
|
|
76
|
+
baseId = id
|
|
77
|
+
} else {
|
|
78
|
+
const norm = baseUrl.replace(/\/+$/, "")
|
|
79
|
+
const preset = GATEWAY_PRESETS.find((p) => p.baseUrl.replace(/\/+$/, "") === norm)
|
|
80
|
+
baseId =
|
|
81
|
+
(preset?.id ??
|
|
82
|
+
norm
|
|
83
|
+
.replace(/\/v1$/i, "") // OpenAI-compatible gateways: buang akhiran /v1
|
|
84
|
+
.replace(/https?:\/\//, "")
|
|
85
|
+
.replace(/[^a-z0-9]/gi, "-")
|
|
86
|
+
.replace(/-+/g, "-")
|
|
87
|
+
.replace(/^-|-$/g, "")
|
|
88
|
+
.slice(0, 24)) ||
|
|
89
|
+
"gateway"
|
|
90
|
+
}
|
|
91
|
+
let uniqId = baseId.slice(0, 30)
|
|
92
|
+
if (!id) {
|
|
93
|
+
let n = 2
|
|
94
|
+
while (existingIds.includes(uniqId)) {
|
|
95
|
+
uniqId = `${baseId}-${n}`.slice(0, 30)
|
|
96
|
+
n++
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return uniqId
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function detectAndSave(
|
|
103
|
+
baseUrl: string,
|
|
104
|
+
apiKey: string,
|
|
105
|
+
id?: string,
|
|
106
|
+
opts: { global?: boolean; cwd?: string; fallbackModels?: string[]; allowLocal?: boolean } = {},
|
|
107
|
+
): Promise<ProviderEntry> {
|
|
108
|
+
// Fallback model dipakai bila provider tidak punya endpoint GET /models
|
|
109
|
+
// (mis. Anthropic) atau deteksi gagal karena JARINGAN — agar wizard tetap
|
|
110
|
+
// berhasil. Key SALAH (401/403) bukan alasan fallback: menyimpannya dengan
|
|
111
|
+
// daftar palsu membuat auth gagal baru ketahuan saat inferensi.
|
|
112
|
+
// Cache 30 menit juga dibuang dulu: retry add dengan key terkoreksi harus
|
|
113
|
+
// re-fetch, bukan menyajikan daftar basi dari percobaan sebelumnya.
|
|
114
|
+
clearDetectCache()
|
|
115
|
+
let detected: DetectResult
|
|
116
|
+
try {
|
|
117
|
+
detected = await detectModels(baseUrl, apiKey)
|
|
118
|
+
if (detected.models.length === 0 && !detected.authFailed && opts.fallbackModels?.length) {
|
|
119
|
+
detected = {
|
|
120
|
+
models: opts.fallbackModels,
|
|
121
|
+
providerHint: detected.providerHint,
|
|
122
|
+
authFailed: false,
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
} catch (e) {
|
|
126
|
+
if (!opts.fallbackModels) throw e
|
|
127
|
+
const hint = baseUrl.includes("anthropic")
|
|
128
|
+
? "anthropic"
|
|
129
|
+
: baseUrl.includes("deepseek")
|
|
130
|
+
? "unknown"
|
|
131
|
+
: "unknown"
|
|
132
|
+
detected = {
|
|
133
|
+
models: opts.fallbackModels,
|
|
134
|
+
providerHint: hint as "openai" | "anthropic" | "responses" | "unknown",
|
|
135
|
+
authFailed: false,
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// Key ditolak server (401/403): gagal keras dengan pesan actionable.
|
|
139
|
+
// Menyimpan dengan fallback di sini = "Saved (3 models)" palsu yang baru
|
|
140
|
+
// ketahuan saat inferensi — temuan audit yang sedang diperbaiki.
|
|
141
|
+
if (detected.models.length === 0 && detected.authFailed) {
|
|
142
|
+
throw new Error(
|
|
143
|
+
`unauthorized: ${baseUrl} menolak API key (401/403) — periksa key, provider tidak disimpan`,
|
|
144
|
+
)
|
|
145
|
+
}
|
|
146
|
+
// dedup id: id ramah via preset/slug, tanpa hash acak (lihat deriveProviderId)
|
|
147
|
+
const prevCfg = await loadConfig(opts.cwd, { allowLocal: opts.allowLocal })
|
|
148
|
+
const existing = prevCfg.providers.map((p) => p.id)
|
|
149
|
+
const uniqId = deriveProviderId(baseUrl, existing, id)
|
|
150
|
+
// Pertahankan knob user (thinking effort) bila provider sudah ada — tanpa
|
|
151
|
+
// ini tiap add/edit me-reset effort ke default diam-diam ("hilang").
|
|
152
|
+
const prevEffort = prevCfg.providers.find((p) => p.id === uniqId)?.reasoningEffort
|
|
153
|
+
const entry: ProviderEntry = {
|
|
154
|
+
id: uniqId,
|
|
155
|
+
baseUrl,
|
|
156
|
+
apiKey,
|
|
157
|
+
models: detected.models,
|
|
158
|
+
providerHint: detected.providerHint,
|
|
159
|
+
...(prevEffort ? { reasoningEffort: prevEffort } : {}),
|
|
160
|
+
}
|
|
161
|
+
await saveProvider(entry, opts)
|
|
162
|
+
return entry
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export async function removeProvider(id: string, opts: { global?: boolean; cwd?: string } = {}) {
|
|
166
|
+
const path =
|
|
167
|
+
(opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
|
|
168
|
+
return withConfigLock(path, async () => {
|
|
169
|
+
let cfg: MinicodeConfig = { providers: [] }
|
|
170
|
+
try {
|
|
171
|
+
cfg = normalizeConfig(JSON.parse(await readFile(path, "utf8")))
|
|
172
|
+
} catch (e) {
|
|
173
|
+
// Sama seperti saveProvider (audit #08 P1): korup = backup + gagal
|
|
174
|
+
// keras, bukan reset diam-diam yang menghapus seluruh config.
|
|
175
|
+
if (e instanceof SyntaxError) {
|
|
176
|
+
const raw = await readFile(path, "utf8").catch(() => "")
|
|
177
|
+
const backup = `${path}.corrupt.${Date.now()}`
|
|
178
|
+
await atomicWriteText(backup, raw).catch(() => {})
|
|
179
|
+
throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
|
|
180
|
+
}
|
|
181
|
+
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e
|
|
182
|
+
}
|
|
183
|
+
cfg.providers = cfg.providers.filter((p) => p.id !== id)
|
|
184
|
+
await writeConfigAtomic(path, cfg)
|
|
185
|
+
})
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Re-detect models untuk provider yang ada (model baru otomatis tersinkron).
|
|
189
|
+
// Tidak menyentuh apiKey/baseUrl — hanya memperbarui daftar models.
|
|
190
|
+
// Membaca MERGED config (local prioritas atas global) dan menulis kembali ke
|
|
191
|
+
// KEDUA file tempat provider ternyata disimpan — mirip perilaku loadConfig,
|
|
192
|
+
// sehingga `/sync` bekerja walau provider disimpan di local (bukan global).
|
|
193
|
+
export interface SyncResult {
|
|
194
|
+
updated: { id: string; from: number; to: number }[]
|
|
195
|
+
/** Provider yang gagal total (network/timeout) — bedakan dari "tak ada
|
|
196
|
+
* perubahan" agar /sync jujur. Catatan: 401/403 dari /models ditelan
|
|
197
|
+
* detectModels sebagai "kosong" (Anthropic memang tak punya endpoint itu),
|
|
198
|
+
* jadi daftar ini hanya untuk kegagalan transport dan keystore yang hilang
|
|
199
|
+
* (keduanya butuh aksi operator), bukan vonis auth. */
|
|
200
|
+
failed: { id: string; reason: string }[]
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export async function refreshProviderModels(
|
|
204
|
+
opts: { global?: boolean; cwd?: string; allowLocal?: boolean } = {},
|
|
205
|
+
): Promise<SyncResult> {
|
|
206
|
+
// /sync harus benar-benar re-fetch — tanpa ini detectModels menyajikan cache
|
|
207
|
+
// 30 menit dan /sync menjadi no-op ("from == to") padahal provider punya
|
|
208
|
+
// model baru.
|
|
209
|
+
clearDetectCache()
|
|
210
|
+
const merged = await loadConfig(opts.cwd, { allowLocal: opts.allowLocal })
|
|
211
|
+
const providers: ProviderEntry[] = merged.providers
|
|
212
|
+
if (providers.length === 0 && (opts.global ?? true)) {
|
|
213
|
+
// tidak ada provider di merge — coba file global secara eksplisit
|
|
214
|
+
const g = await readFile(globalConfigPath(), "utf8")
|
|
215
|
+
.then((raw) => normalizeConfig(JSON.parse(raw)).providers)
|
|
216
|
+
.catch(() => [])
|
|
217
|
+
providers.push(...g)
|
|
218
|
+
}
|
|
219
|
+
if (providers.length === 0) return { updated: [], failed: [] }
|
|
220
|
+
|
|
221
|
+
const updated = new Map<string, ProviderEntry>()
|
|
222
|
+
const failed: { id: string; reason: string }[] = []
|
|
223
|
+
for (let i = 0; i < providers.length; i++) {
|
|
224
|
+
const p = providers[i]!
|
|
225
|
+
if (!p.apiKey || !p.baseUrl) continue
|
|
226
|
+
// Selesaikan referensi keystore SEBELUM deteksi (sama seperti
|
|
227
|
+
// buildProviderListAsync): tanpa ini literal "keystore:..." terkirim
|
|
228
|
+
// sebagai Bearer → 401 → [] → sync diam-diam no-op selamanya — tak masuk
|
|
229
|
+
// updated maupun failed, dan daftar model tak pernah tersinkron.
|
|
230
|
+
const apiKey = await resolveDetectApiKey(p.apiKey)
|
|
231
|
+
if (apiKey == null) {
|
|
232
|
+
failed.push({
|
|
233
|
+
id: p.id,
|
|
234
|
+
reason: `keystore entry missing/unreadable — run: minicode config set-key ${p.id}`.slice(
|
|
235
|
+
0,
|
|
236
|
+
120,
|
|
237
|
+
),
|
|
238
|
+
})
|
|
239
|
+
continue
|
|
240
|
+
}
|
|
241
|
+
try {
|
|
242
|
+
const detected = await detectModels(p.baseUrl, apiKey)
|
|
243
|
+
if (detected.models.length) {
|
|
244
|
+
updated.set(p.id, { ...p, models: detected.models, providerHint: detected.providerHint })
|
|
245
|
+
} else if (detected.authFailed) {
|
|
246
|
+
// Key ditolak (401/403): bedakan dari provider tanpa endpoint
|
|
247
|
+
// (Anthropic-style, tetap diam) — operator harus periksa key-nya.
|
|
248
|
+
failed.push({ id: p.id, reason: "unauthorized (401/403) — periksa API key" })
|
|
249
|
+
}
|
|
250
|
+
} catch (e) {
|
|
251
|
+
// provider offline/timeout — catat, jangan diam. Daftar lama dibiarkan.
|
|
252
|
+
failed.push({ id: p.id, reason: String((e as Error)?.message ?? e).slice(0, 120) })
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Tulis kembali ke setiap file yang memuat provider yang diupdate — dalam
|
|
257
|
+
// format yang sudah ada di file tersebut (global dan/atau local).
|
|
258
|
+
const results: { id: string; from: number; to: number }[] = []
|
|
259
|
+
// check existence via direct read attempt (no TOCTOU pre-check).
|
|
260
|
+
// Berkas lokal hanya disentuh bila operator opt-in (default deny — /sync
|
|
261
|
+
// tanpa flag tak boleh menghubungi endpoint repo tak dikenal).
|
|
262
|
+
const paths = new Set<string>()
|
|
263
|
+
const checkPaths = opts.allowLocal
|
|
264
|
+
? [globalConfigPath(), resolve(opts.cwd ?? process.cwd(), LOCAL)]
|
|
265
|
+
: [globalConfigPath()]
|
|
266
|
+
for (const p of checkPaths) {
|
|
267
|
+
try {
|
|
268
|
+
await readFile(p, "utf8")
|
|
269
|
+
paths.add(p)
|
|
270
|
+
} catch {}
|
|
271
|
+
}
|
|
272
|
+
for (const path of paths) {
|
|
273
|
+
// Kunci per-file (audit #07): /sync + saveProvider paralel tanpa ini
|
|
274
|
+
// last-wins dan menelan update satu sama lain.
|
|
275
|
+
await withConfigLock(path, async () => {
|
|
276
|
+
try {
|
|
277
|
+
const cfg: MinicodeConfig = normalizeConfig(JSON.parse(await readFile(path, "utf8")))
|
|
278
|
+
let changed = false
|
|
279
|
+
for (const p of cfg.providers) {
|
|
280
|
+
const nu = updated.get(p.id)
|
|
281
|
+
if (nu) {
|
|
282
|
+
p.models = nu.models
|
|
283
|
+
p.providerHint = nu.providerHint
|
|
284
|
+
changed = true
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (changed) await writeConfigAtomic(path, cfg)
|
|
288
|
+
} catch {
|
|
289
|
+
// file corrupt/unreadable — lewati
|
|
290
|
+
}
|
|
291
|
+
})
|
|
292
|
+
}
|
|
293
|
+
for (const [id, nu] of updated) {
|
|
294
|
+
const orig = providers.find((p) => p.id === id)!
|
|
295
|
+
results.push({ id, from: orig.models.length, to: nu.models.length })
|
|
296
|
+
}
|
|
297
|
+
return { updated: results, failed }
|
|
298
|
+
}
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
import { ProviderError } from "#minicore/core/errors.ts"
|
|
2
|
+
import type { ModelProvider, ProviderEvent, StreamRequest } from "#minicore/core/provider.ts"
|
|
3
|
+
import { allowedEfforts, thinkingFamily } from "./effort.ts"
|
|
4
|
+
|
|
5
|
+
export interface ResponsesConfig {
|
|
6
|
+
id?: string
|
|
7
|
+
baseUrl: string
|
|
8
|
+
apiKey?: string
|
|
9
|
+
models: readonly string[]
|
|
10
|
+
defaultModel?: string
|
|
11
|
+
reasoningEffort?: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Minimal Responses API adapter — /v1/responses, previous_response_id chaining, store:false
|
|
15
|
+
// Untuk P11 P1.1: providerHint "responses" → wire ini, bukan chat/completions.
|
|
16
|
+
// Implementasi streaming SSE mirip openai-compat, tapi endpoint berbeda.
|
|
17
|
+
//
|
|
18
|
+
// Chaining: response id terakhir per model disimpan per-instance provider,
|
|
19
|
+
// bukan global — global bocor antar sesi CLI paralel yang sharing model sama.
|
|
20
|
+
// Instance dibuat per sesi via buildProviderList, jadi isolasi sesi gratis.
|
|
21
|
+
const allChains = new Set<Map<string, string>>()
|
|
22
|
+
export function clearResponsesChain(): void {
|
|
23
|
+
// Global clear untuk compat — bersihkan semua instance yang pernah dibuat
|
|
24
|
+
for (const m of allChains) m.clear()
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Petakan riwayat kernel ke Responses input items TANPA menghancurkan linkage.
|
|
29
|
+
* Versi lama me-JSON-kan seluruh pesan (tool_calls, tool_call_id, reasoning,
|
|
30
|
+
* multimodal hilang) sehingga turn lanjutan buta terhadap tool-nya sendiri.
|
|
31
|
+
* Multimodal non-teks tetap di-stringify (keterbatasan jujur: Responses
|
|
32
|
+
* input teks; image akan ditangani bila adapter mendukung part image).
|
|
33
|
+
*/
|
|
34
|
+
export function toResponsesInput(
|
|
35
|
+
messages: readonly {
|
|
36
|
+
role: string
|
|
37
|
+
content?: unknown
|
|
38
|
+
toolCalls?: unknown
|
|
39
|
+
toolCallId?: string
|
|
40
|
+
isError?: boolean
|
|
41
|
+
}[],
|
|
42
|
+
): unknown[] {
|
|
43
|
+
const out: unknown[] = []
|
|
44
|
+
for (const m of messages) {
|
|
45
|
+
const text = typeof m.content === "string" ? m.content : JSON.stringify(m.content ?? null)
|
|
46
|
+
if (m.role === "assistant" && Array.isArray((m as { toolCalls?: unknown }).toolCalls)) {
|
|
47
|
+
if (text) out.push({ role: "assistant", content: text })
|
|
48
|
+
for (const c of (m as unknown as { toolCalls: { id: string; name: string; args: unknown }[] })
|
|
49
|
+
.toolCalls) {
|
|
50
|
+
out.push({
|
|
51
|
+
type: "function_call",
|
|
52
|
+
call_id: c.id,
|
|
53
|
+
name: c.name,
|
|
54
|
+
arguments: typeof c.args === "string" ? c.args : JSON.stringify(c.args ?? {}),
|
|
55
|
+
})
|
|
56
|
+
}
|
|
57
|
+
continue
|
|
58
|
+
}
|
|
59
|
+
if (m.role === "tool") {
|
|
60
|
+
const t = m as unknown as { toolCallId?: string; content?: unknown; isError?: boolean }
|
|
61
|
+
const content = typeof t.content === "string" ? t.content : JSON.stringify(t.content ?? null)
|
|
62
|
+
out.push({
|
|
63
|
+
type: "function_call_output",
|
|
64
|
+
call_id: t.toolCallId ?? "",
|
|
65
|
+
output: t.isError ? `ERROR: ${content}` : content,
|
|
66
|
+
})
|
|
67
|
+
continue
|
|
68
|
+
}
|
|
69
|
+
out.push({ role: m.role, content: text })
|
|
70
|
+
}
|
|
71
|
+
return out
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function createResponsesProvider(config: ResponsesConfig): ModelProvider {
|
|
75
|
+
const baseUrl = config.baseUrl.replace(/\/+$/, "")
|
|
76
|
+
const endpoint = `${baseUrl}/responses`
|
|
77
|
+
const lastResponseByModel = new Map<string, string>()
|
|
78
|
+
allChains.add(lastResponseByModel)
|
|
79
|
+
const provider: ModelProvider & { kind: "responses"; clearResponsesChain?: () => void } = {
|
|
80
|
+
id: config.id ?? "responses",
|
|
81
|
+
models: config.models,
|
|
82
|
+
// brand kind: router memakai ini untuk (a) skip binary-fix gaya Anthropic,
|
|
83
|
+
// (b) skip penyelipan system-message (diurus via `instructions` di bawah).
|
|
84
|
+
kind: "responses",
|
|
85
|
+
clearResponsesChain: () => lastResponseByModel.clear(),
|
|
86
|
+
async *stream(request: StreamRequest, signal: AbortSignal): AsyncIterable<ProviderEvent> {
|
|
87
|
+
const modelKey = request.model ?? config.defaultModel ?? config.models[0] ?? "default"
|
|
88
|
+
const prev = lastResponseByModel.get(modelKey)
|
|
89
|
+
// Effort hanya untuk keluarga OpenAI reasoning dengan level yang
|
|
90
|
+
// didukung model itu (mis. pro = high saja); sisanya omit — default
|
|
91
|
+
// bawaan model yang berlaku. Tanpa ini model non-reasoning 400.
|
|
92
|
+
const wantEffort = config.reasoningEffort
|
|
93
|
+
const sendEffort =
|
|
94
|
+
wantEffort &&
|
|
95
|
+
thinkingFamily(modelKey) === "openai-reasoning" &&
|
|
96
|
+
allowedEfforts(modelKey).includes(wantEffort as "low" | "medium" | "high")
|
|
97
|
+
? wantEffort
|
|
98
|
+
: undefined
|
|
99
|
+
const body = JSON.stringify({
|
|
100
|
+
model: request.model ?? config.defaultModel ?? config.models[0],
|
|
101
|
+
input: toResponsesInput(request.messages),
|
|
102
|
+
tools: request.tools?.length
|
|
103
|
+
? request.tools.map((t) => ({
|
|
104
|
+
type: "function",
|
|
105
|
+
name: t.name,
|
|
106
|
+
description: t.description,
|
|
107
|
+
parameters: t.parameters,
|
|
108
|
+
}))
|
|
109
|
+
: undefined,
|
|
110
|
+
// System prompt KERNEL (MEMORY, repomap, instruksi) — versi lama
|
|
111
|
+
// membuangnya total (body tanpa field ini). Responses API punya
|
|
112
|
+
// field khusus; jangan selipkan sebagai user message.
|
|
113
|
+
...(request.system?.trim() ? { instructions: request.system } : {}),
|
|
114
|
+
stream: true,
|
|
115
|
+
store: false,
|
|
116
|
+
...(sendEffort ? { reasoning: { effort: sendEffort } } : {}),
|
|
117
|
+
// Rantai konteks antar turn; tanpa ini server memperlakukan tiap
|
|
118
|
+
// request sebagai sesi baru (biaya konteks + hilang ingatan server).
|
|
119
|
+
...(prev ? { previous_response_id: prev } : {}),
|
|
120
|
+
})
|
|
121
|
+
const headers: Record<string, string> = {
|
|
122
|
+
"content-type": "application/json",
|
|
123
|
+
accept: "text/event-stream",
|
|
124
|
+
...(config.apiKey ? { authorization: `Bearer ${config.apiKey}` } : {}),
|
|
125
|
+
}
|
|
126
|
+
let res: Response
|
|
127
|
+
try {
|
|
128
|
+
res = await fetch(endpoint, { method: "POST", headers, body, signal })
|
|
129
|
+
} catch (e) {
|
|
130
|
+
if ((e as Error).name === "AbortError") throw e
|
|
131
|
+
throw new ProviderError("network", (e as Error).message)
|
|
132
|
+
}
|
|
133
|
+
if (!res.ok) {
|
|
134
|
+
const txt = await res.text().catch(() => "")
|
|
135
|
+
const retryAfter = res.headers.get("retry-after")
|
|
136
|
+
if (res.status === 429) {
|
|
137
|
+
const ms = retryAfter ? Number(retryAfter) * 1000 : undefined
|
|
138
|
+
throw new ProviderError(
|
|
139
|
+
"rate_limit",
|
|
140
|
+
`rate limited (${res.status}): ${txt.slice(0, 500)}`,
|
|
141
|
+
Number.isFinite(ms) ? ms : undefined,
|
|
142
|
+
)
|
|
143
|
+
}
|
|
144
|
+
// Samakan dengan adapter lain: 401/403 = auth (fail-fast, tanpa
|
|
145
|
+
// retry buta). Sebelumnya jatuh ke "unknown" lalu di-retry 3x.
|
|
146
|
+
if (res.status === 401 || res.status === 403) {
|
|
147
|
+
throw new ProviderError("auth", `auth rejected (${res.status}): ${txt.slice(0, 500)}`)
|
|
148
|
+
}
|
|
149
|
+
// Samakan dengan adapter lain: konteks kepanjangan = compact-and-retry
|
|
150
|
+
// di loop, bukan retry-buta 3x lalu throw. Frasa diselaraskan dengan
|
|
151
|
+
// openai-compat/anthropic (`context_length`, `maximum context`,
|
|
152
|
+
// `prompt is too long`) + `context window`. Sengaja TANPA kata
|
|
153
|
+
// telanjang `token`/`too long`/`context`: "invalid token" atau
|
|
154
|
+
// "tokenizer error" bukan kepanjangan konteks — mengklasifikasikannya
|
|
155
|
+
// sebagai context_length_exceeded menghancurkan riwayat sia-sia.
|
|
156
|
+
if (
|
|
157
|
+
(res.status === 400 || res.status === 422) &&
|
|
158
|
+
/context_length|maximum context|prompt is too long|context window/i.test(txt)
|
|
159
|
+
) {
|
|
160
|
+
throw new ProviderError(
|
|
161
|
+
"context_length_exceeded",
|
|
162
|
+
`context too long (${res.status}): ${txt.slice(0, 500)}`,
|
|
163
|
+
)
|
|
164
|
+
}
|
|
165
|
+
throw new ProviderError(
|
|
166
|
+
res.status >= 500 ? "server" : "unknown",
|
|
167
|
+
`${res.status}: ${txt.slice(0, 500)}`,
|
|
168
|
+
)
|
|
169
|
+
}
|
|
170
|
+
if (!res.body) throw new ProviderError("network", "empty response body")
|
|
171
|
+
// Simplified SSE: forward text deltas
|
|
172
|
+
const reader = res.body.getReader()
|
|
173
|
+
const decoder = new TextDecoder()
|
|
174
|
+
let buf = ""
|
|
175
|
+
// F-01: akumulasi function_call per item (Responses tidak punya delta
|
|
176
|
+
// gaya chat completions; argumen mengalir via
|
|
177
|
+
// response.function_call_arguments.delta lalu item final via
|
|
178
|
+
// response.output_item.done). Tanpa ini tool yang dideklarasikan di
|
|
179
|
+
// request tidak pernah dieksekusi — agen tampak selesai padahal buta.
|
|
180
|
+
const pendingCalls = new Map<string, { id: string; name: string; args: string }>()
|
|
181
|
+
let finished = false
|
|
182
|
+
const parseCallArgs = (raw: string): unknown => {
|
|
183
|
+
if (!raw) return {}
|
|
184
|
+
try {
|
|
185
|
+
return JSON.parse(raw)
|
|
186
|
+
} catch {
|
|
187
|
+
return { raw }
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
const yieldCall = function* (
|
|
191
|
+
id: string,
|
|
192
|
+
name: string,
|
|
193
|
+
argsRaw: string,
|
|
194
|
+
): Generator<ProviderEvent> {
|
|
195
|
+
if (finished) {
|
|
196
|
+
// Cermin openai-compat: tool setelah finish = stream rusak, jangan
|
|
197
|
+
// eksekusi ganda diam-diam — gagal keras sebagai network retryable.
|
|
198
|
+
throw new ProviderError("network", "tool call after finish")
|
|
199
|
+
}
|
|
200
|
+
yield { type: "tool_call", id: id || name, name, args: parseCallArgs(argsRaw) }
|
|
201
|
+
}
|
|
202
|
+
try {
|
|
203
|
+
while (true) {
|
|
204
|
+
if (signal.aborted) throw new DOMException("Aborted", "AbortError")
|
|
205
|
+
const { done, value } = await reader.read()
|
|
206
|
+
if (done) break
|
|
207
|
+
buf += decoder.decode(value, { stream: true })
|
|
208
|
+
let idx = buf.indexOf("\n")
|
|
209
|
+
while (idx >= 0) {
|
|
210
|
+
const line = buf.slice(0, idx).replace(/\r$/, "")
|
|
211
|
+
buf = buf.slice(idx + 1)
|
|
212
|
+
if (line.startsWith("data:")) {
|
|
213
|
+
const payload = line.slice(5).trim()
|
|
214
|
+
// F-02: [DONE] = akhir stream yang sukses. Versi lama `return`
|
|
215
|
+
// tanpa finish sehingga kernel melempar "stream ended without a
|
|
216
|
+
// finish reason" + 3 retry sia-sia atas respons yang valid.
|
|
217
|
+
if (payload === "[DONE]") {
|
|
218
|
+
for (const [, acc] of pendingCalls) {
|
|
219
|
+
yield* yieldCall(acc.id, acc.name, acc.args)
|
|
220
|
+
}
|
|
221
|
+
pendingCalls.clear()
|
|
222
|
+
if (!finished) {
|
|
223
|
+
finished = true
|
|
224
|
+
yield { type: "finish", reason: "stop" }
|
|
225
|
+
}
|
|
226
|
+
return
|
|
227
|
+
}
|
|
228
|
+
// Hanya JSON rusak yang di-skip di sini: error dari yieldCall
|
|
229
|
+
// (mis. tool-setelah-finish) HARUS merambat ke kernel, jangan
|
|
230
|
+
// sampai tertelan catch di bawah.
|
|
231
|
+
let data: Record<string, unknown>
|
|
232
|
+
try {
|
|
233
|
+
data = JSON.parse(payload) as Record<string, unknown>
|
|
234
|
+
} catch {
|
|
235
|
+
continue
|
|
236
|
+
}
|
|
237
|
+
// response.completed → simpan id untuk chaining turn berikut.
|
|
238
|
+
// Format nyata: {type:"response.completed", response:{id:"resp_…"}}.
|
|
239
|
+
const dtype = data.type as string | undefined
|
|
240
|
+
if (dtype === "response.completed" || dtype === "completed") {
|
|
241
|
+
const resp = data.response as { id?: unknown; usage?: unknown } | undefined
|
|
242
|
+
const rid = resp?.id ?? data.id
|
|
243
|
+
if (typeof rid === "string" && rid) lastResponseByModel.set(modelKey, rid)
|
|
244
|
+
// Tanpa usage event, Responses tak pernah menyumbang token ke
|
|
245
|
+
// budget/cost (buta spend). Bentuk shape sama dengan adapter
|
|
246
|
+
// openai-compat agar kolektor tak perlu tahu provider.
|
|
247
|
+
const u = resp?.usage as
|
|
248
|
+
| { input_tokens?: unknown; output_tokens?: unknown; total_tokens?: unknown }
|
|
249
|
+
| undefined
|
|
250
|
+
if (
|
|
251
|
+
u &&
|
|
252
|
+
(u.input_tokens != null || u.output_tokens != null || u.total_tokens != null)
|
|
253
|
+
) {
|
|
254
|
+
yield {
|
|
255
|
+
type: "extension",
|
|
256
|
+
kind: "usage",
|
|
257
|
+
data: {
|
|
258
|
+
inputTokens: typeof u.input_tokens === "number" ? u.input_tokens : undefined,
|
|
259
|
+
outputTokens:
|
|
260
|
+
typeof u.output_tokens === "number" ? u.output_tokens : undefined,
|
|
261
|
+
totalTokens: typeof u.total_tokens === "number" ? u.total_tokens : undefined,
|
|
262
|
+
},
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
const rawDelta: unknown = (data.delta as unknown) ?? data
|
|
267
|
+
const drec = (
|
|
268
|
+
typeof rawDelta === "object" && rawDelta !== null
|
|
269
|
+
? (rawDelta as Record<string, unknown>)
|
|
270
|
+
: {}
|
|
271
|
+
) as Record<string, unknown> & { output_text?: string }
|
|
272
|
+
// Bentuk function_call Responses: item diumumkan via
|
|
273
|
+
// output_item.added, argumen mengalir via
|
|
274
|
+
// function_call_arguments.delta, item final via output_item.done.
|
|
275
|
+
//Juga tangani bentuk ringkas satu-event {type:"function_call",...}
|
|
276
|
+
// yang dipakai sebagian gateway.
|
|
277
|
+
const item = data.item as
|
|
278
|
+
| {
|
|
279
|
+
id?: unknown
|
|
280
|
+
type?: unknown
|
|
281
|
+
call_id?: unknown
|
|
282
|
+
name?: unknown
|
|
283
|
+
arguments?: unknown
|
|
284
|
+
}
|
|
285
|
+
| undefined
|
|
286
|
+
if (dtype === "response.output_item.added" && item?.type === "function_call") {
|
|
287
|
+
const key =
|
|
288
|
+
typeof item.id === "string" && item.id
|
|
289
|
+
? item.id
|
|
290
|
+
: typeof item.call_id === "string"
|
|
291
|
+
? item.call_id
|
|
292
|
+
: `item_${pendingCalls.size}`
|
|
293
|
+
const cid = typeof item.call_id === "string" && item.call_id ? item.call_id : key
|
|
294
|
+
pendingCalls.set(key, {
|
|
295
|
+
id: cid,
|
|
296
|
+
name: typeof item.name === "string" ? item.name : "",
|
|
297
|
+
args: typeof item.arguments === "string" ? item.arguments : "",
|
|
298
|
+
})
|
|
299
|
+
} else if (dtype === "response.function_call_arguments.delta") {
|
|
300
|
+
const key =
|
|
301
|
+
typeof data.item_id === "string" && data.item_id
|
|
302
|
+
? data.item_id
|
|
303
|
+
: ([...pendingCalls.keys()].pop() ?? "")
|
|
304
|
+
const acc = pendingCalls.get(key)
|
|
305
|
+
if (acc && typeof data.delta === "string") acc.args += data.delta
|
|
306
|
+
} else if (dtype === "response.output_item.done" && item?.type === "function_call") {
|
|
307
|
+
const key =
|
|
308
|
+
typeof item.id === "string" && pendingCalls.has(item.id)
|
|
309
|
+
? item.id
|
|
310
|
+
: ([...pendingCalls.keys()].pop() ?? "")
|
|
311
|
+
const acc = pendingCalls.get(key)
|
|
312
|
+
const id = (typeof item.call_id === "string" && item.call_id) || acc?.id || key
|
|
313
|
+
const name = (typeof item.name === "string" && item.name) || acc?.name || ""
|
|
314
|
+
const argsRaw =
|
|
315
|
+
(typeof item.arguments === "string" && item.arguments) || acc?.args || ""
|
|
316
|
+
pendingCalls.delete(key)
|
|
317
|
+
if (name) yield* yieldCall(id, name, argsRaw)
|
|
318
|
+
} else if (data.type === "function_call" && typeof data.name === "string") {
|
|
319
|
+
const id =
|
|
320
|
+
typeof data.call_id === "string"
|
|
321
|
+
? data.call_id
|
|
322
|
+
: typeof data.id === "string"
|
|
323
|
+
? data.id
|
|
324
|
+
: data.name
|
|
325
|
+
yield* yieldCall(
|
|
326
|
+
id,
|
|
327
|
+
data.name,
|
|
328
|
+
typeof data.arguments === "string" ? data.arguments : "",
|
|
329
|
+
)
|
|
330
|
+
}
|
|
331
|
+
const text =
|
|
332
|
+
(typeof rawDelta === "string" ? rawDelta : undefined) ??
|
|
333
|
+
drec.text ??
|
|
334
|
+
drec.content ??
|
|
335
|
+
drec.output_text
|
|
336
|
+
if (typeof text === "string" && text) yield { type: "text", text }
|
|
337
|
+
const finish =
|
|
338
|
+
(data as { finish_reason?: string }).finish_reason ??
|
|
339
|
+
(drec as { finish_reason?: string }).finish_reason
|
|
340
|
+
if (finish) {
|
|
341
|
+
finished = true
|
|
342
|
+
yield {
|
|
343
|
+
type: "finish",
|
|
344
|
+
reason:
|
|
345
|
+
finish === "length"
|
|
346
|
+
? "length"
|
|
347
|
+
: finish === "tool_calls"
|
|
348
|
+
? "tool_calls"
|
|
349
|
+
: "stop",
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
idx = buf.indexOf("\n")
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
} finally {
|
|
357
|
+
reader.releaseLock()
|
|
358
|
+
}
|
|
359
|
+
// Provider quirky bisa berakhir tanpa finish eksplisit: flush sisa
|
|
360
|
+
// function_call yang terakumulasi (argumen parsial → {raw}, ditolak
|
|
361
|
+
// validateArgs sebagai observasi error — aman), lalu finish stop agar
|
|
362
|
+
// kernel tidak menganggap stream terputus.
|
|
363
|
+
for (const [, acc] of pendingCalls) {
|
|
364
|
+
yield* yieldCall(acc.id, acc.name, acc.args)
|
|
365
|
+
}
|
|
366
|
+
pendingCalls.clear()
|
|
367
|
+
if (!finished) yield { type: "finish", reason: "stop" }
|
|
368
|
+
},
|
|
369
|
+
}
|
|
370
|
+
return provider
|
|
371
|
+
}
|