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,126 @@
|
|
|
1
|
+
import { LIMITS } from "../constants.ts"
|
|
2
|
+
|
|
3
|
+
export interface DetectedModel {
|
|
4
|
+
id: string
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface DetectResult {
|
|
8
|
+
models: string[]
|
|
9
|
+
providerHint: "openai" | "anthropic" | "responses" | "unknown"
|
|
10
|
+
/**
|
|
11
|
+
* True bila server menjawab 401/403 di salah satu attempt: key salah/
|
|
12
|
+
* kedaluwarsa. Beda dari "tanpa endpoint /models" (404, mis. Anthropic)
|
|
13
|
+
* dan dari jaringan mati (tak ada respons sama sekali). Pemanggil JANGAN
|
|
14
|
+
* menutupi ini dengan fallback model — laporkan unauthorized dengan jujur.
|
|
15
|
+
*/
|
|
16
|
+
authFailed: boolean
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Cache in-memory per baseUrl (30 menit) — /sync yang sering dipanggil tidak
|
|
20
|
+
// perlu re-deteksi network tiap kali. Key = url tanpa apiKey (secrets tidak
|
|
21
|
+
// pernah disimpan atau di-log).
|
|
22
|
+
const cache = new Map<string, { at: number; result: DetectResult }>()
|
|
23
|
+
const CACHE_TTL_MS = 30 * 60 * 1000
|
|
24
|
+
|
|
25
|
+
export function clearDetectCache(): void {
|
|
26
|
+
cache.clear()
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function cacheKey(baseUrl: string): string {
|
|
30
|
+
return baseUrl.replace(/\/+$/, "").toLowerCase()
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function hybridHeaders(apiKey: string): Record<string, string>[] {
|
|
34
|
+
if (!apiKey) return [{}]
|
|
35
|
+
// hybrid: coba Bearer dan x-api-key
|
|
36
|
+
return [
|
|
37
|
+
{ Authorization: `Bearer ${apiKey}`, "x-api-key": apiKey },
|
|
38
|
+
{ Authorization: `Bearer ${apiKey}` },
|
|
39
|
+
{ "x-api-key": apiKey },
|
|
40
|
+
]
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function tryFetchModels(
|
|
44
|
+
baseUrl: string,
|
|
45
|
+
headers: Record<string, string>,
|
|
46
|
+
signal: AbortSignal,
|
|
47
|
+
): Promise<{ models: string[] | null; contacted: boolean; sawAuth: boolean }> {
|
|
48
|
+
const urls = [`${baseUrl.replace(/\/+$/, "")}/models`, `${baseUrl.replace(/\/+$/, "")}/v1/models`]
|
|
49
|
+
let contacted = false
|
|
50
|
+
let sawAuth = false
|
|
51
|
+
for (const url of urls) {
|
|
52
|
+
// timeout PER-ATTEMPT: satu fetch yang menggantung tidak memakan seluruh
|
|
53
|
+
// budget sinyal luar — kombinasi via AbortSignal.any.
|
|
54
|
+
const perAttempt = AbortSignal.timeout(LIMITS.DETECT_ATTEMPT_TIMEOUT_MS)
|
|
55
|
+
const attemptSignal = signal ? AbortSignal.any([signal, perAttempt]) : perAttempt
|
|
56
|
+
try {
|
|
57
|
+
const res = await fetch(url, { headers, signal: attemptSignal })
|
|
58
|
+
contacted = true // server menjawab (walau 404) — bukan jaringan mati
|
|
59
|
+
// 401/403 = key salah, BUKAN "tanpa endpoint": catat agar pemanggil
|
|
60
|
+
// tak menutupinya dengan fallback model (yang membuat key salah
|
|
61
|
+
// terlihat sukses tersimpan).
|
|
62
|
+
if (res.status === 401 || res.status === 403) sawAuth = true
|
|
63
|
+
if (!res.ok) continue
|
|
64
|
+
const json = (await res.json()) as { data?: { id: string }[]; models?: { id: string }[] }
|
|
65
|
+
const data = json.data ?? json.models ?? []
|
|
66
|
+
if (Array.isArray(data) && data.length)
|
|
67
|
+
return { models: data.map((m) => m.id).filter(Boolean), contacted, sawAuth }
|
|
68
|
+
// anthropic format: {data: [{id, display_name}]}
|
|
69
|
+
if (Array.isArray((json as unknown as { models: unknown }).models)) {
|
|
70
|
+
return {
|
|
71
|
+
models: (json as unknown as { models: { id: string }[] }).models.map((m) => m.id),
|
|
72
|
+
contacted,
|
|
73
|
+
sawAuth,
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
} catch {}
|
|
77
|
+
}
|
|
78
|
+
return { models: null, contacted, sawAuth }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function detectModels(
|
|
82
|
+
baseUrl: string,
|
|
83
|
+
apiKey: string,
|
|
84
|
+
signal?: AbortSignal,
|
|
85
|
+
): Promise<DetectResult> {
|
|
86
|
+
// serve dari cache bila masih segar (anti request redundant dalam 30 menit)
|
|
87
|
+
const key = cacheKey(baseUrl)
|
|
88
|
+
const hit = cache.get(key)
|
|
89
|
+
if (hit && Date.now() - hit.at < CACHE_TTL_MS) return hit.result
|
|
90
|
+
|
|
91
|
+
// CAP global — jangan pernah biarkan user menunggu lama pada gateway offline
|
|
92
|
+
const sig = signal ?? AbortSignal.timeout(LIMITS.DETECT_GLOBAL_TIMEOUT_MS)
|
|
93
|
+
let everContacted = false
|
|
94
|
+
let everAuthFailed = false
|
|
95
|
+
for (const h of hybridHeaders(apiKey)) {
|
|
96
|
+
if (sig.aborted) break
|
|
97
|
+
const { models, contacted, sawAuth } = await tryFetchModels(baseUrl, h, sig)
|
|
98
|
+
everContacted = everContacted || contacted
|
|
99
|
+
everAuthFailed = everAuthFailed || sawAuth
|
|
100
|
+
if (models?.length) {
|
|
101
|
+
// P11 P1.4 — wire dari probe, bukan substring URL semata: path
|
|
102
|
+
// /responses berarti endpoint Responses API (previous_response_id).
|
|
103
|
+
// Substring host (anthropic) tetap dipakai hanya sebagai fallback
|
|
104
|
+
// terakhir, bukan penentu utama. Bandingkan pada bentuk lowercase
|
|
105
|
+
// (temuan audit #03: baseUrl mentah membuat host kapital lolos).
|
|
106
|
+
const path = baseUrl.toLowerCase()
|
|
107
|
+
const hint = path.includes("/responses")
|
|
108
|
+
? "responses"
|
|
109
|
+
: path.includes("anthropic")
|
|
110
|
+
? "anthropic"
|
|
111
|
+
: "openai"
|
|
112
|
+
const result = {
|
|
113
|
+
models,
|
|
114
|
+
providerHint: hint as DetectResult["providerHint"],
|
|
115
|
+
authFailed: everAuthFailed,
|
|
116
|
+
}
|
|
117
|
+
cache.set(key, { at: Date.now(), result })
|
|
118
|
+
return result
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
// Tak satu pun attempt mendapat respons HTTP = jaringan mati, bukan
|
|
122
|
+
// "provider tanpa model" (Anthropic menjawab 404 tapi tetap kontak).
|
|
123
|
+
// Lempar agar /sync mencatat failed, bukan diam.
|
|
124
|
+
if (!everContacted) throw new Error(`unreachable: ${baseUrl}`)
|
|
125
|
+
return { models: [], providerHint: "unknown", authFailed: everAuthFailed }
|
|
126
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// Kemampuan thinking per KELUARGA model + fail-soft universal.
|
|
2
|
+
//
|
|
3
|
+
// Kondisi lapangan (bukan asumsi): effort low/medium/high hanya bermakna
|
|
4
|
+
// untuk keluarga reasoning yang terbukti; tiap keluarga beda param wire
|
|
5
|
+
// (OpenAI reasoning_effort string, Anthropic budget/adaptive); sisanya
|
|
6
|
+
// (DeepSeek, Gemini, Groq, Ollama, free-tier, custom gateway) TAK PUNYA
|
|
7
|
+
// konsep ini — dikirimi param = diabaikan atau 4xx/5xx. Default universal
|
|
8
|
+
// = omit (tanpa param): default bawaan tiap model sudah di-tune vendornya.
|
|
9
|
+
//
|
|
10
|
+
// Karena daftar 650+ model berubah tiap minggu dan provider baru tak punya
|
|
11
|
+
// metadata kapabilitas, kebenaran TIDAK digantungkan ke daftar: keluarga
|
|
12
|
+
// (stabil tahunan) mengatur APA yang dikirim, fail-soft menutup sisanya.
|
|
13
|
+
import { abortError, ProviderError } from "#minicore/core/errors.ts"
|
|
14
|
+
import type { ModelProvider } from "#minicore/core/provider.ts"
|
|
15
|
+
|
|
16
|
+
export type ThinkingFamily = "openai-reasoning" | "claude-legacy" | "claude-adaptive" | "none"
|
|
17
|
+
|
|
18
|
+
export type EffortLevel = "low" | "medium" | "high"
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Keluarga thinking dari id model. Heuristik prefix/versi, bukan daftar
|
|
22
|
+
* model (daftar membusuk tiap minggu; keluarga stabil tahunan).
|
|
23
|
+
*/
|
|
24
|
+
export function thinkingFamily(modelId: string): ThinkingFamily {
|
|
25
|
+
const m = modelId.toLowerCase()
|
|
26
|
+
// OpenAI reasoning: o-series + gpt-5/6 (reasoning_effort).
|
|
27
|
+
if (/^(o1|o3|o4|gpt-5|gpt-6)([-._]|$)/.test(m)) return "openai-reasoning"
|
|
28
|
+
if (m.startsWith("claude-")) {
|
|
29
|
+
// Format versi beda era: "claude-3-7-sonnet-..." vs "claude-sonnet-4-5".
|
|
30
|
+
const nums = m
|
|
31
|
+
.split(/[-._]/)
|
|
32
|
+
.slice(1)
|
|
33
|
+
.filter((p) => /^\d+$/.test(p))
|
|
34
|
+
.map(Number)
|
|
35
|
+
const major = nums[0]
|
|
36
|
+
const minor = nums[1]
|
|
37
|
+
if (major === 3) return minor === 7 ? "claude-legacy" : "none"
|
|
38
|
+
if (major === 4) return minor != null && minor >= 6 ? "claude-adaptive" : "claude-legacy"
|
|
39
|
+
if (major != null && major >= 5) return "claude-adaptive"
|
|
40
|
+
// Nama non-numerik (mythos-preview): arah vendor = adaptive.
|
|
41
|
+
if (major == null) return "claude-adaptive"
|
|
42
|
+
return "none"
|
|
43
|
+
}
|
|
44
|
+
return "none"
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Level effort yang BOLEH ditawarkan/dikirim untuk model ini.
|
|
49
|
+
* Truth-table ringkas riset lapangan (OpenAI): pro=hanya high; sisanya
|
|
50
|
+
* low/med/high. Keluarga lain: full knob (dipetakan native di adapter).
|
|
51
|
+
* "none" → [] (tak pernah dikirimi param thinking, titik).
|
|
52
|
+
*/
|
|
53
|
+
export function allowedEfforts(modelId: string): EffortLevel[] {
|
|
54
|
+
const family = thinkingFamily(modelId)
|
|
55
|
+
if (family === "none") return []
|
|
56
|
+
if (family === "openai-reasoning" && /gpt-5-pro/.test(modelId.toLowerCase())) return ["high"]
|
|
57
|
+
return ["low", "medium", "high"]
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Opsi picker: selalu diawali "default" (= omit, tanpa param). */
|
|
61
|
+
export function effortOptionsForModel(modelId: string): ("default" | EffortLevel)[] {
|
|
62
|
+
return ["default", ...allowedEfforts(modelId)]
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Ingatan strip per provider::model selama proses: model yang pernah
|
|
66
|
+
// menolak param (400 deterministik) langsung tanpa param di turn berikut.
|
|
67
|
+
// 500 TIDAK diingat (bisa transien). Reset saat proses restart.
|
|
68
|
+
const strippedModels = new Set<string>()
|
|
69
|
+
|
|
70
|
+
/** Reset ingatan strip (test saja). */
|
|
71
|
+
export function __resetEffortMemoryForTest(): void {
|
|
72
|
+
strippedModels.clear()
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const STRIP_TRIGGER: ReadonlySet<string> = new Set(["invalid_request", "server"])
|
|
76
|
+
|
|
77
|
+
export interface StrippedRetryOptions {
|
|
78
|
+
providerId: string
|
|
79
|
+
/**
|
|
80
|
+
* Lewati primary untuk model ini (mis. keluarga yang pasti tak mendukung)
|
|
81
|
+
* — langsung ke fallback tanpa request sia-sia.
|
|
82
|
+
*/
|
|
83
|
+
skipPrimary?: (model: string) => boolean
|
|
84
|
+
/** Kategori yang memicu ulangi-tanpa-param. Default: invalid_request+server. */
|
|
85
|
+
triggerCategories?: ReadonlySet<string>
|
|
86
|
+
/** Dipanggil tepat sebelum fallback (observability; default: diam). */
|
|
87
|
+
onStrip?: (info: { model: string; category: string }) => void
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Inti fail-soft GENERIK: ulangi request sekali via fallback bila primary
|
|
92
|
+
* menolak dengan kategori pemicu. Dipakai effort hari ini; param wire
|
|
93
|
+
* berikutnya (verbosity, dsb.) tinggal pakai tanpa kode baru.
|
|
94
|
+
* - Abort tak pernah ditelan. Kategori lain diteruskan apa adanya.
|
|
95
|
+
* - 400 (invalid_request) deterministik → diingat; 500 mungkin transien.
|
|
96
|
+
*/
|
|
97
|
+
export function withStrippedRetry(
|
|
98
|
+
primary: ModelProvider,
|
|
99
|
+
fallback: ModelProvider,
|
|
100
|
+
opts: StrippedRetryOptions,
|
|
101
|
+
): ModelProvider {
|
|
102
|
+
const trigger = opts.triggerCategories ?? STRIP_TRIGGER
|
|
103
|
+
return {
|
|
104
|
+
id: primary.id,
|
|
105
|
+
get models() {
|
|
106
|
+
return primary.models
|
|
107
|
+
},
|
|
108
|
+
async *stream(request, signal) {
|
|
109
|
+
if (signal.aborted) throw abortError(signal)
|
|
110
|
+
const model = request.model ?? ""
|
|
111
|
+
const key = `${opts.providerId}::${model}`
|
|
112
|
+
if (strippedModels.has(key) || opts.skipPrimary?.(model)) {
|
|
113
|
+
yield* fallback.stream(request, signal)
|
|
114
|
+
return
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
yield* primary.stream(request, signal)
|
|
118
|
+
return
|
|
119
|
+
} catch (e) {
|
|
120
|
+
if (signal.aborted) throw e
|
|
121
|
+
if (e instanceof ProviderError && trigger.has(e.category)) {
|
|
122
|
+
if (e.category === "invalid_request") strippedModels.add(key)
|
|
123
|
+
try {
|
|
124
|
+
opts.onStrip?.({ model: key || "model", category: e.category })
|
|
125
|
+
} catch {}
|
|
126
|
+
yield* fallback.stream(request, signal)
|
|
127
|
+
return
|
|
128
|
+
}
|
|
129
|
+
throw e
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Bungkus provider ber-effort dengan kembaran tanpa-effort. Dua lapis:
|
|
137
|
+
* 1. `shouldSend(model)` false → langsung tanpa effort (tanpa request
|
|
138
|
+
* sia-sia; untuk keluarga yang pasti tak mendukung).
|
|
139
|
+
* 2. 400/500 saat param thinking terkirim = param ditolak → ulangi sekali
|
|
140
|
+
* tanpa param. 400 deterministik diingat per provider::model; 500
|
|
141
|
+
* mungkin transien → tanpa ingatan.
|
|
142
|
+
* Kategori lain (auth/network/rate_limit/budget) diteruskan apa adanya —
|
|
143
|
+
* bukan penolakan param. Abort tak pernah ditelan.
|
|
144
|
+
*/
|
|
145
|
+
export function withEffortFallback(
|
|
146
|
+
primary: ModelProvider,
|
|
147
|
+
fallback: ModelProvider,
|
|
148
|
+
opts: {
|
|
149
|
+
providerId: string
|
|
150
|
+
effort: string
|
|
151
|
+
shouldSend?: (model: string) => boolean
|
|
152
|
+
},
|
|
153
|
+
): ModelProvider {
|
|
154
|
+
return withStrippedRetry(primary, fallback, {
|
|
155
|
+
providerId: opts.providerId,
|
|
156
|
+
skipPrimary: opts.shouldSend ? (model) => !opts.shouldSend!(model) : undefined,
|
|
157
|
+
onStrip: ({ model }) => {
|
|
158
|
+
try {
|
|
159
|
+
process.stderr.write(
|
|
160
|
+
`[thinking] effort ${opts.effort} unsupported by ${model} — retrying without it\n`,
|
|
161
|
+
)
|
|
162
|
+
} catch {}
|
|
163
|
+
},
|
|
164
|
+
})
|
|
165
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// Penjaga stream provider (F-11 timeout, F-16 text-cap).
|
|
2
|
+
//
|
|
3
|
+
// Dua lubang yang ditutup di SATU titik (buildProviderList) sehingga berlaku
|
|
4
|
+
// untuk SEMUA adapter termasuk vendor openai-compat yang tak boleh disentuh:
|
|
5
|
+
// 1. Tanpa fetch timeout, server hung = turn hung sampai timeout turn.
|
|
6
|
+
// 2. Akumulasi `text` provider tanpa cap = OOM pada stream raksasa.
|
|
7
|
+
//
|
|
8
|
+
// Bentuk wrapper meniru pola withStrippedRetry, DITAMBAH preservasi properti
|
|
9
|
+
// (`...provider`: kind untuk router, clearResponsesChain untuk responses).
|
|
10
|
+
// Abort parent diteruskan apa adanya (tak pernah ditelan/dikonversi); hanya
|
|
11
|
+
// timeout MILIK guard yang diklasifikasikan ulang menjadi ProviderError
|
|
12
|
+
// "server" agar tak dikira network-putus atau abort-user.
|
|
13
|
+
import { abortError, ProviderError } from "#minicore/core/errors.ts"
|
|
14
|
+
import type { ModelProvider, ProviderEvent, StreamRequest } from "#minicore/core/provider.ts"
|
|
15
|
+
import { LIMITS } from "../constants.ts"
|
|
16
|
+
|
|
17
|
+
export function withStreamGuards(
|
|
18
|
+
provider: ModelProvider,
|
|
19
|
+
opts: { timeoutMs?: number; maxTextChars?: number; maxReasonChars?: number } = {},
|
|
20
|
+
): ModelProvider {
|
|
21
|
+
const timeoutMs = opts.timeoutMs ?? LIMITS.PROVIDER_REQUEST_TIMEOUT_MS
|
|
22
|
+
const maxTextChars = opts.maxTextChars ?? LIMITS.PROVIDER_TEXT_MAX_CHARS
|
|
23
|
+
// Reasoning = bukan bagian jawaban; cap agresif (2MB logis ≈ 500k token —
|
|
24
|
+
// jauh di atas reasoning sah mana pun, jauh di bawah OOM).
|
|
25
|
+
const maxReasonChars = opts.maxReasonChars ?? LIMITS.PROVIDER_REASON_MAX_CHARS
|
|
26
|
+
return {
|
|
27
|
+
...provider,
|
|
28
|
+
id: provider.id,
|
|
29
|
+
get models() {
|
|
30
|
+
return provider.models
|
|
31
|
+
},
|
|
32
|
+
async *stream(request: StreamRequest, signal: AbortSignal): AsyncIterable<ProviderEvent> {
|
|
33
|
+
if (signal.aborted) throw abortError(signal)
|
|
34
|
+
const ctl = new AbortController()
|
|
35
|
+
const onParentAbort = () => ctl.abort(signal.reason)
|
|
36
|
+
if (signal.aborted) ctl.abort(signal.reason)
|
|
37
|
+
else signal.addEventListener("abort", onParentAbort, { once: true })
|
|
38
|
+
const timer = setTimeout(
|
|
39
|
+
() => ctl.abort(new Error(`provider request timed out after ${timeoutMs}ms`)),
|
|
40
|
+
timeoutMs,
|
|
41
|
+
)
|
|
42
|
+
// Jangan menahan exit proses bila turn sudah selesai dari sisi lain.
|
|
43
|
+
;(timer as unknown as { unref?: () => void }).unref?.()
|
|
44
|
+
let timedOut = false
|
|
45
|
+
const onLinkedAbort = () => {
|
|
46
|
+
if (!signal.aborted) timedOut = true
|
|
47
|
+
}
|
|
48
|
+
ctl.signal.addEventListener("abort", onLinkedAbort, { once: true })
|
|
49
|
+
let textChars = 0
|
|
50
|
+
let reasonChars = 0
|
|
51
|
+
let marked = false
|
|
52
|
+
let reasonMarked = false
|
|
53
|
+
try {
|
|
54
|
+
for await (const ev of provider.stream(request, ctl.signal)) {
|
|
55
|
+
// F-16 diperluas (investigasi Phase 5): extension "reasoning" juga
|
|
56
|
+
// diakumulasi kernel (loop `reasoning += ev.data.text` TANPA cap) —
|
|
57
|
+
// dulu hanya ev.type "text" yang dipotong, sehingga reasoning stream
|
|
58
|
+
// adalah satu-satunya jalur akumulasi tak terbatas (terbukti probe
|
|
59
|
+
// E-2: 200MB+ chars, heap tumbuh, tanpa cap). Cap terpisah karena
|
|
60
|
+
// reasoning bukan bagian jawaban — boleh dipotong agresif tanpa
|
|
61
|
+
// merusak konten hasil.
|
|
62
|
+
if (ev.type === "text" && typeof ev.text === "string" && ev.text) {
|
|
63
|
+
if (textChars >= maxTextChars) continue
|
|
64
|
+
textChars += ev.text.length
|
|
65
|
+
if (textChars > maxTextChars) {
|
|
66
|
+
const keep = ev.text.slice(0, ev.text.length - (textChars - maxTextChars))
|
|
67
|
+
if (keep) yield { type: "text", text: keep }
|
|
68
|
+
if (!marked) {
|
|
69
|
+
marked = true
|
|
70
|
+
yield { type: "text", text: "\n… [provider text truncated: turn cap exceeded]" }
|
|
71
|
+
}
|
|
72
|
+
continue
|
|
73
|
+
}
|
|
74
|
+
} else if (ev.type === "extension" && ev.kind === "reasoning") {
|
|
75
|
+
const d = ev.data as { text?: unknown } | undefined
|
|
76
|
+
if (typeof d?.text === "string" && d.text) {
|
|
77
|
+
if (reasonChars >= maxReasonChars) continue
|
|
78
|
+
reasonChars += d.text.length
|
|
79
|
+
if (reasonChars > maxReasonChars) {
|
|
80
|
+
const keep = d.text.slice(0, d.text.length - (reasonChars - maxReasonChars))
|
|
81
|
+
if (keep) yield { type: "extension", kind: "reasoning", data: { text: keep } }
|
|
82
|
+
if (!reasonMarked) {
|
|
83
|
+
reasonMarked = true
|
|
84
|
+
yield {
|
|
85
|
+
type: "extension",
|
|
86
|
+
kind: "reasoning",
|
|
87
|
+
data: { text: "\n… [reasoning truncated: cap exceeded]" },
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
continue
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
yield ev
|
|
95
|
+
}
|
|
96
|
+
} catch (e) {
|
|
97
|
+
if (timedOut)
|
|
98
|
+
throw new ProviderError("server", `provider request timed out after ${timeoutMs}ms`)
|
|
99
|
+
throw e
|
|
100
|
+
} finally {
|
|
101
|
+
clearTimeout(timer)
|
|
102
|
+
signal.removeEventListener("abort", onParentAbort)
|
|
103
|
+
ctl.signal.removeEventListener("abort", onLinkedAbort)
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
}
|
|
107
|
+
}
|