minicode-ai 0.21.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/cli/commands/exec.ts +44 -1
- package/cli/commands.ts +5 -2
- package/cli/setup.ts +24 -0
- package/docs/TERMINAL_CONTRACT.md +30 -7
- package/docs/architecture.md +9 -5
- package/docs/concepts.md +1 -1
- package/docs/contributing.md +2 -1
- package/docs/environment.md +1 -0
- package/docs/policy-sandbox.md +6 -1
- package/docs/security.md +12 -4
- package/docs/skills.md +1 -1
- package/package.json +2 -2
- package/src/config.ts +8 -6
- package/src/daemon/discovery.ts +24 -0
- package/src/policy/bash-guard.ts +170 -6
- package/src/policy/compaction.ts +34 -7
- package/src/policy/jail.ts +10 -22
- package/src/policy/permission.ts +9 -6
- package/src/presentation/projection.ts +1 -1
- package/src/providers/anthropic.ts +14 -4
- package/src/providers/responses.ts +1 -1
- package/src/providers/sse-bounds.ts +16 -2
- package/src/ui/approval/prompt.ts +17 -6
- package/src/ui/footer.ts +2 -2
- package/src/ui/i18n/en.ts +9 -1
- package/src/ui/i18n/id.ts +9 -1
- package/src/ui/input/prompt-engine.ts +6 -0
- package/src/ui/render/diff.ts +51 -2
- package/src/ui/render/highlight.ts +68 -37
- package/src/ui/render/sanitize.ts +5 -1
- package/src/ui/render/session-summary.ts +6 -4
- package/src/ui/render/table-grid.ts +123 -13
- package/src/ui/render/table.ts +4 -2
- package/src/ui/render/theme.ts +11 -3
- package/src/ui/render/width.ts +35 -6
- package/src/ui/render/wrap.ts +28 -6
- package/src/ui/runtime/loading-bar.ts +17 -5
- package/src/ui/screens/dialog.ts +23 -2
- package/src/ui/screens/form.ts +52 -10
- package/src/ui/screens/model-manager.ts +8 -2
- package/src/ui/screens/picker.ts +11 -3
- package/src/ui/screens/provider-manager.ts +11 -3
- package/src/ui/screens/wizard.ts +29 -1
- package/src/ui/tui/app.ts +57 -20
- package/src/ui/tui/transcript.ts +42 -7
- package/vendor/minicore/src/providers/openai-compat.ts +30 -1
package/src/policy/compaction.ts
CHANGED
|
@@ -280,9 +280,14 @@ function boundCompactionResult(
|
|
|
280
280
|
store: ContextStore,
|
|
281
281
|
result: readonly import("#minicore/core/types.ts").Message[],
|
|
282
282
|
keepRecentTurns: number,
|
|
283
|
-
targetTokens
|
|
283
|
+
targetTokens: number | undefined,
|
|
284
|
+
maxSummaryChars: number,
|
|
284
285
|
): readonly import("#minicore/core/types.ts").Message[] {
|
|
285
|
-
|
|
286
|
+
// R9 — pagu ringkasan mengikuti jendela (summaryCharBudgetForWindow), bukan
|
|
287
|
+
// 4k konstan. Tanpa ini ringkasan LLM untuk model berjendela raksasa
|
|
288
|
+
// (1M token) yang SUDAH diproduksi dengan budget skala 32k dipangkas ulang
|
|
289
|
+
// ke COMPACTION_SUMMARY_MAX_CHARS, sehingga fakta lama over-discard.
|
|
290
|
+
let bounded = boundSummary(result, maxSummaryChars)
|
|
286
291
|
if (targetTokens !== undefined && estimateMessages(bounded, minicodeEstimator) > targetTokens) {
|
|
287
292
|
bounded = boundedMechanical(store, Math.min(1, keepRecentTurns), targetTokens)
|
|
288
293
|
}
|
|
@@ -307,6 +312,9 @@ export function createLlmCompaction(opts: LlmCompactionOptions = {}): Compaction
|
|
|
307
312
|
? Math.floor((limit as number) * LIMITS.COMPACTION_SUMMARY_TARGET_RATIO)
|
|
308
313
|
: undefined
|
|
309
314
|
}
|
|
315
|
+
// R9 — pagu karakter ringkasan mengikuti jendela (satu sumber, dipakai juga
|
|
316
|
+
// oleh boundCompactionResult agar ringkasan LLM tidak di-clamp balik ke 4k).
|
|
317
|
+
const summaryChars = () => summaryCharBudgetForWindow(opts.getContextWindowTokens?.())
|
|
310
318
|
// F3.1 anti-thrash (state per strategi = per sesi, karena strategy dibuat
|
|
311
319
|
// sekali di setup): kernel memicu kompaksi budget sekali PER TURN, jadi
|
|
312
320
|
// turn panjang dengan jendela penuh-kembali langsung (= satu output raksasa)
|
|
@@ -384,6 +392,7 @@ export function createLlmCompaction(opts: LlmCompactionOptions = {}): Compaction
|
|
|
384
392
|
fallback.compact(store, { keepRecentTurns: 1 }),
|
|
385
393
|
1,
|
|
386
394
|
targetTokens(),
|
|
395
|
+
summaryChars(),
|
|
387
396
|
)
|
|
388
397
|
}
|
|
389
398
|
const progress = before > 0 ? (before - out.length) / before : 1
|
|
@@ -399,7 +408,13 @@ export function createLlmCompaction(opts: LlmCompactionOptions = {}): Compaction
|
|
|
399
408
|
)
|
|
400
409
|
}
|
|
401
410
|
}
|
|
402
|
-
return boundCompactionResult(
|
|
411
|
+
return boundCompactionResult(
|
|
412
|
+
store,
|
|
413
|
+
out,
|
|
414
|
+
cOpts.keepRecentTurns,
|
|
415
|
+
targetTokens(),
|
|
416
|
+
summaryChars(),
|
|
417
|
+
)
|
|
403
418
|
} finally {
|
|
404
419
|
clearTimeout(timer)
|
|
405
420
|
signal.removeEventListener("abort", onAbort)
|
|
@@ -646,11 +661,23 @@ export async function compactWithLlm(
|
|
|
646
661
|
: ""
|
|
647
662
|
return `- tool(${m.name}): ${head(raw, toolHeadLen(m.name, 250))}`
|
|
648
663
|
}
|
|
664
|
+
// F6 — pertahankan instruksi terkini verbatim saat active-turn fold. Jalur
|
|
665
|
+
// mekanikal (compactActiveTurn) menyimpan "Current task/request" mentah; jalur
|
|
666
|
+
// LLM merangkum seluruh prefix lewat summarizer sehingga request persis bisa
|
|
667
|
+
// terparafrase atau hilang — terutama saat satu turn didominasi output tool
|
|
668
|
+
// raksasa. Sertakan request terakhir verbatim (dengan pagu) di awal input
|
|
669
|
+
// summarizer supaya apa yang sebenarnya diminta user tidak menyusut.
|
|
670
|
+
const currentRequest = (() => {
|
|
671
|
+
if (!activeTurn) return ""
|
|
672
|
+
const lastUser = [...prefix].reverse().find((m) => m.role === "user")
|
|
673
|
+
const text = lastUser ? contentToText(lastUser.content).trim() : ""
|
|
674
|
+
return text ? `Current request (verbatim):\n${head(text, 1200)}\n\n` : ""
|
|
675
|
+
})()
|
|
649
676
|
const scrubbedPrefix = scrubSecrets(
|
|
650
|
-
prefix
|
|
651
|
-
|
|
652
|
-
.
|
|
653
|
-
|
|
677
|
+
(currentRequest + prefix.map(lineFor).join("\n")).slice(
|
|
678
|
+
0,
|
|
679
|
+
opts.maxInputChars ?? LIMITS.COMPACTION_LLM_INPUT_MIN_CHARS,
|
|
680
|
+
),
|
|
654
681
|
)
|
|
655
682
|
// Guard anti-injeksi (temuan audit #02): prefix berisi output tool/web/repo
|
|
656
683
|
// tak-terpercaya yang bisa memuat "abaikan instruksi". Tanpa pagar, payload
|
package/src/policy/jail.ts
CHANGED
|
@@ -47,29 +47,20 @@ export function isSensitive(p: string): boolean {
|
|
|
47
47
|
// ("always" palsu!), config (server MCP jahat!), atau membutakan recovery.
|
|
48
48
|
// BACA tetap boleh (observability/debug). Pola di-anchor ke segmen
|
|
49
49
|
// `.minicode/` agar file user bernama mirip di tempat lain tak kena.
|
|
50
|
-
// Pengecualian:
|
|
51
|
-
//
|
|
52
|
-
//
|
|
50
|
+
// Pengecualian: restore dari `.minicode/.trash/` (ditangani di permission.ts,
|
|
51
|
+
// bukan di sini, agar arahnya eksplisit).
|
|
52
|
+
//
|
|
53
|
+
// `.minicode/hooks/` TIDAK lagi dikecualikan (audit 2026-11-12): hook
|
|
54
|
+
// dieksekusi otomatis lewat scan direktori begitu `MINICODE_HOOKS=1`, jadi
|
|
55
|
+
// carve-out tulis = model/prompt-injection bisa menanam kode lalu menjalankannya
|
|
56
|
+
// di sesi yang sama, di luar permission/jail/sandbox. Skrip hook sekarang
|
|
57
|
+
// dibuat operator di luar sesi (shell manual), bukan lewat file tool.
|
|
53
58
|
const OWNED_STATE_RE = /(?:^|[/\\])\.minicode(?:[/\\]|$)/i
|
|
54
59
|
|
|
55
|
-
// Skrip hooks milik user (.minicode/hooks/): BUKAN state runtime — alur
|
|
56
|
-
// legit "buatkan hook" menulis lewat tool (dikunci test delegate-audit).
|
|
57
|
-
// Registrasi eksekusi tetap dikunci (allowlist.json owned), jadi file
|
|
58
|
-
// titipan tak jalan sendiri. skills//steering/MEMORY tetap terkunci:
|
|
59
|
-
// isinya ikut ke konteks (persistensi prompt-injection), user kelola via shell.
|
|
60
|
-
const HOOKS_RE = /(?:^|[/\\])\.minicode[/\\]hooks(?:[/\\]|$)/i
|
|
61
|
-
|
|
62
|
-
/** true bila jalurargumen tool menunjuk skrip hooks user (carve-out tulis). */
|
|
63
|
-
export function isHookScript(p: string): boolean {
|
|
64
|
-
if (!p || DOTDOT_SEG_RE.test(p)) return false
|
|
65
|
-
return HOOKS_RE.test(p)
|
|
66
|
-
}
|
|
67
|
-
|
|
68
60
|
export function isOwnedState(p: string): boolean {
|
|
69
61
|
if (!p) return false
|
|
70
62
|
const cleaned = cleanPathForMatch(p)
|
|
71
|
-
|
|
72
|
-
return matchesOwned && !isHookScript(p) && !isHookScript(cleaned)
|
|
63
|
+
return OWNED_STATE_RE.test(p) || OWNED_STATE_RE.test(cleaned)
|
|
73
64
|
}
|
|
74
65
|
/**
|
|
75
66
|
* Kunci realpath untuk owned-state (temuan audit 2026-09-22 F-CRIT): cek
|
|
@@ -90,10 +81,7 @@ export function isOwnedStateReal(p: string, root: string): boolean {
|
|
|
90
81
|
let tail = ""
|
|
91
82
|
for (let i = 0; i < 64; i++) {
|
|
92
83
|
try {
|
|
93
|
-
|
|
94
|
-
// Carve-out hooks: skrip hooks sah tetap lewat kunci ini (registrasi
|
|
95
|
-
// eksekusinya terkunci di allowlist.json yang owned).
|
|
96
|
-
return isOwnedState(real) && !isHookScript(real)
|
|
84
|
+
return isOwnedState(resolve(realpathSync(probe), tail))
|
|
97
85
|
} catch {
|
|
98
86
|
const parent = dirname(probe)
|
|
99
87
|
if (parent === probe) break
|
package/src/policy/permission.ts
CHANGED
|
@@ -18,7 +18,6 @@ import {
|
|
|
18
18
|
import { inspectBashCommand } from "./bash-guard.ts"
|
|
19
19
|
import {
|
|
20
20
|
isCwdOutsideRoot,
|
|
21
|
-
isHookScript,
|
|
22
21
|
isOwnedState,
|
|
23
22
|
isOwnedStateReal,
|
|
24
23
|
isRealPathOutsideRoot,
|
|
@@ -649,7 +648,10 @@ export function createPermissionHandler(
|
|
|
649
648
|
const v = inspectBashCommand(cmd, root)
|
|
650
649
|
return v.denied ? (v.reason ?? "blocked command") : null
|
|
651
650
|
} catch {
|
|
652
|
-
|
|
651
|
+
// Fail-closed: guard yang melempar exception bukan bukti perintah aman.
|
|
652
|
+
// Sebelumnya `return null` membuat setiap error internal menjadi ALLOW —
|
|
653
|
+
// satu bug di guard cukup untuk membuka seluruh permukaan eksekusi.
|
|
654
|
+
return "bash-guard internal error — command refused (fail-closed)"
|
|
653
655
|
}
|
|
654
656
|
}
|
|
655
657
|
|
|
@@ -908,9 +910,10 @@ export function createPermissionHandler(
|
|
|
908
910
|
? ([(earlyArgs?.from as string) ?? "", (earlyArgs?.to as string) ?? ""] as const)
|
|
909
911
|
: ([(earlyArgs?.path as string) ?? ""] as const)
|
|
910
912
|
// Carve-out sah (string mentah): restore `.minicode/.trash/` →
|
|
911
|
-
// workspace
|
|
912
|
-
//
|
|
913
|
-
//
|
|
913
|
+
// workspace — satu-satunya gerak sah yang menyentuh state. Cek string
|
|
914
|
+
// dulu supaya jalur sah (yang target nyatanya justru `.minicode/`)
|
|
915
|
+
// tidak ikut ditahan kunci realpath. Skrip hooks TIDAK lagi punya
|
|
916
|
+
// carve-out (lihat jail.ts): hook auto-dieksekusi saat opt-in.
|
|
914
917
|
if (call.name === "move_file") {
|
|
915
918
|
const f = rawTargets[0] ?? ""
|
|
916
919
|
const t = rawTargets[1] ?? ""
|
|
@@ -925,7 +928,7 @@ export function createPermissionHandler(
|
|
|
925
928
|
}
|
|
926
929
|
} else {
|
|
927
930
|
const p = rawTargets[0] ?? ""
|
|
928
|
-
if (p !== "" && (isOwnedState(p) ||
|
|
931
|
+
if (p !== "" && (isOwnedState(p) || isOwnedStateReal(p, root))) {
|
|
929
932
|
return deny(call, "jail: owned state")
|
|
930
933
|
}
|
|
931
934
|
}
|
|
@@ -947,7 +947,7 @@ export function machineError(e: unknown): MachineError {
|
|
|
947
947
|
if (kind === "timeout" || (/timeout|timed out/i.test(message) && kind !== "aborted"))
|
|
948
948
|
return { category: "AGENT_ERROR", message, action: "retry with a higher --timeout" }
|
|
949
949
|
if (kind === "max_steps_exceeded" || /max.?steps/i.test(message))
|
|
950
|
-
return { category: "AGENT_ERROR", message, action: "raise --max-steps" }
|
|
950
|
+
return { category: "AGENT_ERROR", message, action: "continue via /resume or raise --max-steps" }
|
|
951
951
|
if (kind === "aborted" || /^(run cancelled|turn aborted|aborted)/i.test(message))
|
|
952
952
|
return { category: "USER_ERROR", message }
|
|
953
953
|
if (/refusing|denied|not allowed|not permitted/i.test(message))
|
|
@@ -134,7 +134,7 @@ export function createAnthropicProvider(config: AnthropicConfig): ModelProvider
|
|
|
134
134
|
throw new ProviderError("network", e instanceof Error ? e.message : String(e))
|
|
135
135
|
}
|
|
136
136
|
if (!response.ok) {
|
|
137
|
-
const txt = await readProviderErrorBody(response).catch(() => "")
|
|
137
|
+
const txt = await readProviderErrorBody(response, signal).catch(() => "")
|
|
138
138
|
throw toAnthropicError(response.status, txt, response.headers)
|
|
139
139
|
}
|
|
140
140
|
if (!response.body) throw new ProviderError("network", "empty response body")
|
|
@@ -413,9 +413,19 @@ function toAnthropicError(status: number, body: string, headers: Headers): Provi
|
|
|
413
413
|
if (status === 401 || status === 403)
|
|
414
414
|
return new ProviderError("auth", `auth failed (${status}): ${detail}`)
|
|
415
415
|
if (status === 400 || status === 422) {
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
416
|
+
// Samakan frasa deteksi overflow dengan adapter lain (openai-compat /
|
|
417
|
+
// responses): gateway kompatibel-Anthropic bisa memfrasakan jendela konteks
|
|
418
|
+
// sebagai "context window"/"input is too long" — tanpa frasa itu, kasus
|
|
419
|
+
// compact-and-retry jatuh jadi invalid_request terminal.
|
|
420
|
+
const lower = body.toLowerCase()
|
|
421
|
+
const isCtx = [
|
|
422
|
+
"context_length",
|
|
423
|
+
"context length",
|
|
424
|
+
"maximum context",
|
|
425
|
+
"prompt is too long",
|
|
426
|
+
"input is too long",
|
|
427
|
+
"context window",
|
|
428
|
+
].some((phrase) => lower.includes(phrase))
|
|
419
429
|
return new ProviderError(
|
|
420
430
|
isCtx ? "context_length_exceeded" : "invalid_request",
|
|
421
431
|
`${status}: ${detail}`,
|
|
@@ -140,7 +140,7 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
|
|
|
140
140
|
// Bila request gagal saat membawa previous_response_id, hapus ID tersebut
|
|
141
141
|
// agar turn berikutnya tidak macet permanen pada ID yang kedaluwarsa/ditolak.
|
|
142
142
|
if (prev) lastResponseByModel.delete(modelKey)
|
|
143
|
-
const txt = await readProviderErrorBody(res).catch(() => "")
|
|
143
|
+
const txt = await readProviderErrorBody(res, signal).catch(() => "")
|
|
144
144
|
const retryAfter = res.headers.get("retry-after")
|
|
145
145
|
if (res.status === 429) {
|
|
146
146
|
const ms = retryAfter ? Number(retryAfter) * 1000 : undefined
|
|
@@ -99,16 +99,29 @@ export function boundedSseBody(
|
|
|
99
99
|
})
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
-
/** Body error dibaca secukupnya untuk kategori/pesan, lalu sisa stream dibuang.
|
|
103
|
-
|
|
102
|
+
/** Body error dibaca secukupnya untuk kategori/pesan, lalu sisa stream dibuang.
|
|
103
|
+
* `signal` membuat pembacaan abort-aware: server yang mengembalikan status error
|
|
104
|
+
* lalu menstall body-nya tidak boleh menggantung reader selamanya — cancel reader
|
|
105
|
+
* saat abort sehingga jalur error tetap terbatas waktu. */
|
|
106
|
+
export async function readProviderErrorBody(
|
|
107
|
+
response: Response,
|
|
108
|
+
signal?: AbortSignal,
|
|
109
|
+
): Promise<string> {
|
|
104
110
|
if (!response.body) return ""
|
|
111
|
+
if (signal?.aborted) return ""
|
|
105
112
|
const reader = response.body.getReader()
|
|
106
113
|
const chunks: Uint8Array[] = []
|
|
107
114
|
let size = 0
|
|
108
115
|
let reachedEof = false
|
|
116
|
+
const onAbort = () => {
|
|
117
|
+
void reader.cancel(signal?.reason).catch(() => {})
|
|
118
|
+
}
|
|
119
|
+
signal?.addEventListener("abort", onAbort, { once: true })
|
|
109
120
|
try {
|
|
110
121
|
while (size < LIMITS.PROVIDER_ERROR_BODY_MAX_BYTES) {
|
|
122
|
+
if (signal?.aborted) break
|
|
111
123
|
const { done, value } = await reader.read()
|
|
124
|
+
if (signal?.aborted) break
|
|
112
125
|
if (done) {
|
|
113
126
|
reachedEof = true
|
|
114
127
|
break
|
|
@@ -121,6 +134,7 @@ export async function readProviderErrorBody(response: Response): Promise<string>
|
|
|
121
134
|
}
|
|
122
135
|
return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8")
|
|
123
136
|
} finally {
|
|
137
|
+
signal?.removeEventListener("abort", onAbort)
|
|
124
138
|
if (!reachedEof) await reader.cancel().catch(() => {})
|
|
125
139
|
reader.releaseLock()
|
|
126
140
|
}
|
|
@@ -13,6 +13,7 @@ import { t } from "../i18n/locale.ts"
|
|
|
13
13
|
import { askLine } from "../input/input.ts"
|
|
14
14
|
import { sanitizeAnsiLine } from "../render/sanitize.ts"
|
|
15
15
|
import { c } from "../render/theme.ts"
|
|
16
|
+
import { truncateToWidth } from "../render/width.ts"
|
|
16
17
|
import { getApprovalSink } from "../tui/transcript.ts"
|
|
17
18
|
|
|
18
19
|
/** Subset struktural tool call yang dibutuhkan view — tanpa tipe kernel. */
|
|
@@ -73,10 +74,16 @@ export async function promptAsk(call: ApprovalRequest): Promise<"allow" | "deny"
|
|
|
73
74
|
const toolName = sanitizeAnsiLine(call.name)
|
|
74
75
|
const args = (call.args ?? {}) as Record<string, unknown>
|
|
75
76
|
|
|
77
|
+
// Sanitasi DULU, potong SESUDAH: `slice` mentah bisa membelah surrogate
|
|
78
|
+
// pair (byte U+FFFD di layar) dan memotong sekuens ANSI di tengah sehingga
|
|
79
|
+
// ekor `\x1b[` menggantung (terminal menelan output berikutnya sebagai
|
|
80
|
+
// parameter CSI) — audit 2026-11-12, MEDIUM-1.
|
|
81
|
+
const summarize = (value: unknown, max: number): string =>
|
|
82
|
+
truncateToWidth(sanitizeAnsiLine(String(value)), max, "…")
|
|
76
83
|
let actionSummary = ""
|
|
77
|
-
if (args.command) actionSummary = `${t("appr.cmdLabel")} ${
|
|
78
|
-
else if (args.path) actionSummary = `${t("appr.fileLabel")} ${
|
|
79
|
-
else if (args.query) actionSummary = `${t("appr.queryLabel")} ${
|
|
84
|
+
if (args.command) actionSummary = `${t("appr.cmdLabel")} ${summarize(args.command, 100)}`
|
|
85
|
+
else if (args.path) actionSummary = `${t("appr.fileLabel")} ${summarize(args.path, 100)}`
|
|
86
|
+
else if (args.query) actionSummary = `${t("appr.queryLabel")} ${summarize(args.query, 100)}`
|
|
80
87
|
else {
|
|
81
88
|
let json = ""
|
|
82
89
|
try {
|
|
@@ -84,7 +91,7 @@ export async function promptAsk(call: ApprovalRequest): Promise<"allow" | "deny"
|
|
|
84
91
|
} catch {
|
|
85
92
|
json = String(args)
|
|
86
93
|
}
|
|
87
|
-
actionSummary = `${t("appr.argsLabel")} ${json
|
|
94
|
+
actionSummary = `${t("appr.argsLabel")} ${summarize(json, 100)}`
|
|
88
95
|
}
|
|
89
96
|
actionSummary = sanitizeAnsiLine(actionSummary)
|
|
90
97
|
|
|
@@ -162,7 +169,9 @@ export async function promptAskText(question: string, options?: string[]): Promi
|
|
|
162
169
|
// Paritas promptAsk: tanpa sink + stdout pipe = jawab tak terlihat & pipe
|
|
163
170
|
// tercemar → batal fail-closed.
|
|
164
171
|
if (!textSink && !process.stdout.isTTY) return null
|
|
165
|
-
|
|
172
|
+
// Potong SESUDAH sanitasi lewat truncateToWidth (bukan `slice`): `slice`
|
|
173
|
+
// bisa menyisakan `\x1b[` menggantung di ekor potongan.
|
|
174
|
+
const q = truncateToWidth(sanitizeAnsiLine(question), 2000, "…")
|
|
166
175
|
const block = [
|
|
167
176
|
``,
|
|
168
177
|
`${c.warning(c.bold(t("appr.askTitle")))}`,
|
|
@@ -188,7 +197,9 @@ export async function promptAskText(question: string, options?: string[]): Promi
|
|
|
188
197
|
if (ans == null || !ans.trim()) return null
|
|
189
198
|
const out = ans.trim()
|
|
190
199
|
if (sink) {
|
|
191
|
-
|
|
200
|
+
// Gema jawaban juga dipotong lewat truncateToWidth: `slice` bisa membelah
|
|
201
|
+
// surrogate pair (emoji → U+FFFD) atau menyisakan escape menggantung.
|
|
202
|
+
sink.pushBlock([c.muted(` → ${truncateToWidth(sanitizeAnsiLine(out), 200, "…")}`)])
|
|
192
203
|
sink.repaint()
|
|
193
204
|
}
|
|
194
205
|
return out
|
package/src/ui/footer.ts
CHANGED
|
@@ -108,7 +108,7 @@ export function paintPermissionMode(mode: string, style: ModeLabelStyle = "full"
|
|
|
108
108
|
* jadi dirender jelas (bukan redup). */
|
|
109
109
|
export function paintBashStrict(strictBash?: boolean, unrestricted = false): string {
|
|
110
110
|
if (unrestricted) return c.info(glyphs.unlock)
|
|
111
|
-
return strictBash ? c.yellow(glyphs.lock) : c.
|
|
111
|
+
return strictBash ? c.yellow(glyphs.lock) : c.gray(glyphs.lock)
|
|
112
112
|
}
|
|
113
113
|
|
|
114
114
|
/** Spark glyph: redup saat idle, pulse putih↔abu saat busy (frame genap/ganjil). */
|
|
@@ -119,7 +119,7 @@ function sparkGlyph(frame: number): string {
|
|
|
119
119
|
}
|
|
120
120
|
|
|
121
121
|
function paintTimer(text: string, active: boolean, highlight: TimerHighlight = "seconds"): string {
|
|
122
|
-
if (!active) return c.
|
|
122
|
+
if (!active) return c.gray(text)
|
|
123
123
|
const parts = text.split(".")
|
|
124
124
|
if (parts.length !== 3) return c.white(text)
|
|
125
125
|
const rank: Record<TimerHighlight, number> = { seconds: 1, minutes: 2, hours: 3 }
|
package/src/ui/i18n/en.ts
CHANGED
|
@@ -312,7 +312,7 @@ export const en = {
|
|
|
312
312
|
"err.timeout": "Run exceeded timeout",
|
|
313
313
|
"err.timeoutFix": "Increase --timeout or use a faster model.",
|
|
314
314
|
"err.steps": "Tool step limit reached",
|
|
315
|
-
"err.stepsFix": "
|
|
315
|
+
"err.stepsFix": "Progress is saved — run /resume to continue, or raise --max-steps.",
|
|
316
316
|
"err.budget": "Session budget exceeded",
|
|
317
317
|
"err.budgetFix": "Start a new session or increase --budget.",
|
|
318
318
|
"err.busy": "A run is still in progress",
|
|
@@ -339,4 +339,12 @@ export const en = {
|
|
|
339
339
|
"loading.rag": "loading context",
|
|
340
340
|
"loading.session": "preparing session",
|
|
341
341
|
"loading.finalize": "finalizing",
|
|
342
|
+
"diff.noChanges": "(no changes)",
|
|
343
|
+
"diff.truncated": "… diff truncated — input too large",
|
|
344
|
+
"tbl.noColumns": "(no columns)",
|
|
345
|
+
"tbl.noEntries": "(no entries)",
|
|
346
|
+
"summary.session": "Session",
|
|
347
|
+
"summary.model": "Model",
|
|
348
|
+
"summary.usage": "Usage",
|
|
349
|
+
"summary.tokens": "tokens",
|
|
342
350
|
} as const
|
package/src/ui/i18n/id.ts
CHANGED
|
@@ -314,7 +314,7 @@ export const id: Record<MsgKey, string> = {
|
|
|
314
314
|
"err.timeout": "Run melewati batas waktu",
|
|
315
315
|
"err.timeoutFix": "Naikkan --timeout atau pakai model lebih cepat.",
|
|
316
316
|
"err.steps": "Batas langkah tool tercapai",
|
|
317
|
-
"err.stepsFix": "
|
|
317
|
+
"err.stepsFix": "Progres sudah tersimpan — lanjutkan via /resume, atau naikkan --max-steps.",
|
|
318
318
|
"err.budget": "Budget sesi terlampaui",
|
|
319
319
|
"err.budgetFix": "Mulai sesi baru atau naikkan --budget.",
|
|
320
320
|
"err.busy": "Run masih berjalan",
|
|
@@ -341,4 +341,12 @@ export const id: Record<MsgKey, string> = {
|
|
|
341
341
|
"loading.rag": "memuat konteks",
|
|
342
342
|
"loading.session": "menyiapkan sesi",
|
|
343
343
|
"loading.finalize": "menyelesaikan",
|
|
344
|
+
"diff.noChanges": "(tidak ada perubahan)",
|
|
345
|
+
"diff.truncated": "… diff dipotong — input terlalu besar",
|
|
346
|
+
"tbl.noColumns": "(tanpa kolom)",
|
|
347
|
+
"tbl.noEntries": "(tanpa entri)",
|
|
348
|
+
"summary.session": "Sesi",
|
|
349
|
+
"summary.model": "Model",
|
|
350
|
+
"summary.usage": "Pemakaian",
|
|
351
|
+
"summary.tokens": "token",
|
|
344
352
|
}
|
|
@@ -232,6 +232,12 @@ export function applyKey(
|
|
|
232
232
|
.replace(/\t/g, " ")
|
|
233
233
|
// biome-ignore lint/suspicious/noControlCharactersInRegex: membuang byte kontrol dari paste
|
|
234
234
|
.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "")
|
|
235
|
+
// C1 (0x80–0x9F) juga dibuang: U+009B bertindak sebagai CSI di banyak
|
|
236
|
+
// terminal, jadi paste bisa menyuntik escape TANPA byte ESC — melewati
|
|
237
|
+
// filter di atas dan gate sanitize (buffer composer dilukis apa adanya).
|
|
238
|
+
.replace(/[\u0080-\u009f]/g, "")
|
|
239
|
+
// Separator garis/paragraf Unicode = pindah baris di sebagian terminal.
|
|
240
|
+
.replace(/[\u2028\u2029]/g, "\n")
|
|
235
241
|
if (!ins) return { state, action: "none" }
|
|
236
242
|
const { line, cursor } = insertAt(state.line, state.cursor, ins)
|
|
237
243
|
return { state: withLine(line, cursor), action: "render" }
|
package/src/ui/render/diff.ts
CHANGED
|
@@ -1,8 +1,35 @@
|
|
|
1
1
|
// Diff renderer - Ubuntu Server style: indentasi + warna, tanpa border.
|
|
2
|
+
import { t } from "../i18n/locale.ts"
|
|
2
3
|
import { sanitizeAnsi, sanitizeAnsiLine } from "./sanitize.ts"
|
|
3
4
|
import { c } from "./theme.ts"
|
|
4
5
|
import { truncateToWidth, wrapByWidth } from "./width.ts"
|
|
5
6
|
|
|
7
|
+
/**
|
|
8
|
+
* Batas input diff (audit 2026-11-12, HIGH-5).
|
|
9
|
+
*
|
|
10
|
+
* LCS kata adalah O(n·m) waktu DAN memori (matriks dp penuh). Argumen
|
|
11
|
+
* `edit` datang mentah dari model dan skemanya tak membatasi panjang: satu
|
|
12
|
+
* baris 8k kata butuh ~2 dtk + ratusan MB, dan 20k kata berujung OOM — cukup
|
|
13
|
+
* untuk membekukan CLI linear sebelum satu byte pun dicetak. Dipotong di sini
|
|
14
|
+
* (bukan di schema tool) supaya renderer aman untuk pemanggil mana pun.
|
|
15
|
+
*/
|
|
16
|
+
const DIFF_MAX_CHARS = 64 * 1024
|
|
17
|
+
const DIFF_MAX_LINES = 2000
|
|
18
|
+
/** Sel matriks LCS kata maksimum; di atas ini sorotan-per-kata dilepas. */
|
|
19
|
+
const WORD_LCS_MAX_CELLS = 250_000
|
|
20
|
+
|
|
21
|
+
/** Potong input diff pada batas baris terdekat agar tak ada baris separuh. */
|
|
22
|
+
function capDiffInput(text: string): { text: string; truncated: boolean } {
|
|
23
|
+
const lines = text.split("\n")
|
|
24
|
+
if (lines.length > DIFF_MAX_LINES) {
|
|
25
|
+
return { text: lines.slice(0, DIFF_MAX_LINES).join("\n"), truncated: true }
|
|
26
|
+
}
|
|
27
|
+
if (text.length <= DIFF_MAX_CHARS) return { text, truncated: false }
|
|
28
|
+
const head = text.slice(0, DIFF_MAX_CHARS)
|
|
29
|
+
const nl = head.lastIndexOf("\n")
|
|
30
|
+
return { text: nl > 0 ? head.slice(0, nl) : head, truncated: true }
|
|
31
|
+
}
|
|
32
|
+
|
|
6
33
|
export interface DiffLine {
|
|
7
34
|
type: "add" | "delete" | "context"
|
|
8
35
|
oldLine?: number
|
|
@@ -80,6 +107,15 @@ export function markChangedWords(
|
|
|
80
107
|
const b = tokenizeWords(newLine)
|
|
81
108
|
const n = a.length
|
|
82
109
|
const m = b.length
|
|
110
|
+
// Baris raksasa (minified JSON, satu baris hasil generate): LCS penuh =
|
|
111
|
+
// ratusan MB. Semua token ditandai berubah → paintWords menampilkan polos
|
|
112
|
+
// (rasio > 0.6), jadi tak ada info hilang, hanya tanpa sorotan kata.
|
|
113
|
+
if (n * m > WORD_LCS_MAX_CELLS) {
|
|
114
|
+
return {
|
|
115
|
+
oldMask: new Array<boolean>(n).fill(true),
|
|
116
|
+
newMask: new Array<boolean>(m).fill(true),
|
|
117
|
+
}
|
|
118
|
+
}
|
|
83
119
|
const dp: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0))
|
|
84
120
|
for (let i = n - 1; i >= 0; i--)
|
|
85
121
|
for (let j = m - 1; j >= 0; j--)
|
|
@@ -119,9 +155,17 @@ export function renderDiffCard(
|
|
|
119
155
|
// dirender. Tanpa ini `\n` di path menjadi baris diff palsu dan `ESC[2J`
|
|
120
156
|
// lolos via `cut` (truncate menyalin escape apa pun sebelum F-04).
|
|
121
157
|
const safePath = sanitizeAnsiLine(filePath)
|
|
122
|
-
const
|
|
158
|
+
const cappedOld = capDiffInput(oldText)
|
|
159
|
+
const cappedNew = capDiffInput(newText)
|
|
160
|
+
const diff = computeLineDiff(sanitizeAnsi(cappedOld.text), sanitizeAnsi(cappedNew.text))
|
|
123
161
|
const changes = diff.filter((d) => d.type !== "context")
|
|
124
|
-
|
|
162
|
+
// Tanpa perubahan pada PREFIKS yang dipotong, jangan klaim "no changes":
|
|
163
|
+
// perbedaan bisa berada di bagian yang dibuang. Marker truncasi menang.
|
|
164
|
+
if (changes.length === 0) {
|
|
165
|
+
return c.muted(
|
|
166
|
+
` ${t(cappedOld.truncated || cappedNew.truncated ? "diff.truncated" : "diff.noChanges")}`,
|
|
167
|
+
)
|
|
168
|
+
}
|
|
125
169
|
// Pasangan del/add untuk sorot kata: kelompokkan run perubahan beruntun,
|
|
126
170
|
// pasangkan del ke-i dengan add ke-i (pola hunk unified).
|
|
127
171
|
const wordMask = new Map<number, boolean[]>()
|
|
@@ -198,5 +242,10 @@ export function renderDiffCard(
|
|
|
198
242
|
} else lines.push(...wrapDiffLine(" ", d.content, (s) => c.dim(s)))
|
|
199
243
|
count++
|
|
200
244
|
}
|
|
245
|
+
// Pemotongan input WAJIB terlihat: user harus tahu diff yang tampil bukan
|
|
246
|
+
// keseluruhan perubahan (OUTPUT_UX_RULES: truncate selalu dengan marker).
|
|
247
|
+
if (cappedOld.truncated || cappedNew.truncated) {
|
|
248
|
+
lines.push(c.muted(` ${t("diff.truncated")}`))
|
|
249
|
+
}
|
|
201
250
|
return lines.join("\n")
|
|
202
251
|
}
|
|
@@ -182,30 +182,58 @@ function highlightTsLine(line: string): string {
|
|
|
182
182
|
return highlightTsTokens(line)
|
|
183
183
|
}
|
|
184
184
|
|
|
185
|
+
/**
|
|
186
|
+
* Jalankan `fn` hanya pada bagian DI LUAR sekuens SGR.
|
|
187
|
+
*
|
|
188
|
+
* Sekuens SGR yang dipertahankan sanitizeAnsi adalah byte opak. Dulu tokenizer
|
|
189
|
+
* melihat isinya dan mewarnai `1`/`31` sebagai angka, memecah escape sehingga
|
|
190
|
+
* user melihat literal `1;31m` di dalam code fence (audit 2026-11-12, HIGH-4).
|
|
191
|
+
* Regex di-reuse dengan `lastIndex` direset tiap panggilan.
|
|
192
|
+
*/
|
|
193
|
+
// Dibangun tanpa literal kontrol (aturan lint noControlCharactersInRegex).
|
|
194
|
+
const SGR_SEQ = new RegExp(`${String.fromCharCode(27)}\\[[0-9;:]*m`, "g")
|
|
195
|
+
|
|
196
|
+
function mapOutsideSgr(line: string, fn: (chunk: string) => string): string {
|
|
197
|
+
SGR_SEQ.lastIndex = 0
|
|
198
|
+
let out = ""
|
|
199
|
+
let last = 0
|
|
200
|
+
let m = SGR_SEQ.exec(line)
|
|
201
|
+
while (m) {
|
|
202
|
+
if (m.index > last) out += fn(line.slice(last, m.index))
|
|
203
|
+
out += m[0]
|
|
204
|
+
last = m.index + m[0].length
|
|
205
|
+
m = SGR_SEQ.exec(line)
|
|
206
|
+
}
|
|
207
|
+
if (last < line.length) out += fn(line.slice(last))
|
|
208
|
+
return out
|
|
209
|
+
}
|
|
210
|
+
|
|
185
211
|
function highlightTsTokens(text: string): string {
|
|
186
212
|
// Regex to match string literals, numbers, identifiers, operators
|
|
187
213
|
const tokenRe =
|
|
188
214
|
/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\b\d+(?:\.\d+)?\b|\b[A-Za-z_$][A-Za-z0-9_$]*\b|[{}()[\];:,.<>=+\-*/%!&|^~?]+|\s+)/g
|
|
189
|
-
return text
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
215
|
+
return mapOutsideSgr(text, (chunk) =>
|
|
216
|
+
chunk.replace(tokenRe, (token) => {
|
|
217
|
+
if (token.startsWith('"') || token.startsWith("'") || token.startsWith("`")) {
|
|
218
|
+
return c.string(token)
|
|
219
|
+
}
|
|
220
|
+
if (/^\d+(?:\.\d+)?$/.test(token)) {
|
|
221
|
+
return c.brightYellow(token)
|
|
222
|
+
}
|
|
223
|
+
if (TS_KEYWORDS.has(token)) {
|
|
224
|
+
return c.brightMagenta(c.bold(token))
|
|
225
|
+
}
|
|
226
|
+
if (/^[A-Z][A-Za-z0-9_$]*$/.test(token)) {
|
|
227
|
+
// Type / Class name
|
|
228
|
+
return c.brightCyan(token)
|
|
229
|
+
}
|
|
230
|
+
// Tidak ada cabang khusus untuk true/false/null/undefined: keempatnya sudah
|
|
231
|
+
// ada di TS_KEYWORDS, jadi cabang di atas selalu menang. Cabang terpisah
|
|
232
|
+
// yang pernah ada di sini tak pernah terjangkau (terlihat saat coverage
|
|
233
|
+
// highlight.ts dinaikkan: satu baris mustahil dicapai test apa pun).
|
|
234
|
+
return token
|
|
235
|
+
}),
|
|
236
|
+
)
|
|
209
237
|
}
|
|
210
238
|
|
|
211
239
|
function highlightPythonLine(line: string): string {
|
|
@@ -221,22 +249,24 @@ function highlightPythonLine(line: string): string {
|
|
|
221
249
|
function highlightPythonTokens(text: string): string {
|
|
222
250
|
const tokenRe =
|
|
223
251
|
/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\b\d+(?:\.\d+)?\b|\b[A-Za-z_][A-Za-z0-9_]*\b|[{}()[\];:,.<>=+\-*/%!&|^~?]+|\s+)/g
|
|
224
|
-
return text
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
252
|
+
return mapOutsideSgr(text, (chunk) =>
|
|
253
|
+
chunk.replace(tokenRe, (token) => {
|
|
254
|
+
if (token.startsWith('"') || token.startsWith("'")) {
|
|
255
|
+
return c.string(token)
|
|
256
|
+
}
|
|
257
|
+
if (/^\d+/.test(token)) return c.brightYellow(token)
|
|
258
|
+
if (PY_KEYWORDS.has(token)) return c.brightMagenta(c.bold(token))
|
|
259
|
+
if (/^[A-Z][A-Za-z0-9_]*$/.test(token)) return c.brightCyan(token)
|
|
260
|
+
return token
|
|
261
|
+
}),
|
|
262
|
+
)
|
|
233
263
|
}
|
|
234
264
|
|
|
235
265
|
function highlightJsonLine(line: string): string {
|
|
236
266
|
// Key vs string value vs number/bool
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
(match, str, colon, bool, num) => {
|
|
267
|
+
const tokenRe = /("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|\b(-?\d+(?:\.\d+)?)\b/g
|
|
268
|
+
return mapOutsideSgr(line, (chunk) =>
|
|
269
|
+
chunk.replace(tokenRe, (match, str, colon, bool, num) => {
|
|
240
270
|
if (str) {
|
|
241
271
|
if (colon) return c.brightCyan(str) + colon
|
|
242
272
|
return c.string(str)
|
|
@@ -244,7 +274,7 @@ function highlightJsonLine(line: string): string {
|
|
|
244
274
|
if (bool) return c.yellow(bool)
|
|
245
275
|
if (num) return c.brightYellow(num)
|
|
246
276
|
return match
|
|
247
|
-
},
|
|
277
|
+
}),
|
|
248
278
|
)
|
|
249
279
|
}
|
|
250
280
|
|
|
@@ -261,15 +291,16 @@ function highlightShellLine(line: string): string {
|
|
|
261
291
|
function highlightShellTokens(text: string): string {
|
|
262
292
|
// Alternatif flag (`-x`/`--long`) WAJIB sebelum kata: tanpa itu `-` tak pernah
|
|
263
293
|
// jadi awal token (cabang yellow di bawah mati — dulu flag tampil polos).
|
|
264
|
-
|
|
265
|
-
/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\$[A-Za-z0-9_]+|-{1,2}[A-Za-z0-9][A-Za-z0-9_-]*|\b[A-Za-z_][A-Za-z0-9_-]*\b|\s+)/g
|
|
266
|
-
|
|
294
|
+
const tokenRe =
|
|
295
|
+
/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\$[A-Za-z0-9_]+|-{1,2}[A-Za-z0-9][A-Za-z0-9_-]*|\b[A-Za-z_][A-Za-z0-9_-]*\b|\s+)/g
|
|
296
|
+
return mapOutsideSgr(text, (chunk) =>
|
|
297
|
+
chunk.replace(tokenRe, (token) => {
|
|
267
298
|
if (token.startsWith('"') || token.startsWith("'")) return c.string(token)
|
|
268
299
|
if (token.startsWith("$")) return c.brightCyan(token)
|
|
269
300
|
if (SH_KEYWORDS.has(token)) return c.brightMagenta(c.bold(token))
|
|
270
301
|
if (token.startsWith("-")) return c.yellow(token)
|
|
271
302
|
return token
|
|
272
|
-
},
|
|
303
|
+
}),
|
|
273
304
|
)
|
|
274
305
|
}
|
|
275
306
|
|
|
@@ -98,9 +98,13 @@ export function sanitizeAnsi(s: string): string {
|
|
|
98
98
|
/**
|
|
99
99
|
* Versi satu-baris: newline juga dibuang (jadi spasi).
|
|
100
100
|
* Untuk tempat yang menggambar tepat satu baris — judul, label, sel tabel.
|
|
101
|
+
*
|
|
102
|
+
* U+2028/U+2029 (LINE/PARAGRAPH SEPARATOR) ikut jadi spasi: sebagian terminal
|
|
103
|
+
* memperlakukannya sebagai pindah baris, dan satu label yang memecah baris
|
|
104
|
+
* menggeser seluruh geometri frame (audit 2026-11-12).
|
|
101
105
|
*/
|
|
102
106
|
export function sanitizeAnsiLine(s: string): string {
|
|
103
|
-
return sanitizeAnsi(s).replace(
|
|
107
|
+
return sanitizeAnsi(s).replace(/[\n\u2028\u2029]/g, " ")
|
|
104
108
|
}
|
|
105
109
|
|
|
106
110
|
// ── Sanitasi sadar-stream (temuan F1) ──
|