minicode-ai 0.21.0 → 0.23.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 +15 -2
- package/cli/index.ts +11 -0
- package/cli/setup.ts +88 -33
- package/cli/tui.ts +3 -3
- package/docs/TERMINAL_CONTRACT.md +69 -13
- package/docs/architecture.md +9 -5
- package/docs/concepts.md +1 -1
- package/docs/contributing.md +2 -1
- package/docs/environment.md +4 -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/app/session.ts +129 -20
- package/src/config.ts +108 -8
- package/src/constants.ts +29 -4
- package/src/daemon/discovery.ts +24 -0
- package/src/policy/bash-guard.ts +170 -6
- package/src/policy/compaction.ts +61 -7
- package/src/policy/context-budget.ts +132 -0
- package/src/policy/context-escalation.ts +140 -0
- package/src/policy/context-window.ts +47 -9
- package/src/policy/context.ts +10 -1
- package/src/policy/jail.ts +10 -22
- package/src/policy/microcompact.ts +162 -0
- package/src/policy/permission.ts +9 -6
- package/src/presentation/projection.ts +1 -1
- package/src/providers/anthropic.ts +31 -7
- package/src/providers/detect.ts +128 -13
- package/src/providers/provision.ts +78 -1
- package/src/providers/responses.ts +14 -2
- package/src/providers/sse-bounds.ts +16 -2
- package/src/session/persistence.ts +56 -0
- package/src/ui/approval/prompt.ts +17 -6
- package/src/ui/assistant/simple.ts +1 -1
- package/src/ui/footer.ts +2 -2
- package/src/ui/i18n/en.ts +28 -5
- package/src/ui/i18n/id.ts +30 -5
- package/src/ui/input/input.ts +2 -2
- package/src/ui/input/prompt-engine.ts +6 -0
- package/src/ui/render/activity-panel.ts +21 -3
- package/src/ui/render/diff.ts +51 -2
- package/src/ui/render/highlight.ts +68 -37
- package/src/ui/render/hint.ts +28 -0
- package/src/ui/render/logo.ts +91 -0
- package/src/ui/render/sanitize.ts +5 -1
- package/src/ui/render/session-summary.ts +28 -5
- package/src/ui/render/table-grid.ts +123 -13
- package/src/ui/render/table.ts +4 -2
- package/src/ui/render/theme.ts +16 -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/runtime/screen.ts +4 -2
- package/src/ui/screens/dialog.ts +23 -2
- package/src/ui/screens/form.ts +71 -33
- package/src/ui/screens/lifecycle.ts +80 -0
- package/src/ui/screens/model-manager.ts +85 -83
- package/src/ui/screens/picker.ts +39 -25
- package/src/ui/screens/provider-manager.ts +58 -55
- package/src/ui/screens/watchdog.ts +27 -0
- package/src/ui/screens/wizard.ts +12 -1
- package/src/ui/tui/app.ts +62 -22
- package/src/ui/tui/transcript.ts +93 -23
- package/vendor/minicore/src/core/compact.ts +10 -0
- package/vendor/minicore/src/core/errors.ts +11 -1
- package/vendor/minicore/src/core/executor.ts +6 -1
- package/vendor/minicore/src/core/loop.ts +92 -2
- package/vendor/minicore/src/core/session.ts +8 -0
- package/vendor/minicore/src/providers/openai-compat.ts +45 -3
package/docs/policy-sandbox.md
CHANGED
|
@@ -30,7 +30,7 @@ Set terkait: `INTERNAL_WRITE_TOOLS`, `FILE_WRITE_TOOLS`, `GATED_TOOLS` (+ `*.*`
|
|
|
30
30
|
| `echo x > "%TEMP%\evil"` | ditolak; target berisi ekspansi `%NAMA%` tak bisa dipastikan aman secara statis |
|
|
31
31
|
| `py -c …`, `python3.14 -c …` | ditolak bersama varian launcher dan versi Python |
|
|
32
32
|
| `type ..\..\windows\system32\config\sam`, `Get-Content .../ntds.dit` | ditolak (hive Windows + `reg save|export` hive + `vssadmin create|delete shadow` + `ntdsutil`; `reg query`, `vssadmin list`, `system.txt` biasa tetap lolos) |
|
|
33
|
-
| `write_file .minicode/<apa-pun>` | ditolak fail-closed (kunci penuh segmen `.minicode/`;
|
|
33
|
+
| `write_file .minicode/<apa-pun>` | ditolak fail-closed (kunci penuh segmen `.minicode/`; satu-satunya pengecualian restore `.trash/` → workspace; skrip `.minicode/hooks/` kini ikut terkunci — lihat [Keamanan](security.md)) |
|
|
34
34
|
| `bash <(curl x)` | ditolak |
|
|
35
35
|
| `rm -rf ..`, `rm --recursive --force /`, `rm -rf /; :` | ditolak |
|
|
36
36
|
| `command env`, `nice env`, dkk. (wrapper) | deteksi env-dump ter-anchor ke awal | ditolak via `stripCommandWrappers` (buang wrapper berlapis) |
|
|
@@ -38,6 +38,11 @@ Set terkait: `INTERNAL_WRITE_TOOLS`, `FILE_WRITE_TOOLS`, `GATED_TOOLS` (+ `*.*`
|
|
|
38
38
|
| `type .e^nv`, `ty^pe .env` (escape caret cmd.exe) | ditolak setelah caret dinormalisasi sebelum aturan nama/jail |
|
|
39
39
|
| `type %USERPROFILE%\notes.txt` | ditolak; argumen pembaca berpola `%NAMA%` tak bisa dipastikan aman |
|
|
40
40
|
| `for /f %i in (.env) do @echo %i` | ditolak; file set pada loop `for /f` ikut diperiksa |
|
|
41
|
+
| `cat${IFS}.env`, `cat$IFS.env`, `cat${IFS:0:1}.env` (audit 2026-11-12) | ditolak; `$IFS` adalah pemisah kata, dinormalisasi jadi spasi sebelum aturan nama |
|
|
42
|
+
| `cat .?nv`, `cat .[e]nv` | ditolak; glob `?`/`[]` mengembang ke nama lain sama seperti `*` |
|
|
43
|
+
| `cat .{env,}`, `cat {.env,x}` | ditolak; brace expansion diekspansi sebelum pemeriksaan |
|
|
44
|
+
| `cat$(printf ' ').env` | ditolak; argumen pembaca berupa substitusi perintah tak bisa dipastikan statis |
|
|
45
|
+
| `echo "rm -rf /"`, `git commit -m "docs: sudo rm"` | lolos (arah over-block); isi kutip milik echo/printf/grep/`-m` git adalah DATA, bukan perintah — kecuali memuat `$(`, backtick, atau `$VAR` yang tetap dieksekusi |
|
|
41
46
|
|
|
42
47
|
Allowlist (bentuk perintah yang boleh; diperiksa SETELAH bash-guard). Dua daftar:
|
|
43
48
|
- **Narrow** (`--allowlist`, task tak-terpercaya): `git status/diff/log/branch/show`, `bun test/run/x tsc`, `npm/bun/pnpm/yarn install|add`, `npm run/exec/install/ci/test/start`, `node`, `npx`, `ls dir cat type head tail wc grep rg find which echo pwd`. Tulis via shell (`mkdir cp mv rm touch`) ditahan — pakai `write_file`/`edit` yang ter-jail.
|
package/docs/security.md
CHANGED
|
@@ -52,17 +52,25 @@ provider model pihak ketiga.
|
|
|
52
52
|
yang belum bermutasi (by-design, bukan korupsi).
|
|
53
53
|
- State milik runtime (`.minicode/` — DB, todos, plans, checkpoints, jurnal,
|
|
54
54
|
traces, allowlist, config, + file APAPUN lain di bawahnya): tulis via file
|
|
55
|
-
tools ditolak fail-closed (pengecualian: restore
|
|
56
|
-
|
|
57
|
-
luar permission system, aktif hanya via opt-in `MINICODE_HOOKS=1` dan
|
|
58
|
-
dilarang di WorkMode non-`EXECUTE`); baca tetap boleh (observability). Tulis
|
|
55
|
+
tools ditolak fail-closed (satu-satunya pengecualian: restore
|
|
56
|
+
`.minicode/.trash/` → workspace); baca tetap boleh (observability). Tulis
|
|
59
57
|
catatan sendiri ke workspace, bukan ke `.minicode/`.
|
|
58
|
+
- Skrip hooks `.minicode/hooks/` ikut terkunci untuk penulisan (audit
|
|
59
|
+
2026-11-12). Hook adalah kode arbitrer di luar permission system yang
|
|
60
|
+
dieksekusi OTOMATIS lewat scan direktori saat opt-in `MINICODE_HOOKS=1`
|
|
61
|
+
(hanya WorkMode `EXECUTE`, timeout 5 dtk, env disanitasi). Kalau file tool
|
|
62
|
+
boleh menulis ke sana, model/prompt-injection bisa menanam hook lalu
|
|
63
|
+
menjalankannya di sesi yang sama — jadi skrip hook dibuat operator di luar
|
|
64
|
+
sesi. Repo clone-an yang sudah memuat `.minicode/hooks/*.js` tetap harus
|
|
65
|
+
diperlakukan sebagai config lokal tak tepercaya: periksa isinya sebelum
|
|
66
|
+
menyalakan `MINICODE_HOOKS=1`.
|
|
60
67
|
|
|
61
68
|
## Config lokal & supply chain
|
|
62
69
|
|
|
63
70
|
- Config lokal `.minicode/config.json` + allowlist **diabaikan secara default** — repo clone-an tidak bisa men-spawn MCP, menyedot prompt, atau memasang hook. Percayai dengan `--allow-local-config`.
|
|
64
71
|
- Server MCP terdaftar tidak mendapat wildcard auto-allow. Capability tetap harus diotorisasi; di ASK pemanggilan yang digate meminta persetujuan per pasangan server+tool+args, sedangkan AUTO menjalankan capability authorized tanpa prompt rutin. `[a] Always` menyimpan cakupan yang disetujui ke allowlist.
|
|
65
72
|
- Config/allowlist/auth ditulis atomik + chmod 600; token OAuth terpisah di `~/.minicode/auth.json` (bukan config yang rawan ter-commit).
|
|
73
|
+
- Daemon menaruh `bootstrap` secret di `<cwd>/.minicode/daemon-endpoint.json` (`0600`). Di Windows mode POSIX diabaikan, jadi ACL berkas itu dicabut dari warisan dan dibatasi ke user pemilik via `icacls` (best-effort). Residual: pada mesin multi-user Windows di mana `icacls` gagal, user lain yang bisa membaca folder repo masih bisa membaca secret dan menerbitkan capability daemon (loopback, bukan remote).
|
|
66
74
|
- `mcp serve` stdio-only (tanpa mode HTTP → tanpa permukaan jaringan), curated tools, permission aktif; `--all-tools` opt-in operator.
|
|
67
75
|
|
|
68
76
|
## Checkpoint & recovery
|
package/docs/skills.md
CHANGED
|
@@ -39,7 +39,7 @@ Hooks mati secara default; nyalakan dengan `MINICODE_HOOKS=1`.
|
|
|
39
39
|
| Konteks | Env `MINICODE_HOOK_CTX` (JSON run) |
|
|
40
40
|
| Sanitasi | Env hook disanitasi tanpa secret; hook dilewati bila sesi dibatalkan |
|
|
41
41
|
|
|
42
|
-
Hooks global + lokal di-merge (bukan lewat allowlist). Karena hook adalah kode arbitrer di luar permission system, ia hanya jalan bila `MINICODE_HOOKS=1` dan WorkMode `EXECUTE` (tidak di `DISCUSS`/`PLAN`); setiap hook dikenai timeout 5 dtk dan env-nya disanitasi. Repo clone-an
|
|
42
|
+
Hooks global + lokal di-merge (bukan lewat allowlist). Karena hook adalah kode arbitrer di luar permission system, ia hanya jalan bila `MINICODE_HOOKS=1` dan WorkMode `EXECUTE` (tidak di `DISCUSS`/`PLAN`); setiap hook dikenai timeout 5 dtk dan env-nya disanitasi. File tool **tidak** boleh menulis ke `.minicode/hooks/` (audit 2026-11-12) — skrip hook dibuat operator di luar sesi, sehingga model tidak bisa menanam hook yang langsung dieksekusi. Repo clone-an yang sudah memuat `.minicode/hooks/*.js` tetap tak tepercaya: periksa isinya sebelum menyalakan `MINICODE_HOOKS=1` (lihat [Keamanan](security.md)).
|
|
43
43
|
|
|
44
44
|
## Lanjut
|
|
45
45
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "minicode-ai",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Open-source terminal coding agent on a
|
|
3
|
+
"version": "0.23.0",
|
|
4
|
+
"description": "Open-source terminal coding agent on a vendored zero-dependency MiniCore kernel — layered permissions, path jail, sandboxing, MCP/LSP, and durable shadow-git checkpoints",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"private": false,
|
|
7
7
|
"publishConfig": {
|
package/src/app/session.ts
CHANGED
|
@@ -26,6 +26,8 @@ import {
|
|
|
26
26
|
createIncrementalTokenCounter,
|
|
27
27
|
minicodeEstimator,
|
|
28
28
|
} from "../policy/context.ts"
|
|
29
|
+
import { contextBudgetFor, outputReserveFor } from "../policy/context-budget.ts"
|
|
30
|
+
import { nextLadderStep } from "../policy/context-escalation.ts"
|
|
29
31
|
import { DEFAULT_FALLBACK_CONTEXT_WINDOW_TOKENS } from "../policy/context-window.ts"
|
|
30
32
|
import { parallelExecutor } from "../policy/executor.ts"
|
|
31
33
|
import {
|
|
@@ -148,6 +150,8 @@ export async function createMinicodeSession(
|
|
|
148
150
|
Omit<SessionConfig, "permissions" | "estimator" | "recovery" | "system" | "executor">
|
|
149
151
|
> & {
|
|
150
152
|
systemExtra?: string
|
|
153
|
+
/** Bahasa chat model ("id"/"en"); undefined = tanpa direktif (test/bench). */
|
|
154
|
+
lang?: "en" | "id"
|
|
151
155
|
cwd?: string
|
|
152
156
|
/** Live model identity used for per-model token calibration. */
|
|
153
157
|
getContextModel?: () => string | undefined
|
|
@@ -190,6 +194,18 @@ export async function createMinicodeSession(
|
|
|
190
194
|
noProgress?: NoProgressOptions | false
|
|
191
195
|
/** Hook opsional agar composition root dapat mereset riwayat osilasi saat verify hijau. */
|
|
192
196
|
onNoProgress?: (detector: NoProgressDetector) => void
|
|
197
|
+
/**
|
|
198
|
+
* Dipanggil saat jendela konteks dinaikkan otomatis setelah overflow
|
|
199
|
+
* terverifikasi. Composition root memakainya untuk memberi tahu user
|
|
200
|
+
* (footer/log) dan — bila diinginkan — mempersistensikan nilai baru.
|
|
201
|
+
* Tidak pernah dipanggil untuk 429/402/auth/jaringan.
|
|
202
|
+
*/
|
|
203
|
+
onContextWindowEscalated?: (info: {
|
|
204
|
+
model: string
|
|
205
|
+
fromTokens: number
|
|
206
|
+
toTokens: number
|
|
207
|
+
observedTokens: number
|
|
208
|
+
}) => void
|
|
193
209
|
/**
|
|
194
210
|
* [Area B · PROMPT 06] Penyimpanan binding persetujuan milik SESI.
|
|
195
211
|
*
|
|
@@ -267,6 +283,7 @@ export async function createMinicodeSession(
|
|
|
267
283
|
cwd: defaultCwd,
|
|
268
284
|
extra: opts.systemExtra ?? "",
|
|
269
285
|
signal: (opts as unknown as { signal?: AbortSignal }).signal,
|
|
286
|
+
lang: opts.lang,
|
|
270
287
|
})
|
|
271
288
|
const {
|
|
272
289
|
concurrency,
|
|
@@ -540,15 +557,48 @@ export async function createMinicodeSession(
|
|
|
540
557
|
let lastProviderInputTokens: number | undefined
|
|
541
558
|
let lastRequestMessageCount = 0
|
|
542
559
|
const contextWindowForModel = (model?: string): number => {
|
|
560
|
+
// Eskalasi adaptif menang atas resolusi statis: ia adalah bukti dari
|
|
561
|
+
// endpoint bahwa jendela lebih besar daripada tebakan. Tetap tunduk pada
|
|
562
|
+
// nilai eksak operator? TIDAK: operator yang memasang flag eksplisit sudah
|
|
563
|
+
// dihormati di `contextWindowBase`, namun bila flag itu TERBUKTI kurang
|
|
564
|
+
// (overflow nyata terjadi), menaikkan satu anak tangga lebih benar daripada
|
|
565
|
+
// mengulang kegagalan yang sama.
|
|
566
|
+
const escalated = escalatedWindows.get(escalationKey(model))
|
|
567
|
+
if (escalated !== undefined) return escalated
|
|
568
|
+
return contextWindowBase(model)
|
|
569
|
+
}
|
|
570
|
+
// Batas output model: dipakai sebagai reserve output (bukan angka tetap 20k).
|
|
571
|
+
// Dicari dari metadata provider (`maxOutputTokens`, diisi dari `/models` bila
|
|
572
|
+
// endpoint melaporkannya); tanpa metadata → `undefined` = reserve default.
|
|
573
|
+
const maxOutputTokensForModel = (model?: string): number | undefined => {
|
|
574
|
+
try {
|
|
575
|
+
const fromCore = rest.maxOutputTokensForModel?.(model)
|
|
576
|
+
if (typeof fromCore === "number" && Number.isSafeInteger(fromCore) && fromCore > 0)
|
|
577
|
+
return fromCore
|
|
578
|
+
const fromProvider = (
|
|
579
|
+
provider as { maxOutputTokensForModel?: (m?: string) => number }
|
|
580
|
+
).maxOutputTokensForModel?.(model)
|
|
581
|
+
if (
|
|
582
|
+
typeof fromProvider === "number" &&
|
|
583
|
+
Number.isSafeInteger(fromProvider) &&
|
|
584
|
+
fromProvider > 0
|
|
585
|
+
)
|
|
586
|
+
return fromProvider
|
|
587
|
+
} catch {}
|
|
588
|
+
return undefined
|
|
589
|
+
}
|
|
590
|
+
// ── Eskalasi adaptif jendela konteks ───────────────────────────────────
|
|
591
|
+
// Nilai yang dinaikkan SESI INI saja (bukan ditulis ke config: perubahan
|
|
592
|
+
// konfigurasi harus lewat /sync atau niat operator). Kunci = `provider::model`
|
|
593
|
+
// ternormalisasi; nilai = jendela hasil eskalasi.
|
|
594
|
+
const escalatedWindows = new Map<string, number>()
|
|
595
|
+
const escalationKey = (model?: string): string => {
|
|
596
|
+
const raw = model ?? currentContextModel() ?? "default"
|
|
597
|
+
return raw.includes("::") ? raw : `${provider.id}::${raw}`
|
|
598
|
+
}
|
|
599
|
+
/** Jendela "dasar" sebelum eskalasi: hasil resolusi biasa, tanpa eskalasi. */
|
|
600
|
+
const contextWindowBase = (model?: string): number => {
|
|
543
601
|
const explicit = rest.contextWindowTokens
|
|
544
|
-
if (
|
|
545
|
-
!rest.contextWindowTokensForModel &&
|
|
546
|
-
typeof explicit === "number" &&
|
|
547
|
-
Number.isSafeInteger(explicit) &&
|
|
548
|
-
explicit > 0
|
|
549
|
-
) {
|
|
550
|
-
return explicit
|
|
551
|
-
}
|
|
552
602
|
try {
|
|
553
603
|
const resolved =
|
|
554
604
|
rest.contextWindowTokensForModel?.(model) ?? provider.contextWindowTokensForModel?.(model)
|
|
@@ -559,6 +609,33 @@ export async function createMinicodeSession(
|
|
|
559
609
|
? explicit
|
|
560
610
|
: DEFAULT_FALLBACK_CONTEXT_WINDOW_TOKENS
|
|
561
611
|
}
|
|
612
|
+
/**
|
|
613
|
+
* Naikkan jendela satu anak tangga setelah overflow terverifikasi.
|
|
614
|
+
*
|
|
615
|
+
* KENAPA otomatis: user yang sedang bekerja tidak bisa tahu ada anak tangga
|
|
616
|
+
* berikutnya — dan sesi yang mati di tengah jalan jauh lebih mahal daripada
|
|
617
|
+
* satu eskalasi. Namun ia tetap BOUNDED: satu langkah per kejadian, tak
|
|
618
|
+
* pernah melebihi batas atas, dan hasilnya hanya berlaku untuk sesi ini.
|
|
619
|
+
*/
|
|
620
|
+
const escalateContextWindow = (model: string | undefined, observedTokens: number) => {
|
|
621
|
+
const key = escalationKey(model)
|
|
622
|
+
const base = escalatedWindows.get(key) ?? contextWindowBase(model)
|
|
623
|
+
// Bila pengamatan sudah jelas melampaui jendela dasar, naik dari nilai
|
|
624
|
+
// pengamatan; kalau tidak, naik dari jendela yang sekarang dipakai.
|
|
625
|
+
const from = Math.max(base, Number.isFinite(observedTokens) ? observedTokens : 0)
|
|
626
|
+
const next = nextLadderStep(from)
|
|
627
|
+
if (next === undefined || next <= base) return
|
|
628
|
+
escalatedWindows.set(key, next)
|
|
629
|
+
try {
|
|
630
|
+
rest.onContextWindowEscalated?.({
|
|
631
|
+
model: key,
|
|
632
|
+
fromTokens: base,
|
|
633
|
+
toTokens: next,
|
|
634
|
+
observedTokens,
|
|
635
|
+
})
|
|
636
|
+
} catch {}
|
|
637
|
+
}
|
|
638
|
+
|
|
562
639
|
const dynamicProvider: ModelProvider = {
|
|
563
640
|
id: provider.id,
|
|
564
641
|
get models() {
|
|
@@ -568,6 +645,7 @@ export async function createMinicodeSession(
|
|
|
568
645
|
const system = computeLiveSystem()
|
|
569
646
|
const model = req.model ?? currentContextModel()
|
|
570
647
|
let limit = contextWindowForModel(model)
|
|
648
|
+
const maxOutputTokens = maxOutputTokensForModel(model)
|
|
571
649
|
const estimatorModel = model?.includes("::") ? model : (currentContextModel() ?? model)
|
|
572
650
|
let calibration = calibrationFor(estimatorModel)
|
|
573
651
|
let estimator = (text: string) => preciseEstimator(estimatorModel, text)
|
|
@@ -598,10 +676,11 @@ export async function createMinicodeSession(
|
|
|
598
676
|
}
|
|
599
677
|
// Sisakan ruang framing dan respons minimum. Tanpa reserve, request yang
|
|
600
678
|
// tepat menyentuh batas provider tetap ditolak setelah biaya dibakar.
|
|
601
|
-
// Reserve
|
|
602
|
-
//
|
|
603
|
-
//
|
|
604
|
-
|
|
679
|
+
// Reserve dihitung dari anggaran konteks terpusat (`context-budget.ts`):
|
|
680
|
+
// `min(max_output_tokens, 20k)` dengan lantai 4k dan lantai 2% jendela.
|
|
681
|
+
// Nilai lama `min(256, limit/10)` praktis nol untuk jendela besar, jadi
|
|
682
|
+
// model berjendela 1M tetap kehabisan ruang jawaban di ambang batas.
|
|
683
|
+
let reserve = outputReserveFor(limit, maxOutputTokens)
|
|
605
684
|
let outputAllowance = Math.max(0, limit - inputTokens - reserve)
|
|
606
685
|
let outputTokens = 0
|
|
607
686
|
const streamedText = createIncrementalTokenCounter()
|
|
@@ -626,6 +705,13 @@ export async function createMinicodeSession(
|
|
|
626
705
|
// jalur recovery `force_compact_and_retry`: meringkas lalu coba lagi,
|
|
627
706
|
// alih-alih mati `✗ Context window exceeded`. Bounded — loop recovery
|
|
628
707
|
// menolak bila kompaksi no-op (compactedForRecovery sudah set).
|
|
708
|
+
//
|
|
709
|
+
// Eskalasi adaptif: overflow INI adalah bukti terverifikasi bahwa jendela
|
|
710
|
+
// yang kita pakai terlalu kecil ATAU penuh. Naikkan satu anak tangga untuk
|
|
711
|
+
// sesi ini supaya percobaan berikutnya (dan turn berikut) punya ruang.
|
|
712
|
+
// Hanya dipanggil pada jalur yang benar-benar kehabisan konteks — bukan
|
|
713
|
+
// 429/402/auth/jaringan.
|
|
714
|
+
escalateContextWindow(model, actualInput + actualOutput)
|
|
629
715
|
return new ProviderError(
|
|
630
716
|
"context_length_exceeded",
|
|
631
717
|
`context window budget reached for the selected model: input ${actualInput} + output ${actualOutput} exceeds ${limit} tokens; reduce the prompt/tools or select a larger context window`,
|
|
@@ -665,7 +751,7 @@ export async function createMinicodeSession(
|
|
|
665
751
|
estimateSystem(system, estimator) +
|
|
666
752
|
estimateTools(tools, estimator),
|
|
667
753
|
)
|
|
668
|
-
reserve =
|
|
754
|
+
reserve = outputReserveFor(limit, maxOutputTokens)
|
|
669
755
|
outputAllowance = Math.max(0, limit - inputTokens - reserve)
|
|
670
756
|
}
|
|
671
757
|
}
|
|
@@ -677,7 +763,7 @@ export async function createMinicodeSession(
|
|
|
677
763
|
estimateSystem(system, estimator) +
|
|
678
764
|
estimateTools(tools, estimator),
|
|
679
765
|
)
|
|
680
|
-
reserve =
|
|
766
|
+
reserve = outputReserveFor(limit, maxOutputTokens)
|
|
681
767
|
outputAllowance = Math.max(0, limit - inputTokens - reserve)
|
|
682
768
|
}
|
|
683
769
|
admittedFactor = currentFactor
|
|
@@ -706,14 +792,16 @@ export async function createMinicodeSession(
|
|
|
706
792
|
// sebenarnya konteks kepanjangan meski teksnya tak menyebut "context".
|
|
707
793
|
// Reklasifikasi sebagai context_length_exceeded supaya kernel menempuh
|
|
708
794
|
// compact-and-retry (bounded + no-op-safe) alih-alih mati fatal. Ambang
|
|
709
|
-
//
|
|
710
|
-
//
|
|
711
|
-
//
|
|
712
|
-
//
|
|
795
|
+
// tanngal
|
|
796
|
+
// `localInputTokens >= contextReclassifyThreshold(limit)` — ambang
|
|
797
|
+
// RELATIF jendela (`min(50_000, window*0.5)`), bukan 50.000 mutlak.
|
|
798
|
+
// Angka mutlak membuat model berjendela < 50k mustahil menempuh
|
|
799
|
+
// compact-and-retry: jendelanya penuh jauh sebelum ambang tercapai,
|
|
800
|
+
// sehingga 400 generik selalu mati fatal.
|
|
713
801
|
if (
|
|
714
802
|
error instanceof ProviderError &&
|
|
715
803
|
(error.category === "invalid_request" || error.category === "unknown") &&
|
|
716
|
-
localInputTokens >=
|
|
804
|
+
localInputTokens >= contextBudgetFor(limit, maxOutputTokens).reclassifyThreshold
|
|
717
805
|
) {
|
|
718
806
|
throw overflow(inputTokens, outputTokens)
|
|
719
807
|
}
|
|
@@ -736,6 +824,7 @@ export async function createMinicodeSession(
|
|
|
736
824
|
...rest,
|
|
737
825
|
contextWindowTokens: contextWindowForModel(currentContextModel()),
|
|
738
826
|
contextWindowTokensForModel: contextWindowForModel,
|
|
827
|
+
maxOutputTokensForModel: maxOutputTokensForModel,
|
|
739
828
|
// Kompaksi lebih agresif (host-side): ringkas mulai 65% jendela, bukan 75%.
|
|
740
829
|
budget: aggressiveBudgetPolicy,
|
|
741
830
|
provider: dynamicProvider,
|
|
@@ -873,7 +962,27 @@ export async function createMinicodeSession(
|
|
|
873
962
|
},
|
|
874
963
|
run(input: string, runOpts?: { signal?: AbortSignal; model?: string }) {
|
|
875
964
|
activeContextModel = runOpts?.model ?? opts.model
|
|
876
|
-
|
|
965
|
+
const modelForRun = activeContextModel
|
|
966
|
+
return core.run(input, runOpts).catch((error: unknown) => {
|
|
967
|
+
// Kernel melaporkan kehabisan konteks sebagai `budget_exceeded` dengan
|
|
968
|
+
// `details.reason` = `fixpoint` atau `critical`. Keduanya BUKTI
|
|
969
|
+
// terverifikasi bahwa jendela yang dipakai terlalu kecil untuk sesi ini
|
|
970
|
+
// — sama sahnya dengan penolakan provider. Tanpa eskalasi di sini,
|
|
971
|
+
// sesi yang sudah di titik tetap langsung mati padahal endpoint mungkin
|
|
972
|
+
// punya kapasitas jauh lebih besar.
|
|
973
|
+
//
|
|
974
|
+
// Bukan pemicu: `max_steps_exceeded`, `max_turns`, `aborted`, timeout,
|
|
975
|
+
// dan error provider non-konteks — menaikkan jendela tak akan menolong.
|
|
976
|
+
if (error instanceof AgentError && error.kind === "budget_exceeded") {
|
|
977
|
+
const reason = error.details?.reason
|
|
978
|
+
if (reason === "fixpoint" || reason === "critical") {
|
|
979
|
+
const used =
|
|
980
|
+
typeof error.details?.fixedTokens === "number" ? error.details.fixedTokens : 0
|
|
981
|
+
escalateContextWindow(modelForRun, used)
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
throw error
|
|
985
|
+
})
|
|
877
986
|
},
|
|
878
987
|
abort() {
|
|
879
988
|
core.abort()
|
package/src/config.ts
CHANGED
|
@@ -17,20 +17,33 @@ const configLocks = new Map<string, Promise<void>>()
|
|
|
17
17
|
export async function withConfigLock<T>(path: string, fn: () => Promise<T>): Promise<T> {
|
|
18
18
|
const prev = configLocks.get(path) ?? Promise.resolve()
|
|
19
19
|
let release!: () => void
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
20
|
+
const gate = new Promise<void>((res) => (release = res))
|
|
21
|
+
// Yang DISIMPAN harus rantai yang sama dengan yang dibandingkan di finally.
|
|
22
|
+
// Dulu map menyimpan `prev.then(() => next)` sementara finally membandingkan
|
|
23
|
+
// dengan `next` — tak pernah sama, sehingga entri map tidak pernah dihapus
|
|
24
|
+
// dan rantai promise tumbuh per penulisan config.
|
|
25
|
+
const tail = prev.then(() => gate)
|
|
26
|
+
configLocks.set(path, tail)
|
|
25
27
|
await prev
|
|
26
28
|
try {
|
|
27
29
|
return await fn()
|
|
28
30
|
} finally {
|
|
29
31
|
release()
|
|
30
|
-
if (configLocks.get(path) ===
|
|
32
|
+
if (configLocks.get(path) === tail) configLocks.delete(path)
|
|
31
33
|
}
|
|
32
34
|
}
|
|
33
35
|
|
|
36
|
+
/** Asal nilai jendela konteks. `user` = operator menetapkan sendiri (presedensi
|
|
37
|
+
* tertinggi, tak pernah ditimpa otomatis); `endpoint` = dibaca dari metadata
|
|
38
|
+
* `/models` endpoint yang dipakai; `probe` = hasil eskalasi adaptif terverifikasi;
|
|
39
|
+
* `public-directory` = katalog publik (cache); `static-table` = tabel bawaan. */
|
|
40
|
+
export type ContextWindowSource =
|
|
41
|
+
| "user"
|
|
42
|
+
| "endpoint"
|
|
43
|
+
| "probe"
|
|
44
|
+
| "public-directory"
|
|
45
|
+
| "static-table"
|
|
46
|
+
|
|
34
47
|
export interface ProviderEntry {
|
|
35
48
|
id: string
|
|
36
49
|
baseUrl: string
|
|
@@ -38,9 +51,22 @@ export interface ProviderEntry {
|
|
|
38
51
|
apiKey: string
|
|
39
52
|
models: string[]
|
|
40
53
|
/** Context window tokens by exact model id; `*` is a provider-wide fallback.
|
|
41
|
-
* Values
|
|
42
|
-
*
|
|
54
|
+
* Values may be operator-supplied or discovered from the endpoint's `/models`
|
|
55
|
+
* metadata. Gateways often expose aliases whose real capacity is invisible
|
|
56
|
+
* otherwise, so an exact value from the endpoint in use wins over any catalog. */
|
|
43
57
|
contextWindows?: Record<string, number>
|
|
58
|
+
/** Asal tiap nilai `contextWindows`, per model id. Dipakai untuk presedensi:
|
|
59
|
+
* nilai `user` tak boleh ditimpa otomatis oleh endpoint/sync, sedangkan nilai
|
|
60
|
+
* `endpoint` boleh diperbarui dan kalah dari nilai eksak yang lebih baru.
|
|
61
|
+
* Entri tanpa catatan diperlakukan sebagai `user` (kompatibel ke belakang:
|
|
62
|
+
* config lama tanpa field ini dianggap niat operator). */
|
|
63
|
+
contextWindowSources?: Record<string, ContextWindowSource>
|
|
64
|
+
/** Batas output per model id (`max_output_tokens`) bila endpoint melaporkan.
|
|
65
|
+
* Dipakai sebagai reserve output proporsional; tanpa ini reserve memakai
|
|
66
|
+
* default 20k. */
|
|
67
|
+
maxOutputTokens?: Record<string, number>
|
|
68
|
+
/** Alias lama/global untuk batas output berlaku ke semua model provider. */
|
|
69
|
+
maxOutputTokensDefault?: number
|
|
44
70
|
providerHint?: string
|
|
45
71
|
/** Knob generik reasoning effort — dipetakan per-wire (openai reasoning_effort, anthropic thinking, gemini). */
|
|
46
72
|
reasoningEffort?: "low" | "medium" | "high"
|
|
@@ -105,6 +131,79 @@ export function localConfigNotice(cwd: string, allowLocal: boolean): string | un
|
|
|
105
131
|
return `[config] local config enabled: ${p}`
|
|
106
132
|
}
|
|
107
133
|
|
|
134
|
+
const VALID_CONTEXT_SOURCES: readonly ContextWindowSource[] = [
|
|
135
|
+
"user",
|
|
136
|
+
"endpoint",
|
|
137
|
+
"probe",
|
|
138
|
+
"public-directory",
|
|
139
|
+
"static-table",
|
|
140
|
+
]
|
|
141
|
+
|
|
142
|
+
/** Peta token-positif per model — dipakai untuk `contextWindows` dan
|
|
143
|
+
* `maxOutputTokens` supaya validasi keduanya tak bisa berbeda diam-diam. */
|
|
144
|
+
function normalizeTokenMap(
|
|
145
|
+
raw: unknown,
|
|
146
|
+
opts: { allowStar: boolean },
|
|
147
|
+
): Record<string, number> | undefined {
|
|
148
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined
|
|
149
|
+
const out: Record<string, number> = {}
|
|
150
|
+
for (const [model, tokens] of Object.entries(raw as Record<string, unknown>)) {
|
|
151
|
+
const keyOk = opts.allowStar ? model === "*" || model.length > 0 : model.length > 0
|
|
152
|
+
if (
|
|
153
|
+
keyOk &&
|
|
154
|
+
typeof tokens === "number" &&
|
|
155
|
+
Number.isSafeInteger(tokens) &&
|
|
156
|
+
tokens > 0 &&
|
|
157
|
+
tokens <= 20_000_000
|
|
158
|
+
) {
|
|
159
|
+
out[model] = tokens
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return Object.keys(out).length > 0 ? out : undefined
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Field kapasitas tambahan (`contextWindowSources`, `maxOutputTokens`) — dipisah
|
|
166
|
+
* agar `normalizeConfig` tetap terbaca dan asalnya tak bisa hilang diam-diam:
|
|
167
|
+
* asal hanya dipertahankan untuk model yang punya nilai jendela, sisa asing
|
|
168
|
+
* dibuang supaya config tidak menumpuk sampah dari versi lama. */
|
|
169
|
+
function normalizeCapacityExtras(
|
|
170
|
+
p: ProviderEntry,
|
|
171
|
+
contextWindows: Record<string, number> | undefined,
|
|
172
|
+
): Pick<ProviderEntry, "contextWindowSources" | "maxOutputTokens" | "maxOutputTokensDefault"> {
|
|
173
|
+
const extras: Pick<
|
|
174
|
+
ProviderEntry,
|
|
175
|
+
"contextWindowSources" | "maxOutputTokens" | "maxOutputTokensDefault"
|
|
176
|
+
> = {}
|
|
177
|
+
const rawSources = (p as { contextWindowSources?: unknown }).contextWindowSources
|
|
178
|
+
if (rawSources && typeof rawSources === "object" && !Array.isArray(rawSources)) {
|
|
179
|
+
const sources: Record<string, ContextWindowSource> = {}
|
|
180
|
+
for (const [model, value] of Object.entries(rawSources as Record<string, unknown>)) {
|
|
181
|
+
if (
|
|
182
|
+
typeof value === "string" &&
|
|
183
|
+
(VALID_CONTEXT_SOURCES as readonly string[]).includes(value) &&
|
|
184
|
+
contextWindows?.[model] !== undefined
|
|
185
|
+
) {
|
|
186
|
+
sources[model] = value as ContextWindowSource
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (Object.keys(sources).length > 0) extras.contextWindowSources = sources
|
|
190
|
+
}
|
|
191
|
+
const maxOut = normalizeTokenMap((p as { maxOutputTokens?: unknown }).maxOutputTokens, {
|
|
192
|
+
allowStar: false,
|
|
193
|
+
})
|
|
194
|
+
if (maxOut) extras.maxOutputTokens = maxOut
|
|
195
|
+
const maxOutDefault = (p as { maxOutputTokensDefault?: unknown }).maxOutputTokensDefault
|
|
196
|
+
if (
|
|
197
|
+
typeof maxOutDefault === "number" &&
|
|
198
|
+
Number.isSafeInteger(maxOutDefault) &&
|
|
199
|
+
maxOutDefault > 0 &&
|
|
200
|
+
maxOutDefault <= 20_000_000
|
|
201
|
+
) {
|
|
202
|
+
extras.maxOutputTokensDefault = maxOutDefault
|
|
203
|
+
}
|
|
204
|
+
return extras
|
|
205
|
+
}
|
|
206
|
+
|
|
108
207
|
export function normalizeConfig(raw: unknown): MinicodeConfig {
|
|
109
208
|
const cfg = raw as Record<string, unknown>
|
|
110
209
|
const providers = Array.isArray(cfg?.providers)
|
|
@@ -132,6 +231,7 @@ export function normalizeConfig(raw: unknown): MinicodeConfig {
|
|
|
132
231
|
...p,
|
|
133
232
|
contextWindows:
|
|
134
233
|
contextWindows && Object.keys(contextWindows).length > 0 ? contextWindows : undefined,
|
|
234
|
+
...normalizeCapacityExtras(p, contextWindows),
|
|
135
235
|
}
|
|
136
236
|
})
|
|
137
237
|
: []
|
package/src/constants.ts
CHANGED
|
@@ -54,11 +54,36 @@ export const LIMITS = {
|
|
|
54
54
|
* request provider: `Math.min(reserve, limit/10)` — cadangan tak naik tanpa
|
|
55
55
|
* batas pada jendela raksasa (1M token tetap cukup 256 untuk framing). */
|
|
56
56
|
CONTEXT_WINDOW_RESERVE_CAP_TOKENS: 256,
|
|
57
|
-
/**
|
|
58
|
-
* 400 `invalid_request` generik sebagai
|
|
59
|
-
* mati fatal. Di bawah ambang ini, 400
|
|
60
|
-
* konteks). Proxy monotonik ukuran konteks,
|
|
57
|
+
/** BATAS ATAS ambang ukuran konteks (estimasi chars/token lokal) untuk
|
|
58
|
+
* mengklasifikasi 400 `invalid_request` generik sebagai
|
|
59
|
+
* `context_length_exceeded` alih-alih mati fatal. Di bawah ambang ini, 400
|
|
60
|
+
* dianggap error format sah (bukan konteks). Proxy monotonik ukuran konteks,
|
|
61
|
+
* bukan hitungan presisi.
|
|
62
|
+
*
|
|
63
|
+
* KENAPA batas atas, bukan angka mutlak: nilai ini dulu 50.000 mutlak,
|
|
64
|
+
* sehingga model berjendela < 50.000 tak pernah bisa menempuh jalur
|
|
65
|
+
* recovery `compact-and-retry` — jendelanya penuh jauh sebelum ambangnya
|
|
66
|
+
* tercapai. Ambang efektif kini `min(nilai ini, window * 0.5)` (lihat
|
|
67
|
+
* `contextReclassifyThreshold`), jadi tetap aman untuk jendela besar tanpa
|
|
68
|
+
* mematikan recovery di jendela kecil. */
|
|
61
69
|
CONTEXT_RECLASSIFY_400_MIN_LOCAL_TOKENS: 50_000,
|
|
70
|
+
/** Fraksi jendela konteks untuk ambang reklasifikasi 400 di atas. 0.5 dipilih
|
|
71
|
+
* karena 400 generik yang benar-benar "konteks kepanjangan" praktis selalu
|
|
72
|
+
* terjadi setelah separuh jendela terpakai (chars/4 under-count paling buruk
|
|
73
|
+
* ~2×, jadi 0.5 masih di bawah garis aman). */
|
|
74
|
+
CONTEXT_RECLASSIFY_400_WINDOW_RATIO: 0.5,
|
|
75
|
+
/** Microcompact — jumlah hasil tool TERBARU yang dipertahankan utuh. 5 adalah
|
|
76
|
+
* titik kumpul lintas implementasi harness produksi (median 5 dari enam
|
|
77
|
+
* implementasi yang disurvei); di bawah 3 model cenderung mengulang
|
|
78
|
+
* pembacaan berkas yang sama. */
|
|
79
|
+
MICROCOMPACT_KEEP_RECENT: 5,
|
|
80
|
+
/** Hemat minimum agar pemangkasan hasil tool sepadan. Di bawah ini, yang
|
|
81
|
+
* dibuang hanya informasi tanpa manfaat token. */
|
|
82
|
+
MICROCOMPACT_MIN_SAVING_TOKENS: 20_000,
|
|
83
|
+
/** Hasil tool harus menempati porsi ini dari budget konteks agar pemangkasan
|
|
84
|
+
* dipertimbangkan — bila konteks dikuasai pesan lain, memangkas tool hanya
|
|
85
|
+
* membuang fakta. */
|
|
86
|
+
MICROCOMPACT_MIN_TOOL_SHARE: 0.4,
|
|
62
87
|
/** R11 — ambang volume-baca per turn (char hasil tool terakumulasi) untuk
|
|
63
88
|
* observer opt-in `MINICODE_READ_VOLUME_GUARD=1`. Di atas ini, peringatkan
|
|
64
89
|
* sekali per turn: "banyak dibaca tanpa kompaksi" = risiko degradasi
|
package/src/daemon/discovery.ts
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
// koneksi yang berhasil; lease segar hanya menghasilkan "suspect" —
|
|
15
15
|
// ada kandidat, belum terbukti.
|
|
16
16
|
|
|
17
|
+
import { execFileSync } from "node:child_process"
|
|
17
18
|
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"
|
|
18
19
|
import { resolve } from "node:path"
|
|
19
20
|
import { resolveLocalDbPath } from "../lib/db-path.ts"
|
|
@@ -77,11 +78,34 @@ function leasePath(cwd?: string): string {
|
|
|
77
78
|
return resolveLocalDbPath(LEASE_FILE, cwd)
|
|
78
79
|
}
|
|
79
80
|
|
|
81
|
+
/**
|
|
82
|
+
* Win32 mengabaikan mode POSIX, jadi `0600` pada berkas endpoint (yang memuat
|
|
83
|
+
* bootstrap secret) TIDAK membatasi siapa pun. Satu-satunya kontrol nyata
|
|
84
|
+
* adalah ACL: cabut warisan lalu beri hak penuh hanya ke user pemilik.
|
|
85
|
+
*
|
|
86
|
+
* Best-effort dan senyap: kegagalan icacls (kebijakan domain, PATH aneh)
|
|
87
|
+
* tidak boleh menggagalkan daemon — tapi juga tidak boleh dianggap aman.
|
|
88
|
+
* Residual yang tersisa (mesin multi-user Windows tanpa izin mengubah ACL)
|
|
89
|
+
* didokumentasikan di docs/security.md.
|
|
90
|
+
*/
|
|
91
|
+
function hardenAcl(path: string): void {
|
|
92
|
+
if (process.platform !== "win32") return
|
|
93
|
+
const user = process.env.USERNAME
|
|
94
|
+
if (!user) return
|
|
95
|
+
try {
|
|
96
|
+
execFileSync("icacls", [path, "/inheritance:r", "/grant:r", `${user}:F`], {
|
|
97
|
+
stdio: "ignore",
|
|
98
|
+
windowsHide: true,
|
|
99
|
+
})
|
|
100
|
+
} catch {}
|
|
101
|
+
}
|
|
102
|
+
|
|
80
103
|
/** Tulis atomik (tmp + rename) supaya pembaca tak pernah melihat file separuh. */
|
|
81
104
|
function writeAtomic(path: string, value: unknown, mode = 0o600): void {
|
|
82
105
|
const tmp = `${path}.${process.pid}.tmp`
|
|
83
106
|
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode })
|
|
84
107
|
renameSync(tmp, path)
|
|
108
|
+
if (mode <= 0o600) hardenAcl(path)
|
|
85
109
|
}
|
|
86
110
|
|
|
87
111
|
export function writeEndpoint(ep: DaemonEndpoint, cwd?: string): string {
|