minicode-ai 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +1 -1
  2. package/cli/commands/exec.ts +44 -1
  3. package/cli/commands.ts +5 -2
  4. package/cli/setup.ts +24 -0
  5. package/docs/TERMINAL_CONTRACT.md +30 -7
  6. package/docs/architecture.md +9 -5
  7. package/docs/concepts.md +1 -1
  8. package/docs/contributing.md +2 -1
  9. package/docs/environment.md +1 -0
  10. package/docs/policy-sandbox.md +6 -1
  11. package/docs/security.md +12 -4
  12. package/docs/skills.md +1 -1
  13. package/package.json +2 -2
  14. package/src/config.ts +8 -6
  15. package/src/daemon/discovery.ts +24 -0
  16. package/src/policy/bash-guard.ts +170 -6
  17. package/src/policy/compaction.ts +34 -7
  18. package/src/policy/jail.ts +10 -22
  19. package/src/policy/permission.ts +9 -6
  20. package/src/presentation/projection.ts +1 -1
  21. package/src/providers/anthropic.ts +14 -4
  22. package/src/providers/responses.ts +1 -1
  23. package/src/providers/sse-bounds.ts +16 -2
  24. package/src/ui/approval/prompt.ts +17 -6
  25. package/src/ui/footer.ts +2 -2
  26. package/src/ui/i18n/en.ts +9 -1
  27. package/src/ui/i18n/id.ts +9 -1
  28. package/src/ui/input/prompt-engine.ts +6 -0
  29. package/src/ui/render/diff.ts +51 -2
  30. package/src/ui/render/highlight.ts +68 -37
  31. package/src/ui/render/sanitize.ts +5 -1
  32. package/src/ui/render/session-summary.ts +6 -4
  33. package/src/ui/render/table-grid.ts +123 -13
  34. package/src/ui/render/table.ts +4 -2
  35. package/src/ui/render/theme.ts +11 -3
  36. package/src/ui/render/width.ts +35 -6
  37. package/src/ui/render/wrap.ts +28 -6
  38. package/src/ui/runtime/loading-bar.ts +17 -5
  39. package/src/ui/screens/dialog.ts +23 -2
  40. package/src/ui/screens/form.ts +52 -10
  41. package/src/ui/screens/model-manager.ts +8 -2
  42. package/src/ui/screens/picker.ts +11 -3
  43. package/src/ui/screens/provider-manager.ts +11 -3
  44. package/src/ui/screens/wizard.ts +29 -1
  45. package/src/ui/tui/app.ts +57 -20
  46. package/src/ui/tui/transcript.ts +42 -7
  47. package/vendor/minicore/src/providers/openai-compat.ts +30 -1
@@ -9,7 +9,7 @@ import {
9
9
  type DecodedKey,
10
10
  type DecoderState,
11
11
  } from "../input/prompt-engine.ts"
12
- import { sanitizeAnsiLine } from "../render/sanitize.ts"
12
+ import { cleanUntrusted, sanitizeAnsiLine } from "../render/sanitize.ts"
13
13
  import { c, glyphs, stripAnsi } from "../render/theme.ts"
14
14
  import { truncateToWidth } from "../render/width.ts"
15
15
  import { type AltScreen, openAltScreen } from "../runtime/screen.ts"
@@ -400,7 +400,10 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
400
400
  if (res.ok) notice = `${glyphs.check} ${sanitizeAnsiLine(res.ok)}`
401
401
  else if (res.err) notice = `${glyphs.cross} ${sanitizeAnsiLine(res.err)}`
402
402
  } catch (e) {
403
- notice = `${glyphs.cross} ${(e as Error).message}`
403
+ // Pesan error jaringan/controller = input tak-terpercaya: tanpa
404
+ // sanitasi, body provider bisa menyuntik `ESC[2J` ke popup dan
405
+ // menghapus layar TUI (audit 2026-11-12, MEDIUM-2).
406
+ notice = `${glyphs.cross} ${sanitizeAnsiLine((e as Error).message)}`
404
407
  } finally {
405
408
  busy = false
406
409
  await reload().catch(() => {})
@@ -632,7 +635,12 @@ export async function runProviderManagerView(opts: ProviderManagerViewOptions):
632
635
  cleanup()
633
636
  } catch {}
