minicode-ai 0.15.0 → 0.20.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 (99) hide show
  1. package/README.md +6 -4
  2. package/cli/commands/exec.ts +3 -2
  3. package/cli/commands/openwork.ts +1 -1
  4. package/cli/commands.ts +6 -6
  5. package/cli/index.ts +4 -4
  6. package/cli/model-manager.ts +1 -1
  7. package/cli/setup.ts +57 -30
  8. package/cli/tui.ts +106 -11
  9. package/docs/CONTROL-PLANE-MAP.md +6 -4
  10. package/docs/OUTPUT_EVENT_MODEL.md +4 -3
  11. package/docs/OUTPUT_PROTOCOL_SPEC.md +1 -1
  12. package/docs/OUTPUT_RENDERING_SPEC.md +16 -4
  13. package/docs/OUTPUT_UX_RULES.md +38 -32
  14. package/docs/P14_OPEN_WORK.md +290 -0
  15. package/docs/README.md +1 -1
  16. package/docs/SUMMARY.md +36 -22
  17. package/docs/TERMINAL_CONTRACT.md +54 -7
  18. package/docs/UI_RENDER_PIPELINE.md +47 -8
  19. package/docs/agents.md +1 -1
  20. package/docs/architecture.md +9 -8
  21. package/docs/autonomous-scheduler.md +142 -0
  22. package/docs/choosing-mode.md +2 -2
  23. package/docs/cli.md +4 -4
  24. package/docs/concepts.md +5 -5
  25. package/docs/config-providers.md +3 -3
  26. package/docs/contributing.md +7 -9
  27. package/docs/environment.md +5 -4
  28. package/docs/getting-started.md +4 -4
  29. package/docs/mcp-lsp.md +2 -2
  30. package/docs/memory-sessions.md +1 -1
  31. package/docs/policy-sandbox.md +7 -4
  32. package/docs/pricing-budget.md +3 -3
  33. package/docs/quickstart.md +1 -1
  34. package/docs/repl.md +5 -5
  35. package/docs/security-model.md +1 -1
  36. package/docs/security.md +9 -8
  37. package/docs/skills.md +2 -2
  38. package/docs/terminal.md +10 -2
  39. package/docs/tools.md +4 -4
  40. package/docs/troubleshooting.md +3 -3
  41. package/docs/verify-benchmark.md +0 -3
  42. package/package.json +9 -18
  43. package/src/app/session.ts +40 -7
  44. package/src/constants.ts +31 -0
  45. package/src/hooks/run.ts +5 -6
  46. package/src/mcp/http-transport.ts +1 -1
  47. package/src/policy/bash-guard.ts +26 -6
  48. package/src/policy/compaction.ts +107 -17
  49. package/src/policy/consequence-engine.ts +3 -3
  50. package/src/policy/context-window.ts +24 -1
  51. package/src/policy/context.ts +16 -4
  52. package/src/policy/permission.ts +219 -4
  53. package/src/presentation/adapter.ts +1 -1
  54. package/src/presentation/events.ts +2 -2
  55. package/src/presentation/label.ts +3 -3
  56. package/src/presentation/model.ts +4 -0
  57. package/src/presentation/store.ts +2 -2
  58. package/src/runtime/child-execution.ts +1 -1
  59. package/src/runtime/composition.ts +5 -5
  60. package/src/runtime/execution-registry.ts +1 -1
  61. package/src/runtime/production-execution.ts +3 -3
  62. package/src/runtime/production-runtime.ts +2 -2
  63. package/src/runtime/runtime-capabilities.ts +1 -1
  64. package/src/runtime/runtime-status-facts.ts +1 -1
  65. package/src/runtime/runtime-task-admission.ts +2 -2
  66. package/src/session/context-assembly.ts +8 -1
  67. package/src/session/context-identity.ts +2 -2
  68. package/src/session/context-projection.ts +36 -11
  69. package/src/session/persistence.ts +1 -1
  70. package/src/task/autonomous-context.ts +2 -2
  71. package/src/task/autonomous-policy.ts +3 -3
  72. package/src/task/model.ts +2 -2
  73. package/src/task/production-scheduler.ts +2 -2
  74. package/src/task/scheduler.ts +3 -2
  75. package/src/task/scheduling-policy.ts +2 -1
  76. package/src/task/trigger.ts +5 -5
  77. package/src/tools/read_image.ts +2 -1
  78. package/src/tools/task.ts +1 -1
  79. package/src/ui/assistant/simple.ts +33 -30
  80. package/src/ui/footer.ts +48 -9
  81. package/src/ui/i18n/en.ts +1 -0
  82. package/src/ui/i18n/id.ts +1 -0
  83. package/src/ui/input/prompt-engine.ts +36 -10
  84. package/src/ui/render/cells.ts +320 -0
  85. package/src/ui/render/composer-wrap.ts +73 -0
  86. package/src/ui/render/detail.ts +2 -2
  87. package/src/ui/render/ledger.ts +47 -0
  88. package/src/ui/render/theme.ts +32 -4
  89. package/src/ui/render/width.ts +2 -2
  90. package/src/ui/render/wrap.ts +5 -3
  91. package/src/ui/runtime/screen.ts +84 -7
  92. package/src/ui/runtime/statusline.ts +26 -0
  93. package/src/ui/screens/model-manager.ts +1 -1
  94. package/src/ui/tui/app.ts +336 -65
  95. package/src/ui/tui/transcript.ts +247 -88
  96. package/vendor/minicore/VENDOR.md +15 -11
  97. package/vendor/minicore/src/core/events.ts +1 -0
  98. package/vendor/minicore/src/core/loop.ts +10 -0
  99. package/vendor/minicore/src/core/session.ts +39 -0
