minicode-ai 0.23.0 → 0.25.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.
Files changed (75) hide show
  1. package/README.md +2 -2
  2. package/cli/tui.ts +28 -2
  3. package/docs/README.md +2 -2
  4. package/docs/SUMMARY.md +10 -19
  5. package/docs/TERMINAL_CONTRACT.md +82 -28
  6. package/docs/architecture.md +1 -1
  7. package/docs/autonomous-scheduler.md +283 -2
  8. package/docs/choosing-mode.md +4 -4
  9. package/docs/concepts.md +39 -3
  10. package/docs/config.md +90 -4
  11. package/docs/environment.md +3 -0
  12. package/docs/getting-started.md +58 -2
  13. package/docs/repl.md +1 -1
  14. package/docs/security.md +49 -2
  15. package/docs/tools.md +2 -1
  16. package/package.json +2 -36
  17. package/src/app/provider-layer.ts +1 -1
  18. package/src/config.ts +2 -0
  19. package/src/constants.ts +3 -0
  20. package/src/lib/safe-open.ts +21 -12
  21. package/src/memory/vector.ts +0 -31
  22. package/src/policy/context-window.ts +0 -33
  23. package/src/policy/no-progress.ts +1 -1
  24. package/src/policy/permission.ts +5 -0
  25. package/src/policy/scrub.ts +15 -2
  26. package/src/policy/tool-contract.ts +11 -9
  27. package/src/presentation/reducer.ts +1 -0
  28. package/src/providers/anthropic.ts +3 -3
  29. package/src/providers/detect.ts +27 -0
  30. package/src/providers/provision.ts +15 -1
  31. package/src/task/autonomous-policy.ts +7 -0
  32. package/src/task/graph-validate.ts +1 -1
  33. package/src/task/session-authority.ts +0 -5
  34. package/src/task/store.ts +0 -4
  35. package/src/tools/ask_user.ts +14 -1
  36. package/src/tools/bash.ts +57 -9
  37. package/src/tools/context.ts +10 -0
  38. package/src/tools/delete_file.ts +3 -2
  39. package/src/tools/edit.ts +5 -4
  40. package/src/tools/git.ts +70 -12
  41. package/src/tools/glob.ts +13 -5
  42. package/src/tools/grep.ts +26 -10
  43. package/src/tools/index.ts +3 -2
  44. package/src/tools/lsp.ts +15 -9
  45. package/src/tools/move_file.ts +4 -3
  46. package/src/tools/patch.ts +5 -4
  47. package/src/tools/read_file.ts +3 -2
  48. package/src/tools/read_image.ts +3 -2
  49. package/src/tools/task.ts +1 -0
  50. package/src/tools/todo.ts +4 -8
  51. package/src/tools/write_file.ts +4 -3
  52. package/src/ui/approval/prompt.ts +226 -77
  53. package/src/ui/footer.ts +41 -29
  54. package/src/ui/i18n/en.ts +4 -0
  55. package/src/ui/i18n/id.ts +4 -0
  56. package/src/ui/render/activity-group.ts +1 -0
  57. package/src/ui/render/ledger.ts +1 -9
  58. package/src/ui/render/logo.ts +0 -5
  59. package/src/ui/render/markdown-table.ts +0 -3
  60. package/src/ui/render/table-grid.ts +0 -3
  61. package/src/ui/render/theme.ts +31 -5
  62. package/src/ui/runtime/screen.ts +7 -1
  63. package/src/ui/screens/dialog.ts +45 -81
  64. package/src/ui/screens/form.ts +10 -10
  65. package/src/ui/screens/model-manager.ts +7 -10
  66. package/src/ui/screens/picker.ts +8 -11
  67. package/src/ui/screens/provider-manager.ts +9 -13
  68. package/src/ui/tui/app.ts +92 -9
  69. package/src/ui/tui/transcript.ts +4 -0
  70. package/docs/P14_OPEN_WORK.md +0 -290
  71. package/docs/config-providers.md +0 -87
  72. package/docs/glossary.md +0 -39
  73. package/docs/quickstart.md +0 -60
  74. package/docs/security-model.md +0 -96
  75. package/docs/terminal.md +0 -91
package/docs/security.md CHANGED
@@ -2,11 +2,32 @@
2
2
 
3
3
  ## Prinsip
4
4
 
5
+ Minicode mengontrol **kemampuan bertingkat** (layered capability control), bukan niat model.
6
+ Model boleh salah paham; yang menentukan apa yang benar-benar terjadi adalah gerbang
7
+ deterministik di bawahnya: izin → jail → guard → validasi → eksekusi → bukti.
8
+
5
9
  1. **Fail-closed di jalur tak pasti**: tool tanpa backend tersedia menolak (`code_run`), sandbox yang diminta tapi tidak tersedia ditolak (fail-closed; fallback host hanya via `MINICODE_SANDBOX_ALLOW_FALLBACK=1`), provider OAuth yang belum login dibuang dari daftar, auth non-TTY fail-fast.
6
10
  2. **Ukur, bukan klaim**: bash-guard divalidasi korpus manual pola serangan + perintah sah — jalankan `bun run gate:bash` untuk angka terkini (exit 0 = 0 bypass / 0 over-block).
7
11
  3. **Teks eksternal = tidak terpercaya**: output tool, MCP, web, bahkan output verify dibungkus fence; `sanitizeAnsi` menyaring escape ANSI dari teks model/tool sebelum render.
