minicode-ai 0.9.26 → 0.9.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/cli/repl.ts +6 -0
- package/docs/ARCHITECTURE.html +5 -5
- package/docs/changelog.md +1 -1
- package/package.json +9 -2
- package/src/ui/assistant/simple.ts +56 -10
- package/src/ui/render/sanitize.ts +103 -0
- package/src/ui/runtime/chrome.ts +88 -20
- package/vendor/minicore/VENDOR.md +2 -20
- package/vendor/minicore/src/core/executor.ts +3 -3
- package/vendor/minicore/src/core/loop.ts +23 -22
- package/vendor/minicore/src/core/permission.ts +4 -5
- package/vendor/minicore/src/core/recovery.ts +3 -1
- package/vendor/minicore/src/core/session.ts +11 -11
- package/vendor/minicore/src/core/tokens.ts +12 -15
- package/vendor/minicore/src/core/tool.ts +4 -6
- package/vendor/minicore/src/providers/openai-compat.ts +14 -14
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,28 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.9.28] - 2026-09-18 — Terminal rendering hardening: stream-aware ANSI + resize-safe footer
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- **Fragmentasi ANSI antar-chunk (F1, HIGH)**: `sanitizeAnsi()` berjalan per-chunk sehingga escape terpotong (`"ESC["` + `"32mHello"`) tampil literal. Kini `splitTrailingEscape()` menahan ekor tak-lengkap (CSI/SGR/OSC/malformed/unterminated) dan `createStreamSanitizer()` menyambungnya ke chunk berikut sebelum sanitasi — satu instans per aliran (model/reasoning/bash), ekor sisa dibuang deterministik saat completed/detach/abort. Terbukti setara whole-string di semua titik belah (properti test).
|
|
9
|
+
- **Kebocoran ANSI ke non-TTY (F2, MEDIUM)**: SGR model lolos mentah ke stdout pipe. Kini kebijakan eksplisit — TTY dipertahankan, non-TTY dibuang (`stripSgr` di `wOut`/`wErr` + `rememberTurn`, cerminan `colorLevel` → `stdout.isTTY`); cabang TTY terbukti tak over-strip, pipe anak nyata nol `ESC[`.
|
|
10
|
+
- **Korupsi layout saat resize (HIGH)**: repaint footer hanya melukis baris dasar baru tanpa menghapus frame lama (5 resize → 4 kopi di model VT) dan tanpa me-reset region yang bisa hilang diam-diam di ConPTY. Kini satu jalur `reconcile()`: reset-dulu → tegakkan region → hapus frame lama (bila teralamatkan) → lukis; dipakai present/refresh/setBusy/onResize. Badai 500 resize + stream: maks 1 footer hidup/iterasi.
|
|
11
|
+
- **Buffer thinking tanpa marker (F3, LOW)**: head-drop kini membawa `… (early thinking truncated)`; overlap listener approval/busy-key (O1) didokumentasikan tanpa refactor (fail-closed).
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
- Peta proteksi `docs/TERMINAL_CONTRACT.md` + `docs/ARCHITECTURE.html` (pill `v0.9.28`) diselaraskan; tanpa redesign renderer/EventBus/REPL.
|
|
15
|
+
|
|
16
|
+
## [0.9.27] - 2026-09-18 — Upstream sync: 10 seam kernel dihilirkan, vendor nol-divergensi
|
|
17
|
+
|
|
18
|
+
### Fixed
|
|
19
|
+
- **Seluruh seam vendor dihilirkan ke MiniCore (nol divergensi tersisa)**: 10 seam yang dulu hanya ada di `vendor/minicore` kini menjadi kemampuan kernel generik di upstream (`7b546d1` + `ae9d1be`, sudah push): plumbing `cwd` + `permissionMode` (string/getter live, resolve per turn), seed `turnCount`/`stepCount`, side-map `provider_meta`/`thought_signature` + knob `reasoningEffort`, `describeDenial` opsional, estimasi sadar-gambar + `estimateSessionContext` + getter `Session.contextTokens`, dan flag kompaksi terpisah `compactedForBudget`/`compactedForRecovery`. `bun run vendor:minicore` + `bun run vendor:check` kini hijau (`sinkron, 19 file`) dengan kedua worktree bersih — tanpa menghapus perubahan, tanpa force-push.
|
|
20
|
+
- **Cap `retryAfter` upstream terserap**: `minicore@1eceea9` (cap 30 dtk di `recovery.ts`) di-fast-forward sebelum hilirkan — penutup lapis-app (`cappedRecovery` + router) kini redundan dengan kernel, bukan divergen.
|
|
21
|
+
- **Label reason kompaksi digenerikkan (catatan migrasi)**: `context:compacted` reason jalur policy kini `pressure:<p>` / `pressure:<p>:no-op` (dulu `budget:<…>`); `recovery` tetap. Semantik utuh (flag terpisah + `:no-op` tetap ada), prefix `pressure:` sama dengan yang dipakai `BudgetPolicy` kernel — listener yang match prefix `pressure:` yang lama tetap jalan; yang match `budget:` harus pindah. Tidak ada test/layar yang mengunci string lama (`simple.ts` interpolasi generik; `control-plane.test.ts` menguji perilaku, hijau tanpa perubahan).
|
|
22
|
+
|
|
23
|
+
### Changed
|
|
24
|
+
- **Vendor provenance diregenerasi**: `VENDOR.md` kini pin `ae9d1be` (19 file, hash baru, tanpa daftar seam — tidak ada yang tersisa), worktree dinormalisasi LF sesuai `.gitattributes`, `docs/ARCHITECTURE.html` (pill `v0.9.27`, pin kernel) + `docs/CONTROL-PLANE-MAP.md` (reason generik) diselaraskan.
|
|
25
|
+
- Artefak AI/workbench sibling (`.workbuddy-ai/`, `outputs/`) di-backup di luar repo dan tidak ikut ke upstream — bukan source, bukan patch.
|
|
26
|
+
|
|
5
27
|
## [0.9.26] - 2026-09-17 — Rename paket npm: `minicode-ai`
|
|
6
28
|
|
|
7
29
|
### Changed
|
package/cli/repl.ts
CHANGED
|
@@ -400,6 +400,12 @@ export async function runRepl(ctx: CliSession): Promise<void> {
|
|
|
400
400
|
if (chunk.includes(0x03)) ctrl.abort()
|
|
401
401
|
}
|
|
402
402
|
process.stdin.resume()
|
|
403
|
+
// O1 (audit UI 2026-09): approval `askLine` di tengah turn menempelkan
|
|
404
|
+
// listener "data" KEDUA di atas onBusyKey ini — byte yang sama (mis.
|
|
405
|
+
// Ctrl+C) diterima keduanya. SENGAJA tidak di-refactor: onBusyKey abort
|
|
406
|
+
// turn, askLine membatalkan approval menjadi deny via raceAbort
|
|
407
|
+
// (permission.ts) — gabungannya fail-closed ke arah aman. Jangan
|
|
408
|
+
// "merapikan" dengan melepas salah satunya tanpa memikirkan ulang.
|
|
403
409
|
process.stdin.on("data", onBusyKey)
|
|
404
410
|
const turnStart = Date.now()
|
|
405
411
|
try {
|
package/docs/ARCHITECTURE.html
CHANGED
|
@@ -464,7 +464,7 @@ footer.site .spacer { flex: 1; }
|
|
|
464
464
|
<span class="mi">search</span><span>Cari modul, simbol, env…</span><kbd>Ctrl K</kbd>
|
|
465
465
|
</div>
|
|
466
466
|
<div class="top-actions">
|
|
467
|
-
<span class="vpill hide-m">v0.9.
|
|
467
|
+
<span class="vpill hide-m">v0.9.28 · Bun-only · 0 deps</span>
|
|
468
468
|
<button class="iconbtn" id="themeBtn" aria-label="Ganti tema terang/gelap" title="Ganti tema"><span class="mi">dark_mode</span></button>
|
|
469
469
|
</div>
|
|
470
470
|
</header>
|
|
@@ -543,7 +543,7 @@ footer.site .spacer { flex: 1; }
|
|
|
543
543
|
<div class="meta">
|
|
544
544
|
<span class="pill blue"><span class="dot"></span>entry: cli/index.ts</span>
|
|
545
545
|
<span class="pill green"><span class="dot"></span>37 tool bawaan</span>
|
|
546
|
-
<span class="pill">kernel
|
|
546
|
+
<span class="pill">kernel ae9d1be · lihat vendor/minicore/VENDOR.md</span>
|
|
547
547
|
</div>
|
|
548
548
|
|
|
549
549
|
<div class="card-grid">
|
|
@@ -578,7 +578,7 @@ footer.site .spacer { flex: 1; }
|
|
|
578
578
|
<div class="layer">
|
|
579
579
|
<div class="lnum">3</div>
|
|
580
580
|
<div><div class="ltitle">Kernel MiniCore <span class="chip c3">L3</span></div>
|
|
581
|
-
<div class="lpath">vendor/minicore/ · pin
|
|
581
|
+
<div class="lpath">vendor/minicore/ · pin ae9d1be</div></div>
|
|
582
582
|
<div class="ldesc">Loop agen inti. Beku: hanya seam aditif yang boleh diubah (<code>compactAsync</code>, <code>initialMessages</code>, <code>cwd</code>); sinkron via <code>bun run vendor:minicore</code>, cek via <code>bun run vendor:check</code>.</div>
|
|
583
583
|
</div>
|
|
584
584
|
</div>
|
|
@@ -869,7 +869,7 @@ export const kalkulatorTool: Tool = {
|
|
|
869
869
|
<ol>
|
|
870
870
|
<li><code>bun run vendor:minicore</code> — tarik upstream ke vendor/.</li>
|
|
871
871
|
<li><code>bun run vendor:check</code> — pastikan vendor == pin di dokumentasi.</li>
|
|
872
|
-
<li>
|
|
872
|
+
<li>Seam lokal: tidak ada yang tersisa (0.9.27 menghilirkan semuanya: <code>cwd</code>, <code>permissionMode</code>, <code>provider_meta</code>, <code>reasoningEffort</code>, <code>describeDenial</code>, estimasi sadar-gambar, <code>estimateSessionContext</code>/<code>contextTokens</code>, flag kompaksi ganda) — perubahan kernel = PR ke upstream lalu sync ulang, bukan tambal vendor.</li>
|
|
873
873
|
</ol>
|
|
874
874
|
<div class="guard">guard: perubahan kernel wajib lolos seluruh gate (§6) + bench smoke supaya loop tidak regresi.</div>
|
|
875
875
|
</div>
|
|
@@ -1039,7 +1039,7 @@ bun run bench # benchmark loop agen</pre></div>
|
|
|
1039
1039
|
<footer class="site">
|
|
1040
1040
|
<span>Minicode · Peta struktur hidup — terminal contract FROZEN (<a href="TERMINAL_CONTRACT.md">docs/TERMINAL_CONTRACT.md</a>)</span>
|
|
1041
1041
|
<span class="spacer"></span>
|
|
1042
|
-
<span>v0.9.
|
|
1042
|
+
<span>v0.9.28 · diperbarui 2026-09-18</span>
|
|
1043
1043
|
</footer>
|
|
1044
1044
|
|
|
1045
1045
|
</div>
|
package/docs/changelog.md
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
Riwayat rilis dan status eksekusi kini digenerate otomatis dari [`PLAN.md`](../PLAN.md) saat build website — lihat [changelog di website](https://
|
|
3
|
+
Riwayat rilis dan status eksekusi kini digenerate otomatis dari [`PLAN.md`](../PLAN.md) saat build website — lihat [changelog di website](https://minicode.fun/docs/changelog.html).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "minicode-ai",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.28",
|
|
4
4
|
"description": "Coding agent CLI built on the frozen MiniCore runtime — tools, MCP, LSP, sandbox, shadow-git checkpoints",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"private": false,
|
|
@@ -13,10 +13,16 @@
|
|
|
13
13
|
"agent",
|
|
14
14
|
"cli",
|
|
15
15
|
"coding-agent",
|
|
16
|
+
"coding-assistant",
|
|
17
|
+
"terminal",
|
|
16
18
|
"llm",
|
|
19
|
+
"llm-agent",
|
|
17
20
|
"mcp",
|
|
18
21
|
"lsp",
|
|
19
|
-
"bun"
|
|
22
|
+
"bun",
|
|
23
|
+
"openai",
|
|
24
|
+
"anthropic",
|
|
25
|
+
"ollama"
|
|
20
26
|
],
|
|
21
27
|
"homepage": "https://github.com/startupmini/minicode#readme",
|
|
22
28
|
"repository": {
|
|
@@ -78,6 +84,7 @@
|
|
|
78
84
|
"web:build": "bun scripts/build-web.ts",
|
|
79
85
|
"web:serve": "bun --hot scripts/web-serve.ts",
|
|
80
86
|
"web:check": "bun scripts/web-check.ts",
|
|
87
|
+
"web:indexnow": "bun scripts/web-indexnow.ts",
|
|
81
88
|
"web:vitals": "bun scripts/web-vitals.ts"
|
|
82
89
|
},
|
|
83
90
|
"dependencies": {},
|
|
@@ -17,7 +17,13 @@ import { formatArgsPreview, formatProviderError, formatUsage } from "../render/f
|
|
|
17
17
|
import { highlightCode } from "../render/highlight.ts"
|
|
18
18
|
import { decorateMarkdown, type FenceMatch, parseFence } from "../render/markdown.ts"
|
|
19
19
|
import { reasoning } from "../render/reasoning.ts"
|
|
20
|
-
import {
|
|
20
|
+
import {
|
|
21
|
+
cleanUntrusted,
|
|
22
|
+
createStreamSanitizer,
|
|
23
|
+
sanitizeAnsi,
|
|
24
|
+
sanitizeAnsiLine,
|
|
25
|
+
stripSgr,
|
|
26
|
+
} from "../render/sanitize.ts"
|
|
21
27
|
import { c, glyphs, stripAnsi } from "../render/theme.ts"
|
|
22
28
|
import { displayWidth, truncateToWidth } from "../render/width.ts"
|
|
23
29
|
import { formatWrapped } from "../render/wrap.ts"
|
|
@@ -39,7 +45,8 @@ export function getLastTurnText(): string {
|
|
|
39
45
|
}
|
|
40
46
|
const rememberTurn = (s: string) => {
|
|
41
47
|
if (!s) return
|
|
42
|
-
|
|
48
|
+
// Samakan dengan yang terlihat: kebijakan pipa (F2) berlaku juga untuk /copy.
|
|
49
|
+
lastTurnText += process.stdout.isTTY ? s : stripSgr(s)
|
|
43
50
|
if (lastTurnText.length > LAST_TURN_MAX_CHARS)
|
|
44
51
|
lastTurnText = lastTurnText.slice(-LAST_TURN_MAX_CHARS)
|
|
45
52
|
}
|
|
@@ -60,8 +67,10 @@ export function writeClipboardOsc52(text: string): boolean {
|
|
|
60
67
|
return true
|
|
61
68
|
}
|
|
62
69
|
|
|
63
|
-
const wOut = (s: string) =>
|
|
64
|
-
|
|
70
|
+
const wOut = (s: string) =>
|
|
71
|
+
runWithoutStatus(() => process.stdout.write(process.stdout.isTTY ? s : stripSgr(s)))
|
|
72
|
+
const wErr = (s: string) =>
|
|
73
|
+
runWithoutStatus(() => process.stderr.write(process.stdout.isTTY ? s : stripSgr(s)))
|
|
65
74
|
|
|
66
75
|
// Error provider terakhir turn ini — diingat, BUKAN dicetak langsung.
|
|
67
76
|
// Alasan: error tengah-turn sering pulih via fallback router; mencetak tiap
|
|
@@ -103,6 +112,15 @@ function patchBlocks(patches: unknown): [string, string] {
|
|
|
103
112
|
|
|
104
113
|
export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () => void {
|
|
105
114
|
let streamBuffer = ""
|
|
115
|
+
// Sanitizer sadar-stream per aliran teks (temuan F1): ekor escape yang
|
|
116
|
+
// terpotong di batas chunk ditahan dan disambung ke chunk berikut SEBELUM
|
|
117
|
+
// sanitasi — tanpa ini "ESC[" + "32m" tampil literal. Satu instans per
|
|
118
|
+
// aliran (model/reasoning/bash) agar state ekor tak tercampur. Ekor yang
|
|
119
|
+
// tersisa saat turn selesai/detach DIBUANG (flush di bawah): escape tanpa
|
|
120
|
+
// teks lanjutan tak punya efek tampak kecuali mutasi state terminal.
|
|
121
|
+
const textSan = createStreamSanitizer()
|
|
122
|
+
const reasoningSan = createStreamSanitizer()
|
|
123
|
+
const bashSan = createStreamSanitizer()
|
|
106
124
|
// State fence dipegang DI SINI, bukan di decorateMarkdown: baris datang per
|
|
107
125
|
// event streaming, sedangkan decorateMarkdown memproses satu teks utuh.
|
|
108
126
|
// Sebelumnya `line.includes("```")` toggle naif → fence ~~~ tidak dikenal,
|
|
@@ -115,6 +133,12 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
|
|
|
115
133
|
// menambah baris header baru sebagai ganti menimpa yang lama.
|
|
116
134
|
let thinkState: "off" | "min" | "exp" = "off"
|
|
117
135
|
let thinkingBuf = ""
|
|
136
|
+
// Batas buffer thinking + marker head-drop (F3): bila kepala dibuang,
|
|
137
|
+
// operator wajib tahu dari /expand bahwa isi tak lengkap — jangan biarkan
|
|
138
|
+
// ia percaya seluruh thinking tersedia. Terminologi mengikuti marker
|
|
139
|
+
// truncasi lain ("… (N more…)", ", capped 1MB").
|
|
140
|
+
const THINKING_BUF_MAX = 200_000
|
|
141
|
+
const THINKING_TRUNCATED_MARKER = "… (earlier thinking truncated)\n"
|
|
118
142
|
// Sisa baris reasoning yang belum ber-newline (mode expanded): di-flush
|
|
119
143
|
// per baris utuh agar tampilan rapi, bukan salad fragmen per chunk.
|
|
120
144
|
let reasoningLine = ""
|
|
@@ -264,6 +288,11 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
|
|
|
264
288
|
flushLine(streamBuffer)
|
|
265
289
|
streamBuffer = ""
|
|
266
290
|
}
|
|
291
|
+
// Ekor escape yang tertahan (F1) dibuang di sini — deterministik, tak
|
|
292
|
+
// pernah bocor mentah; begitu pula saat detach/abort di bawah.
|
|
293
|
+
textSan.flush()
|
|
294
|
+
reasoningSan.flush()
|
|
295
|
+
bashSan.flush()
|
|
267
296
|
flushThinking()
|
|
268
297
|
finalizeAnswer()
|
|
269
298
|
if (opts.verbose) wErr(c.muted(`\n done\n`))
|
|
@@ -284,7 +313,7 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
|
|
|
284
313
|
answerBuf = ""
|
|
285
314
|
answerTruncated = false
|
|
286
315
|
}
|
|
287
|
-
const clean =
|
|
316
|
+
const clean = cleanUntrusted(textSan.push(e.text), !!process.stdout.isTTY)
|
|
288
317
|
streamBuffer += clean
|
|
289
318
|
rememberTurn(clean)
|
|
290
319
|
flushBuf()
|
|
@@ -316,7 +345,8 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
|
|
|
316
345
|
if (text) {
|
|
317
346
|
// Teks reasoning TAK TERPERCAYA seperti provider:text — sanitasi
|
|
318
347
|
// saat masuk (bukan saat flush) agar tak ada jalur cetak yang lupa.
|
|
319
|
-
|
|
348
|
+
// Sadar-stream (F1) + kebijakan pipa (F2) seperti teks model.
|
|
349
|
+
reasoningLine += cleanUntrusted(reasoningSan.push(text), !!process.stdout.isTTY)
|
|
320
350
|
const parts = reasoningLine.split("\n")
|
|
321
351
|
for (let i = 0; i < parts.length - 1; i++) wErr(c.muted(`${parts[i]}\n`))
|
|
322
352
|
reasoningLine = parts[parts.length - 1] ?? ""
|
|
@@ -331,9 +361,19 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
|
|
|
331
361
|
}
|
|
332
362
|
if (text) {
|
|
333
363
|
// Sama: buffer thinking ikut tercemar bila mentah (flush expanded
|
|
334
|
-
// mencetaknya verbatim + /expand menampilkannya lagi).
|
|
335
|
-
|
|
336
|
-
|
|
364
|
+
// mencetaknya verbatim + /expand menampilkannya lagi). Sadar-stream
|
|
365
|
+
// (F1) + kebijakan pipa (F2); marker truncasi di bawah (F3).
|
|
366
|
+
thinkingBuf += cleanUntrusted(reasoningSan.push(text), !!process.stdout.isTTY)
|
|
367
|
+
if (thinkingBuf.length > THINKING_BUF_MAX) {
|
|
368
|
+
// Total ber-marker dibatasi THINKING_BUF_MAX (= cap per-entry
|
|
369
|
+
// bufferSection) agar tak ada pemotongan diam-diam kedua di hilir.
|
|
370
|
+
const body = thinkingBuf.startsWith(THINKING_TRUNCATED_MARKER)
|
|
371
|
+
? thinkingBuf.slice(THINKING_TRUNCATED_MARKER.length)
|
|
372
|
+
: thinkingBuf
|
|
373
|
+
thinkingBuf =
|
|
374
|
+
THINKING_TRUNCATED_MARKER +
|
|
375
|
+
body.slice(-(THINKING_BUF_MAX - THINKING_TRUNCATED_MARKER.length))
|
|
376
|
+
}
|
|
337
377
|
}
|
|
338
378
|
}
|
|
339
379
|
} else if (e.kind === "usage") {
|
|
@@ -343,9 +383,10 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
|
|
|
343
383
|
} else if (e.kind === "bash-output") {
|
|
344
384
|
// Progres bash inkremental — hanya di --verbose supaya output default
|
|
345
385
|
// tidak dibanjiri log build. Ringkasan tetap muncul di execution:completed.
|
|
386
|
+
// Sadar-stream (F1): progres datang per event seperti teks model.
|
|
346
387
|
if (opts.verbose) {
|
|
347
388
|
const d = e.data as { text?: string }
|
|
348
|
-
if (d.text) wErr(c.muted(
|
|
389
|
+
if (d.text) wErr(c.muted(cleanUntrusted(bashSan.push(d.text), !!process.stdout.isTTY)))
|
|
349
390
|
}
|
|
350
391
|
} else if (e.kind === "error") {
|
|
351
392
|
const d = e.data as { message?: string; category?: string }
|
|
@@ -540,6 +581,11 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
|
|
|
540
581
|
flushLine(streamBuffer)
|
|
541
582
|
streamBuffer = ""
|
|
542
583
|
}
|
|
584
|
+
// Ekor escape tertahan (F1) dibuang di sini juga: abort/error/budget
|
|
585
|
+
// tanpa turn:completed tak boleh meninggalkan ANSI tail.
|
|
586
|
+
textSan.flush()
|
|
587
|
+
reasoningSan.flush()
|
|
588
|
+
bashSan.flush()
|
|
543
589
|
flushReasoningTail()
|
|
544
590
|
flushThinking()
|
|
545
591
|
finalizeAnswer()
|
|
@@ -78,3 +78,106 @@ export function sanitizeAnsi(s: string): string {
|
|
|
78
78
|
export function sanitizeAnsiLine(s: string): string {
|
|
79
79
|
return sanitizeAnsi(s).replace(/\n/g, " ")
|
|
80
80
|
}
|
|
81
|
+
|
|
82
|
+
// ── Sanitasi sadar-stream (temuan F1) ──
|
|
83
|
+
//
|
|
84
|
+
// sanitizeAnsi() bekerja pada string utuh, sedangkan teks model datang
|
|
85
|
+
// per-chunk: escape yang terpotong tepat di batas ("ESC[" + "32mHello")
|
|
86
|
+
// tampil literal "32mHello". Strateginya: tahan ekor yang MUNGKIN sekuens
|
|
87
|
+
// tak-lengkap, sambung ke chunk berikut SEBELUM sanitasi. Hanya ekor
|
|
88
|
+
// tak-lengkap yang ditahan — sekuens lengkap langsung disanitasi seperti
|
|
89
|
+
// dulu (perilaku lama utuh, tanpa duplikasi logika grammar: aturan
|
|
90
|
+
// "lengkap vs terpotong" mencerminkan escapeLength di width.ts).
|
|
91
|
+
|
|
92
|
+
/** Batas ekor tahan: OSC tanpa terminator tak boleh tumbuh tanpa batas. */
|
|
93
|
+
const MAX_ESC_TAIL = 4096
|
|
94
|
+
|
|
95
|
+
function isCsiParamOrInter(code: number): boolean {
|
|
96
|
+
// Sama seperti csiByteKind di width.ts: parameter 0x30–0x3F, intermediate
|
|
97
|
+
// 0x21–0x2F. SPASI bukan intermediate (komentar di width.ts).
|
|
98
|
+
return (code >= 0x30 && code <= 0x3f) || (code >= 0x21 && code <= 0x2f)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Pisahkan kemungkinan ekor escape tak-lengkap di ujung string.
|
|
103
|
+
* Kembalikan {head, tail}: head aman disanitasi SEKARANG, tail wajib
|
|
104
|
+
* disambung ke chunk berikut (atau dibuang saat stream selesai — tak pernah
|
|
105
|
+
* render mentah). Sekuens lengkap tidak pernah ditahan.
|
|
106
|
+
*/
|
|
107
|
+
export function splitTrailingEscape(s: string): { head: string; tail: string } {
|
|
108
|
+
const idx = s.lastIndexOf("\x1b")
|
|
109
|
+
if (idx === -1) return { head: s, tail: "" }
|
|
110
|
+
const next = s[idx + 1]
|
|
111
|
+
// ESC tunggal di ujung: bisa menjadi awal apa pun → tahan.
|
|
112
|
+
if (next === undefined) return { head: s.slice(0, idx), tail: s.slice(idx) }
|
|
113
|
+
if (next === "[") {
|
|
114
|
+
// CSI: lengkap bila ada byte final sebelum string habis.
|
|
115
|
+
let j = idx + 2
|
|
116
|
+
while (j < s.length && isCsiParamOrInter(s.charCodeAt(j)!)) j++
|
|
117
|
+
if (j >= s.length) return { head: s.slice(0, idx), tail: s.slice(idx) }
|
|
118
|
+
return { head: s, tail: "" }
|
|
119
|
+
}
|
|
120
|
+
if (next === "]" || next === "P" || next === "_" || next === "^" || next === "X") {
|
|
121
|
+
// OSC/DCS/APC/PM/SOS: lengkap bila ada terminator BEL atau ESC \.
|
|
122
|
+
const rest = s.slice(idx + 2)
|
|
123
|
+
if (!rest.includes("\u0007") && !rest.includes("\x1b\\")) {
|
|
124
|
+
return { head: s.slice(0, idx), tail: s.slice(idx) }
|
|
125
|
+
}
|
|
126
|
+
return { head: s, tail: "" }
|
|
127
|
+
}
|
|
128
|
+
if (next === "(" || next === ")" || next === "#") {
|
|
129
|
+
// Charset 3-byte: tahan bila terpotong.
|
|
130
|
+
if (s.length - idx < 3) return { head: s.slice(0, idx), tail: s.slice(idx) }
|
|
131
|
+
return { head: s, tail: "" }
|
|
132
|
+
}
|
|
133
|
+
// Fe 2-byte (ESC 7, ESC M, …): lengkap.
|
|
134
|
+
return { head: s, tail: "" }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Sanitizer stateful untuk satu stream teks: push() per chunk, flush() saat
|
|
139
|
+
* stream selesai. Ekor tak-lengkap yang tersisa di flush() DIBUANG (bukan
|
|
140
|
+
* dirender) — escape tanpa teks lanjutan tak punya efek tampak kecuali
|
|
141
|
+
* mutasi state terminal, yang tak pernah diinginkan dari teks tak-terpercaya.
|
|
142
|
+
*/
|
|
143
|
+
export interface StreamSanitizer {
|
|
144
|
+
push(chunk: string): string
|
|
145
|
+
flush(): string
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function createStreamSanitizer(): StreamSanitizer {
|
|
149
|
+
let tail = ""
|
|
150
|
+
return {
|
|
151
|
+
push(chunk: string): string {
|
|
152
|
+
const combined = tail + chunk
|
|
153
|
+
const part = splitTrailingEscape(combined)
|
|
154
|
+
tail = part.tail.length > MAX_ESC_TAIL ? "" : part.tail
|
|
155
|
+
return sanitizeAnsi(part.head)
|
|
156
|
+
},
|
|
157
|
+
flush(): string {
|
|
158
|
+
tail = ""
|
|
159
|
+
return ""
|
|
160
|
+
},
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ── Kebijakan ANSI non-TTY (temuan F2) ──
|
|
165
|
+
|
|
166
|
+
const ESC_CH = String.fromCharCode(27)
|
|
167
|
+
|
|
168
|
+
/** Buang SGR (sesudah sanitizeAnsi, hanya ini yang tersisa) untuk pipa. */
|
|
169
|
+
export function stripSgr(s: string): string {
|
|
170
|
+
// Pola dibangun tanpa literal kontrol (aturan lint noControlCharactersInRegex).
|
|
171
|
+
return s.replace(new RegExp(`${ESC_CH}\\[[0-9;:]*m`, "g"), "")
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Satu pintu kebijakan ANSI teks tak-terpercaya: TTY → SGR dipertahankan
|
|
176
|
+
* (renderer mewarnai); non-TTY → semua ANSI dibuang agar pipe/CI
|
|
177
|
+
* deterministik. Cerminan colorLevel() di theme.ts yang mengacu
|
|
178
|
+
* stdout.isTTY — satu aturan untuk semua stream.
|
|
179
|
+
*/
|
|
180
|
+
export function cleanUntrusted(s: string, stdoutTty: boolean): string {
|
|
181
|
+
const clean = sanitizeAnsi(s)
|
|
182
|
+
return stdoutTty ? clean : stripSgr(clean)
|
|
183
|
+
}
|
package/src/ui/runtime/chrome.ts
CHANGED
|
@@ -121,6 +121,13 @@ export function createFooterChrome(opts: FooterChromeOptions): FooterChrome {
|
|
|
121
121
|
let regionOn = false
|
|
122
122
|
let detached = false
|
|
123
123
|
let resizeBound: (() => void) | null = null
|
|
124
|
+
// Geometri frame footer yang TERAKHIR dilukis (jumlah baris saat itu).
|
|
125
|
+
// Invarian: repaint SELALU menghapus frame lama dulu bila geometri berubah
|
|
126
|
+
// dan baris lama masih teralamatkan — tanpa ini setiap resize meninggalkan
|
|
127
|
+
// satu kopi footer yatim di scrollback (duplikat menumpuk tiap siklus
|
|
128
|
+
// besar-kecil, terbukti oleh model VT: 5 resize → 4 kopi). null = tidak ada
|
|
129
|
+
// frame hidup (belum pernah / sudah dilepas / geometri tak teralamatkan).
|
|
130
|
+
let paintedRows: number | null = null
|
|
124
131
|
// Pulse spark: frame naik saat busy. Timer HANYA hidup selama turn; idle =
|
|
125
132
|
// frame 0 (spark redup). Fail-safe: callback timer dibungkus try/catch dan
|
|
126
133
|
// tak pernah menyentuh jalur turn — animasi mati, turn tetap jalan.
|
|
@@ -157,22 +164,76 @@ export function createFooterChrome(opts: FooterChromeOptions): FooterChrome {
|
|
|
157
164
|
regionOn = true
|
|
158
165
|
}
|
|
159
166
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
167
|
+
// Hapus frame footer yang sedang hidup (bila teralamatkan). Dipakai saat
|
|
168
|
+
// geometri berubah (eraseOldFrame) dan saat detach (frame lengket tak boleh
|
|
169
|
+
// tertinggal sebagai duplikat salinan scrollback).
|
|
170
|
+
const erasePaintedFrame = (): void => {
|
|
171
|
+
if (paintedRows === null) return
|
|
172
|
+
const r = rows()
|
|
173
|
+
if (paintedRows - 1 >= 1 && paintedRows <= r) {
|
|
174
|
+
process.stdout.write(SAVE_CURSOR)
|
|
175
|
+
process.stdout.write(`\x1b[${paintedRows - 1};1H${CLEAR}`)
|
|
176
|
+
process.stdout.write(`\x1b[${paintedRows};1H${CLEAR}`)
|
|
177
|
+
process.stdout.write(RESTORE_CURSOR)
|
|
178
|
+
}
|
|
179
|
+
paintedRows = null
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Hapus frame footer LAMA bila geometri berubah dan barisnya masih
|
|
183
|
+
// teralamatkan di layar saat ini. Bila layar menyusut di bawah frame lama
|
|
184
|
+
// (paintedRows > r), frame lama sudah menjadi scrollback dan tak bisa
|
|
185
|
+
// dihapus via pengalamatan — catat null (jujur: yatim, bukan hidup) agar
|
|
186
|
+
// repaint berikut tidak salah mengira ada frame yang dijaga.
|
|
187
|
+
const eraseOldFrame = (r: number): void => {
|
|
188
|
+
if (paintedRows === null || paintedRows === r) return
|
|
189
|
+
erasePaintedFrame()
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Satu-satunya jalur yang menyentuh region/frame (present, refresh,
|
|
193
|
+
// setBusy, onResize SEMUA lewat sini): reset dulu (rekonsiliasi — region
|
|
194
|
+
// bisa hilang diam-diam saat resize ConPTY atau program anak me-reset;
|
|
195
|
+
// keyakinan lokal `regionOn` tak pernah dipercaya), lalu tegakkan region
|
|
196
|
+
// baru + hapus frame lama + lukis frame baru (kecuali pemanggil melukis
|
|
197
|
+
// sendiri dalam bingkai SYNC-nya, mis. present). Tiap pemanggilan sinkron
|
|
198
|
+
// penuh — tak ada interleaving antar-repaint (JS single thread), jadi
|
|
199
|
+
// state selalu konsisten antar-repaint tanpa lock.
|
|
200
|
+
const reconcile = (r: number, paint = true): void => {
|
|
201
|
+
if (detached) return
|
|
202
|
+
process.stdout.write(SAVE_CURSOR)
|
|
203
|
+
process.stdout.write(RESET_REGION)
|
|
204
|
+
process.stdout.write(RESTORE_CURSOR)
|
|
205
|
+
regionOn = false
|
|
206
|
+
if (r < 10) {
|
|
207
|
+
// Terlalu pendek: jangan tegakkan apa pun. Frame hidup (bila ada)
|
|
208
|
+
// kemungkinan besar terdorong reflow ke 2 baris dasar layar kecil —
|
|
209
|
+
// bersihkan keduanya agar tak menjadi duplikat permanen saat tumbuh
|
|
210
|
+
// kembali (bukti model VT: susut-ke-8 lalu tumbuh → 2 footer hidup).
|
|
211
|
+
// Bila reflow justru memotong bawah, ini hanya mengosongkan 2 baris
|
|
212
|
+
// viewport (scrollback utuh, pulih oleh output berikut) — tak pernah
|
|
213
|
+
// menyentuh baris di luar 2 dasar. Tanpa frame hidup: diam total.
|
|
214
|
+
if (paintedRows !== null && r >= 2) {
|
|
168
215
|
process.stdout.write(SAVE_CURSOR)
|
|
169
|
-
process.stdout.write(
|
|
216
|
+
process.stdout.write(`\x1b[${r - 1};1H${CLEAR}`)
|
|
217
|
+
process.stdout.write(`\x1b[${r};1H${CLEAR}`)
|
|
170
218
|
process.stdout.write(RESTORE_CURSOR)
|
|
171
|
-
regionOn = false
|
|
172
|
-
return
|
|
173
219
|
}
|
|
174
|
-
|
|
220
|
+
paintedRows = null
|
|
221
|
+
return
|
|
222
|
+
}
|
|
223
|
+
enableRegion(r)
|
|
224
|
+
eraseOldFrame(r)
|
|
225
|
+
if (paint) {
|
|
175
226
|
paintFooter(r)
|
|
227
|
+
paintedRows = r
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const onResize = (): void => {
|
|
232
|
+
try {
|
|
233
|
+
if (detached) return
|
|
234
|
+
// Resize = invalidasi total: geometri lama mati, rekonsiliasi penuh.
|
|
235
|
+
// Sengaja TANPA early-return regionOn — keyakinan lokal bisa basi.
|
|
236
|
+
reconcile(rows())
|
|
176
237
|
} catch {}
|
|
177
238
|
}
|
|
178
239
|
|
|
@@ -185,9 +246,8 @@ export function createFooterChrome(opts: FooterChromeOptions): FooterChrome {
|
|
|
185
246
|
refresh() {
|
|
186
247
|
if (detached) return
|
|
187
248
|
try {
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
paintFooter(r)
|
|
249
|
+
// Sama seperti present tapi tanpa memindahkan kursor (prompt aktif).
|
|
250
|
+
reconcile(rows())
|
|
191
251
|
} catch {}
|
|
192
252
|
},
|
|
193
253
|
setBusy(busy: boolean) {
|
|
@@ -199,8 +259,10 @@ export function createFooterChrome(opts: FooterChromeOptions): FooterChrome {
|
|
|
199
259
|
pulseTimer = setInterval(() => {
|
|
200
260
|
try {
|
|
201
261
|
frame += 1
|
|
202
|
-
|
|
203
|
-
|
|
262
|
+
// Lewat reconcile (bukan paint langsung): resize di tengah turn
|
|
263
|
+
// ikut menyembuhkan region + menghapus frame lama, bukan
|
|
264
|
+
// menumpuk frame baru di atasnya.
|
|
265
|
+
reconcile(rows())
|
|
204
266
|
} catch {
|
|
205
267
|
// Runtime rewel: matikan animasi, jangan pernah gagalkan turn.
|
|
206
268
|
stopPulse()
|
|
@@ -209,8 +271,7 @@ export function createFooterChrome(opts: FooterChromeOptions): FooterChrome {
|
|
|
209
271
|
} else {
|
|
210
272
|
stopPulse()
|
|
211
273
|
frame = 0
|
|
212
|
-
|
|
213
|
-
if (regionOn && r >= 10) paintFooter(r) // kembali redup seketika
|
|
274
|
+
reconcile(rows()) // kembali redup seketika
|
|
214
275
|
}
|
|
215
276
|
} catch {}
|
|
216
277
|
},
|
|
@@ -220,7 +281,6 @@ export function createFooterChrome(opts: FooterChromeOptions): FooterChrome {
|
|
|
220
281
|
const r = rows()
|
|
221
282
|
if (r < 10) return // terminal terlalu pendek — jangan sentuh apa pun
|
|
222
283
|
if (!regionOn) {
|
|
223
|
-
enableRegion(r)
|
|
224
284
|
if (!resizeBound) {
|
|
225
285
|
resizeBound = onResize
|
|
226
286
|
try {
|
|
@@ -228,9 +288,13 @@ export function createFooterChrome(opts: FooterChromeOptions): FooterChrome {
|
|
|
228
288
|
} catch {}
|
|
229
289
|
}
|
|
230
290
|
}
|
|
291
|
+
// Rekonsiliasi TANPA lukis (paint=false): lukisan dilakukan sekali di
|
|
292
|
+
// bawah dalam bingkai SYNC agar tak ada frame ganda per present.
|
|
293
|
+
reconcile(r, false)
|
|
231
294
|
// Satu frame sinkron agar repaint footer tidak robek.
|
|
232
295
|
process.stdout.write(SYNC_START)
|
|
233
296
|
paintFooter(r)
|
|
297
|
+
paintedRows = r
|
|
234
298
|
// Kursor ke baris input (tepat di atas blank footer — kini 2 baris total).
|
|
235
299
|
process.stdout.write(`\x1b[${r - 2};1H`)
|
|
236
300
|
process.stdout.write(SYNC_END)
|
|
@@ -247,6 +311,10 @@ export function createFooterChrome(opts: FooterChromeOptions): FooterChrome {
|
|
|
247
311
|
} catch {}
|
|
248
312
|
resizeBound = null
|
|
249
313
|
}
|
|
314
|
+
// Hapus frame lengket dulu agar salinan scrollback di bawah bukan
|
|
315
|
+
// duplikatnya (sebelumnya: reset lalu cetak → dua baris status
|
|
316
|
+
// terlihat bersamaan sesaat).
|
|
317
|
+
erasePaintedFrame()
|
|
250
318
|
if (regionOn) {
|
|
251
319
|
process.stdout.write(RESET_REGION)
|
|
252
320
|
regionOn = false
|
|
@@ -3,27 +3,9 @@
|
|
|
3
3
|
Salinan kernel MiniCore agar `bun install` tidak membutuhkan clone sibling
|
|
4
4
|
`../minicore`. Sumber kebenaran tetap repo minicore.
|
|
5
5
|
|
|
6
|
-
- source commit: `
|
|
6
|
+
- source commit: `ae9d1be362d24b685f83858f65ee12cbfa3ca75a`
|
|
7
7
|
- files: 19
|
|
8
|
-
- hash: `
|
|
9
|
-
- seam aditif lokal (belum ada di upstream — JANGAN sync membabi buta,
|
|
10
|
-
`bun run vendor:minicore` akan MENGHAPUSnya): `cwd` + `permissionMode`
|
|
11
|
-
(session→loop→executor→ToolContext), `turnCount`/`stepCount` seed,
|
|
12
|
-
`provider_meta`/`thought_signature` side-map + `reasoningEffort` knob di
|
|
13
|
-
openai-compat, `describeDenial` opsional di PermissionHandler + alasan
|
|
14
|
-
deny di executor (`permission denied: <reason>`; tanpa method = pesan
|
|
15
|
-
polos seperti dulu), estimasi token sadar-gambar di tokens.ts
|
|
16
|
-
(`estimateImageTokens` + `estimateMessage` hitung byte gambar alih-alih
|
|
17
|
-
placeholder/JSON-blowup). Kontrak control-plane Phase 6: `estimateSessionContext`
|
|
18
|
-
(tokens.ts — satu sumber angka konteks untuk loop + Session getter),
|
|
19
|
-
`Session.contextTokens` getter (session.ts — ekspos ke driver/UI/budget),
|
|
20
|
-
flag kompaksi terpisah `compactedForBudget`/`compactedForRecovery` + event
|
|
21
|
-
`context:compacted` reason `budget:<pressure>`/`budget:<pressure>:no-op`/`recovery`
|
|
22
|
-
(loop.ts — dulu flag tunggal mengaburkan dua semantics: kompaksi budget
|
|
23
|
-
membakar satu-satunya retry recovery). Berkas tersentuh: `src/core/{session,loop,executor,tool,permission,tokens}.ts`,
|
|
24
|
-
`src/providers/openai-compat.ts`. (Kernel upstream 1eceea9 punya cap
|
|
25
|
-
retryAfter sendiri; vendor ini belum mengambilnya — cap ditutup lapis-app
|
|
26
|
-
minicode.) Hilirkan dulu ke repo minicore, baru sync ulang.
|
|
8
|
+
- hash: `96bcd6f7b8b62a4e`
|
|
27
9
|
|
|
28
10
|
Perbarui dengan `bun run vendor:minicore` (butuh `../minicore`).
|
|
29
11
|
CI memverifikasi kesinkronan lewat `bun run vendor:check`.
|
|
@@ -56,9 +56,9 @@ export async function runCall(call: ToolCall, deps: ExecutorDeps): Promise<ToolR
|
|
|
56
56
|
}
|
|
57
57
|
throwIfAborted(deps.signal);
|
|
58
58
|
if (decision === "deny") {
|
|
59
|
-
//
|
|
60
|
-
//
|
|
61
|
-
// describeDenial
|
|
59
|
+
// Optional handler diagnostic, surfaced so the model observes an
|
|
60
|
+
// actionable reason ("permission denied: <reason>"). Diagnostic-only:
|
|
61
|
+
// describeDenial must never fail the denial itself — hence the guard.
|
|
62
62
|
let suffix = "";
|
|
63
63
|
try {
|
|
64
64
|
const r = await deps.permissions.describeDenial?.(snapshotToolCall(safeCall));
|
|
@@ -10,8 +10,8 @@ import type { ToolSchema } from "./tool.ts";
|
|
|
10
10
|
import type { ToolCall, ToolResult } from "./types.ts";
|
|
11
11
|
import type { SessionInternal, Step, TurnResult } from "./session.ts";
|
|
12
12
|
|
|
13
|
-
/** Resolve
|
|
14
|
-
*
|
|
13
|
+
/** Resolve the session permission mode for this turn's deps (a plain
|
|
14
|
+
* string or a live getter). Never throws — failure resolves to undefined. */
|
|
15
15
|
function resolvePermissionMode(mode: SessionInternal["permissionMode"]): string | undefined {
|
|
16
16
|
try {
|
|
17
17
|
if (typeof mode === "function") {
|
|
@@ -40,13 +40,13 @@ export async function executeTurn(
|
|
|
40
40
|
const steps: Step[] = [];
|
|
41
41
|
let stepIndex = 0;
|
|
42
42
|
let finalText: string | undefined;
|
|
43
|
-
//
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
//
|
|
47
|
-
//
|
|
48
|
-
//
|
|
49
|
-
//
|
|
43
|
+
// Two separate flags — policy-path and recovery-path compaction have
|
|
44
|
+
// different semantics. A single flag used to conflate them: a policy
|
|
45
|
+
// compaction burned the one recovery retry (though recovery was never
|
|
46
|
+
// tried), and vice versa. The recovery flag is ALWAYS set (a guard
|
|
47
|
+
// against an infinite loop: force_compact_and_retry is exempt from
|
|
48
|
+
// maxProviderRetries); the policy flag is set when a policy compaction
|
|
49
|
+
// is attempted (once per turn, guarding against per-step O(n) repeats).
|
|
50
50
|
let compactedForBudget = false;
|
|
51
51
|
let compactedForRecovery = false;
|
|
52
52
|
|
|
@@ -65,13 +65,14 @@ export async function executeTurn(
|
|
|
65
65
|
const before = s.store.messages.length;
|
|
66
66
|
await compactStore(s, signal);
|
|
67
67
|
compactedForBudget = true;
|
|
68
|
-
// reason
|
|
69
|
-
// (no-op =
|
|
70
|
-
//
|
|
68
|
+
// The reason distinguishes the trigger and whether compaction
|
|
69
|
+
// actually shrank the store (no-op = nothing evictable in messages;
|
|
70
|
+
// reporters must tell that apart from fixed system+schema overhead,
|
|
71
|
+
// which compaction never touches).
|
|
71
72
|
const reduced = s.store.messages.length < before;
|
|
72
73
|
s.events.emit({
|
|
73
74
|
type: "context:compacted",
|
|
74
|
-
reason: reduced ? `
|
|
75
|
+
reason: reduced ? `pressure:${pressure}` : `pressure:${pressure}:no-op`,
|
|
75
76
|
});
|
|
76
77
|
pressure = s.budget.evaluate({
|
|
77
78
|
usedTokens: contextTokens(s),
|
|
@@ -138,9 +139,8 @@ export async function executeTurn(
|
|
|
138
139
|
}
|
|
139
140
|
if (completed === "length") {
|
|
140
141
|
errorMessage = "provider output reached length limit";
|
|
141
|
-
//
|
|
142
|
-
//
|
|
143
|
-
// retry recovery ini.
|
|
142
|
+
// onLength reads the RECOVERY flag — not the policy flag. A single
|
|
143
|
+
// flag used to let a policy compaction burn this recovery retry.
|
|
144
144
|
action = s.recovery.onLength(compactedForRecovery);
|
|
145
145
|
} else if (completed === "error") {
|
|
146
146
|
action = { type: "throw" };
|
|
@@ -168,8 +168,9 @@ export async function executeTurn(
|
|
|
168
168
|
if (compactedForRecovery)
|
|
169
169
|
throw new AgentError("budget_exceeded", errorMessage ?? "context too large", { cause: action });
|
|
170
170
|
await compactStore(s, signal);
|
|
171
|
-
//
|
|
172
|
-
//
|
|
171
|
+
// The recovery flag is ALWAYS set (even on no-op):
|
|
172
|
+
// force_compact_and_retry is exempt from maxProviderRetries, so a
|
|
173
|
+
// repeated no-op would otherwise loop forever.
|
|
173
174
|
compactedForRecovery = true;
|
|
174
175
|
s.events.emit({ type: "context:compacted", reason: "recovery" });
|
|
175
176
|
break;
|
|
@@ -204,8 +205,8 @@ export async function executeTurn(
|
|
|
204
205
|
state: snapshotState(s.state),
|
|
205
206
|
maxResultTokens: s.toolResultMaxTokens,
|
|
206
207
|
cwd: s.cwd,
|
|
207
|
-
//
|
|
208
|
-
//
|
|
208
|
+
// Resolved per turn so a live getter reflects runtime mode changes
|
|
209
|
+
// in the next tool context. Failed resolution is undefined (safe).
|
|
209
210
|
permissionMode: resolvePermissionMode(s.permissionMode),
|
|
210
211
|
};
|
|
211
212
|
let rawResults: readonly ToolResult[];
|
|
@@ -320,8 +321,8 @@ function delay(ms: number, signal: AbortSignal): Promise<void> {
|
|
|
320
321
|
}
|
|
321
322
|
|
|
322
323
|
function contextTokens(s: SessionInternal): number {
|
|
323
|
-
//
|
|
324
|
-
//
|
|
324
|
+
// Single source in tokens.ts `estimateSessionContext` — shared by the
|
|
325
|
+
// loop and the Session getter so no duplicate estimator can drift.
|
|
325
326
|
return estimateSessionContext(s.store, s.system, s.registry.list(), s.estimator);
|
|
326
327
|
}
|
|
327
328
|
|
|
@@ -14,11 +14,10 @@ export type Decision = "allow" | "deny";
|
|
|
14
14
|
export interface PermissionHandler {
|
|
15
15
|
check(call: ToolCall, deps: ExecutorDeps): Promise<Decision>;
|
|
16
16
|
/**
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* lama tanpa method ini tetap jalan tanpa perubahan perilaku.
|
|
17
|
+
* Optional diagnostic for the most recent denial of `call`, so the model
|
|
18
|
+
* can steer instead of retrying blindly until max steps. Invoked right
|
|
19
|
+
* after `check` returns "deny"; returning undefined/"" keeps the plain
|
|
20
|
+
* denial message. Optional — handlers without it behave as before.
|
|
22
21
|
*/
|
|
23
22
|
describeDenial?(call: ToolCall): Promise<string | undefined> | string | undefined;
|
|
24
23
|
}
|
|
@@ -28,7 +28,9 @@ export const defaultRecoveryPolicy: RecoveryPolicy = {
|
|
|
28
28
|
},
|
|
29
29
|
};
|
|
30
30
|
|
|
31
|
+
const RETRY_AFTER_MAX_MS = 30_000;
|
|
32
|
+
|
|
31
33
|
function backoffDelay(attempt: number, retryAfter?: number): number {
|
|
32
|
-
if (retryAfter != null) return retryAfter;
|
|
34
|
+
if (retryAfter != null) return Math.min(retryAfter, RETRY_AFTER_MAX_MS);
|
|
33
35
|
return Math.min(1_000 * 2 ** (attempt - 1), 8_000);
|
|
34
36
|
}
|
|
@@ -38,10 +38,10 @@ export interface SessionConfig {
|
|
|
38
38
|
model?: string;
|
|
39
39
|
cwd?: string;
|
|
40
40
|
/**
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
41
|
+
* Session permission mode, forwarded to each turn's ToolContext so tools
|
|
42
|
+
* can adapt their behavior. Plain string or live getter — prefer the
|
|
43
|
+
* getter when the mode can change at runtime. Optional; absent preserves
|
|
44
|
+
* the legacy behavior (ctx.permissionMode undefined).
|
|
45
45
|
*/
|
|
46
46
|
permissionMode?: string | (() => string);
|
|
47
47
|
/**
|
|
@@ -120,11 +120,11 @@ export interface Session {
|
|
|
120
120
|
readonly state: Readonly<SessionState>;
|
|
121
121
|
readonly events: EventBus;
|
|
122
122
|
/**
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
* estimator
|
|
126
|
-
*
|
|
127
|
-
*
|
|
123
|
+
* Current context size from the same source of truth as the loop's
|
|
124
|
+
* pressure evaluation (messages + system + tools under the session
|
|
125
|
+
* estimator). One number for drivers and UI — no duplicate estimator.
|
|
126
|
+
* O(history) per access (snapshot pattern); recomputed over the
|
|
127
|
+
* committed store on every access.
|
|
128
128
|
*/
|
|
129
129
|
readonly contextTokens: number;
|
|
130
130
|
run(input: string, opts?: { signal?: AbortSignal; model?: string }): Promise<TurnResult>;
|
|
@@ -207,8 +207,8 @@ export function createSession(config: SessionConfig): Session {
|
|
|
207
207
|
get events() {
|
|
208
208
|
return events;
|
|
209
209
|
},
|
|
210
|
-
//
|
|
211
|
-
//
|
|
210
|
+
// Same source of truth as the loop — estimateSessionContext in
|
|
211
|
+
// tokens.ts — never a duplicate estimator.
|
|
212
212
|
get contextTokens() {
|
|
213
213
|
return estimateSessionContext(store, config.system, impl.registry.list(), impl.estimator);
|
|
214
214
|
},
|
|
@@ -18,12 +18,10 @@ export function contentToText(content: Content): string {
|
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
/**
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* src/policy/context.ts estimateImageTokens agar laporan read_image dan
|
|
26
|
-
* budget konsisten.
|
|
21
|
+
* Token estimate for inline image bytes. The text placeholder above would
|
|
22
|
+
* price a 100KB image at ~15 tokens, hiding it from budget pressure until
|
|
23
|
+
* the context genuinely overflows — so image parts are priced from their
|
|
24
|
+
* base64 wire size instead.
|
|
27
25
|
*/
|
|
28
26
|
export function estimateImageTokens(byteLength: number): number {
|
|
29
27
|
return Math.ceil(Math.ceil((byteLength * 4) / 3) / DEFAULT_CHARS_PER_TOKEN);
|
|
@@ -60,9 +58,9 @@ export function estimateMessage(message: Message, est: TokenEstimator): number {
|
|
|
60
58
|
return estimateContent(message.content, est) + est(safeStringify(message.toolCalls ?? [])) + est(message.reasoning ?? "");
|
|
61
59
|
case "tool": {
|
|
62
60
|
const c = message.content;
|
|
63
|
-
//
|
|
64
|
-
//
|
|
65
|
-
//
|
|
61
|
+
// Binary tool results (e.g. images): JSON.stringify of a Uint8Array
|
|
62
|
+
// explodes into a {"0":..} map, faking pressure and triggering
|
|
63
|
+
// premature compaction. Price it as image bytes instead.
|
|
66
64
|
if (c instanceof Uint8Array) return estimateImageTokens(c.byteLength);
|
|
67
65
|
return est(typeof c === "string" ? c : safeStringify(c ?? null));
|
|
68
66
|
}
|
|
@@ -90,12 +88,11 @@ export function estimateSystem(system: string | undefined, est: TokenEstimator):
|
|
|
90
88
|
}
|
|
91
89
|
|
|
92
90
|
/**
|
|
93
|
-
*
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
* import session↔loop).
|
|
91
|
+
* Single source for the current context size: messages + system + tools —
|
|
92
|
+
* everything sent per request. Shared by the loop (pressure evaluation)
|
|
93
|
+
* and the Session getter (observability) so no duplicate estimator can
|
|
94
|
+
* drift. Pure over its arguments; takes the store shape instead of
|
|
95
|
+
* SessionInternal to avoid a session<->loop circular import.
|
|
99
96
|
*/
|
|
100
97
|
export function estimateSessionContext(
|
|
101
98
|
store: { messages: readonly Message[] },
|
|
@@ -24,12 +24,10 @@ export interface ToolContext {
|
|
|
24
24
|
readonly state: Readonly<SessionState>;
|
|
25
25
|
readonly cwd?: string;
|
|
26
26
|
/**
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
* SessionConfig (boleh string atau getter live agar Shift+Tab runtime
|
|
32
|
-
* ikut tercermin).
|
|
27
|
+
* Session permission mode at dispatch time (e.g. "auto" | "plan").
|
|
28
|
+
* Optional for backward compatibility; tools that adapt to read-only
|
|
29
|
+
* sessions read this instead of guessing from prompt text. Resolved per
|
|
30
|
+
* turn from SessionConfig (plain string or live getter).
|
|
33
31
|
*/
|
|
34
32
|
readonly permissionMode?: string;
|
|
35
33
|
emit(event: AgentEvent): void;
|
|
@@ -7,16 +7,16 @@ import type { ModelProvider, ProviderEvent, StreamRequest } from "../core/provid
|
|
|
7
7
|
import type { ToolSchema } from "../core/tool.ts";
|
|
8
8
|
import type { Content, Message } from "../core/types.ts";
|
|
9
9
|
|
|
10
|
-
//
|
|
11
|
-
// thought_signature).
|
|
12
|
-
// `
|
|
13
|
-
// additionalProperties:false)
|
|
14
|
-
//
|
|
10
|
+
// Provider-metadata side-map: toolCallId -> extra provider payload (e.g.
|
|
11
|
+
// Gemini thought_signature / extra_content). It must NOT travel inside
|
|
12
|
+
// `args` — the executor rejects unknown properties (all schemas are
|
|
13
|
+
// additionalProperties:false), so smuggling it there fails validation.
|
|
14
|
+
// Side-map keeps args clean; consume-once + cap so long sessions can't leak.
|
|
15
15
|
const providerMetaByCallId = new Map<string, unknown>()
|
|
16
16
|
function stashProviderMeta(id: string, meta: unknown): void {
|
|
17
17
|
if (!id || meta == null) return
|
|
18
18
|
providerMetaByCallId.set(id, meta)
|
|
19
|
-
//
|
|
19
|
+
// Cap: drop the oldest entry when a very long session piles up.
|
|
20
20
|
if (providerMetaByCallId.size > 500) {
|
|
21
21
|
const first = providerMetaByCallId.keys().next()
|
|
22
22
|
if (!first.done) providerMetaByCallId.delete(first.value)
|
|
@@ -163,9 +163,9 @@ export function createOpenAICompatProvider(config: OpenAICompatConfig): ModelPro
|
|
|
163
163
|
calls.set(index, acc);
|
|
164
164
|
if (order.indexOf(index) < 0) order.push(index);
|
|
165
165
|
if (typeof td.id === "string" && td.id) acc.id = td.id;
|
|
166
|
-
//
|
|
167
|
-
// verbatim
|
|
168
|
-
//
|
|
166
|
+
// Preserve provider metadata (thought_signature / extra_content)
|
|
167
|
+
// verbatim in the side-map — never in args — for echo on
|
|
168
|
+
// history replay in toMessages.
|
|
169
169
|
const extra =
|
|
170
170
|
(td as Record<string, unknown>).extra_content ??
|
|
171
171
|
(td as Record<string, unknown>).thought_signature ??
|
|
@@ -199,8 +199,8 @@ export function createOpenAICompatProvider(config: OpenAICompatConfig): ModelPro
|
|
|
199
199
|
args = { raw: acc.args };
|
|
200
200
|
}
|
|
201
201
|
}
|
|
202
|
-
//
|
|
203
|
-
//
|
|
202
|
+
// Args stay clean (the executor rejects unknown properties);
|
|
203
|
+
// provider metadata is filed in the side-map by call id.
|
|
204
204
|
const callId = acc.id || `call_${index}`
|
|
205
205
|
if (acc._extra != null) stashProviderMeta(callId, acc._extra);
|
|
206
206
|
yield { type: "tool_call", id: callId, name: acc.name, args };
|
|
@@ -236,9 +236,9 @@ function toMessages(messages: readonly Message[]): unknown[] {
|
|
|
236
236
|
// saat thinking mode aktif, agar multi-turn tidak 400.
|
|
237
237
|
...((message as { reasoning?: string }).reasoning ? { reasoning_content: (message as { reasoning?: string }).reasoning } : {}),
|
|
238
238
|
tool_calls: message.toolCalls?.length
|
|
239
|
-
|
|
240
|
-
//
|
|
241
|
-
// args
|
|
239
|
+
? message.toolCalls.map((call) => {
|
|
240
|
+
// Echo provider metadata from the side-map (consume-once);
|
|
241
|
+
// args are sent exactly as received, with no hidden keys.
|
|
242
242
|
const extra = takeProviderMeta(call.id)
|
|
243
243
|
return {
|
|
244
244
|
id: call.id,
|