package/src/hooks/run.ts CHANGED
@@ -17,12 +17,11 @@ export interface RunHookCtx {
17
17
  * tanpa gate bila tidak dijaga, melanggar kontrak read-only. Diekspor agar
18
18
  * composition root + test memakai predikat yang sama.
19
19
  *
20
- * P12 S2.2 — WorkMode-aware. WorkMode DISCUSS adalah posture read-only penuh
21
- * (ceiling handler menolak semua tool tulis/eksekusi, termasuk delegate), jadi
22
- * hooks (eksekusi Node di luar permission system) juga TIDAK boleh jalan —
23
- * walau permissionMode="auto". PLAN/EXECUTE mempertahankan perilaku lama:
24
- * keputusan murni dari permission mode. Param workMode opsional agar pemanggil
25
- * lama tanpa WorkMode tetap kompatibel (default undefined = perilaku lama).
20
+ * P12 S2.2 + P0.2 — WorkMode-aware. Hooks (eksekusi Node di luar permission
21
+ * system) HANYA boleh jalan di WorkMode EXECUTE; DISCUSS dan PLAN dilarang
22
+ * karena keduanya posture non-eksekusi (ceiling handler menolak tool
23
+ * tulis/eksekusi). Pemanggil legacy tanpa workMode memakai keputusan murni
24
+ * permission mode (default undefined = perilaku lama).
26
25
  */
27
26
  export function shouldRunHooks(
28
27
  permissionMode: string,
@@ -255,7 +255,7 @@ export class McpHttpTransport implements McpTransportLike {
255
255
  * notifikasi tanpa id) berarti request kita **tidak** terjawab. Tanpa cek ini,
256
256
  * balasan untuk request orang lain — atau notifikasi kosong — akan diterima
257
257
  * sebagai hasil, dan `result: undefined` menjalar ke pemanggil sebagai
258
- * "sukses". Ditemukan oleh experiments/extreme-mcp-adversarial.ts.
258
+ * "sukses". Ditemukan oleh harness MCP adversarial (server jahat).
259
259
  *
260
260
  * `expectId` opsional agar helper tetap bisa diuji tanpa konteks request.
261
261
  * Diekspor untuk test.
@@ -140,8 +140,8 @@ export function inlineSimpleVars(cmd: string): string {
140
140
  *
141
141
  * `command env`, `nice env`, `time env`, `exec env` semuanya menjalankan `env`,
142
142
  * tapi wrapper-nya menggeser posisi kata sehingga pola yang ter-anchor ke awal
143
- * perintah (mis. deteksi env-dump) tidak lagi cocok. Ditemukan oleh
144
- * experiments/extreme-bash-fuzz.ts: `command env` lolos sementara `env` ditolak.
143
+ * perintah (mis. deteksi env-dump) tidak lagi cocok. Ditemukan oleh fuzz
144
+ * bash-guard: `command env` lolos sementara `env` ditolak.
145
145
  *
146
146
  * Wrapper dibuang berulang karena bisa berlapis (`time nice env`).
147
147
  * Diekspor untuk test.
@@ -300,9 +300,16 @@ const GIT_DIR_OVERRIDE = /(?:^|\s)(?:-C\s*(\S+)|--(?:git-dir|work-tree)(?:=|\s+)
300
300
  * `-c` di atas, lewat assignment env. */
301
301
  const GIT_EXEC_ENV = /(?:^|[;&|\n]\s*)GIT_(?:PAGER|SSH|ASKPASS|EDITOR|DIR|WORK_TREE)\s*=/i
302
302
 
303
- /** Interpreter dijalankan dengan kode inline (semua bentuk flag). */
303
+ /**
304
+ * Interpreter dijalankan dengan kode inline (semua bentuk flag).
305
+ *
306
+ * Interpreter diperluas mengikuti allowlist developer (python/node/bun/…
307
+ * sudah lama; tambah lua/julia/elixir/groovy/scala/tcl/dotnet/swift/dart/java)
308
+ * supaya `lua -e`, `julia -e`, `elixir -e`, dst tetap ditolak — tanpa ini,
309
+ * memperluas allowlist ke bahasa baru membuka jalur kode-inline pada bahasa itu.
310
+ */
304
311
  const INLINE_INTERPRETER =
305
- /\b(?:pyw?|python[\d.]*|pypy[\d.]*|sh|bash|dash|zsh|ksh|node|deno|bun|perl|ruby|php|Rscript)(?:\.exe)?\b\s+(?:-\w*\s+)*(?:-c|-e|-E|--eval|--print|-p|--command|-r|--execute|--require|--import|--loader)\b/i
312
+ /\b(?:pyw?|python[\d.]*|pypy[\d.]*|sh|bash|dash|zsh|ksh|node|deno|bun|perl|ruby|php|Rscript|lua|luajit|julia|elixir|escript|erl|groovy|scala|tclsh|dotnet|swift|swiftc|dart|java|raku)(?:\.exe)?\b\s+(?:-\w*\s+)*(?:-c|-e|-E|--eval|-eval|--print|-p|--command|-r|--execute|--require|--import|--loader)\b/i
306
313
  // Residual jujur (audit 2026-09-16 B3): eksekusi via stdin/redirect TANPA
307
314
  // flag inline (`bash -s < skrip`, `python3 < prog`, `... | python3 -`) tidak
308
315
  // ditahan — menahan `| python3 -` mematahkan pipeline sah, dan `bash berkas`
@@ -313,9 +320,10 @@ const INLINE_INTERPRETER =
313
320
  /** Process substitution / here-string yang memasukkan output perintah lain. */
314
321
  const PROCESS_SUB = /<\s*\(|>\s*\(|<<<|\bsource\s+<|\.\s+<\(/
315
322
 
316
- /** Pipe ke shell/interpreter — bentuk apa pun sumbernya. */
323
+ /** Pipe ke shell/interpreter — bentuk apa pun sumbernya (interpreter baru
324
+ * mengikuti perluasan allowlist developer). */
317
325
  const PIPE_TO_SHELL =
318
- /\|\s*(?:sudo\s+)?(?:sh|bash|dash|zsh|ksh|python|python2|python3|pyw?|node|deno|bun|perl|ruby|php|iex|Invoke-Expression|powershell|pwsh)(?:\.exe)?\b/i
326
+ /\|\s*(?:sudo\s+)?(?:sh|bash|dash|zsh|ksh|python|python2|python3|pyw?|node|deno|bun|perl|ruby|php|iex|Invoke-Expression|powershell|pwsh|lua|luajit|julia|elixir|escript|erl|groovy|scala|tclsh|dotnet|swift|swiftc|dart|java|raku)(?:\.exe)?\b/i
319
327
 
320
328
  /** Unduh ke berkas lalu jalankan berkas itu dalam satu baris. Catatan pola:
321
329
  * - `certutil -urlcache` ikut (downloader Windows di luar curl/wget/iwr).
@@ -520,6 +528,18 @@ const STATIC_DENY: [RegExp, string][] = [
520
528
  // arbitrer dari argumen single-command. `wscript`/`cscript` (Windows Script
521
529
  // Host), `mshta` (HTML app), `rundll32`/`regsvr32` (load arbitrary DLL).
522
530
  [/\b(?:mshta|wscript|cscript|rundll32|regsvr32)(?:\.exe)?\b/i, "dangerous windows launcher"],
531
+ // Verba rilis/kredensial registry — aksi IREVERSIBEL yang butuh kredensial,
532
+ // bukan bagian alur membangun aplikasi: `npm publish`, `cargo publish`/
533
+ // `login`, `gem push`, `dotnet nuget push`, `poetry publish`,
534
+ // `docker push`/`login`, `mvn deploy`, `gradle publish`, `dart pub publish`,
535
+ // `twine upload`, `cargo owner`/`yank`. Ditahan di SEMUA mode (armor) agar
536
+ // allowlist developer boleh LUAS tanpa membuka jalur terbit diam-diam.
537
+ // Over-block dijaga ketat: verba rilis HARUS tepat setelah manager (+ satu
538
+ // subcommand opsional), jadi `npm run deploy` TIDAK kena ("run" bukan verba).
539
+ [
540
+ /\b(?:npm|cargo|gem|poetry|twine|dotnet|docker|podman|mvn|gradle|bun|yarn|pnpm|dart|flutter|pub|nuget)\b(?:\s+(?:nuget|pub|compose|token))?\s+(?:publish|unpublish|push|deploy|login|logout|adduser|upload|yank|owner|signout)\b/i,
541
+ "registry publish/credential verb",
542
+ ],
523
543
  ]
524
544
 
525
545
  /**
@@ -18,6 +18,30 @@ export function parseCompactKeepTurns(raw: string | undefined): number | undefin
18
18
  return Number.isInteger(n) && n >= 1 ? n : undefined
19
19
  }
20
20
 
21
+ // R9/T5 — tool "pembawa fakta": hasilnya (isi file, match grep, output
22
+ // bash/test, hasil fetch/web) adalah FAKTA yang harus dipertahankan sebaik
23
+ // mungkin saat kompaksi. Prosa dan tool lain tetap dipangkas pendek untuk
24
+ // hemat token. Head fakta jauh lebih panjang (800 char) daripada prosa
25
+ // (~250 char) karena kehilangan satu baris match grep / satu baris output test
26
+ // saja dapat merusak kesimpulan audit model setelah ringkasan dipakai lagi.
27
+ const FACT_TOOLS = new Set([
28
+ "read_file",
29
+ "grep",
30
+ "glob",
31
+ "bash",
32
+ "bash_output",
33
+ "code_run",
34
+ "web_fetch",
35
+ "web_search",
36
+ ])
37
+ const FACT_HEAD_CHARS = 800
38
+
39
+ /** Panjang head saat memangkas baris kompaksi per-peran: hasil tool pembawa
40
+ * fakta dapat head panjang; selain itu pakai `fallback` (prosa pendek). */
41
+ function toolHeadLen(name: string | null | undefined, fallback: number): number {
42
+ return name != null && FACT_TOOLS.has(name) ? FACT_HEAD_CHARS : fallback
43
+ }
44
+
21
45
  export interface LlmCompactionOptions {
22
46
  provider?: ModelProvider
23
47
  model?: string // deepseek v4 flash
@@ -90,8 +114,12 @@ function boundedMechanical(
90
114
  * omitted>`), memakai `getKeptCount` + `mechanicalLine` yang sama — supaya
91
115
  * fallback (saat LLM tak tersedia/thrash) tidak menghapus fakta yang justru
92
116
  * dibutuhkan untuk audit. Tetap dibatasi `boundSummary`/`fitSummaryToTokenBudget`.
117
+ *
118
+ * Diekspor (R10/A) supaya produsen proyeksi durable (`context-projection.ts`)
119
+ * memakai folder yang MEMPERTAHANKAN hasil tool — bukan folder kernel
120
+ * `mechanicalCompaction` yang menulis `<result omitted>` dan membuang fakta.
93
121
  */
94
- function mechanicalKeepResults(
122
+ export function mechanicalKeepResults(
95
123
  store: ContextStore,
96
124
  keepRecentTurns: number,
97
125
  ): readonly import("#minicore/core/types.ts").Message[] {
@@ -156,7 +184,7 @@ function mechanicalLine(message: import("#minicore/core/types.ts").Message): str
156
184
  }
157
185
  if (message.role === "tool") {
158
186
  const result = toolContentText(message.content)
159
- return `- tool(${message.name})${message.isError ? " ERROR" : ""}: ${headText(result, 260)}`
187
+ return `- tool(${message.name})${message.isError ? " ERROR" : ""}: ${headText(result, toolHeadLen(message.name, 260))}`
160
188
  }
161
189
  return `- ${message.role}: ${headText(contentToText(message.content), 180)}`
162
190
  }
@@ -268,7 +296,7 @@ export function createLlmCompaction(opts: LlmCompactionOptions = {}): Compaction
268
296
  const limit = opts.getContextWindowTokens?.()
269
297
  const target =
270
298
  Number.isSafeInteger(limit) && (limit as number) > 0
271
- ? Math.floor((limit as number) * 0.5)
299
+ ? Math.floor((limit as number) * LIMITS.COMPACTION_SUMMARY_TARGET_RATIO)
272
300
  : undefined
273
301
  return boundedMechanical(store, cOpts.keepRecentTurns, target)
274
302
  },
@@ -276,7 +304,7 @@ export function createLlmCompaction(opts: LlmCompactionOptions = {}): Compaction
276
304
  const targetTokens = () => {
277
305
  const limit = opts.getContextWindowTokens?.()
278
306
  return Number.isSafeInteger(limit) && (limit as number) > 0
279
- ? Math.floor((limit as number) * 0.5)
307
+ ? Math.floor((limit as number) * LIMITS.COMPACTION_SUMMARY_TARGET_RATIO)
280
308
  : undefined
281
309
  }
282
310
  // F3.1 anti-thrash (state per strategi = per sesi, karena strategy dibuat
@@ -306,7 +334,7 @@ export function createLlmCompaction(opts: LlmCompactionOptions = {}): Compaction
306
334
  // Jalur LLM sudah dinyatakan thrash sesi-ini: lempar agar loop memakai
307
335
  // mekanikal sinkron (bukan diam, bukan retry LLM).
308
336
  if (llmDisabled) throw new Error("llm compaction disabled after thrash")
309
- // cap 15s — jangan biarkan LLM summary memblokir loop terlalu lama;
337
+ // cap 10s — jangan biarkan LLM summary memblokir loop terlalu lama;
310
338
  // kalau gagal/timeout, loop otomatis fallback ke compact() sinkron.
311
339
  const ac = new AbortController()
312
340
  const timer = setTimeout(
@@ -338,6 +366,8 @@ export function createLlmCompaction(opts: LlmCompactionOptions = {}): Compaction
338
366
  ? Math.min(configured!, target)
339
367
  : target
340
368
  })(),
369
+ maxSummaryChars: summaryCharBudgetForWindow(opts.getContextWindowTokens?.()),
370
+ maxInputChars: summaryInputCharBudget(opts.getContextWindowTokens?.()),
341
371
  ...(opts.onUsage ? { onUsage: opts.onUsage } : {}),
342
372
  },
343
373
  ac.signal,
@@ -411,6 +441,41 @@ const SUMMARY_HEADER =
411
441
  const SUMMARY_ELISION =
412
442
  "[older context omitted from the active prompt; ask again for details that are missing]\n"
413
443
 
444
+ /**
445
+ * R9 — pagu ringkasan kompaksi LLM mengikuti ukuran jendela, bukan 4k char
446
+ * konstan. Model berjendela raksasa (1M token) diberi ruang ringkasan lebih
447
+ * kaya (hingga `COMPACTION_SUMMARY_SCALED_MAX_CHARS`) supaya fakta lama tak
448
+ * over-discard; model kecil tetap hemat di lantai `COMPACTION_SUMMARY_MAX_CHARS`.
449
+ * Formula kasar: ~1 char per 25 token jendela, diklem [min, max]. Nilai non-
450
+ * positif/tak-terdefinisi → lantai (perilaku lama persis).
451
+ */
452
+ export function summaryCharBudgetForWindow(windowTokens: number | undefined): number {
453
+ const min = LIMITS.COMPACTION_SUMMARY_MAX_CHARS
454
+ const max = LIMITS.COMPACTION_SUMMARY_SCALED_MAX_CHARS
455
+ if (windowTokens === undefined || !Number.isSafeInteger(windowTokens) || windowTokens <= 0) {
456
+ return min
457
+ }
458
+ const scaled = Math.floor(windowTokens / 25)
459
+ return Math.min(max, Math.max(min, scaled))
460
+ }
461
+
462
+ /**
463
+ * R10/B — pagu INPUT summarizer kompaksi LLM (`scrubbedPrefix`), mengikuti
464
+ * jendela. Input harus SELALU ≥ output (`summaryCharBudgetForWindow`) agar
465
+ * summarizer membaca lebih banyak daripada yang diminta dihasilkan. Formula
466
+ * kasar: ~1 char per 8 token jendela, diklem [6k, 48k]. Nilai non-positif/
467
+ * tak-terdefinisi → lantai (perilaku lama 6k char persis).
468
+ */
469
+ export function summaryInputCharBudget(windowTokens: number | undefined): number {
470
+ const min = LIMITS.COMPACTION_LLM_INPUT_MIN_CHARS
471
+ const max = LIMITS.COMPACTION_LLM_INPUT_SCALED_MAX_CHARS
472
+ if (windowTokens === undefined || !Number.isSafeInteger(windowTokens) || windowTokens <= 0) {
473
+ return min
474
+ }
475
+ const scaled = Math.floor(windowTokens / 8)
476
+ return Math.min(max, Math.max(min, scaled))
477
+ }
478
+
414
479
  /**
415
480
  * Pagu keras untuk pesan ringkasan gabungan (P0 long-horizon).
416
481
  *
@@ -439,8 +504,12 @@ const SUMMARY_ELISION =
439
504
  * melalui `compactWithLlm` (tiap panggilan melakukan dynamic import sehingga
440
505
  * menembus batas 5 dtk per test).
441
506
  */
442
- export function composeBoundedSummary(priorText: string, fresh: string): string {
443
- const cap = LIMITS.COMPACTION_SUMMARY_MAX_CHARS
507
+ export function composeBoundedSummary(
508
+ priorText: string,
509
+ fresh: string,
510
+ maxChars: number = LIMITS.COMPACTION_SUMMARY_MAX_CHARS,
511
+ ): string {
512
+ const cap = maxChars > 0 ? Math.floor(maxChars) : LIMITS.COMPACTION_SUMMARY_MAX_CHARS
444
513
  // `String.slice` memotong per code unit UTF-16, jadi bisa memelah surrogate
445
514
  // pair dan menyisakan surrogate TUNGGAL. Itu bukan sekadar kosmetik: teks
446
515
  // summary dikirim ke provider sebagai JSON, dan lone surrogate bisa
@@ -481,6 +550,13 @@ export async function compactWithLlm(
481
550
  opts: {
482
551
  keepRecentTurns: number
483
552
  maxSummaryTokens?: number
553
+ /** R9 — pagu karakter ringkasan LLM (hasil `summaryCharBudgetForWindow`).
554
+ * Bila absen, pakai `COMPACTION_SUMMARY_MAX_CHARS` (perilaku lama). */
555
+ maxSummaryChars?: number
556
+ /** R10/B — pagu karakter INPUT prefix summarizer (hasil
557
+ * `summaryInputCharBudget`). Bila absen, pakai lantai 6k char (perilaku
558
+ * lama). */
559
+ maxInputChars?: number
484
560
  provider?: ModelProvider
485
561
  model?: string
486
562
  baseUrl?: string
@@ -546,9 +622,12 @@ export async function compactWithLlm(
546
622
 
547
623
  // use safe head like mechanical: content truncated, tool results included
548
624
  // seperlunya — hasil tool SUKSES adalah sumber fakta (isi file, output
549
- // grep/bash, verifikasi). Do not buang: head 300 chars per hasil.
625
+ // grep/bash, verifikasi). Do not buang: head 800 chars untuk tool pembawa
626
+ // fakta, 250 untuk sisanya (lihat FACT_HEAD_CHARS/toolHeadLen).
550
627
  const head = (s: string, n: number) => (s.length <= n ? s : `${s.slice(0, n)}…`)
551
- // Tuned 250/300 for 30% cost save vs 400/300 — still factual
628
+ // Tuned 250 (prosa/sisanya) / 800 (tool pembawa fakta) vs 400 — still factual. Hasil tool
629
+ // pembawa fakta (grep/bash/read/test/…) memakai head panjang (toolHeadLen)
630
+ // agar match/output penting tak terbuang saat ringkasan LLM dibentuk.
552
631
  const lineFor = (m: import("#minicore/core/types.ts").Message): string => {
553
632
  if (m.role === "user") return `- user: ${head(contentToText(m.content), 250)}`
554
633
  if (m.role === "assistant") {
@@ -557,16 +636,22 @@ export async function compactWithLlm(
557
636
  .join(", ")
558
637
  return `- assistant${calls ? ` [${calls}]` : ""}: ${head(contentToText(m.content), 250)}`
559
638
  }
560
- if (m.isError) return `- tool(${m.name}) ERROR: ${head(String(m.content), 250)}`
639
+ if (m.isError)
640
+ return `- tool(${m.name}) ERROR: ${head(String(m.content), toolHeadLen(m.name, 250))}`
561
641
  const raw =
562
642
  typeof m.content === "string"
563
643
  ? m.content
564
644
  : Array.isArray(m.content)
565
645
  ? contentToText(m.content)
566
646
  : ""
567
- return `- tool(${m.name}): ${head(raw, 250)}`
647
+ return `- tool(${m.name}): ${head(raw, toolHeadLen(m.name, 250))}`
568
648
  }
569
- const scrubbedPrefix = scrubSecrets(prefix.map(lineFor).join("\n").slice(0, 6000))
649
+ const scrubbedPrefix = scrubSecrets(
650
+ prefix
651
+ .map(lineFor)
652
+ .join("\n")
653
+ .slice(0, opts.maxInputChars ?? LIMITS.COMPACTION_LLM_INPUT_MIN_CHARS),
654
+ )
570
655
  // Guard anti-injeksi (temuan audit #02): prefix berisi output tool/web/repo
571
656
  // tak-terpercaya yang bisa memuat "abaikan instruksi". Tanpa pagar, payload
572
657
  // itu masuk ringkasan lalu bertahan melewati compaction (prompt injection
@@ -577,7 +662,7 @@ export async function compactWithLlm(
577
662
  // token terbuang tanpa manfaat. Estimasi kasar 4 char/token (konservatif).
578
663
  const summaryBudgetChars = Math.max(
579
664
  200,
580
- LIMITS.COMPACTION_SUMMARY_MAX_CHARS - SUMMARY_HEADER.length,
665
+ (opts.maxSummaryChars ?? LIMITS.COMPACTION_SUMMARY_MAX_CHARS) - SUMMARY_HEADER.length,
581
666
  )
582
667
  const summaryBudgetTokens = Math.min(
583
668
  Math.floor(summaryBudgetChars / 4),
@@ -657,7 +742,7 @@ export async function compactWithLlm(
657
742
  }
658
743
  const lruSummary = {
659
744
  role: "user" as const,
660
- content: composeBoundedSummary("", summary),
745
+ content: composeBoundedSummary("", summary, opts.maxSummaryChars),
661
746
  }
662
747
  // P13 S1 — persist summary ke vector (opt-out via MINICODE_AUTO_MEMORY=0).
663
748
  // cwd diteruskan eksplisit: tanpa ini summary mendarat di DB global/sembarang
@@ -665,8 +750,13 @@ export async function compactWithLlm(
665
750
  if (process.env.MINICODE_AUTO_MEMORY !== "0") {
666
751
  try {
667
752
  const { addMemory } = await import("../memory/vector.ts")
668
- // fire-and-forget, jangan gagalkan compaction bila embedding gagal
669
- void addMemory(summary.slice(0, 1200), { category: "summary", cwd: opts.cwd }).catch(() => {})
753
+ // fire-and-forget, jangan gagalkan compaction bila embedding gagal.
754
+ // safeHead (bukan slice) supaya potongan tak meninggalkan lone high
755
+ // surrogate di ekornya (kalau titik batas memecah pasangan surrogate,
756
+ // string bisa gagal serialisasi/gagal embedding).
757
+ void addMemory(safeHead(summary, 1200), { category: "summary", cwd: opts.cwd }).catch(
758
+ () => {},
759
+ )
670
760
  } catch {}
671
761
  }
672
762
  // Bila ada prior (summary dari kompaksi sebelumnya), gabungkan isi prior dan
@@ -677,7 +767,7 @@ export async function compactWithLlm(
677
767
  const priorText = typeof prior[0]!.content === "string" ? prior[0]!.content : ""
678
768
  const combined = {
679
769
  role: "user" as const,
680
- content: composeBoundedSummary(priorText, summary),
770
+ content: composeBoundedSummary(priorText, summary, opts.maxSummaryChars),
681
771
  }
682
772
  return [combined, ...keptTail]
683
773
  }
@@ -5,9 +5,9 @@
5
5
  // berikutnya. Modul ini PURE dan deterministik: tanpa I/O, tanpa clock, tanpa
6
6
  // jaringan — masukan yang sama selalu menghasilkan keputusan yang sama.
7
7
  //
8
- // Batas lapisan: `src/policy/` hanya boleh mengimpor pustaka standar Node dan
9
- // modul policy lain (lihat test/ui-boundary.test.ts). Karena itu tipe ACE juga
10
- // diimpor oleh session/runtime-header.ts dan composition root, bukan sebaliknya.
8
+ // Modul ini PURE (tanpa IO/clock/network) dan hanya impor tipe Node +
9
+ // `./tool-contract.ts`. Karena itu tipe ACE diimpor oleh session/runtime-header.ts
10
+ // dan composition root, bukan sebaliknya.
11
11
  //
12
12
  // [ACE-INV-01] HARD CONSTRAINT: percobaan manipulasi evaluator SELALU
13
13
  // mengalahkan metrik lain. Tidak ada kombinasi input yang boleh mengubah
@@ -5,7 +5,15 @@ import { contextWindowsCachePath } from "./pricing.ts"
5
5
 
6
6
  /** App fallback for providers that do not publish model metadata.
7
7
  * Operators can set an exact `ProviderEntry.contextWindows` value or use the
8
- * explicit `--context-window` override when a gateway exposes aliases. */
8
+ * explicit `--context-window` override when a gateway exposes aliases.
9
+ *
10
+ * SENGAJA beda dari `DEFAULT_ALIAS_CONTEXT_WINDOW_TOKENS` (128K): ini adalah
11
+ * batas-bawah aman untuk model yang BENAR-BENAR tak dikenal (nilai minimal yang
12
+ * didukung hampir semua model), sedangkan default alias router memilih 128K
13
+ * karena model aslinya pasti model besar — hanya identitasnya yang disembunyikan
14
+ * oleh alias `auto`/`best`. Menyatukan keduanya ke satu nilai akan membuat
15
+ * salah satu sisi salah arah: 32K → alias dikompaksi prematur; 128K → model
16
+ * belum-tentu-mendukung melampaui jendela. */
9
17
  export const DEFAULT_FALLBACK_CONTEXT_WINDOW_TOKENS = 32_000
10
18
 
11
19
  // Alias router (`auto`/`best`/...) model aslinya tak diketahui dari config.
@@ -26,6 +34,11 @@ export interface ContextWindowResolution {
26
34
  | "safe-default"
27
35
  readonly model?: string
28
36
  readonly providerId?: string
37
+ /** R9/T8 — hadir bila katalog built-in dan overlay models.dev saling beda
38
+ * >2× (katalog mungkin ketinggalan zaman). Murni diagnostik: pemanggil boleh
39
+ * memperingatkan user; resolusi TETAP pakai katalog (over-estimate ditoleransi
40
+ * lewat jalur recovery). */
41
+ readonly drift?: { catalogTokens: number; overlayTokens: number }
29
42
  }
30
43
 
31
44
  function validWindow(value: unknown): value is number {
@@ -149,11 +162,21 @@ export function resolveContextWindow(
149
162
  if (modelId) {
150
163
  const catalogTokens = findContextWindowFromCatalog(modelId)
151
164
  if (validWindow(catalogTokens)) {
165
+ // R9/T8 — katalog diutamakan (kurasi manual) tapi bisa basi. Bila overlay
166
+ // models.dev (cache dari `pricing sync`) punya nilai > 2× beda, tandai
167
+ // drift supaya setup memperingatkan user — resolusi tetap katalog (aman:
168
+ // over-estimate turun anggun via compact-and-retry).
169
+ const overlayTokens = findContextWindowFromOverlay(modelId)
170
+ const drift =
171
+ validWindow(overlayTokens) && catalogTokens > 0
172
+ ? Math.max(overlayTokens / catalogTokens, catalogTokens / overlayTokens)
173
+ : 0
152
174
  return {
153
175
  tokens: catalogTokens,
154
176
  source: "catalog",
155
177
  ...(modelId ? { model: modelId } : {}),
156
178
  ...(providerId ? { providerId } : {}),
179
+ ...(drift > 2 ? { drift: { catalogTokens, overlayTokens: overlayTokens as number } } : {}),
157
180
  }
158
181
  }
159
182
  }
@@ -95,7 +95,11 @@ export const minicodeEstimator: TokenEstimator = (text: string) => {
95
95
  return Math.ceil(len / cpt + dense * 0.75)
96
96
  }
97
97
 
98
- // helper for image content: base64 overhead 4/3 — use when estimating tool image results
98
+ // helper for image content: base64 overhead 4/3 — use when estimating tool image results.
99
+ // CATATAN (R9/T10): ini BATAS BAWAH. Model vision asli menghitung token per-tile
100
+ // (patch), bukan chars/4 atas base64 — akurasi penuh butuh tokenizer gambar
101
+ // per-model. Cukup untuk admission kasus gambar langka; jangan dipakai sebagai
102
+ // angka presisi biaya/kompaksi gambar.
99
103
  export function estimateImageTokens(bytes: number): number {
100
104
  const b64 = Math.ceil((bytes * 4) / 3)
101
105
  return Math.ceil(b64 / DEFAULT_CHARS_PER_TOKEN)
@@ -159,8 +163,12 @@ export function createCalibratedEstimator(opts: { maxFactor?: number } = {}): Ca
159
163
 
160
164
  // Satu-satunya titik yang menyesuaikan `factor` dari sampel
161
165
  // (estimer vs provider aktual). Idempoten dan konservatif: factor tidak
162
- // pernah < 1, sehingga estimasi lokal tidak pernah dilemahkan; hanya naik
163
- // proporsional saat aktual > estimasi (mencegah under-budget kompaksi).
166
+ // pernah < 1, sehingga estimasi lokal tidak pernah dilemahkan. Factor
167
+ // mengikuti ratio observasi TERBARU (reassign, bukan akumulasi max) — jadi
168
+ // ia BISA turun bila drift mereda (mis. 2.0 → 1.2), sambil tetap di-clamp
169
+ // ke [1, maxFactor]. Ini sengaja: revisi ke bawah menurunkan inflasi
170
+ // kompaksi-palsu, sedangkan revisi ke atas mencegah under-budget (mekanisme
171
+ // yang sama, arah aman masing-masing).
164
172
  //
165
173
  // [Live Hardening 0.13.x] Gerbang anti-sampel in-flight: selama turn berjalan
166
174
  // host-visible `state.history` SENGAJA basi (kernel menulis ke turnStore
@@ -291,12 +299,16 @@ export async function buildSystemPrompt(
291
299
  "- Read first, then act: inspect the file before editing it; locate symbols with glob/grep.",
292
300
  "- Prefer the dedicated tools (read_file, edit, apply_patch, git_*) over bash for file and repo access.",
293
301
  "- For tasks with 3+ steps, maintain the todo list; keep exactly one item in_progress.",
294
- "- Ask the user only when truly blocked on a decision; delegate large independent research to a sub-agent.",
302
+ "- Ask the user only when truly blocked on a decision; delegate large independent research to a sub-agent (for auditing a large repo/document, fan out one `explore` sub-agent per area and synthesize their findings).",
295
303
  "- On a tool error or permission denial, read the message and change approach — do not repeat the same call.",
296
304
  // F3.3 kontrak selesai: klaim "done" tanpa bukti adalah pola gagal
297
305
  // VERIFY_FAIL di bench (berhenti sendiri tapi verify gagal). Murah:
298
306
  // satu baris instruksi + diukur, bukan gate kode yang rapuh.
299
307
  "- Verify before claiming done: reproduce or check the result (run the relevant test/command, re-read the edited file) before reporting success. If verification fails, keep working — never declare victory on an unchecked change.",
308
+ // B1: anti-amnesia — hasil turn dibuang bila timeout/abort (turn transaksional),
309
+ // jadi untuk task panjang/model berjendela besar, model WAJIB menulis temuan
310
+ // ke state durable sedini mungkin (bukan merangkum di akhir turn).
311
+ "- For long or multi-step tasks, persist findings/progress as you go (write to a file or write_memory) so partial work survives a timeout or interruption — don't wait until the very end to summarize.",
300
312
  "- Work only inside the workspace. Do not attempt to read or write files outside it, in secret paths, or in .minicode/.",
301
313
  ].join("\n"),
302
314
  )