minicode-ai 0.23.0 → 0.26.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 (104) hide show
  1. package/README.md +5 -3
  2. package/cli/commands/config.ts +123 -0
  3. package/cli/setup.ts +107 -8
  4. package/cli/tui.ts +28 -2
  5. package/docs/README.md +2 -2
  6. package/docs/SUMMARY.md +10 -19
  7. package/docs/TERMINAL_CONTRACT.md +113 -28
  8. package/docs/architecture.md +1 -1
  9. package/docs/autonomous-scheduler.md +283 -2
  10. package/docs/choosing-mode.md +4 -4
  11. package/docs/concepts.md +39 -3
  12. package/docs/config.md +103 -5
  13. package/docs/environment.md +4 -0
  14. package/docs/getting-started.md +69 -5
  15. package/docs/repl.md +1 -1
  16. package/docs/security.md +49 -2
  17. package/docs/tools.md +2 -1
  18. package/package.json +2 -36
  19. package/src/app/provider-layer.ts +1 -1
  20. package/src/app/session.ts +187 -17
  21. package/src/config.ts +21 -8
  22. package/src/constants.ts +17 -1
  23. package/src/lib/net.ts +6 -15
  24. package/src/lib/public-http.ts +128 -0
  25. package/src/lib/safe-open.ts +21 -12
  26. package/src/memory/vector.ts +0 -31
  27. package/src/policy/auto-resume.ts +63 -0
  28. package/src/policy/compaction.ts +354 -70
  29. package/src/policy/context-budget.ts +4 -6
  30. package/src/policy/context-window-assign.ts +114 -0
  31. package/src/policy/context-window-catalog.ts +4 -1
  32. package/src/policy/context-window-presets.ts +165 -0
  33. package/src/policy/context-window.ts +19 -37
  34. package/src/policy/context.ts +11 -9
  35. package/src/policy/executor.ts +69 -27
  36. package/src/policy/microcompact.ts +76 -15
  37. package/src/policy/no-progress.ts +1 -1
  38. package/src/policy/permission.ts +5 -0
  39. package/src/policy/recovery-budget.ts +281 -0
  40. package/src/policy/scrub.ts +15 -2
  41. package/src/policy/step-escalation.ts +82 -0
  42. package/src/policy/tokenizer-registry.ts +1 -0
  43. package/src/policy/tool-contract.ts +11 -9
  44. package/src/presentation/reducer.ts +1 -0
  45. package/src/providers/anthropic.ts +3 -3
  46. package/src/providers/detect.ts +40 -7
  47. package/src/providers/provision.ts +23 -1
  48. package/src/runtime/child-execution.ts +4 -2
  49. package/src/runtime/execution-backend.ts +3 -0
  50. package/src/sandbox/os.ts +53 -9
  51. package/src/session/context-assembly.ts +11 -7
  52. package/src/session/persistence.ts +19 -3
  53. package/src/task/autonomous-policy.ts +7 -0
  54. package/src/task/graph-validate.ts +1 -1
  55. package/src/task/session-authority.ts +0 -5
  56. package/src/task/store.ts +0 -4
  57. package/src/tools/ask_user.ts +14 -1
  58. package/src/tools/bash.ts +68 -17
  59. package/src/tools/code_run.ts +19 -20
  60. package/src/tools/context.ts +10 -0
  61. package/src/tools/delete_file.ts +3 -2
  62. package/src/tools/edit.ts +5 -4
  63. package/src/tools/git.ts +70 -12
  64. package/src/tools/glob.ts +13 -5
  65. package/src/tools/grep.ts +26 -10
  66. package/src/tools/index.ts +3 -2
  67. package/src/tools/lsp.ts +15 -9
  68. package/src/tools/move_file.ts +4 -3
  69. package/src/tools/patch.ts +5 -4
  70. package/src/tools/read_file.ts +3 -2
  71. package/src/tools/read_image.ts +3 -2
  72. package/src/tools/task.ts +5 -1
  73. package/src/tools/todo.ts +4 -8
  74. package/src/tools/web_fetch.ts +13 -19
  75. package/src/tools/write_file.ts +4 -3
  76. package/src/ui/approval/prompt.ts +226 -77
  77. package/src/ui/assistant/simple.ts +61 -10
  78. package/src/ui/footer.ts +41 -29
  79. package/src/ui/i18n/en.ts +7 -0
  80. package/src/ui/i18n/id.ts +7 -0
  81. package/src/ui/input/prompt-engine.ts +53 -21
  82. package/src/ui/render/activity-group.ts +9 -0
  83. package/src/ui/render/activity-panel.ts +20 -2
  84. package/src/ui/render/ledger.ts +1 -9
  85. package/src/ui/render/logo.ts +0 -5
  86. package/src/ui/render/markdown-table.ts +0 -3
  87. package/src/ui/render/table-grid.ts +0 -3
  88. package/src/ui/render/theme.ts +31 -5
  89. package/src/ui/runtime/screen.ts +7 -1
  90. package/src/ui/screens/dialog.ts +45 -81
  91. package/src/ui/screens/form.ts +10 -10
  92. package/src/ui/screens/model-manager.ts +7 -10
  93. package/src/ui/screens/picker.ts +8 -11
  94. package/src/ui/screens/provider-manager.ts +9 -13
  95. package/src/ui/tui/app.ts +118 -20
  96. package/src/ui/tui/transcript.ts +179 -29
  97. package/vendor/minicore/src/core/loop.ts +20 -1
  98. package/vendor/minicore/src/core/session.ts +6 -0
  99. package/docs/P14_OPEN_WORK.md +0 -290
  100. package/docs/config-providers.md +0 -87
  101. package/docs/glossary.md +0 -39
  102. package/docs/quickstart.md +0 -60
  103. package/docs/security-model.md +0 -96
  104. package/docs/terminal.md +0 -91
