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,24 @@
|
|
|
1
|
+
// Satu sumber state "level detail tool call": expanded vs compact.
|
|
2
|
+
//
|
|
3
|
+
// Posisi Minicode = agentic Unix shell: tool call transparan di aliran output.
|
|
4
|
+
// Default tergantung konteks: one-shot/exec = expanded; REPL interaktif
|
|
5
|
+
// mengaktifkan compact saat start (lihat runRepl) kecuali env diset eksplisit.
|
|
6
|
+
// `MINICODE_COMPACT=1`/`0` atau `/compact` selalu menang. Getter — jangan simpan
|
|
7
|
+
// `detail.compact` ke const di module scope; baca saat pakai supaya perubahan
|
|
8
|
+
// env (mis. /compact) langsung berlaku.
|
|
9
|
+
export const detail = {
|
|
10
|
+
get compact(): boolean {
|
|
11
|
+
return process.env.MINICODE_COMPACT === "1"
|
|
12
|
+
},
|
|
13
|
+
set compact(v: boolean) {
|
|
14
|
+
process.env.MINICODE_COMPACT = v ? "1" : "0"
|
|
15
|
+
},
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Set eksplisit (on/off) atau toggle bila `next` tidak diberikan. */
|
|
19
|
+
export function setCompactMode(next?: boolean): boolean {
|
|
20
|
+
const cur = detail.compact
|
|
21
|
+
const nextVal = next ?? !cur
|
|
22
|
+
detail.compact = nextVal
|
|
23
|
+
return nextVal
|
|
24
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Diff renderer - Ubuntu Server style: indentasi + warna, tanpa border.
|
|
2
|
+
import { c } from "./theme.ts"
|
|
3
|
+
import { truncateToWidth } from "./width.ts"
|
|
4
|
+
|
|
5
|
+
export interface DiffLine {
|
|
6
|
+
type: "add" | "delete" | "context"
|
|
7
|
+
oldLine?: number
|
|
8
|
+
newLine?: number
|
|
9
|
+
content: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Diff baris heuristik O(n·m) tanpa alokasi slice per langkah (dulu
|
|
14
|
+
* `slice(i).includes(...)` yang meng-copy sisa array tiap iterasi).
|
|
15
|
+
*
|
|
16
|
+
* Aturan dua sisi: bila baris baru tak ada di sisa lama → add; bila baris
|
|
17
|
+
* lama tak ada di sisa baru → delete; bila KEDUANYA muncul di sisi lain
|
|
18
|
+
* (reorder ambigu, mis. lama `[a,b]` vs baru `[b,a,b]`) → dahulukan add agar
|
|
19
|
+
* baris lama tetap tersedia untuk match berikut (3 op, bukan 4).
|
|
20
|
+
* Cukup untuk diff card edit/apply_patch (DIFF_MAX_LINES=24) — TIDAK untuk
|
|
21
|
+
* file besar (>2000 baris); Myers tetap tidak dibutuhkan di sini.
|
|
22
|
+
*/
|
|
23
|
+
export function computeLineDiff(oldText: string, newText: string): DiffLine[] {
|
|
24
|
+
const oldLines = oldText.split("\n")
|
|
25
|
+
const newLines = newText.split("\n")
|
|
26
|
+
const result: DiffLine[] = []
|
|
27
|
+
let i = 0,
|
|
28
|
+
j = 0,
|
|
29
|
+
oldNum = 1,
|
|
30
|
+
newNum = 1
|
|
31
|
+
|
|
32
|
+
// indexOf dari posisi (tanpa slice) — O(n) tanpa alokasi per langkah.
|
|
33
|
+
const oldHasFrom = (s: string, from: number): boolean => oldLines.indexOf(s, from) !== -1
|
|
34
|
+
const newHasFrom = (s: string, from: number): boolean => newLines.indexOf(s, from) !== -1
|
|
35
|
+
|
|
36
|
+
while (i < oldLines.length || j < newLines.length) {
|
|
37
|
+
if (i < oldLines.length && j < newLines.length && oldLines[i] === newLines[j]) {
|
|
38
|
+
result.push({ type: "context", content: oldLines[i]! })
|
|
39
|
+
i++
|
|
40
|
+
j++
|
|
41
|
+
} else if (j < newLines.length && (i >= oldLines.length || !oldHasFrom(newLines[j]!, i))) {
|
|
42
|
+
result.push({ type: "add", newLine: newNum++, content: newLines[j]! })
|
|
43
|
+
j++
|
|
44
|
+
} else if (i < oldLines.length && (j >= newLines.length || !newHasFrom(oldLines[i]!, j))) {
|
|
45
|
+
result.push({ type: "delete", oldLine: oldNum++, content: oldLines[i]! })
|
|
46
|
+
i++
|
|
47
|
+
} else if (j < newLines.length) {
|
|
48
|
+
// Reorder ambigu: keduanya ada di sisi lain — add dulu.
|
|
49
|
+
result.push({ type: "add", newLine: newNum++, content: newLines[j]! })
|
|
50
|
+
j++
|
|
51
|
+
} else {
|
|
52
|
+
result.push({ type: "delete", oldLine: oldNum++, content: oldLines[i]! })
|
|
53
|
+
i++
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return result
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ── Sorot kata berubah ──
|
|
60
|
+
// Baris add/delete yang berpasangan (pola hunk unified: run delete lalu run
|
|
61
|
+
// add) dibedakan per KATA, bukan sebaris penuh — mata langsung ke token yang
|
|
62
|
+
// berubah. LCS DP kecil: baris kode pendek sehingga O(kata^2) per pasangan
|
|
63
|
+
// tidak terasa; cap baris global tetap DIFF_MAX_LINES.
|
|
64
|
+
const tokenizeWords = (s: string): string[] => s.split(/(\s+)/).filter((t) => t !== "")
|
|
65
|
+
|
|
66
|
+
/** Masker token yang berubah dari LCS dua baris (true = beda). Diekspor untuk test. */
|
|
67
|
+
export function markChangedWords(
|
|
68
|
+
oldLine: string,
|
|
69
|
+
newLine: string,
|
|
70
|
+
): { oldMask: boolean[]; newMask: boolean[] } {
|
|
71
|
+
const a = tokenizeWords(oldLine)
|
|
72
|
+
const b = tokenizeWords(newLine)
|
|
73
|
+
const n = a.length
|
|
74
|
+
const m = b.length
|
|
75
|
+
const dp: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0))
|
|
76
|
+
for (let i = n - 1; i >= 0; i--)
|
|
77
|
+
for (let j = m - 1; j >= 0; j--)
|
|
78
|
+
dp[i]![j] = a[i] === b[j] ? dp[i + 1]![j + 1]! + 1 : Math.max(dp[i + 1]![j]!, dp[i]![j + 1]!)
|
|
79
|
+
const oldMask = new Array<boolean>(n).fill(true)
|
|
80
|
+
const newMask = new Array<boolean>(m).fill(true)
|
|
81
|
+
let i = 0
|
|
82
|
+
let j = 0
|
|
83
|
+
while (i < n && j < m) {
|
|
84
|
+
if (a[i] === b[j]) {
|
|
85
|
+
oldMask[i] = false
|
|
86
|
+
newMask[j] = false
|
|
87
|
+
i++
|
|
88
|
+
j++
|
|
89
|
+
} else if (dp[i + 1]![j]! >= dp[i]![j + 1]!) i++
|
|
90
|
+
else j++
|
|
91
|
+
}
|
|
92
|
+
return { oldMask, newMask }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const paintWords = (text: string, mask: boolean[], paint: (s: string) => string): string => {
|
|
96
|
+
const toks = tokenizeWords(text)
|
|
97
|
+
// Bila hampir semua token beda, bold semuanya = noise — tampilkan polos.
|
|
98
|
+
const changed = mask.filter(Boolean).length
|
|
99
|
+
if (toks.length === 0 || changed / toks.length > 0.6) return text
|
|
100
|
+
return toks.map((t, k) => (mask[k] ? paint(t) : t)).join("")
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Render diff with 1 line context around changes
|
|
104
|
+
export function renderDiffCard(
|
|
105
|
+
filePath: string,
|
|
106
|
+
oldText: string,
|
|
107
|
+
newText: string,
|
|
108
|
+
opts: { maxLines?: number; width?: number } = {},
|
|
109
|
+
): string {
|
|
110
|
+
const diff = computeLineDiff(oldText, newText)
|
|
111
|
+
const changes = diff.filter((d) => d.type !== "context")
|
|
112
|
+
if (changes.length === 0) return c.muted(" (no changes)")
|
|
113
|
+
// Pasangan del/add untuk sorot kata: kelompokkan run perubahan beruntun,
|
|
114
|
+
// pasangkan del ke-i dengan add ke-i (pola hunk unified).
|
|
115
|
+
const wordMask = new Map<number, boolean[]>()
|
|
116
|
+
{
|
|
117
|
+
let i = 0
|
|
118
|
+
while (i < diff.length) {
|
|
119
|
+
if (diff[i]!.type === "context") {
|
|
120
|
+
i++
|
|
121
|
+
continue
|
|
122
|
+
}
|
|
123
|
+
const dels: number[] = []
|
|
124
|
+
const adds: number[] = []
|
|
125
|
+
while (i < diff.length && diff[i]!.type !== "context") {
|
|
126
|
+
if (diff[i]!.type === "delete") dels.push(i)
|
|
127
|
+
else adds.push(i)
|
|
128
|
+
i++
|
|
129
|
+
}
|
|
130
|
+
const n = Math.min(dels.length, adds.length)
|
|
131
|
+
for (let k = 0; k < n; k++) {
|
|
132
|
+
const { oldMask, newMask } = markChangedWords(
|
|
133
|
+
diff[dels[k]!]!.content,
|
|
134
|
+
diff[adds[k]!]!.content,
|
|
135
|
+
)
|
|
136
|
+
wordMask.set(dels[k]!, oldMask)
|
|
137
|
+
wordMask.set(adds[k]!, newMask)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const max = opts.maxLines ?? 12
|
|
143
|
+
// Baris diff bisa sepanjang baris kode aslinya. Tanpa batas, satu baris 300
|
|
144
|
+
// karakter membungkus sendiri di terminal dan merusak frame TUI yang
|
|
145
|
+
// menghitung tinggi per baris. Default mengikuti lebar terminal.
|
|
146
|
+
const width = opts.width ?? (process.stdout.columns || 80)
|
|
147
|
+
const cut = (s: string) => truncateToWidth(s, Math.max(8, width - 1))
|
|
148
|
+
|
|
149
|
+
const lines: string[] = [c.accent(c.bold(cut(` ${filePath}`)))]
|
|
150
|
+
// collect indices of changes plus 1 context line before/after
|
|
151
|
+
const include = new Set<number>()
|
|
152
|
+
diff.forEach((d, i) => {
|
|
153
|
+
if (d.type !== "context") {
|
|
154
|
+
include.add(i)
|
|
155
|
+
if (i > 0 && diff[i - 1]?.type === "context") include.add(i - 1)
|
|
156
|
+
if (i + 1 < diff.length && diff[i + 1]?.type === "context") include.add(i + 1)
|
|
157
|
+
}
|
|
158
|
+
})
|
|
159
|
+
let count = 0
|
|
160
|
+
for (let i = 0; i < diff.length; i++) {
|
|
161
|
+
if (!include.has(i)) continue
|
|
162
|
+
if (count >= max) {
|
|
163
|
+
const added = changes.filter((d) => d.type === "add").length
|
|
164
|
+
const removed = changes.filter((d) => d.type === "delete").length
|
|
165
|
+
lines.push(c.muted(` ... (+${added} \u2212${removed})`))
|
|
166
|
+
break
|
|
167
|
+
}
|
|
168
|
+
const d = diff[i]!
|
|
169
|
+
if (d.type === "add") {
|
|
170
|
+
const mask = wordMask.get(i)
|
|
171
|
+
const body = mask ? paintWords(d.content, mask, (s) => c.bold(s)) : d.content
|
|
172
|
+
lines.push(c.success(cut(` + ${body}`)))
|
|
173
|
+
} else if (d.type === "delete") {
|
|
174
|
+
const mask = wordMask.get(i)
|
|
175
|
+
const body = mask ? paintWords(d.content, mask, (s) => c.bold(s)) : d.content
|
|
176
|
+
lines.push(c.error(cut(` - ${body}`)))
|
|
177
|
+
} else lines.push(c.dim(cut(` ${d.content}`)))
|
|
178
|
+
count++
|
|
179
|
+
}
|
|
180
|
+
return lines.join("\n")
|
|
181
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// Pemetaan error provider/agent → pesan yang bisa ditindaklanjuti.
|
|
2
|
+
//
|
|
3
|
+
// PENTING: modul ini punya 10 test tapi dulu TIDAK dipanggil dari mana pun di
|
|
4
|
+
// kode produksi. Renderer memakai formatProviderError() yang mencetak
|
|
5
|
+
// `[kategori] <pesan mentah>`, sehingga body JSON provider tumpah utuh ke layar.
|
|
6
|
+
// Terlihat pada uji live OpenRouter: satu error 429 mencetak 400+ karakter
|
|
7
|
+
// berisi `metadata`, `provider_error_code`, `limit_source`, dan URL dokumentasi
|
|
8
|
+
// — di dalam frame TUI selebar 100 kolom.
|
|
9
|
+
|
|
10
|
+
export interface FriendlyError {
|
|
11
|
+
message: string
|
|
12
|
+
fix?: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Ambil kalimat paling berguna dari body error provider.
|
|
17
|
+
*
|
|
18
|
+
* Bentuk yang ditemui di lapangan:
|
|
19
|
+
* - OpenAI/umum : {"error":{"message":"..."}}
|
|
20
|
+
* - OpenRouter : {"error":{"message":"Provider returned error","metadata":{"raw":"<alasan sebenarnya>","remedy_hint":"..."}}}
|
|
21
|
+
* Di sini `message` justru tidak informatif; `metadata.raw` yang menjelaskan.
|
|
22
|
+
* - Cloudflare : HTML dengan <title>host | 502: Bad gateway</title>
|
|
23
|
+
*/
|
|
24
|
+
export function extractProviderDetail(raw: string): { detail?: string; hint?: string } {
|
|
25
|
+
const trimmed = raw.trim()
|
|
26
|
+
// JSON: cari objek pertama yang bisa di-parse.
|
|
27
|
+
const start = trimmed.indexOf("{")
|
|
28
|
+
if (start !== -1) {
|
|
29
|
+
try {
|
|
30
|
+
const parsed = JSON.parse(trimmed.slice(start)) as {
|
|
31
|
+
error?: {
|
|
32
|
+
message?: string
|
|
33
|
+
metadata?: { raw?: string; remedy_hint?: string; provider_name?: string }
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const err = parsed.error
|
|
37
|
+
const meta = err?.metadata
|
|
38
|
+
// metadata.raw lebih spesifik daripada message generik OpenRouter.
|
|
39
|
+
const detail = firstSentence(meta?.raw ?? err?.message)
|
|
40
|
+
const hint = firstSentence(meta?.remedy_hint)
|
|
41
|
+
return { ...(detail ? { detail } : {}), ...(hint ? { hint } : {}) }
|
|
42
|
+
} catch {
|
|
43
|
+
// Body terpotong (streaming) — jatuh ke regex di bawah.
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
// HTML: judul halaman error biasanya sudah menjelaskan.
|
|
47
|
+
const title = /<title>([^<]{1,120})<\/title>/i.exec(trimmed)
|
|
48
|
+
if (title) return { detail: title[1]!.trim() }
|
|
49
|
+
// Regex terakhir untuk body yang TERPOTONG (stream terputus di tengah JSON).
|
|
50
|
+
// `raw` didahulukan: pada OpenRouter itu yang memuat alasan sebenarnya,
|
|
51
|
+
// sementara `message` hanya "Provider returned error". Kutip penutup dibuat
|
|
52
|
+
// opsional — pada body terpotong ia memang belum ada.
|
|
53
|
+
for (const field of ["raw", "message"]) {
|
|
54
|
+
const re = new RegExp(`"${field}"\\s*:\\s*"((?:[^"\\\\]|\\\\.){1,300})"?`)
|
|
55
|
+
const m = re.exec(trimmed)
|
|
56
|
+
const value = m?.[1]?.replace(/\\"/g, '"').trim()
|
|
57
|
+
if (value) return { detail: firstSentence(value) }
|
|
58
|
+
}
|
|
59
|
+
return {}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Satu kalimat pertama, dipangkas — bukan paragraf berisi URL dan kode. */
|
|
63
|
+
function firstSentence(s?: string, max = 150): string | undefined {
|
|
64
|
+
if (!s) return undefined
|
|
65
|
+
const clean = s.replace(/\s+/g, " ").trim()
|
|
66
|
+
if (!clean) return undefined
|
|
67
|
+
const cut = /^(.{20,}?[.!?])\s/.exec(clean)
|
|
68
|
+
const one = cut ? cut[1]! : clean
|
|
69
|
+
return one.length > max ? `${one.slice(0, max - 1)}…` : one
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Redaksi rahasia minimal untuk jalur tampil (temuan audit #03, diperketat
|
|
74
|
+
* audit #10 §8/§10/§11).
|
|
75
|
+
*
|
|
76
|
+
* src/ui DILARANG mengimpor policy/scrub.ts (ui-boundary), jadi pola penuh
|
|
77
|
+
* tinggal di sana sebagai kanonis. Yang di sini hanya jaring pengaman untuk
|
|
78
|
+
* kasus konkret: proxy/server menggemakan kredensial ke dalam body error
|
|
79
|
+
* (mis. `Authorization: Bearer …`), yang lalu dirender verbatim oleh
|
|
80
|
+
* formatError. Bukan pengganti scrubSecrets — hanya untuk pesan error.
|
|
81
|
+
*
|
|
82
|
+
* Dua bentuk ditangani BERURUTAN (temuan audit #10, reproducer: header
|
|
83
|
+
* Authorization Bearer — sebelumnya hanya `Authorization:` yang teredaksi
|
|
84
|
+
* sebagai key=value sehingga token aslinya tetap tampil):
|
|
85
|
+
* 1. `Bearer <token>` spasi (bentuk header HTTP yang sah — tanpa `:`/`=`).
|
|
86
|
+
* 2. `key=value`/`key: value` untuk kata-kunci kredensial + cookie/session.
|
|
87
|
+
* `sessionid` dibatasi lowercase eksplisit (audit #11 §18: pola insensitif
|
|
88
|
+
* ikut menyamarkan identifier `sessionId` di pesan error).
|
|
89
|
+
* Guard nilai quoted/berdigit/panjang dipakai di kedua pola kv (audit #11
|
|
90
|
+
* §18: tanpa guard, `token: string` dan SQL `session_id = ?` ikut tersamarkan
|
|
91
|
+
* sehingga diagnostik sah buta).
|
|
92
|
+
*/
|
|
93
|
+
function redactSecrets(s: string): string {
|
|
94
|
+
// Nilai berbentuk kredensial: quoted, atau berdigit, atau panjang.
|
|
95
|
+
// Identifier/type-word (`string`, `graphemes`, `?`) lolos; token realistis kena.
|
|
96
|
+
// `=` termasuk agar nilai cookie berbentuk pasangan kunci-nilai utuh tersamarkan.
|
|
97
|
+
const V = `(?:"[^"]+"|'[^']+'|[A-Za-z0-9_~+/=-]*\\d[A-Za-z0-9_~+/=-]*|[A-Za-z0-9_~+/=-]{12,})`
|
|
98
|
+
const V4 = `(?:"[^"]+"|'[^']+'|[A-Za-z0-9_~+/=-]*\\d[A-Za-z0-9_~+/=-]*|[A-Za-z0-9_~+/=-]{4,})`
|
|
99
|
+
return s
|
|
100
|
+
.replace(/\bbearer\s+["']?[A-Za-z0-9._~+/-]{6,}["']?/gi, "Bearer [redacted]")
|
|
101
|
+
.replace(
|
|
102
|
+
new RegExp(
|
|
103
|
+
`((?:api[_-]?key|token|authorization|secret|password|client[_-]?secret|cookie)\\s*[:=]\\s*)(?!\\[redacted\\])(${V})`,
|
|
104
|
+
"gi",
|
|
105
|
+
),
|
|
106
|
+
"$1[redacted]",
|
|
107
|
+
)
|
|
108
|
+
.replace(new RegExp(`(\\bsession[-_]?id\\s*[:=]\\s*)(${V4})`, "g"), "$1[redacted]")
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Mapping kategori formal -> pesan user-friendly. Detail provider disertakan
|
|
112
|
+
// sebagai satu kalimat bila ada (itu yang memberi tahu model mana yang limit,
|
|
113
|
+
// atau tool mana yang tidak didukung) — bukan seluruh body.
|
|
114
|
+
export function friendlyFromCategory(category: string, detail: string): FriendlyError {
|
|
115
|
+
const truth = redactSecrets(detail.trim())
|
|
116
|
+
const { detail: providerDetail, hint } = extractProviderDetail(truth)
|
|
117
|
+
const withDetail = (base: string) =>
|
|
118
|
+
providerDetail && providerDetail.toLowerCase() !== base.toLowerCase()
|
|
119
|
+
? `${base}: ${providerDetail}`
|
|
120
|
+
: base
|
|
121
|
+
|
|
122
|
+
switch (category) {
|
|
123
|
+
case "rate_limit":
|
|
124
|
+
return {
|
|
125
|
+
message: withDetail("Provider is rate-limiting requests"),
|
|
126
|
+
fix: hint ?? "Wait a moment and try again, or use --ratelimit to throttle requests.",
|
|
127
|
+
}
|
|
128
|
+
case "auth": {
|
|
129
|
+
const low = truth.toLowerCase()
|
|
130
|
+
if (
|
|
131
|
+
low.includes("insufficient balance") ||
|
|
132
|
+
low.includes("credits") ||
|
|
133
|
+
low.includes("billing") ||
|
|
134
|
+
low.includes("quota") ||
|
|
135
|
+
low.includes("credit limit")
|
|
136
|
+
) {
|
|
137
|
+
return {
|
|
138
|
+
message: withDetail("API key balance or quota is exhausted"),
|
|
139
|
+
fix: hint ?? "Switch provider via /model, or top up credits.",
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
message: withDetail("Provider rejected authentication"),
|
|
144
|
+
fix: hint ?? "Check your API key, or switch provider via /model.",
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
case "server":
|
|
148
|
+
return {
|
|
149
|
+
message: withDetail("Provider is temporarily unavailable"),
|
|
150
|
+
fix: hint ?? "Wait a moment and try again, or switch provider via /model.",
|
|
151
|
+
}
|
|
152
|
+
case "network":
|
|
153
|
+
return {
|
|
154
|
+
message: withDetail("Failed to reach provider"),
|
|
155
|
+
fix: hint ?? "Check your connection and try again.",
|
|
156
|
+
}
|
|
157
|
+
case "invalid_request":
|
|
158
|
+
return {
|
|
159
|
+
message: withDetail("Request was rejected by provider"),
|
|
160
|
+
fix: hint ?? "Check the model name or select another model with /model.",
|
|
161
|
+
}
|
|
162
|
+
case "context_length_exceeded":
|
|
163
|
+
return {
|
|
164
|
+
message: withDetail("Context window exceeded"),
|
|
165
|
+
fix:
|
|
166
|
+
hint ??
|
|
167
|
+
"Start a new session (/exit then minicode), or use a model with a larger context window.",
|
|
168
|
+
}
|
|
169
|
+
case "content_filter":
|
|
170
|
+
return {
|
|
171
|
+
message: withDetail("Request was blocked by provider content filter"),
|
|
172
|
+
fix: hint ?? "Rewrite the prompt, or switch provider via /model.",
|
|
173
|
+
}
|
|
174
|
+
default: {
|
|
175
|
+
// Kategori "unknown" menampung status HTTP lain (mis. 402 dari vendor
|
|
176
|
+
// yang frozen) — kenali pola tagihan/limit dari TEKS agar pesannya
|
|
177
|
+
// tetap actionable, bukan dump mentah.
|
|
178
|
+
const low = truth.toLowerCase()
|
|
179
|
+
if (
|
|
180
|
+
low.includes("insufficient balance") ||
|
|
181
|
+
low.includes("credits") ||
|
|
182
|
+
low.includes("billing") ||
|
|
183
|
+
low.includes("quota") ||
|
|
184
|
+
low.includes("credit limit") ||
|
|
185
|
+
low.includes("requires more credits") ||
|
|
186
|
+
low.includes("fewer max_tokens")
|
|
187
|
+
) {
|
|
188
|
+
return {
|
|
189
|
+
message: withDetail("API key balance or quota is exhausted"),
|
|
190
|
+
fix: hint ?? "Switch provider via /model, or top up credits.",
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (
|
|
194
|
+
low.includes("rate limit") ||
|
|
195
|
+
low.includes("rate_limit") ||
|
|
196
|
+
low.includes("429") ||
|
|
197
|
+
low.includes("freeusagelimit") ||
|
|
198
|
+
low.includes("try again later")
|
|
199
|
+
) {
|
|
200
|
+
return {
|
|
201
|
+
message: withDetail("Provider is rate-limiting requests"),
|
|
202
|
+
fix: hint ?? "Wait a moment and try again, or use --ratelimit to throttle requests.",
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (providerDetail) return { message: providerDetail, ...(hint ? { fix: hint } : {}) }
|
|
206
|
+
const cut = truth.length > 160 ? `${truth.slice(0, 157)}…` : truth
|
|
207
|
+
return { message: cut }
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Fallback string-only (AgentError: timeout/aborted/max_steps, dst.)
|
|
213
|
+
export function friendlyError(raw: string): FriendlyError {
|
|
214
|
+
const lower = raw.toLowerCase()
|
|
215
|
+
if (lower.includes("timed out") || lower.includes("timeout"))
|
|
216
|
+
return {
|
|
217
|
+
message: "Run exceeded timeout",
|
|
218
|
+
fix: "Increase --timeout or use a faster model.",
|
|
219
|
+
}
|
|
220
|
+
if (lower.includes("max steps") || lower.includes("max_steps"))
|
|
221
|
+
return {
|
|
222
|
+
message: "Tool step limit reached",
|
|
223
|
+
fix: "Split the task into smaller prompts.",
|
|
224
|
+
}
|
|
225
|
+
if (lower.includes("budget"))
|
|
226
|
+
return { message: "Session budget exceeded", fix: "Start a new session or increase --budget." }
|
|
227
|
+
if (lower.includes("busy"))
|
|
228
|
+
return { message: "A run is still in progress", fix: "Wait for the current run to finish." }
|
|
229
|
+
if (lower.includes("aborted")) return { message: "Run was aborted" }
|
|
230
|
+
const { detail } = extractProviderDetail(raw)
|
|
231
|
+
if (detail) return { message: redactSecrets(detail) }
|
|
232
|
+
const cut = raw.length > 160 ? `${raw.slice(0, 157)}…` : raw
|
|
233
|
+
return { message: redactSecrets(cut) }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Satu baris siap tampil: pesan + saran. Dipakai renderer TUI & one-shot. */
|
|
237
|
+
export function formatFriendly(e: FriendlyError): string {
|
|
238
|
+
return e.fix ? `${e.message}\n → ${e.fix}` : e.message
|
|
239
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Formatter pesan event yang dipakai printer linier (simple.ts), sehingga
|
|
2
|
+
// "apa yang ditampilkan" konsisten antar konsumen (tidak dobel logika).
|
|
3
|
+
import type { UiToolCallRef } from "../contract.ts"
|
|
4
|
+
import { formatFriendly, friendlyFromCategory } from "./errors.ts"
|
|
5
|
+
import { formatUsd } from "./money.ts"
|
|
6
|
+
|
|
7
|
+
export function formatArgsPreview(args: unknown): string {
|
|
8
|
+
try {
|
|
9
|
+
const a = args as Record<string, unknown>
|
|
10
|
+
if (a.path) return String(a.path)
|
|
11
|
+
if (a.command) return String(a.command).slice(0, 60)
|
|
12
|
+
if (a.cmd) return String(a.cmd).slice(0, 60)
|
|
13
|
+
if (a.pattern) return String(a.pattern)
|
|
14
|
+
if (a.query) return String(a.query)
|
|
15
|
+
if (a.prompt) return String(a.prompt).slice(0, 40)
|
|
16
|
+
return JSON.stringify(a).slice(0, 40)
|
|
17
|
+
} catch {
|
|
18
|
+
return "[args]"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function formatStepCalls(calls: readonly UiToolCallRef[], argCap = 35): string {
|
|
23
|
+
return calls.map((tc) => `${tc.name}(${JSON.stringify(tc.args).slice(0, argCap)})`).join(", ")
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function formatUsage(parts: {
|
|
27
|
+
inputTokens?: number
|
|
28
|
+
outputTokens?: number
|
|
29
|
+
totalTokens?: number
|
|
30
|
+
}): string {
|
|
31
|
+
const p = [
|
|
32
|
+
parts.inputTokens != null ? `in:${parts.inputTokens}` : null,
|
|
33
|
+
parts.outputTokens != null ? `out:${parts.outputTokens}` : null,
|
|
34
|
+
parts.totalTokens != null ? `total:${parts.totalTokens}` : null,
|
|
35
|
+
].filter(Boolean) as string[]
|
|
36
|
+
return p.join(" ")
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Error provider siap tampil: kategori formal dipetakan ke pesan yang bisa
|
|
41
|
+
* ditindaklanjuti, detail provider diringkas ke satu kalimat.
|
|
42
|
+
*
|
|
43
|
+
* Sebelumnya fungsi ini mencetak `[kategori] <pesan mentah>` — body JSON
|
|
44
|
+
* provider tumpah utuh ke layar. Satu 429 dari OpenRouter menghasilkan 400+
|
|
45
|
+
* karakter berisi `metadata`, `provider_error_code`, dan URL dokumentasi.
|
|
46
|
+
*/
|
|
47
|
+
export function formatProviderError(e: { category?: string; message?: string }): string {
|
|
48
|
+
const friendly = friendlyFromCategory(e.category ?? "unknown", e.message ?? "")
|
|
49
|
+
return formatFriendly(friendly)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function formatCost(cost?: number): string {
|
|
53
|
+
return cost != null ? formatUsd(cost) : "N/A"
|
|
54
|
+
}
|