634
637
  try {
635
- console.log(`⚠ ${t("prov.failOpen", { msg: String((e as Error)?.message ?? e) })}`)
638
+ // Pesan setup gagal (bisa memuat body jaringan) = teks tak-terpercaya.
639
+ console.log(
640
+ `⚠ ${t("prov.failOpen", {
641
+ msg: cleanUntrusted(String((e as Error)?.message ?? e), !!process.stdout.isTTY),
642
+ })}`,
643
+ )
636
644
  } catch {}
637
645
  try {
638
646
  resolve()
@@ -11,6 +11,34 @@ import { dialogBox } from "./dialog.ts"
11
11
  import { runForm, validateUrl } from "./form.ts"
12
12
  import { runPicker } from "./picker.ts"
13
13
 
14
+ /**
15
+ * Batas tunggu simpan-provider (audit 2026-11-12, MEDIUM-7).
16
+ *
17
+ * `detect()` sendiri punya timeout, tapi callback controller juga melakukan
18
+ * I/O config (kunci, tulis disk) yang bisa lambat; tanpa batas, kotak
19
+ * "mendeteksi…" bertahan selama proses menggantung dan user tak punya jalan
20
+ * keluar (tak ada Esc di kotak progres). Timeout = pesan jujur, UI pulih.
21
+ */
22
+ async function withWatchdog<T>(fn: () => Promise<T>, ms = 60_000): Promise<T> {
23
+ let timer: ReturnType<typeof setTimeout> | undefined
24
+ const pending = Promise.resolve().then(fn)
25
+ // Rejection telat tanpa handler = unhandledRejection (Bun: crash).
26
+ pending.catch(() => {})
27
+ try {
28
+ return await Promise.race([
29
+ pending,
30
+ new Promise<never>((_, reject) => {
31
+ timer = setTimeout(() => reject(new Error(t("ntc.timeout"))), ms)
32
+ try {
33
+ ;(timer as unknown as { unref?: () => void }).unref?.()
34
+ } catch {}
35
+ }),
36
+ ])
37
+ } finally {
38
+ if (timer) clearTimeout(timer)
39
+ }
40
+ }
41
+
14
42
  export interface WizardPreset {
15
43
  label: string
16
44
  baseUrl: string
@@ -148,7 +176,7 @@ export async function runSetupWizardView(opts: SetupWizardViewOptions): Promise<
148
176
  )
149
177
  screen.paintRegion(box.lines, box.topRow)
150
178
  try {
151
- const message = await opts.onSubmit(targetUrl, apiKey)
179
+ const message = await withWatchdog(() => opts.onSubmit(targetUrl, apiKey))
152
180
  // Pesan dari jaringan (nama model/gateway) — sanitasi sebelum tampil.
153
181
  screen.clearRegion()
154
182
  const doneBox = dialogBox(
package/src/ui/tui/app.ts CHANGED
@@ -131,6 +131,19 @@ export function timerHighlight(ms: number): TimerHighlight {
131
131
  return "seconds"
132
132
  }
133
133
 
134
+ /**
135
+ * Indeks awal jendela dropdown yang menjaga item terpilih (`sel`) selalu tampil.
136
+ * Sebelum A1, jendela selalu `slice(0, visible)` sehingga `sel >= visible` tak
137
+ * pernah tersorot tetapi Enter tetap mengirim `hints[sel]` — perintah destruktif
138
+ * yang tak terlihat. Kontrak: untuk `0 <= sel < total` berlaku
139
+ * `start <= sel < start + min(visible, total)`.
140
+ */
141
+ export function dropdownWindowStart(sel: number, visible: number, total: number): number {
142
+ const v = Math.max(1, Math.floor(visible))
143
+ if (total <= v) return 0
144
+ return Math.max(0, Math.min(sel - v + 1, total - v))
145
+ }
146
+
134
147
  interface FrameLayout {
135
148
  frame: string[]
136
149
  cursor: { row: number; col: number }
@@ -292,8 +305,6 @@ export class TuiApp {
292
305
  */
293
306
  private busUnsubs: (() => void)[] = []
294
307
  private repaintTimer: ReturnType<typeof setTimeout> | undefined
295
- /** Ukuran transkrip saat terakhir ikut ekor (basis indikator "baru"). */
296
- private tailSize = 0
297
308
  /** Ukuran transkrip saat mulai scroll ke atas (basis hitung baris baru). */
298
309
  private scrollBase = 0
299
310
  /** Panjang visual terakhir (kunci posisi baca agar stream tak merampasnya). */
@@ -486,8 +497,7 @@ export class TuiApp {
486
497
  this.thinkingActive = false
487
498
  })
488
499
  sub("context:compacted")
489
- this.tailSize = this.transcript.total()
490
- this.scrollBase = this.tailSize
500
+ this.scrollBase = this.transcript.total()
491
501
  this.setMouseMode(mouseSelectionEnabled() ? "drag" : "off")
492
502
  this.paint(screen)
493
503
  await done
@@ -694,7 +704,10 @@ export class TuiApp {
694
704
  if (this.state.line || this.editing) {
695
705
  this.state = createState()
696
706
  this.histIdx = -1
697
- this.editing = false
707
+ // Prompt TETAP tampil setelah Esc: kontrak I13 mensyaratkan prompt
708
+ // ada saat idle, dan menyembunyikannya membuat layar terlihat mati
709
+ // sampai user menekan tombol berikutnya (audit 2026-11-12, MEDIUM-4).
710
+ this.editing = true
698
711
  this.paintCurrent()
699
712
  }
700
713
  return
@@ -869,6 +882,9 @@ export class TuiApp {
869
882
  this.followTail()
870
883
  this.abortHintOn = false
871
884
  if (!line) {
885
+ // Enter pada baris kosong tetap idle: prompt harus langsung kembali
886
+ // (I13), bukan menghilang sampai ketikan berikutnya.
887
+ this.editing = true
872
888
  this.paintCurrent()
873
889
  return
874
890
  }
@@ -1120,8 +1136,7 @@ export class TuiApp {
1120
1136
  if (this.scrollBack === 0 && pages > 0) this.scrollBase = this.transcript.total()
1121
1137
  this.scrollBack = Math.max(0, Math.round(this.scrollBack + pages * page))
1122
1138
  if (this.scrollBack === 0) {
1123
- this.tailSize = this.transcript.total()
1124
- this.scrollBase = this.tailSize
1139
+ this.scrollBase = this.transcript.total()
1125
1140
  }
1126
1141
  this.paintCurrent()
1127
1142
  }
@@ -1130,7 +1145,7 @@ export class TuiApp {
1130
1145
  * Scroll per BARIS (bukan per halaman) — dipakai auto-scroll seleksi agar
1131
1146
  * gulirnya halus & presisi. `n` = baris terbungkus (+ = ke atas/lama,
1132
1147
  * - = ke bawah/baru); di-clamp ke [0, wrapped - viewH]. Menjaga basis
1133
- * `tailSize`/`scrollBase` sama seperti `scrollBy`.
1148
+ * `scrollBase` sama seperti `scrollBy`.
1134
1149
  */
1135
1150
  private scrollRows(n: number): void {
1136
1151
  const cols = process.stdout.columns || 80
@@ -1141,8 +1156,7 @@ export class TuiApp {
1141
1156
  if (this.scrollBack === 0 && n > 0) this.scrollBase = this.transcript.total()
1142
1157
  this.scrollBack = Math.max(0, Math.min(this.scrollBack + n, maxBack))
1143
1158
  if (this.scrollBack === 0) {
1144
- this.tailSize = this.transcript.total()
1145
- this.scrollBase = this.tailSize
1159
+ this.scrollBase = this.transcript.total()
1146
1160
  }
1147
1161
  this.paintCurrent()
1148
1162
  }
@@ -1165,8 +1179,7 @@ export class TuiApp {
1165
1179
  this.scrollBack = Math.max(0, curWrapped - viewH)
1166
1180
  } else {
1167
1181
  this.scrollBack = 0
1168
- this.tailSize = this.transcript.total()
1169
- this.scrollBase = this.tailSize
1182
+ this.scrollBase = this.transcript.total()
1170
1183
  }
1171
1184
  this.paintCurrent()
1172
1185
  }
@@ -1174,8 +1187,7 @@ export class TuiApp {
1174
1187
  /** Kembali ke ekor: dipakai tiap ketikan/submit baru (I18). */
1175
1188
  private followTail(): void {
1176
1189
  this.scrollBack = 0
1177
- this.tailSize = this.transcript.total()
1178
- this.scrollBase = this.tailSize
1190
+ this.scrollBase = this.transcript.total()
1179
1191
  }
1180
1192
 
1181
1193
  /** Kosongkan transkrip (/clear): viewport + basis scroll ikut di-reset agar
@@ -1234,7 +1246,10 @@ export class TuiApp {
1234
1246
  const content = this.thinkingActive ? thinkingDots(now, start) : status
1235
1247
  return [this.activityRow(content, cols)]
1236
1248
  }
1237
- if (!this.editing) return [""]
1249
+ // Idle: prompt tetap tampil. Dulu baris kosong menggantikannya sehingga
1250
+ // setelah Esc/Enter-kosong layar terlihat mati (I13: prompt tampil saat
1251
+ // boot/idle) — audit 2026-11-12, MEDIUM-4.
1252
+ if (!this.editing) return [chunkByWidth(PROMPT_FIRST, Math.max(10, cols))[0] ?? ""]
1238
1253
  return this.composerLayout(cols).rows
1239
1254
  }
1240
1255
 
@@ -1277,7 +1292,11 @@ export class TuiApp {
1277
1292
  * jalan atau sudah quit.
1278
1293
  */
1279
1294
  repaint(): void {
1280
- if (!this.quitRequested) this.paintCurrent()
1295
+ // Suspend = pemilik layar lain (popup/approval) sedang melukis region
1296
+ // sendiri; melukis frame penuh di sini akan menimpanya. Sebelumnya guard
1297
+ // ini hanya ada di `requestPaint`, jadi API publik tak konsisten (audit
1298
+ // 2026-11-12, MEDIUM-9).
1299
+ if (!this.quitRequested && this.suspended === 0) this.paintCurrent()
1281
1300
  }
1282
1301
 
1283
1302
  private viewportHeight(rows: number, cols: number): number {
@@ -1401,11 +1420,19 @@ export class TuiApp {
1401
1420
  const hints = this.host.listCommands(this.state.line)
1402
1421
  if (!hints.length) return []
1403
1422
  const room = Math.max(0, rows - 2 - this.composerHeight(cols, busy) - 3)
1404
- const shown = hints.slice(0, Math.min(MAX_DROPDOWN_ROWS, room))
1423
+ const visible = Math.max(1, Math.min(MAX_DROPDOWN_ROWS, room))
1424
+ const total = hints.length
1425
+ // A1: jendela MENGIKUTI `sel`, bukan selalu slice dari index 0. `sel` bisa
1426
+ // wrap melewati jumlah baris terlihat (mis. 24 perintah → sel 9..23), dan
1427
+ // bila jendela tetap index 0, tak ada baris tersorot tetapi Enter tetap
1428
+ // mengirim hints[sel] — perintah yang tak pernah terlihat (destruktif untuk
1429
+ // /clear, /undo). `start` menjaga item terpilih selalu tampil.
1430
+ const start = dropdownWindowStart(this.state.sel, visible, total)
1431
+ const shown = hints.slice(start, start + visible)
1405
1432
  const w = Math.max(10, cols)
1406
1433
  const out: string[] = []
1407
1434
  shown.forEach((h, i) => {
1408
- const picked = i === this.state.sel
1435
+ const picked = start + i === this.state.sel
1409
1436
  const text = sanitizeAnsiLine(h).replace(/^\/+/, "")
1410
1437
  out.push(picked ? c.accent(c.bold(text)) : text)
1411
1438
  })
@@ -1625,9 +1652,16 @@ export class TuiApp {
1625
1652
  this.turnStartedAt = 0
1626
1653
  }
1627
1654
  const newCount = this.scrollBack > 0 ? this.transcript.total() - this.scrollBase : 0
1655
+ // Baris indikator WAJIB dipotong ke lebar frame seperti baris lain: teks
1656
+ // locale id lebih panjang dari terminal sempit (51 kolom untuk abort hint),
1657
+ // dan baris lebih lebar dari `cols` membungkus sendiri → frame jadi
1658
+ // `rows+1`, alt-screen scroll, seluruh diff CUP meleset (audit 2026-11-12,
1659
+ // HIGH-3).
1628
1660
  const indicator: string[] = []
1629
- if (busy && this.abortHintOn) indicator.push(c.warning(t("app.abortHint")))
1630
- else if (newCount > 0) indicator.push(c.muted(t("app.newBelow", { n: newCount })))
1661
+ if (busy && this.abortHintOn)
1662
+ indicator.push(c.warning(truncateToWidth(t("app.abortHint"), width)))
1663
+ else if (newCount > 0)
1664
+ indicator.push(c.muted(truncateToWidth(t("app.newBelow", { n: newCount }), width)))
1631
1665
 
1632
1666
  const allMenu = this.menuRows(height, width, busy)
1633
1667
  const allComposer = this.composerRows(width, snap, busy, now)
@@ -1681,6 +1715,9 @@ export class TuiApp {
1681
1715
  } else {
1682
1716
  shownComposer = allComposer.slice(0, composerH)
1683
1717
  cursorRow = viewH + menu.length + indicator.length + 1
1718
+ // Kursor parkir tepat setelah prompt saat idle (bukan kolom 1) supaya
1719
+ // caret terlihat di tempat user akan mengetik.
1720
+ if (!busy) cursorCol = displayWidth(PROMPT_FIRST) + 1
1684
1721
  }
1685
1722
 
1686
1723
  const started = this.turnStartedAt || now
@@ -17,7 +17,7 @@ import type {
17
17
  } from "../contract.ts"
18
18
  import { t } from "../i18n/locale.ts"
19
19
  import { renderActivityPanel } from "../render/activity-panel.ts"
20
- import { paintLedger, runMarker, statusGlyph, statusWord } from "../render/ledger.ts"
20
+ import { paintLedger, runMarker, statusWord } from "../render/ledger.ts"
21
21
  import { parseFence, renderInline } from "../render/markdown.ts"
22
22
  import { type MarkdownTable, parseMarkdownBlocks } from "../render/markdown-table.ts"
23
23
  import { sanitizeAnsi, sanitizeAnsiLine, stripSgr } from "../render/sanitize.ts"
@@ -33,6 +33,10 @@ import { defaultUiState, type UiSessionState } from "../session-state.ts"
33
33
  // substansi berbeda (viewport vs riwayat yang bisa di-replay).
34
34
  export const TRANSCRIPT_CAP = 5000
35
35
  export const TRANSCRIPT_TEXT_MAX_CHARS = 1_000_000
36
+ /** Baris pending lebih panjang dari ini tidak dimemo (kunci = isi baris). */
37
+ const PENDING_MEMO_LINE_MAX = 4096
38
+ /** Batas entri memo proyeksi pending sebelum dibuang seluruhnya. */
39
+ const PENDING_MEMO_MAX_ENTRIES = 4000
36
40
  /** Baris thinking yang terlihat di area live (Fase 3). */
37
41
  const MAX_THINKING_ROWS = 10
38
42
  const TRANSCRIPT_TRUNCATION_MARKER = "… [transcript truncated: turn cap exceeded]"
@@ -500,6 +504,7 @@ export class Transcript {
500
504
  clear(): void {
501
505
  this.lines = []
502
506
  this.rowCache.clear()
507
+ this.pendingRowMemo.clear()
503
508
  this.tables = []
504
509
  this.ids = []
505
510
  this.sourcePrefixes = []
@@ -847,13 +852,28 @@ export class Transcript {
847
852
  return rows
848
853
  }
849
854
 
855
+ /**
856
+ * Memo proyeksi baris pending, dikunci isi baris (bukan indeks).
857
+ *
858
+ * Cache `pendingProjection` lama hanya valid per `pendingVersion`, dan versi
859
+ * itu naik SETIAP delta — jadi tiap paint memproyeksikan ulang seluruh
860
+ * jawaban. Biayanya O(pending) per frame → total O(n²) per turn (audit
861
+ * 2026-11-12, CRITICAL-1): terukur 295 ms/frame pada 200 KB dan 1,4 dtk/
862
+ * frame pada batas 1 MB. Mayoritas baris saat streaming sudah final, jadi
863
+ * proyeksi per baris dimemo: yang tumbuh hanya baris terakhir.
864
+ *
865
+ * Dikunci juga `w` dan fenceState karena keduanya mengubah hasil proyeksi.
866
+ * Baris sangat panjang tidak dimemo (kuncinya akan sebesar barisnya sendiri).
867
+ */
868
+ private pendingRowMemo = new Map<string, TranscriptRow[]>()
869
+
850
870
  /** Proyeksi `pending` (jawaban streaming) + marker truncasi. Di-cache per
851
- * (width, pendingVersion, truncated): tanpa ini `parseMarkdownBlocks(pending)`
852
- * + `normalizeAssistantOutput` diulang penuh tiap paint saat jawaban panjang
853
- * mengalir (O(pending) per frame). pendingVersion naik di stream/commit/clear. */
871
+ * (width, pendingVersion, truncated) untuk hasil total; proyeksi per baris
872
+ * dimemo terpisah agar delta baru tidak memaksa kerja ulang penuh. */
854
873
  private pendingRows(w: number): TranscriptRow[] {
855
874
  if (!this.pending) {
856
875
  this.pendingProjection = null
876
+ this.pendingRowMemo.clear()
857
877
  return []
858
878
  }
859
879
  if (
@@ -872,8 +892,23 @@ export class Transcript {
872
892
  if (block.type === "table") rows.push(...this.projectTable(block.table, -1, w))
873
893
  else
874
894
  for (const line of block.text.split("\n")) {
895
+ const fenceState = pendingFence(line)
896
+ const memoKey =
897
+ line.length <= PENDING_MEMO_LINE_MAX ? `${w}\u0000${fenceState}\u0000${line}` : null
898
+ const memo = memoKey === null ? undefined : this.pendingRowMemo.get(memoKey)
899
+ if (memo) {
900
+ rows.push(...memo)
901
+ continue
902
+ }
875
903
  const clean = stripSgr(sanitizeAnsi(line))
876
- rows.push(...this.projectText(line, clean, -1, w, false, "", true, pendingFence(line)))
904
+ const produced = this.projectText(line, clean, -1, w, false, "", true, fenceState)
905
+ if (memoKey !== null) {
906
+ // Batas sederhana: memo adalah cache tampilan, bukan struktur
907
+ // data — dibuang seluruhnya saat terlalu besar.
908
+ if (this.pendingRowMemo.size >= PENDING_MEMO_MAX_ENTRIES) this.pendingRowMemo.clear()
909
+ this.pendingRowMemo.set(memoKey, produced)
910
+ }
911
+ rows.push(...produced)
877
912
  }
878
913
  }
879
914
  }
@@ -1220,7 +1255,7 @@ export class Transcript {
1220
1255
  : denyReason
1221
1256
  ? `: ${truncateToWidth(sanitizeAnsi(denyReason), 200, "…").split("\n")[0] ?? ""}`
1222
1257
  : ""
1223
- const line = ` ${statusGlyph(status)} ${name}${targetText} ${statusWord(status)}${retry}${child}${verificationMark}${provenanceMark}${message}`
1258
+ const line = ` ${name}${targetText} ${statusWord(status)}${retry}${child}${verificationMark}${provenanceMark}${message}`
1224
1259
  // Lipat aktivitas (opencode-like): saat minimizeActivity ATAU panel
1225
1260
  // aktivitas aktif, baris ledger per-tool TIDAK boleh menghilang diam-diam
1226
1261
  // — ditahan lalu dirangkum saat turn selesai (panel: per keluarga tool;
@@ -1278,7 +1313,7 @@ export class Transcript {
1278
1313
  const targetText = target ? ` ${truncateToWidth(sanitizeAnsiLine(target), 120, "")}` : ""
1279
1314
  const line =
1280
1315
  verification.verdict === "present"
1281
- ? ` ${statusGlyph("completed")} ${name}${targetText} verified`
1316
+ ? ` ${name}${targetText} verified`
1282
1317
  : ` ? ${name}${targetText} unverified (${verification.verdict})`
1283
1318
  this.append(
1284
1319
  verification.verdict === "present" ? paintLedger("completed", line) : c.muted(line),
@@ -7,6 +7,13 @@ 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
+ // HOST seam (F2): byte bounds SSE — sejajar LIMITS.PROVIDER_SSE_FRAME_MAX_BYTES
11
+ // (16MB) dan LIMITS.PROVIDER_SSE_TOTAL_MAX_BYTES (64MB) di sisi host. Vendor
12
+ // self-contained, tak impor src/; nilai diduplikasi sengaja (single source di
13
+ // host tetap src/constants.ts — ini salinan wire-level).
14
+ const MAX_FRAME_BYTES = 16_777_216;
15
+ const MAX_TOTAL_BYTES = 67_108_864;
16
+
10
17
  // Provider-metadata side-map: toolCallId -> extra provider payload (e.g.
11
18
  // Gemini thought_signature / extra_content). It must NOT travel inside
12
19
  // `args` — the executor rejects unknown properties (all schemas are
@@ -352,16 +359,31 @@ async function* sse(body: ReadableStream<Uint8Array>, signal: AbortSignal): Asyn
352
359
  const reader = body.getReader();
353
360
  const decoder = new TextDecoder();
354
361
  let buffer = "";
362
+ let totalBytes = 0;
363
+ let reachedEof = false;
355
364
  try {
356
365
  while (true) {
357
366
  if (signal.aborted) throw new Error("AbortError");
358
367
  const { done, value } = await reader.read();
359
- if (done) break;
368
+ if (done) {
369
+ reachedEof = true;
370
+ break;
371
+ }
372
+ // HOST seam (F2): byte bounds. Sebelumnya stream menumpuk baris tanpa batas
373
+ // sehingga satu `data:` raksasa (upstream rusak/hostil) di-buffer + JSON.parse
374
+ // sebelum guard host sempat memotong event yang sudah ter-decode → OOM.
375
+ totalBytes += value.byteLength;
376
+ if (totalBytes > MAX_TOTAL_BYTES) {
377
+ throw new ProviderError("invalid_request", "SSE stream exceeds total byte limit");
378
+ }
360
379
  buffer += decoder.decode(value, { stream: true });
361
380
  let index: number;
362
381
  while ((index = buffer.indexOf("\n")) >= 0) {
363
382
  const line = buffer.slice(0, index).replace(/\r$/, "");
364
383
  buffer = buffer.slice(index + 1);
384
+ if (line.length > MAX_FRAME_BYTES) {
385
+ throw new ProviderError("invalid_request", "SSE frame exceeds byte limit");
386
+ }
365
387
  if (!line.startsWith("data:")) continue;
366
388
  const payload = line.slice(5).trim();
367
389
  if (payload === "[DONE]") return;
@@ -373,8 +395,15 @@ async function* sse(body: ReadableStream<Uint8Array>, signal: AbortSignal): Asyn
373
395
  }
374
396
  }
375
397
  }
398
+ // Satu baris tak-berakhir yang tumbuh melebihi cap frame = runaway buffer.
399
+ if (buffer.length > MAX_FRAME_BYTES) {
400
+ throw new ProviderError("invalid_request", "SSE frame exceeds byte limit");
401
+ }
376
402
  }
377
403
  } finally {
404
+ // HOST seam (F2): cancel (bukan hanya releaseLock) agar exit prematur /
405
+ // [DONE] melepas body & koneksi, bukan membiarkannya menggantung.
406
+ if (!reachedEof) await reader.cancel().catch(() => {});
378
407
  reader.releaseLock();
379
408
  }
380
409
  }