8
12
  4. **Permission mengontrol pemanggilan, bukan capability**: di ASK, satu approval hanya mencakup pasangan server+tool+args (MCP); capability di balik server tak bisa diketahui statis.
9
13
 
14
+ ## Execution Chain
15
+
16
+ Setiap pemanggilan tool melewati rantai ini, berurutan:
17
+
18
+ ```
19
+ Permission → Jail → Bash Guard → Argument Validation → Executor → Journal / Recovery
20
+ ```
21
+
22
+ | Tahap | Fungsi |
23
+ |---|---|
24
+ | **Permission** | Mode izin (`src/policy/permission.ts`) memutuskan allow/deny/ask per pasangan tool+args. Berlaku SEBELUM efek apa pun. |
25
+ | **Jail** | Path di luar workspace, symlink keluar, file sensitif (`.env`, `.git/config`), dan state milik minicode (`.minicode/*.db`, todos, jurnal, config) ditolak — **bahkan di `--allow-all`** (kecuali mode `unrestricted`, lihat §Mode dan akses di bawah). |
26
+ | **Bash Guard** | Perintah shell dinormalisasi dulu (buang quote/wrapper/variabel sederhana), baru diperiksa polanya. Menolak env-dump, exfiltrasi upload, interpreter inline, destruksi luas. |
27
+ | **Argument Validation** | Skema argumen divalidasi kernel sebelum eksekusi; argumen invalid ditolak tanpa efek. |
28
+ | **Executor** | Menjalankan yang lolos: read paralel, write dibatasi konkurensinya, abort-aware, output dipotong dengan penanda (tak pernah diam-diam). |
29
+ | **Journal / Recovery** | Tiap mutasi dicatat sebagai `pending` lalu `committed`/`failed`/`unknown`; finalisasi menandai cakupan turn durable. Resume tak pernah mengulang buta (lihat [Recovery](#recovery)). |
30
+
10
31
  ## Mode dan akses
11
32
 
12
33
  Kontrol mode punya tiga sumbu: **WorkMode** (`DISCUSS`/`PLAN`/`BUILD`) membatasi cara kerja agent; **PermissionMode** (`AUTO`/`ASK`) menentukan kapan dibutuhkan persetujuan manusia; **Tool Access Policy** menentukan capability yang tersedia. Nilai internal `readonly`, `plan`, `allowlist`, dan `allow-all` masih ada untuk batas akses dan kompatibilitas, tetapi bukan empat mode pengawasan tambahan. Hard deny path jail, owned-state, dan bash-guard tetap berlaku. Detail kombinasi dan interface ada di [Memilih Mode](choosing-mode.md) dan [Policy & Sandbox](policy-sandbox.md).
@@ -77,9 +98,35 @@ provider model pihak ketiga.
77
98
 
78
99
  Setiap turn checkpoint shadow-git + recovery journal `.minicode/journal-<sesi>.jsonl` (`pending` → `committed`/`failed`/`unknown`; finalisasi menandai cakupan turn durable). Saat resume: `committed` yang turn-nya hilang tidak diulang; `pending`/`failed`/`unknown` → direktif verifikasi, dilarang redo buta; `committed` MCP = external-acknowledged wajib baca-balik. Detail di [Memory & Sessions](memory-sessions.md).
79
100
 
101
+ ## Dangerous Capabilities
102
+
103
+ Minicode **tidak menyediakan tool** untuk (terverifikasi di `src/tools/`):
104
+
105
+ - `git fetch`, `pull`, `clone` — tak ada tool git jaringan pembaca
106
+ - `git reset`, `amend`, `rebase`, `checkout`, `branch -D`, `stash drop`
107
+ - Eksekusi remote / deploy bawaan
108
+
109
+ Satu-satunya operasi jaringan git adalah `git_push` (di-gate seperti `git_commit`: TTY minta sekali, non-TTY tolak, `readonly/plan/allowlist` tolak, sub-agent tidak mendapatkannya). Tool ini memakai hardening `GIT_SAFE_BASE` dan di mode `unrestricted` mendapat kredensial git sempit (lihat §Mode dan akses).
110
+
111
+ Catatan jujur: operasi lain tetap BISA diketik lewat `bash` (tunduk pada bash-guard + jail, BUKAN larangan). `git` via bash menjalankan konfigurasi repo apa adanya (hook/filter/driver milik repo). Tool baca `git_*` dinetralkan; `git_push` menetralkan hook/filter via `GIT_SAFE_BASE`; `git_commit` menolak sebelum staging bila filter Git terkonfigurasi. Di repo tak-terpercaya, utamakan tool baca dan tinjau konfigurasi sebelum memakai Git manual.
112
+
113
+ ## Limitations
114
+
115
+ - **Repo hooks/filter/driver:** `git` via bash mengeksekusinya (semantik stock-git); tool baca `git_*` menetralkan filter, sedangkan `git_commit` menolak bila menemukan filter terkonfigurasi.
116
+ - **Bash arbitrer:** guard adalah analisis statis; substitusi dinamis (`$(curl …)`) butuh sandbox OS/docker untuk isolasi nyata.
117
+ - **Efek eksternal MCP:** setelah terjadi, tak bisa dibatalkan dari sini.
118
+ - **Provider/network:** data melewati provider pilihan Anda; Minicode tak menambahkan transmisi sendiri.
119
+ - **Perilaku model:** pemilihan tool, klaim sukses, dan kepatuhan intent adalah sifat model — orkestrasi menjamin bukti dan batas, bukan kebijaksanaan.
120
+ - **Server LSP:** di-spawn dari perintah di config Anda; hanya daftarkan server yang Anda percaya.
121
+ - **Repo tak-terpercaya:** perlakukan seperti menjalankan `git`/`bash` manual di sana — karena memang itu yang terjadi di balik tool.
122
+
123
+ ## Security Contact
124
+
125
+ Belum ada kontak keamanan privat. Laporkan masalah via [GitHub Issues](https://github.com/minilabs-id/minicode/issues) **tanpa menyertakan kredensial, token, atau data sensitif** — cukup langkah reproduksi minimal + output `minicode doctor`.
126
+
80
127
  ## Lanjut
81
128
 
82
- - [Security Model](security-model.md) — rantai eksekusi, trust boundary, dan limitasi dalam satu halaman.
129
+ - [Keamanan](security.md) — rantai eksekusi, trust boundary, dan limitasi dalam satu halaman.
83
130
  - [Policy & Sandbox](policy-sandbox.md) — mode, tool access policy, dan detail guard.
84
- - [Kontrak Terminal](terminal.md) — kenapa warna di-gate TTY.
131
+ - [Kontrak Terminal](TERMINAL_CONTRACT.md) — kenapa warna di-gate TTY.
85
132
  - [Otomasi & CI](exec.md) — batasan agent di CI (fail-closed non-TTY).
package/docs/tools.md CHANGED
@@ -66,7 +66,8 @@ Batas `BASH_BACKGROUND_MAX_JOBS`; semua job mati saat CLI keluar.
66
66
  | `git_status` | `status --porcelain + diff --stat + log -10` | cwd jail |
67
67
  | `git_diff` | `diff` unstaged atau `--staged` | — |
68
68
  | `git_log` | `log --oneline -n` | — |
69
- | `git_commit` | Commit saja | **Di-gate** seperti `delegate_task` (TTY = minta sekali, non-TTY = tolak; `readonly/plan/allowlist` = tolak). Menolak sebelum staging jika config Git efektif memuat custom filter; tinjau filter terpercaya lalu lakukan commit manual. Sub-agent tidak mendapatkannya. Yang sengaja tidak ada: push/amend/reset/rebase/checkout/branch -D/stash drop. Pesan via `-m` tunggal agar `$()`/backtick tidak dieksekusi; `git add -- <paths>` agar file `-weird.txt` tidak jadi flag |
69
+ | `git_commit` | Commit saja | **Di-gate** seperti `delegate_task` (TTY = minta sekali, non-TTY = tolak; `readonly/plan/allowlist` = tolak). Menolak sebelum staging jika config Git efektif memuat custom filter; tinjau filter terpercaya lalu lakukan commit manual. Sub-agent tidak mendapatkannya. Yang sengaja tidak ada: amend/reset/rebase/checkout/branch -D/stash drop. Pesan via `-m` tunggal agar `$()`/backtick tidak dieksekusi; `git add -- <paths>` agar file `-weird.txt` tidak jadi flag |
70
+ | `git_push` | Push branch lokal ke remote | **Di-gate** seperti `git_commit`; butuh branch/remote eksplisit atau `setUpstream`. Hardening `GIT_SAFE_BASE` menetralkan hook pre-push + filter repo. Di mode `unrestricted`, kredensial git sempit (`GH_TOKEN`/`GITHUB_TOKEN`/`SSH_AUTH_SOCK`) diteruskan ke subprocess; di mode lain push hanya berhasil bila kredensial sudah tersedia di mesin (mis. credential helper OS). Sub-agent tidak mendapatkannya |
70
71
 
71
72
  ## Web
72
73
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minicode-ai",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
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,
@@ -51,41 +51,7 @@
51
51
  "scripts/vendor-overlays/minicode-context.patch",
52
52
  "README.md",
53
53
  "LICENSE",
54
- "docs/OUTPUT_EVENT_MODEL.md",
55
- "docs/OUTPUT_PROTOCOL_SPEC.md",
56
- "docs/OUTPUT_RENDERING_SPEC.md",
57
- "docs/OUTPUT_UX_RULES.md",
58
- "docs/P14_OPEN_WORK.md",
59
- "docs/SUMMARY.md",
60
- "docs/TERMINAL_CONTRACT.md",
61
- "docs/UI_RENDER_PIPELINE.md",
62
- "docs/agents.md",
63
- "docs/architecture.md",
64
- "docs/autonomous-scheduler.md",
65
- "docs/choosing-mode.md",
66
- "docs/cli.md",
67
- "docs/concepts.md",
68
- "docs/CONTROL-PLANE-MAP.md",
69
- "docs/config-providers.md",
70
- "docs/config.md",
71
- "docs/contributing.md",
72
- "docs/environment.md",
73
- "docs/exec.md",
74
- "docs/getting-started.md",
75
- "docs/glossary.md",
76
- "docs/mcp-lsp.md",
77
- "docs/memory-sessions.md",
78
- "docs/policy-sandbox.md",
79
- "docs/pricing-budget.md",
80
- "docs/quickstart.md",
81
- "docs/repl.md",
82
- "docs/security-model.md",
83
- "docs/security.md",
84
- "docs/skills.md",
85
- "docs/terminal.md",
86
- "docs/tools.md",
87
- "docs/troubleshooting.md",
88
- "docs/verify-benchmark.md"
54
+ "docs"
89
55
  ],
90
56
  "scripts": {
91
57
  "test": "bun test",
@@ -15,7 +15,7 @@ let currentConfig: MinicodeConfig | null = null
15
15
  * manusia ke stderr, `exec --json` menambah envelope mesin ke stdout.
16
16
  * Pesan = teks yang dulu dicetak langsung sebelum exit(1) — byte-identik. */
17
17
  export class NoProviderError extends Error {
18
- readonly name = "NoProviderError"
18
+ override readonly name = "NoProviderError"
19
19
  }
20
20
 
21
21
  const NO_PROVIDER_MESSAGE =
package/src/config.ts CHANGED
@@ -67,6 +67,8 @@ export interface ProviderEntry {
67
67
  maxOutputTokens?: Record<string, number>
68
68
  /** Alias lama/global untuk batas output berlaku ke semua model provider. */
69
69
  maxOutputTokensDefault?: number
70
+ /** Cache dari metadata endpoint (Fase 7.1); `undefined` = default aktif. */
71
+ enablePromptCaching?: boolean
70
72
  providerHint?: string
71
73
  /** Knob generik reasoning effort — dipetakan per-wire (openai reasoning_effort, anthropic thinking, gemini). */
72
74
  reasoningEffort?: "low" | "medium" | "high"
package/src/constants.ts CHANGED
@@ -12,6 +12,9 @@ export const LIMITS = {
12
12
  /** Tool output truncation */
13
13
  BASH_OUTPUT_MAX_CHARS: 20_000,
14
14
  BASH_DEFAULT_TIMEOUT_MS: 30_000,
15
+ /** Timeout default bash di mode `unrestricted` (30 menit): kompilasi/instal/
16
+ * push jaringan tak boleh mati oleh timeout pendek; `timeoutMs` tetap menang. */
17
+ UNRESTRICTED_BASH_TIMEOUT_MS: 1_800_000,
15
18
  /** bash background: proses hidup melewati batas turn, dipanggil via bash_output */
16
19
  BASH_BACKGROUND_MAX_JOBS: 8,
17
20
  BASH_BACKGROUND_MAX_LIFETIME_MS: 3_600_000,
@@ -52,13 +52,15 @@ async function resolveRealOrAncestor(abs: string): Promise<string> {
52
52
  export async function resolveSafePath(
53
53
  p: string,
54
54
  root: string,
55
+ relaxed = false,
55
56
  ): Promise<{ abs: string; real: string }> {
56
- if (isPathOutsideRoot(p, root)) throw new Error(`path outside workspace: ${p}`)
57
+ if (!relaxed && isPathOutsideRoot(p, root)) throw new Error(`path outside workspace: ${p}`)
57
58
  if (isSensitive(p)) throw new Error(`blocked sensitive file: ${p}`)
58
59
  const abs = isAbsolute(p) ? resolve(p) : resolve(root, p)
59
60
  const realRoot = await realpath(root).catch(() => root)
60
61
  const real = await resolveRealOrAncestor(abs)
61
- if (isPathOutsideRoot(real, realRoot)) throw new Error(`symlink points outside workspace: ${p}`)
62
+ if (!relaxed && isPathOutsideRoot(real, realRoot))
63
+ throw new Error(`symlink points outside workspace: ${p}`)
62
64
  if (isSensitive(real)) throw new Error(`blocked sensitive file: ${p}`)
63
65
  return { abs, real }
64
66
  }
@@ -81,11 +83,12 @@ export async function resolveSafePath(
81
83
  export async function safeOpenRead(
82
84
  abs: string,
83
85
  root: string,
86
+ relaxed = false,
84
87
  ): Promise<{ handle: FileHandle; realPath: string }> {
85
88
  const realRoot = await realpath(root).catch(() => root)
86
89
  // Pre-check cepat (fail-fast tanpa open)
87
90
  const preReal = await realpath(abs).catch(() => abs)
88
- if (isPathOutsideRoot(preReal, realRoot))
91
+ if (!relaxed && isPathOutsideRoot(preReal, realRoot))
89
92
  throw new Error(`symlink points outside workspace: ${abs}`)
90
93
  // Sensitif pada target nyata — symlink bernama jinak bisa menunjuk .env;
91
94
  // di sini agar semua pembaca via open (read_file/read_image/stat) mewarisinya.
@@ -96,7 +99,7 @@ export async function safeOpenRead(
96
99
  // keluar sesudah realpath pertama tetapi sebelum open.
97
100
  const expected = await statPath(preReal, { bigint: true })
98
101
  const checkedReal = await realpath(preReal)
99
- if (isPathOutsideRoot(checkedReal, realRoot))
102
+ if (!relaxed && isPathOutsideRoot(checkedReal, realRoot))
100
103
  throw new Error(`symlink points outside workspace: ${abs}`)
101
104
  if (isSensitive(checkedReal)) throw new Error(`blocked sensitive file: ${abs}`)
102
105
  if (expected.ino === 0n)
@@ -137,8 +140,8 @@ export async function safeOpenRead(
137
140
  return { handle, realPath: checkedReal }
138
141
  }
139
142
 
140
- export async function safeReadFile(abs: string, root: string): Promise<string> {
141
- const { handle } = await safeOpenRead(abs, root)
143
+ export async function safeReadFile(abs: string, root: string, relaxed = false): Promise<string> {
144
+ const { handle } = await safeOpenRead(abs, root, relaxed)
142
145
  try {
143
146
  return await handle.readFile("utf8")
144
147
  } finally {
@@ -154,10 +157,11 @@ export async function safeReadFileCapped(
154
157
  abs: string,
155
158
  root: string,
156
159
  maxBytes: number,
160
+ relaxed = false,
157
161
  ): Promise<{ text: string; truncated: boolean }> {
158
162
  if (!Number.isSafeInteger(maxBytes) || maxBytes < 1)
159
163
  throw new RangeError("maxBytes must be a positive safe integer")
160
- const { handle } = await safeOpenRead(abs, root)
164
+ const { handle } = await safeOpenRead(abs, root, relaxed)
161
165
  try {
162
166
  const st = await handle.stat()
163
167
  if (!st.isFile()) throw new Error(`refusing to read non-regular file: ${abs}`)
@@ -178,8 +182,8 @@ export async function safeReadFileCapped(
178
182
  }
179
183
  }
180
184
 
181
- export async function safeStat(abs: string, root: string) {
182
- const { handle } = await safeOpenRead(abs, root)
185
+ export async function safeStat(abs: string, root: string, relaxed = false) {
186
+ const { handle } = await safeOpenRead(abs, root, relaxed)
183
187
  try {
184
188
  return await handle.stat()
185
189
  } finally {
@@ -201,17 +205,22 @@ export async function safeStat(abs: string, root: string) {
201
205
  * via isPathOutsideRoot(real) + isSensitive(real), dan cek realpath di
202
206
  * bawah menjaga parent-dir yang di-swap jadi symlink keluar.
203
207
  */
204
- export async function assertSafeWriteTarget(abs: string, root: string): Promise<string> {
208
+ export async function assertSafeWriteTarget(
209
+ abs: string,
210
+ root: string,
211
+ relaxed = false,
212
+ ): Promise<string> {
205
213
  const realRoot = await realpath(root).catch(() => root)
206
214
  const dir = dirname(abs)
207
215
  const realDir = await resolveRealOrAncestor(dir)
208
- if (isPathOutsideRoot(realDir, realRoot)) throw new Error(`parent outside workspace: ${abs}`)
216
+ if (!relaxed && isPathOutsideRoot(realDir, realRoot))
217
+ throw new Error(`parent outside workspace: ${abs}`)
209
218
  const fileReal = await realpath(abs).catch(() => null)
210
219
  // basename (bukan split "/"): path Windows memakai backslash — split "/"
211
220
  // mengembalikan seluruh path absolut sehingga resolve() mengabaikan realDir
212
221
  // dan verifikasi parent symlink gugur diam-diam di Windows.
213
222
  const realAbs = fileReal ?? resolve(realDir, basename(abs))
214
- if (isPathOutsideRoot(realAbs, realRoot))
223
+ if (!relaxed && isPathOutsideRoot(realAbs, realRoot))
215
224
  throw new Error(`symlink points outside workspace: ${abs}`)
216
225
  return realAbs
217
226
  }
@@ -959,37 +959,6 @@ async function syncMemoryFileToSupersession(
959
959
  await files.appendMemory(`[supersession] fact ${oldId} → ${newId} (superseded)`, cwd)
960
960
  }
961
961
 
962
- export async function supersedeMemoryByIds(
963
- oldIds: string[],
964
- newId: string,
965
- cwd?: string,
966
- ): Promise<number> {
967
- let n = 0
968
- const db = open(cwd)
969
- try {
970
- await withBusyRetry(() => {
971
- for (const oldId of oldIds) {
972
- const oldRow = memoryEntryHeadId(db, oldId)
973
- if (oldRow) {
974
- // Tombstone SELURUH entri lama (semua chunk berbagi kepala), bukan
975
- // hanya id chunk yang diberikan (D8: entri bisa diberikan lewat
976
- // chunk mana pun).
977
- db.prepare(`UPDATE memory SET superseded_by = ? WHERE id = ? OR parent = ?`).run(
978
- newId,
979
- oldRow.headId,
980
- oldRow.headId,
981
- )
982
- n++
983
- }
984
- }
985
- db.prepare(`UPDATE memory SET supersedes = ? WHERE id = ?`).run(oldIds.join(","), newId)
986
- })
987
- } finally {
988
- db.close()
989
- }
990
- return n
991
- }
992
-
993
962
  /**
994
963
  * [Fase 8 / 8.1] Rekam pelajaran KANDIDAT (belum terverifikasi).
995
964
  * Pelajaran disimpan `provisional` sehingga retrieval default tidak akan
@@ -22,39 +22,6 @@ export const DEFAULT_FALLBACK_CONTEXT_WINDOW_TOKENS = 131_072
22
22
  export const DEFAULT_ALIAS_CONTEXT_WINDOW_TOKENS = 131_072
23
23
  const ROUTER_ALIAS_RE = /^(auto|best|default|cheapest|router)([:_-]|$)/i
24
24
 
25
- /**
26
- * Batas output model (`max_output_tokens`) yang dilaporkan endpoint/config.
27
- * `undefined` = tak diketahui (pemanggil memakai reserve default).
28
- *
29
- * KENAPA terpisah dari jendela: reserve output yang tepat bergantung pada
30
- * batas output model, bukan pada jendela. Menyatukan keduanya membuat model
31
- * berbatas output kecil mendapat reserve kelebihan, dan model berjendela
32
- * raksasa mendapat reserve hampir nol.
33
- */
34
- export function resolveMaxOutputTokens(config: MinicodeConfig, model?: string): number | undefined {
35
- let providerId: string | undefined
36
- let modelId = model
37
- let provider = undefined as MinicodeConfig["providers"][number] | undefined
38
- if (model?.includes("::")) {
39
- const sep = model.indexOf("::")
40
- providerId = model.slice(0, sep)
41
- modelId = model.slice(sep + 2)
42
- provider = config.providers.find((entry) => entry.id === providerId)
43
- } else if (model) {
44
- provider = config.providers.find((entry) => entry.models?.includes(model))
45
- providerId = provider?.id
46
- } else {
47
- provider = config.providers[0]
48
- providerId = provider?.id
49
- modelId = provider?.models?.[0]
50
- }
51
- const exact = modelId ? provider?.maxOutputTokens?.[modelId] : undefined
52
- if (typeof exact === "number" && exact > 0) return exact
53
- const providerDefault = provider?.maxOutputTokensDefault
54
- if (typeof providerDefault === "number" && providerDefault > 0) return providerDefault
55
- return undefined
56
- }
57
-
58
25
  export interface ContextWindowResolution {
59
26
  readonly tokens: number
60
27
  readonly source:
@@ -40,7 +40,7 @@ export type NoProgressVerdict =
40
40
  }
41
41
 
42
42
  export class NoProgressError extends Error {
43
- readonly name = "NoProgressError"
43
+ override readonly name = "NoProgressError"
44
44
  readonly kind: LoopGuardKind
45
45
  readonly reason: LoopGuardReason
46
46
 
@@ -510,6 +510,11 @@ function buildDiffPreview(name: string, args: unknown): string | undefined {
510
510
  const m = line(str(a.message), 160)
511
511
  return m ? out(`commit ${m}`) : undefined
512
512
  }
513
+ case "git_push": {
514
+ const remote = str(a.remote) || "origin"
515
+ const branch = str(a.branch) ? ` ${str(a.branch)}` : ""
516
+ return out(`push ${remote}${branch}`)
517
+ }
513
518
  default: {
514
519
  // Generic: name + ringkasan key=value yang dibasuh — jangan JSON mentah
515
520
  // (struktur/token yang tak dikenal scrub bisa bocor).
@@ -142,9 +142,21 @@ export const SECRET_ENV_RE = new RegExp(
142
142
  "i",
143
143
  )
144
144
 
145
- export function stripSecretsEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
145
+ /** Kredensial git yang boleh lolos ke child HANYA di mode `unrestricted`
146
+ * (push/remote via token/SSH agent). Nama TETAP, bukan wildcard. */
147
+ const GIT_CREDENTIAL_ALLOW_RE = /^(?:GITHUB_TOKEN|GH_TOKEN|SSH_AUTH_SOCK)$/i
148
+
149
+ export function stripSecretsEnv(
150
+ env: NodeJS.ProcessEnv,
151
+ allowGitCredentials = false,
152
+ ): NodeJS.ProcessEnv {
146
153
  const out: NodeJS.ProcessEnv = {}
147
154
  for (const [k, v] of Object.entries(env)) {
155
+ // Passthrough sempit hanya saat unrestricted (push via token/SSH agent).
156
+ if (allowGitCredentials && GIT_CREDENTIAL_ALLOW_RE.test(k)) {
157
+ out[k] = v
158
+ continue
159
+ }
148
160
  if (SECRET_ENV_RE.test(k)) continue
149
161
  out[k] = v
150
162
  }
@@ -157,10 +169,11 @@ export function stripSecretsEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
157
169
  export function sanitizeSpawnEnv(
158
170
  base: NodeJS.ProcessEnv,
159
171
  extra?: Record<string, string>,
172
+ allowGitCredentials = false,
160
173
  ): Record<string, string> {
161
174
  const merged: NodeJS.ProcessEnv = { ...base, ...(extra ?? {}) }
162
175
  const out: Record<string, string> = {}
163
- for (const [k, v] of Object.entries(stripSecretsEnv(merged))) {
176
+ for (const [k, v] of Object.entries(stripSecretsEnv(merged, allowGitCredentials))) {
164
177
  if (v !== undefined) out[k] = v
165
178
  }
166
179
  return out
@@ -422,6 +422,17 @@ export const TOOL_CONTRACTS: readonly ToolContractMetadata[] = [
422
422
  idempotent: false,
423
423
  journalMutation: true,
424
424
  }),
425
+ C({
426
+ name: "git_push",
427
+ sideEffectTier: "EXTERNAL_IRREVERSIBLE",
428
+ concurrencyClass: "exclusive",
429
+ gatedByDefault: true,
430
+ allowedInExplore: false,
431
+ allowedInAutonomous: false,
432
+ allowedInReadonly: false,
433
+ idempotent: false,
434
+ journalMutation: true,
435
+ }),
425
436
  C({
426
437
  name: "delegate_task",
427
438
  sideEffectTier: "EXTERNAL_IRREVERSIBLE",
@@ -494,9 +505,6 @@ const BY_NAME: ReadonlyMap<string, ToolContractMetadata> = new Map(
494
505
  TOOL_CONTRACTS.map((c) => [c.name, c]),
495
506
  )
496
507
 
497
- /** Nama tool yang dikenal registry ini (bukan tool MCP bertitik). */
498
- export const TOOL_CONTRACT_NAMES: readonly string[] = TOOL_CONTRACTS.map((c) => c.name)
499
-
500
508
  /**
501
509
  * Kontrak efektif untuk satu nama tool.
502
510
  *
@@ -595,9 +603,3 @@ export function classifyContractTool(name: string): "mutation" | "none" | "unkno
595
603
  if (c === undefined) return "unknown"
596
604
  return c.journalMutation ? "mutation" : "none"
597
605
  }
598
-
599
- /** True bila tool mengubah apa pun (bukan PURE_READ). */
600
- export function isSideEffectingTool(name: string): boolean {
601
- const c = contractForTool(name)
602
- return c === undefined ? true : c.sideEffectTier !== "PURE_READ"
603
- }
@@ -62,6 +62,7 @@ const MUTATION_TOOLS = new Set([
62
62
  "apply_patch",
63
63
  "delete_file",
64
64
  "git_commit",
65
+ "git_push",
65
66
  ])
66
67
 
67
68
  function isToolTerminal(status: ToolStatus): boolean {
@@ -68,10 +68,10 @@ export function createAnthropicProvider(config: AnthropicConfig): ModelProvider
68
68
  .replace(/\/+$/, "")
69
69
  .replace(/\/v1$/, "")
70
70
  const endpoint = `${baseUrl}/v1/messages`
71
- // Prompt caching aktif default; kill-switch config `enablePromptCaching:false`
72
- // (statis) + env `MINICODE_PROMPT_CACHE=0` (runtime, pola microcompact/probe).
71
+ // Presedensi: env > metadata `/models` > default aktif (undefined = aktif).
72
+
73
73
  const enableCache =
74
- config.enablePromptCaching !== false && process.env.MINICODE_PROMPT_CACHE !== "0"
74
+ process.env.MINICODE_PROMPT_CACHE !== "0" && config.enablePromptCaching !== false
75
75
 
76
76
  // brand `kind` dipakai router agar tahu konten Uint8Array ditangani native
77
77
  const provider: ModelProvider & { kind: "anthropic" } = {
@@ -13,6 +13,8 @@ export interface DetectedModel {
13
13
  /** Batas output model (`max_output_tokens`) bila dilaporkan. Dipakai sebagai
14
14
  * reserve output proporsional, bukan angka tetap. */
15
15
  maxOutputTokens?: number
16
+ /** Dukungan cache yang dilaporkan endpoint (Fase 7.1); `undefined` = tak disebut. */
17
+ promptCaching?: boolean
16
18
  }
17
19
 
18
20
  export interface DetectResult {
@@ -81,6 +83,26 @@ const OUTPUT_FIELD_ALIASES = [
81
83
  "output_token_limit",
82
84
  ] as const
83
85
 
86
+ /** Field penanda dukungan cache (boolean, atau objek = ya). */
87
+ const CACHE_FIELD_ALIASES = [
88
+ "prompt_caching",
89
+ "prompt_cache",
90
+ "supports_prompt_caching",
91
+ "supports_cache",
92
+ "cache_control",
93
+ ] as const
94
+
95
+ /** `undefined` (tak disebut) harus beda dari `false` (menolak) — tri-state. */
96
+ function extractCacheSupport(obj: Record<string, unknown>): boolean | undefined {
97
+ for (const key of CACHE_FIELD_ALIASES) {
98
+ if (!(key in obj)) continue
99
+ const v = obj[key]
100
+ if (typeof v === "boolean") return v
101
+ return v !== null && v !== undefined && v !== "" && v !== 0
102
+ }
103
+ return undefined
104
+ }
105
+
84
106
  function positiveInt(value: unknown): number | undefined {
85
107
  if (typeof value !== "number" || !Number.isFinite(value)) return undefined
86
108
  const n = Math.floor(value)
@@ -106,6 +128,7 @@ function pickField(obj: Record<string, unknown>, aliases: readonly string[]): nu
106
128
  export function extractModelCapacity(entry: unknown): {
107
129
  contextLength?: number
108
130
  maxOutputTokens?: number
131
+ promptCaching?: boolean
109
132
  } {
110
133
  if (!entry || typeof entry !== "object") return {}
111
134
  const obj = entry as Record<string, unknown>
@@ -122,9 +145,13 @@ export function extractModelCapacity(entry: unknown): {
122
145
  const maxOutputTokens =
123
146
  pickField(obj, OUTPUT_FIELD_ALIASES) ??
124
147
  (nested ? pickField(nested, OUTPUT_FIELD_ALIASES) : undefined)
148
+ // Level atas menang; `top_provider` hanya fallback.
149
+ const promptCaching =
150
+ extractCacheSupport(obj) ?? (nested ? extractCacheSupport(nested) : undefined)
125
151
  return {
126
152
  ...(contextLength !== undefined ? { contextLength } : {}),
127
153
  ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),
154
+ ...(promptCaching !== undefined ? { promptCaching } : {}),
128
155
  }
129
156
  }
130
157
 
@@ -123,7 +123,10 @@ export function deriveProviderId(baseUrl: string, existingIds: string[], id?: st
123
123
  export function mergeDiscoveredCapacity(
124
124
  previous: ProviderEntry | undefined,
125
125
  detected: DetectResult,
126
- ): Pick<ProviderEntry, "contextWindows" | "contextWindowSources" | "maxOutputTokens"> {
126
+ ): Pick<
127
+ ProviderEntry,
128
+ "contextWindows" | "contextWindowSources" | "maxOutputTokens" | "enablePromptCaching"
129
+ > {
127
130
  const metadata = detected.modelMetadata
128
131
  if (!metadata || Object.keys(metadata).length === 0) return {}
129
132
  const prevWindows = previous?.contextWindows ?? {}
@@ -160,10 +163,21 @@ export function mergeDiscoveredCapacity(
160
163
  if (live.size > 0 && !live.has(model)) continue
161
164
  if (maxOut[model] === undefined) maxOut[model] = tokens
162
165
  }
166
+ // Fase 7.1: satu model mendukung = provider mendukung; false bila semua menolak.
167
+ let caching: boolean | undefined
168
+ for (const meta of Object.values(metadata)) {
169
+ if (meta.promptCaching === true) {
170
+ caching = true
171
+ break
172
+ }
173
+ if (meta.promptCaching === false) caching ??= false
174
+ }
175
+
163
176
  return {
164
177
  ...(Object.keys(windows).length > 0 ? { contextWindows: windows } : {}),
165
178
  ...(Object.keys(sources).length > 0 ? { contextWindowSources: sources } : {}),
166
179
  ...(Object.keys(maxOut).length > 0 ? { maxOutputTokens: maxOut } : {}),
180
+ ...(caching !== undefined ? { enablePromptCaching: caching } : {}),
167
181
  }
168
182
  }
169
183
 
@@ -189,6 +189,13 @@ export const TOOL_CAPABILITIES: readonly ToolClassification[] = [
189
189
  evidence:
190
190
  "VERIFIED: writes history and identity. The existing sub-agent layer strips it for the same reason (src/tools/task.ts:309-321).",
191
191
  },
192
+ {
193
+ name: "git_push",
194
+ capability: "PRIVILEGED",
195
+ autonomous: false,
196
+ evidence:
197
+ "VERIFIED: publishes local history to a remote - irreversible outside this machine and visible to others. Same class as git_commit; the sub-agent layer strips it too.",
198
+ },
192
199
 
193
200
  // ── memory (session state) ──
194
201
  {
@@ -212,7 +212,7 @@ export function analyseRelations(nodes: readonly GraphNode[]): RelationAnalysis
212
212
  * what distinguishes "seen in this walk" (a cycle) from "seen in an earlier
213
213
  * walk" (already settled).
214
214
  *
215
- * Fan-out is intentionally unbounded: `MAX_PARENT` is declared in TaskStore but
215
+ * Fan-out is intentionally unbounded: `MAX_PARENT` used to be declared in TaskStore but
216
216
  * enforced nowhere, so the width of a containment forest is not bounded here
217
217
  * either (design lock S5).
218
218
  */
@@ -91,11 +91,6 @@ export function newOwnerToken(): string {
91
91
  return `own-${Date.now().toString(36)}-${counter.toString(36)}-${rand}`
92
92
  }
93
93
 
94
- /** Test-only: make token generation reproducible. */
95
- export function resetOwnerTokenCounterForTests(): void {
96
- counter = 0
97
- }
98
-
99
94
  /** The durable row. One per (session, incarnation). */
100
95
  export interface SessionAuthority {
101
96
  readonly sessionId: string
package/src/task/store.ts CHANGED
@@ -88,8 +88,6 @@ function emitTaskTransition(
88
88
  /** Bounds so the JSON columns cannot grow without limit. */
89
89
  const MAX_DEPENDS_ON = 32
90
90
  const MAX_EVIDENCE = 32
91
- const MAX_ACCEPTANCE = 32
92
- const MAX_PARENT = 64
93
91
 
94
92
  /** Shape of the data, not of the table: this rises when column SEMANTICS
95
93
  * change, not merely when a column is added. */
@@ -2923,5 +2921,3 @@ export function legacyDigest(raw: string): string {
2923
2921
  const { createHash } = require("node:crypto") as typeof import("node:crypto")
2924
2922
  return createHash("sha256").update(scrubSecrets(raw)).digest("hex").slice(0, 32)
2925
2923
  }
2926
-
2927
- export const __testing = { MAX_DEPENDS_ON, MAX_EVIDENCE, MAX_ACCEPTANCE, MAX_PARENT }
@@ -11,6 +11,19 @@ import type { ApprovalEventHook, ApprovalHookEvent } from "../presentation/event
11
11
 
12
12
  export type AskTextFn = (question: string, options?: string[]) => Promise<string | null>
13
13
 
14
+ /**
15
+ * Potong tanpa membelah pasangan surrogate: `slice` mentah menyisakan surrogate
16
+ * tinggi yatim → U+FFFD (AUD-010). Lapisan tool tak boleh impor src/ui.
17
+ */
18
+ function sliceSafeChars(s: string, max: number): string {
19
+ if (s.length <= max) return s
20
+ let end = max
21
+ const code = s.charCodeAt(end - 1)
22
+ // Surrogate tinggi di posisi terakhir = pasangannya ikut terpotong; mundur 1.
23
+ if (code >= 0xd800 && code <= 0xdbff) end -= 1
24
+ return s.slice(0, Math.max(0, end))
25
+ }
26
+
14
27
  let askTextFn: AskTextFn | undefined
15
28
 
16
29
  export function setAskTextFn(fn: AskTextFn | undefined): void {
@@ -61,7 +74,7 @@ export const askUserTool: Tool = {
61
74
  .slice(0, 2000)
62
75
  if (!q) throw new Error("question empty")
63
76
  const opts = Array.isArray(options)
64
- ? (options as unknown[]).map((o) => String(o).slice(0, 200)).slice(0, 8)
77
+ ? (options as unknown[]).map((o) => sliceSafeChars(String(o), 200)).slice(0, 8)
65
78
  : undefined
66
79
  // Tanpa view ter-inject atau di luar TTY: tolak, jangan gantung.
67
80
  // Model harus melanjutkan dengan asumsi paling aman, bukan menunggu.