@@ -1,6 +1,7 @@
1
1
  import type { Tool } from "#minicore"
2
2
  import { LIMITS } from "../constants.ts"
3
- import { isPrivateHostWithDns } from "../lib/net.ts"
3
+ import { isPrivateHost } from "../lib/net.ts"
4
+ import { publicHttp } from "../lib/public-http.ts"
4
5
  import { fenceUntrustedToolOutput, isAlreadyFenced, scrubSecrets } from "../policy/scrub.ts"
5
6
 
6
7
  const MAX_REDIRECTS = LIMITS.WEB_FETCH_MAX_REDIRECTS
@@ -92,6 +93,10 @@ export const webFetchTool: Tool = {
92
93
  throw new Error(`invalid url: ${u}`)
93
94
  }
94
95
 
96
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
97
+ throw new Error(`disallowed protocol: ${parsed.protocol}`)
98
+ }
99
+
95
100
  // Default 8000 (bukan 20000): hasil web rakus konteks — satu fetch `README`
96
101
  // /halaman GitHub bisa 17 KB yang menggelembungkan jendela konteks hingga
97
102
  // melampaui batas model. 8000 tetap cukup utk membaca section, jauh lebih
@@ -106,18 +111,11 @@ export const webFetchTool: Tool = {
106
111
  if (ctx.signal.aborted) controller.abort(ctx.signal.reason)
107
112
 
108
113
  try {
109
- // Redirect ditangani MANUAL: tiap hop divalidasi ulang isPrivateHost +
110
- // DNS tanpa cache klien — menutup SSRF via open-redirect & rebinding
111
- // yang mengandalkan cache basi. SISA RESIDUAL jujur (audit 2026-09-16
112
- // B6): validasi-lalu-fetch = check-then-connect; resolver OS bisa
113
- // mengembalikan IP berbeda saat connect dibanding saat cek. Menutupnya
114
- // butuh pin-IP di level socket (di luar API fetch) — ditunda sadar,
115
- // bukan diklaim tertutup.
114
+ // Each redirect uses a fresh validated DNS answer pinned to socket lookup.
115
+ // Host/SNI remain bound to the original hostname, not the selected address.
116
116
  let current = parsed
117
- // F-21: noCache di SEMUA hop (sesuai komentar desain di atas): cache DNS
118
- // 30 dtk memperlebar jendela rebinding + meracuni hasil negatif — tiap
119
- // redirect harus resolve ulang, bukan memakai cache basi.
120
- if (await isPrivateHostWithDns(current.hostname, { noCache: true })) {
117
+ // Every hop resolves independently; validated addresses are never reused across redirects.
118
+ if (isPrivateHost(current.hostname)) {
121
119
  throw new Error(`blocked private host: ${current.hostname}`)
122
120
  }
123
121
  const headers = {
@@ -126,12 +124,9 @@ export const webFetchTool: Tool = {
126
124
  }
127
125
  let res: Response | undefined
128
126
  for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
129
- res = await fetch(current.toString(), {
130
- signal: controller.signal,
131
- headers,
132
- redirect: "manual",
133
- })
127
+ res = await publicHttp.fetch(current, { signal: controller.signal, headers })
134
128
  if (res.status < 300 || res.status >= 400) break
129
+ void res.body?.cancel().catch(() => {})
135
130
  const loc = res.headers.get("location")
136
131
  if (!loc) break
137
132
  let next: URL
@@ -143,11 +138,10 @@ export const webFetchTool: Tool = {
143
138
  if (next.protocol !== "http:" && next.protocol !== "https:") {
144
139
  throw new Error(`redirect to disallowed protocol: ${next.protocol}`)
145
140
  }
146
- if (await isPrivateHostWithDns(next.hostname, { noCache: true })) {
141
+ if (isPrivateHost(next.hostname)) {
147
142
  throw new Error(`blocked private host (redirect target): ${next.hostname}`)
148
143
  }
149
144
  current = next
150
- void res.body?.cancel().catch(() => {})
151
145
  }
152
146
  if (!res) throw new Error("unreachable")
153
147
  if (res.status >= 300 && res.status < 400) {
@@ -5,7 +5,7 @@ import { LIMITS } from "../constants.ts"
5
5
  import { atomicWriteText } from "../lib/atomic-write.ts"
6
6
  import { assertSafeWriteTarget, resolveSafePath } from "../lib/safe-open.ts"
7
7
  import { appendLspDiagnostics } from "../policy/verifier.ts"
8
- import { requireToolCwd } from "./context.ts"
8
+ import { contextUnrestricted, requireToolCwd } from "./context.ts"
9
9
 
10
10
  export const writeFileTool: Tool = {
11
11
  name: "write_file",
@@ -24,10 +24,11 @@ export const writeFileTool: Tool = {
24
24
  ctx.signal.throwIfAborted()
25
25
  const p = path as string
26
26
  const root = requireToolCwd(ctx)
27
+ const relaxed = contextUnrestricted(ctx)
27
28
  // Verifikasi path terpusat (logis + target nyata) — detail di safe-open.ts.
28
- const { real: realAbs } = await resolveSafePath(p, root)
29
+ const { real: realAbs } = await resolveSafePath(p, root, relaxed)
29
30
  // Tolak menimpa symlink final (swap antara cek dan tulis gagal tutup).
30
- await assertSafeWriteTarget(resolve(root, p), root)
31
+ await assertSafeWriteTarget(resolve(root, p), root, relaxed)
31
32
  // guard large write — chars vs bytes (emoji/CJK 4x)
32
33
  const c = content as string
33
34
  if (c.length > LIMITS.WRITE_FILE_MAX_CHARS)
@@ -3,18 +3,20 @@
3
3
  // composition root (cli/setup.ts -> createMinicodeSession -> permission).
4
4
  //
5
5
  // Warga TUI: bila approval sink terdaftar (cli/tui.ts saat App aktif), blok
6
- // pertanyaan dicatat ke transkrip + layar di-repaint SEBELUM user menjawab
7
- // (jejak keputusan permanen, terlihat saat menjawab). Tanpa sink = tulis
8
- // langsung warisan (one-shot/exec). Input jawaban tetap askLine inline di
9
- // baris kursor — aman dari App karena input App dibekukan saat busy (hanya
10
- // abort yang lolos; Esc/Ctrl+C di sini = abort turn + deny, fail-closed).
6
+ // pertanyaan dicatat ke transkrip. Sejak v0.24 prompt dirender sebagai MODAL:
7
+ // backdrop redup (App.suspend) + kotak dialog terpusat (dialogBox+paintRegion),
8
+ // input raw-mode di-echo ke kotak (bukan askLine inline yang bertabrakan dengan
9
+ // painter alt-screen). Tanpa sink (one-shot/exec) = tulis langsung warisan.
11
10
 
12
11
  import { t } from "../i18n/locale.ts"
13
12
  import { askLine } from "../input/input.ts"
13
+ import { createDecoderState, createKeyStreamPump } from "../input/prompt-engine.ts"
14
14
  import { sanitizeAnsiLine } from "../render/sanitize.ts"
15
- import { c } from "../render/theme.ts"
15
+ import { c, glyphs } from "../render/theme.ts"
16
16
  import { truncateToWidth } from "../render/width.ts"
17
- import { getApprovalSink } from "../tui/transcript.ts"
17
+ import { dialogBox, popupBoxWidth } from "../screens/dialog.ts"
18
+ import { createIdleTimer } from "../screens/lifecycle.ts"
19
+ import { type ApprovalSink, getApprovalSink } from "../tui/transcript.ts"
18
20
 
19
21
  /** Subset struktural tool call yang dibutuhkan view — tanpa tipe kernel. */
20
22
  export interface ApprovalRequest {
@@ -52,32 +54,143 @@ function tierLabel(riskTier?: string): string | undefined {
52
54
  }
53
55
  }
54
56
 
57
+ // ── Modal input bersama (approval & ask_user) ──────────────────────────────
58
+ // Baca SATU baris raw-mode sambil me-render ulang kotak tiap ketikan (echo).
59
+ // Enter = submit; Esc/Ctrl+C = batal (null). Idle dua-fase (80s warn / 10s
60
+ // batal) mencegah raw-mode digenggam selamanya (segfault Bun Windows).
61
+
62
+ /** Keputusan approval. */
63
+ type Decision = "allow" | "always" | "deny"
64
+
65
+ /**
66
+ * Baca satu jawaban dari kotak modal. `line` = teks bebas; `choice` = daftar
67
+ * dengan `↑↓`/home/end + Enter (I25) dan ketik-cepat huruf pertama (AUD-005).
68
+ * Satu pembaca untuk dua mode: salinan kedua pasti menyimpang (kelas AUD-003).
69
+ */
70
+ function readModalInput<T extends "line" | "choice">(
71
+ mode: T,
72
+ render: (state: { sel: number; typed: string }) => void,
73
+ opt: T extends "choice" ? { count: number; quick: Readonly<Record<string, number>> } : object,
74
+ ): Promise<T extends "choice" ? number | null : string | null> {
75
+ type R = T extends "choice" ? number | null : string | null
76
+ return new Promise((resolve) => {
77
+ const o = opt as { count?: number; quick?: Record<string, number> }
78
+ const count = o.count ?? 0
79
+ const quick = o.quick ?? {}
80
+ let done = false
81
+ let sel = 0
82
+ let typed = ""
83
+ let onData!: (chunk: Buffer) => void
84
+ const pump = createKeyStreamPump({
85
+ state: createDecoderState(),
86
+ onKeys: (keys) => {
87
+ for (const k of keys) {
88
+ const key = k.key
89
+ if (key.type === "enter") {
90
+ finish((mode === "choice" ? sel : typed) as R)
91
+ return true
92
+ }
93
+ if (key.type === "esc" || key.type === "ctrl-c") {
94
+ finish(null as R)
95
+ return true
96
+ }
97
+ if (mode === "choice") {
98
+ if (key.type === "up") sel = Math.max(0, sel - 1)
99
+ else if (key.type === "down") sel = Math.min(count - 1, sel + 1)
100
+ else if (key.type === "home") sel = 0
101
+ else if (key.type === "end") sel = count - 1
102
+ else if (key.type === "char") {
103
+ // Ketik-cepat: huruf cocok langsung submit.
104
+ const hit = quick[key.ch.toLowerCase()]
105
+ if (hit != null && hit < count) {
106
+ finish(hit as R)
107
+ return true
108
+ }
109
+ }
110
+ } else if (key.type === "char") typed += key.ch
111
+ else if (key.type === "backspace") typed = typed.slice(0, -1)
112
+ }
113
+ idle.reset()
114
+ try {
115
+ render({ sel, typed })
116
+ } catch {}
117
+ return false
118
+ },
119
+ })
120
+ const idle = createIdleTimer({
121
+ warnMs: 80_000,
122
+ cancelMs: 10_000,
123
+ onCancel: () => finish(null as R),
124
+ })
125
+ const finish = (v: R) => {
126
+ if (done) return
127
+ done = true
128
+ try {
129
+ pump.dispose()
130
+ } catch {}
131
+ idle.dispose()
132
+ try {
133
+ process.stdin.removeListener("data", onData)
134
+ } catch {}
135
+ try {
136
+ process.stdin.setRawMode(false)
137
+ } catch {}
138
+ resolve(v)
139
+ }
140
+ onData = (chunk: Buffer) => pump.push(new Uint8Array(chunk))
141
+ try {
142
+ process.stdin.setRawMode(true)
143
+ } catch {}
144
+ process.stdin.on("data", onData)
145
+ try {
146
+ render({ sel: 0, typed: "" })
147
+ } catch {}
148
+ })
149
+ }
150
+
151
+ /** Render kotak modal + baris ekstra (echo / daftar bersorot). */
152
+ function paintModal(
153
+ sink: ApprovalSink,
154
+ spec: { title: string; body: string[]; footer?: string },
155
+ extra: readonly string[],
156
+ ): void {
157
+ if (!sink.paintRegion) return
158
+ const cols = process.stdout.columns || 80
159
+ // Lebar popup SERAGAM (AUD-007): dulu selebar layar, melanggar I20.
160
+ const boxW = popupBoxWidth(cols)
161
+ const box = dialogBox(
162
+ {
163
+ title: spec.title,
164
+ body: [...spec.body, ...extra],
165
+ footer: spec.footer,
166
+ minWidth: boxW,
167
+ maxWidth: boxW,
168
+ },
169
+ Math.max(20, cols),
170
+ Math.max(5, process.stdout.rows || 24),
171
+ )
172
+ sink.paintRegion(box.lines, box.topRow)
173
+ }
174
+
55
175
  export async function promptAsk(call: ApprovalRequest): Promise<"allow" | "deny" | "always"> {
56
176
  if (!process.stdin.isTTY) return "deny"
57
177
  const sink = getApprovalSink()
58
- // Tanpa sink (one-shot/exec) + stdout di-pipe: prompt tak terlihat user DAN
59
- // askLine/blok akan mencemari stdout (kontrak: stdout = output PROGRAM).
60
- // Fail-closed: tolak daripada mencemari pipe (kontrak I23).
178
+ // Tanpa sink (one-shot/exec) + stdout pipe: prompt tak terlihat dan blok
179
+ // mencemari stdout program → fail-closed (kontrak I23).
61
180
  if (!sink && !process.stdout.isTTY) return "deny"
62
- // Non-visual feedback bisa dimatikan untuk aksesibilitas/recording.
63
- // Bell hanya bila stdout TTY: byte `\x07` di stdout pipe mengotori output
64
- // program (kontrak: stdout = output PROGRAM, bukan diagnostik).
181
+ // Bell hanya bila stdout TTY: `\x07` di stdout pipe mengotori output program.
65
182
  if (process.env.MINICODE_BELL !== "0" && process.stdout.isTTY) process.stdout.write("\x07")
66
- // Live-region untuk screen reader: baris polos tanpa ANSI agar terbaca
67
- // sebagai teks, bukan escape mentah. Bell saja mengganggu tanpa informasi.
183
+ // Live-region screen reader: teks polos, bukan escape mentah.
68
184
  if (process.env.MINICODE_A11Y === "1")
69
185
  process.stderr.write(`${t("appr.a11y", { name: sanitizeAnsiLine(call.name) })}\n`)
70
186
 
71
- // toolName/actionSummary berasal dari model/MCP (tidak terpercaya). Tanpa
72
- // sanitasi, `\x1b[2J\x1b[H` di dalam args.command akan membersihkan layar
73
- // terminal user saat prompt persetujuan tampil (sama seperti provider:text).
187
+ // toolName/actionSummary dari model/MCP (tak terpercaya): `\x1b[2J` di args
188
+ // bisa membersihkan layar saat prompt tampil → sanitasi wajib.
74
189
  const toolName = sanitizeAnsiLine(call.name)
75
190
  const args = (call.args ?? {}) as Record<string, unknown>
76
191
 
77
- // Sanitasi DULU, potong SESUDAH: `slice` mentah bisa membelah surrogate
78
- // pair (byte U+FFFD di layar) dan memotong sekuens ANSI di tengah sehingga
79
- // ekor `\x1b[` menggantung (terminal menelan output berikutnya sebagai
80
- // parameter CSI) — audit 2026-11-12, MEDIUM-1.
192
+ // Sanitasi DULU, potong SESUDAH: `slice` mentah bisa membelah surrogate pair
193
+ // dan memotong sekuens ANSI di tengah (audit 2026-11-12, MEDIUM-1).
81
194
  const summarize = (value: unknown, max: number): string =>
82
195
  truncateToWidth(sanitizeAnsiLine(String(value)), max, "…")
83
196
  let actionSummary = ""
@@ -95,56 +208,81 @@ export async function promptAsk(call: ApprovalRequest): Promise<"allow" | "deny"
95
208
  }
96
209
  actionSummary = sanitizeAnsiLine(actionSummary)
97
210
 
98
- // F-APPROVAL-1: bila policy sudah memberi pratinjau diff yang representatif +
99
- // dibasuh secret, tampilkan itu sebagai baris "apa yang akan terjadi" —
100
- // lebih jujur dari ringkasan args. Fallback ringkasan args (di atas) tetap
101
- // dipakai untuk jalur tanpa diff (mis. promptAsk dipanggil langsung/test).
102
- // Diff juga input tak terpercaya (bisa memuat ANSI dari path/konten) → sanitasi.
211
+ // F-APPROVAL-1: pratinjau diff dari policy (sudah dibasuh secret) lebih jujur
212
+ // dari ringkasan args; jalur tanpa diff tetap memakai ringkasan args.
103
213
  const diffPreview = call.diffPreview ? sanitizeAnsiLine(call.diffPreview) : ""
104
214
  const riskText = tierLabel(call.riskTier)
105
215
 
106
- const block = [
107
- ``,
108
- `${c.warning(c.bold(t("appr.title")))}`,
109
- ` ${c.bold(t("appr.tool"))} ${c.info(toolName)}`,
110
- ...(riskText ? [` ${c.dim(t("appr.risk"))} ${c.info(riskText)}`] : []),
111
- ` ${diffPreview ? `${t("appr.diff")} ${diffPreview}` : actionSummary}`,
216
+ const alwaysAvailable = call.canAlways !== false
217
+ const summary = diffPreview ? `${t("appr.diff")} ${diffPreview}` : actionSummary
218
+
219
+ const info = [
220
+ `${c.bold(t("appr.tool"))} ${c.info(toolName)}`,
221
+ ...(riskText ? [`${c.dim(t("appr.risk"))} ${c.info(riskText)}`] : []),
112
222
  ]
223
+ const summaryLine = ` ${summary}`
224
+ const modalBody = [...info, summaryLine]
225
+ // Transkrip menyertakan batang judul; modal memakai bar title kotak.
226
+ const block = [``, c.warning(c.bold(t("appr.title"))), ...info.map((l) => ` ${l}`), summaryLine]
227
+
228
+ // Daftar opsi = sumber tunggal untuk footer, sorotan, dan ketik-cepat.
229
+ // `keys`: huruf pembeda unik agar sinonim dwibahasa panjang cukup 1 ketukan.
230
+ const choices: { label: string; keys: string[]; value: Decision }[] = [
231
+ { label: t("appr.allowOnce"), keys: ["y", "e"], value: "allow" },
232
+ ...(alwaysAvailable
233
+ ? [{ label: t("appr.always"), keys: ["a", "l"], value: "always" as const }]
234
+ : []),
235
+ { label: t("appr.deny"), keys: ["n", "i"], value: "deny" },
236
+ ]
237
+ const quickMap: Record<string, number> = {}
238
+ for (const [i, ch] of choices.entries()) for (const k of ch.keys) quickMap[k] = i
239
+ // `selalu`→s, `tidak`→t: tak berbagi huruf pertama dengan label.
240
+ quickMap.s = choices.findIndex((ch) => ch.value === "always")
241
+ quickMap.t = choices.findIndex((ch) => ch.value === "deny")
242
+
243
+ const choiceHint = t("appr.keyHint")
244
+ let pickedIndex: number | null = null
113
245
  if (sink) {
114
246
  sink.pushBlock(block)
115
247
  sink.repaint()
116
- // Bekukan App selama menunggu jawaban (pola popup komposit): tanpa ini
117
- // listener App + repaint live berlomba dengan askLine — prompt tak
118
- // terlihat, user mengetik buta. Esc/Ctrl+C di sini = deny (batal hanya
119
- // tool ini), BUKAN abort turn — turn lanjut dengan tool lain.
120
248
  sink.suspend()
249
+ try {
250
+ pickedIndex = await readModalInput(
251
+ "choice",
252
+ ({ sel }) => {
253
+ const rendered = choices.map((ch, i) =>
254
+ i === sel ? ` ${c.accent(`${glyphs.check} ${ch.label}`)}` : ` ${c.dim(ch.label)}`,
255
+ )
256
+ paintModal(sink, { title: t("appr.title"), body: modalBody, footer: choiceHint }, [
257
+ "",
258
+ ...rendered,
259
+ ])
260
+ },
261
+ { count: choices.length, quick: quickMap },
262
+ )
263
+ } finally {
264
+ try {
265
+ sink.clearRegion?.()
266
+ } catch {}
267
+ sink.resume()
268
+ }
121
269
  } else {
122
270
  for (const l of block) process.stdout.write(`${l}\n`)
271
+ const labels = choices.map((ch) => c.bold(ch.label)).join(" ")
272
+ const raw = (await askLine({ prompt: `${labels}: ` })) ?? ""
273
+ // Non-TUI tetap ketik (tak ada panah).
274
+ const hit = quickMap[raw.trim().toLowerCase().slice(0, 1)]
275
+ pickedIndex = hit != null && hit >= 0 ? hit : null
123
276
  }
124
277
 
125
- const alwaysAvailable = call.canAlways !== false
126
- const promptText = alwaysAvailable
127
- ? `${c.bold(t("appr.allowOnce"))} ${c.bold(t("appr.always"))} ${c.bold(t("appr.deny"))}: `
128
- : `${c.bold(t("appr.allowOnce"))} ${c.bold(t("appr.deny"))}: `
129
- let ans: string | null
130
- try {
131
- ans = (await askLine({ prompt: promptText })) ?? ""
132
- } finally {
133
- if (sink) sink.resume()
134
- }
135
-
136
- // Terima jawaban dwibahasa (prompt tampil per locale): y/yes/ya,
137
- // n/no/tidak/t, a/always/selalu/s. Selain itu = deny (fail-closed).
138
- const a = ans.trim().toLowerCase()
139
- const wantsAlways = a === "a" || a === "always" || a === "selalu" || a === "s"
140
- const decisionKey = wantsAlways
141
- ? // Opsi yang tidak ditampilkan tidak boleh diterima diam-diam; fail-closed.
142
- alwaysAvailable
143
- ? ("appr.decAlways" as const)
144
- : ("appr.decDeny" as const)
145
- : a === "y" || a === "yes" || a === "ya"
278
+ // Batal/indeks di luar rentang = deny (fail-closed).
279
+ const chosen = pickedIndex != null ? choices[pickedIndex] : undefined
280
+ const decisionKey =
281
+ chosen?.value === "allow"
146
282
  ? ("appr.decAllow" as const)
147
- : ("appr.decDeny" as const)
283
+ : chosen?.value === "always"
284
+ ? ("appr.decAlways" as const)
285
+ : ("appr.decDeny" as const)
148
286
  const decision = t(decisionKey)
149
287
  // Keputusan dicatat di transkrip (jejak audit); warisan mengandalkan
150
288
  // scrollback askLine yang terhapus repaint.
@@ -160,9 +298,8 @@ export async function promptAsk(call: ApprovalRequest): Promise<"allow" | "deny"
160
298
  }
161
299
 
162
300
  /** View pertanyaan ask_user — di-inject ke src/tools/ask_user.ts dari cli/setup.ts.
163
- * Teks pertanyaan berasal dari model (tidak terpercaya): disanitasi sebelum
164
- * tampil agar tak bisa membersihkan layar via escape sequence. Return null
165
- * bila user membatalkan (Esc/Ctrl+C → askLine null) atau jawaban kosong. */
301
+ * Pertanyaan dari model (tak terpercaya) disanitasi sebelum tampil. Return null
302
+ * bila user membatalkan (Esc/Ctrl+C) atau jawaban kosong. */
166
303
  export async function promptAskText(question: string, options?: string[]): Promise<string | null> {
167
304
  if (!process.stdin.isTTY) return null
168
305
  const textSink = getApprovalSink()
@@ -172,35 +309,47 @@ export async function promptAskText(question: string, options?: string[]): Promi
172
309
  // Potong SESUDAH sanitasi lewat truncateToWidth (bukan `slice`): `slice`
173
310
  // bisa menyisakan `\x1b[` menggantung di ekor potongan.
174
311
  const q = truncateToWidth(sanitizeAnsiLine(question), 2000, "…")
175
- const block = [
176
- ``,
177
- `${c.warning(c.bold(t("appr.askTitle")))}`,
178
- ` ${q}`,
179
- ...(options?.length
180
- ? options.map((o, i) => ` ${c.dim(`${i + 1}.`)} ${sanitizeAnsiLine(o)}`)
181
- : []),
182
- ]
312
+ const optionLines = options?.length
313
+ ? options.map((o, i) => ` ${c.dim(`${i + 1}.`)} ${sanitizeAnsiLine(o)}`)
314
+ : []
315
+ const block = [``, `${c.warning(c.bold(t("appr.askTitle")))}`, ` ${q}`, ...optionLines]
316
+ const modalBody = [` ${q}`, ...optionLines]
183
317
  const sink = textSink
318
+ let ans: string | null = null
184
319
  if (sink) {
185
320
  sink.pushBlock(block)
186
321
  sink.repaint()
187
322
  sink.suspend()
323
+ try {
324
+ ans = await readModalInput(
325
+ "line",
326
+ ({ typed }) =>
327
+ paintModal(sink, { title: t("appr.askTitle"), body: modalBody }, [
328
+ ` ${c.dim(">")} ${c.info(sanitizeAnsiLine(typed))}`,
329
+ ]),
330
+ {},
331
+ )
332
+ } finally {
333
+ try {
334
+ sink.clearRegion?.()
335
+ } catch {}
336
+ sink.resume()
337
+ }
188
338
  } else {
189
339
  for (const l of block) process.stdout.write(`${l}\n`)
190
- }
191
- let ans: string | null
192
- try {
193
340
  ans = await askLine({ prompt: `${c.bold(t("appr.answerPrompt"))}` })
194
- } finally {
195
- if (sink) sink.resume()
196
341
  }
197
342
  if (ans == null || !ans.trim()) return null
198
343
  const out = ans.trim()
344
+ // Opsi bernomor: petakan "1".."n" ke teks (AUD-008); teks bebas diteruskan.
345
+ const pick = options?.length ? /^\s*(\d+)\s*$/.exec(out) : null
346
+ const mapped = pick ? options?.[Number(pick[1]) - 1] : undefined
347
+ const finalAnswer = mapped ?? out
199
348
  if (sink) {
200
349
  // Gema jawaban juga dipotong lewat truncateToWidth: `slice` bisa membelah
201
350
  // surrogate pair (emoji → U+FFFD) atau menyisakan escape menggantung.
202
- sink.pushBlock([c.muted(` → ${truncateToWidth(sanitizeAnsiLine(out), 200, "…")}`)])
351
+ sink.pushBlock([c.muted(` → ${truncateToWidth(sanitizeAnsiLine(finalAnswer), 200, "…")}`)])
203
352
  sink.repaint()
204
353
  }
205
- return out
354
+ return finalAnswer
206
355
  }
@@ -176,6 +176,19 @@ function patchBlocks(patches: unknown): [string, string] {
176
176
  return [list.map((p) => p.search ?? "").join("\n"), list.map((p) => p.replace ?? "").join("\n")]
177
177
  }
178
178
 
179
+ /** Tool yang baris `execution:completed`-nya sudah mencetak chevron + nama +
180
+ * target dengan bentuk sama seperti baris `execution:started`. Baris start
181
+ * dilewati untuk tool ini agar tidak tercetak duplikat.
182
+ *
183
+ * Sengaja daftar EKSPLISIT, bukan "semua tool": tool yang baris hasilnya tidak
184
+ * berbentuk chevron+nama+target tetap butuh baris start sebagai satu-satunya
185
+ * penanda "sedang berjalan". */
186
+ function toolPrintsOwnCompletionLine(name: string, args: Record<string, unknown>): boolean {
187
+ if (name === "read_file" || name === "write_file") return typeof args.path === "string"
188
+ if (name === "edit_file" || name === "multi_edit_file") return typeof args.path === "string"
189
+ return false
190
+ }
191
+
179
192
  export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () => void {
180
193
  // Shadow module-level wOut/wErr: saat quiet, paint ditekan tapi SEMUA state
181
194
  // (rememberTurn, rememberCollapsedSection, pendingError, sanitizer) tetap jalan.
@@ -385,8 +398,22 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
385
398
  emitAnswer(`${rendered}\n`)
386
399
  }
387
400
  }
388
- const flushTableStream = (): void => {
389
- consumeTableEvents(tableStream.flush())
401
+ /**
402
+ * Selesaikan teks yang tertahan.
403
+ *
404
+ * `includePartial = false` dipakai saat menyisipkan baris ledger di TENGAH
405
+ * stream. `tableStream.flush()` mengeluarkan `lineBuffer` parsial sebagai
406
+ * baris utuh, sehingga satu baris markdown terpotong di titik event datang
407
+ * dan tiap potongan dibungkus ulang sendiri ("export const" / "multiply =" /
408
+ * "(a: number)" = gejala output pipa terfragmentasi).
409
+ * Tanpa itu, baris parsial tetap tertahan di `tableStream` sampai `
410
+ `
411
+ * berikutnya tiba — urutan teks akhir tidak berubah.
412
+ * Default `true` untuk batas turn/teardown, di mana sisa parsial memang
413
+ * harus dicetak agar tidak hilang diam-diam.
414
+ */
415
+ const flushTableStream = (includePartial = true): void => {
416
+ if (includePartial) consumeTableEvents(tableStream.flush())
390
417
  if (plainLineBuffer) {
391
418
  flushLine(plainLineBuffer)
392
419
  plainLineBuffer = ""
@@ -442,9 +469,25 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
442
469
  if (provenance === "replay" || provenance === "reconstructed") parts.push(provenance)
443
470
  return parts.length > 0 ? ` ${c.muted(`[${parts.join(" · ")}]`)}` : ""
444
471
  }
472
+ /** Tulis satu baris ledger (status/verifikasi/cutoff) di tengah stream teks.
473
+ * `flushTableStream(false)` memaksa baris yang sudah lengkap keluar lebih
474
+ * dulu agar urutan baris benar, TANPA memotong baris yang belum selesai. */
475
+ const emitLedger = (line: string): void => {
476
+ // `false`: jangan keluarkan baris teks yang belum selesai.
477
+ flushTableStream(false)
478
+ wErr(line)
479
+ }
480
+
445
481
  const writePresentationTerminal = (event: UiPresentationEvent): void => {
446
482
  if (!presentationEnabled) return
447
- flushTableStream()
483
+ // JANGAN flush di sini. `flushTableStream()` mengeluarkan `lineBuffer`
484
+ // parsial sebagai baris UTUH; dipanggil pada setiap presentation event
485
+ // (status task, clock, verifikasi, consequence) yang datang di tengah
486
+ // stream teks, ia memecah satu baris markdown menjadi potongan-potongan
487
+ // dan masing-masing dibungkus ulang sendiri — gejala "output pipa
488
+ // terfragmentasi" (satu baris kode jadi 3-4 baris acak).
489
+ // Flush hanya perlu tepat SEBELUM sebuah baris ledger ditulis, jadi
490
+ // ditangani oleh `ledgerLine` di bawah.
448
491
  // F-TASK-1: status task kanonik juga punya baris ledger di jalur linear
449
492
  // (scrollback non-TTY). Sebelum ini event hanya hidup di TUI + machine
450
493
  // envelope — pengguna `minicode exec`/pipe tak pernah melihatnya.
@@ -476,7 +519,7 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
476
519
  : raw === "COMPLETED"
477
520
  ? c.success(line)
478
521
  : c.muted(line)
479
- wErr(`${paint}\n`)
522
+ emitLedger(`${paint}\n`)
480
523
  return
481
524
  }
482
525
  // Observasi verifikasi punya baris sendiri (dedup per invocation):
@@ -496,7 +539,7 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
496
539
  verification.verdict === "present"
497
540
  ? ` ${glyphs.arrow} ${name}${targetText} verified`
498
541
  : ` ? ${name}${targetText} unverified (${verification.verdict})`
499
- wErr(`${verification.verdict === "present" ? c.success(line) : c.muted(line)}\n`)
542
+ emitLedger(`${verification.verdict === "present" ? c.success(line) : c.muted(line)}\n`)
500
543
  return
501
544
  }
502
545
  // P1.5: consequence/context diagnostics juga tampil di scrollback linear.
@@ -516,12 +559,12 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
516
559
  : verdict === "PASS"
517
560
  ? c.success(line)
518
561
  : c.warning(line)
519
- wErr(`${paint}\n`)
562
+ emitLedger(`${paint}\n`)
520
563
  return
521
564
  }
522
565
  if (event.type === "context.cutoff") {
523
566
  const reason = event.reason ? `: ${sanitizeAnsiLine(String(event.reason))}` : ""
524
- wErr(`${c.warning(` ${glyphs.bullet} context cutoff${reason}`)}\n`)
567
+ emitLedger(`${c.warning(` ${glyphs.bullet} context cutoff${reason}`)}\n`)
525
568
  return
526
569
  }
527
570
  if (event.type === "context.window") {
@@ -532,7 +575,7 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
532
575
  used != null
533
576
  ? ` ${used.toLocaleString()}${window ? `/${window.toLocaleString()}` : ""} tokens`
534
577
  : ""
535
- wErr(`${c.muted(` ${glyphs.bullet} context window${tokens}${pct}`)}\n`)
578
+ emitLedger(`${c.muted(` ${glyphs.bullet} context window${tokens}${pct}`)}\n`)
536
579
  return
537
580
  }
538
581
  if (
@@ -563,7 +606,7 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
563
606
  const marker = runMarker(activity)
564
607
  const prefix = isChild ? ` ↳ ${marker ? `${marker} ` : ""}` : ` ${glyphs.arrow} `
565
608
  const line = `${prefix}${name}${targetText}${linearSuffix(activity)}${detail}`
566
- wErr(paintLedger(status, `${line}\n`))
609
+ emitLedger(paintLedger(status, `${line}\n`))
567
610
  }
568
611
 
569
612
  const offs: (() => void)[] = []
@@ -812,10 +855,18 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
812
855
  }
813
856
  // Expanded: user melihat tool apa yang mulai berjalan SEBELUM hasilnya,
814
857
  // inline di aliran output — transparansi ala shell (`set -x`).
858
+ //
859
+ // KECUALI tool yang `execution:completed`-nya sudah mencetak baris dengan
860
+ // bentuk sama (chevron + nama + target). Dulu keduanya aktif bersamaan,
861
+ // sehingga satu `read_file` tampil dua kali berturut-turut persis sama.
862
+ // Baris hasil lebih kaya (membawa suffix durasi/status), jadi yang
863
+ // dibuang adalah baris start.
864
+ const startName = e.execution.call.name
815
865
  const args = (e.execution.call.args ?? {}) as Record<string, unknown>
866
+ if (toolPrintsOwnCompletionLine(startName, args)) return
816
867
  wErr(
817
868
  c.muted(
818
- ` ${glyphs.arrow} ${sanitizeAnsiLine(e.execution.call.name)} ${sanitizeAnsiLine(formatArgsPreview(args))}\n`,
869
+ ` ${glyphs.arrow} ${sanitizeAnsiLine(startName)} ${sanitizeAnsiLine(formatArgsPreview(args))}\n`,
819
870
  ),
820
871
  )
821
872
  }),