minicode-ai 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +2 -2
  2. package/cli/tui.ts +28 -2
  3. package/docs/README.md +2 -2
  4. package/docs/SUMMARY.md +10 -19
  5. package/docs/TERMINAL_CONTRACT.md +82 -28
  6. package/docs/architecture.md +1 -1
  7. package/docs/autonomous-scheduler.md +283 -2
  8. package/docs/choosing-mode.md +4 -4
  9. package/docs/concepts.md +39 -3
  10. package/docs/config.md +90 -4
  11. package/docs/environment.md +3 -0
  12. package/docs/getting-started.md +58 -2
  13. package/docs/repl.md +1 -1
  14. package/docs/security.md +49 -2
  15. package/docs/tools.md +2 -1
  16. package/package.json +2 -36
  17. package/src/app/provider-layer.ts +1 -1
  18. package/src/config.ts +2 -0
  19. package/src/constants.ts +3 -0
  20. package/src/lib/safe-open.ts +21 -12
  21. package/src/memory/vector.ts +0 -31
  22. package/src/policy/context-window.ts +0 -33
  23. package/src/policy/no-progress.ts +1 -1
  24. package/src/policy/permission.ts +5 -0
  25. package/src/policy/scrub.ts +15 -2
  26. package/src/policy/tool-contract.ts +11 -9
  27. package/src/presentation/reducer.ts +1 -0
  28. package/src/providers/anthropic.ts +3 -3
  29. package/src/providers/detect.ts +27 -0
  30. package/src/providers/provision.ts +15 -1
  31. package/src/task/autonomous-policy.ts +7 -0
  32. package/src/task/graph-validate.ts +1 -1
  33. package/src/task/session-authority.ts +0 -5
  34. package/src/task/store.ts +0 -4
  35. package/src/tools/ask_user.ts +14 -1
  36. package/src/tools/bash.ts +57 -9
  37. package/src/tools/context.ts +10 -0
  38. package/src/tools/delete_file.ts +3 -2
  39. package/src/tools/edit.ts +5 -4
  40. package/src/tools/git.ts +70 -12
  41. package/src/tools/glob.ts +13 -5
  42. package/src/tools/grep.ts +26 -10
  43. package/src/tools/index.ts +3 -2
  44. package/src/tools/lsp.ts +15 -9
  45. package/src/tools/move_file.ts +4 -3
  46. package/src/tools/patch.ts +5 -4
  47. package/src/tools/read_file.ts +3 -2
  48. package/src/tools/read_image.ts +3 -2
  49. package/src/tools/task.ts +1 -0
  50. package/src/tools/todo.ts +4 -8
  51. package/src/tools/write_file.ts +4 -3
  52. package/src/ui/approval/prompt.ts +226 -77
  53. package/src/ui/footer.ts +41 -29
  54. package/src/ui/i18n/en.ts +4 -0
  55. package/src/ui/i18n/id.ts +4 -0
  56. package/src/ui/render/activity-group.ts +1 -0
  57. package/src/ui/render/ledger.ts +1 -9
  58. package/src/ui/render/logo.ts +0 -5
  59. package/src/ui/render/markdown-table.ts +0 -3
  60. package/src/ui/render/table-grid.ts +0 -3
  61. package/src/ui/render/theme.ts +31 -5
  62. package/src/ui/runtime/screen.ts +7 -1
  63. package/src/ui/screens/dialog.ts +45 -81
  64. package/src/ui/screens/form.ts +10 -10
  65. package/src/ui/screens/model-manager.ts +7 -10
  66. package/src/ui/screens/picker.ts +8 -11
  67. package/src/ui/screens/provider-manager.ts +9 -13
  68. package/src/ui/tui/app.ts +92 -9
  69. package/src/ui/tui/transcript.ts +4 -0
  70. package/docs/P14_OPEN_WORK.md +0 -290
  71. package/docs/config-providers.md +0 -87
  72. package/docs/glossary.md +0 -39
  73. package/docs/quickstart.md +0 -60
  74. package/docs/security-model.md +0 -96
  75. package/docs/terminal.md +0 -91
@@ -3,7 +3,7 @@ import { dirname } from "node:path"
3
3
  import type { Tool } from "#minicore"
4
4
  import { resolveSafePath } from "../lib/safe-open.ts"
5
5
  import { trashFile } from "../lib/trash.ts"
6
- import { requireToolCwd } from "./context.ts"
6
+ import { contextUnrestricted, requireToolCwd } from "./context.ts"
7
7
 
8
8
  export const moveFileTool: Tool = {
9
9
  name: "move_file",
@@ -21,16 +21,17 @@ export const moveFileTool: Tool = {
21
21
  async execute({ from, to }, ctx) {
22
22
  ctx.signal.throwIfAborted()
23
23
  const root = requireToolCwd(ctx)
24
+ const relaxed = contextUnrestricted(ctx)
24
25
  const f = from as string
25
26
  const t = to as string
26
27
  // Verifikasi kedua ujung via pemilik tunggal (logis + target nyata) —
27
28
  // detail di safe-open.ts. Beda dengan tool satu-berkas hanya karena
28
29
  // move punya dua ujung; substring pesan ("outside workspace",
29
30
  // "blocked sensitive file") dipertahankan agar test regex tetap hijau.
30
- const { abs: absFrom, real: realFrom } = await resolveSafePath(f, root)
31
+ const { abs: absFrom, real: realFrom } = await resolveSafePath(f, root, relaxed)
31
32
  const st = await stat(realFrom).catch(() => null)
32
33
  if (!st) throw new Error(`source not found: ${f}`)
33
- const { abs: absTo } = await resolveSafePath(t, root)
34
+ const { abs: absTo } = await resolveSafePath(t, root, relaxed)
34
35
  await mkdir(dirname(absTo), { recursive: true, mode: 0o700 }).catch(() => {})
35
36
  // S3 — dest yang sudah ada dibackup ke trash dulu (jangan timpa diam-diam).
36
37
  // absTo sudah terverifikasi nyata oleh resolveSafePath, jadi tak perlu
@@ -3,7 +3,7 @@ import type { Tool } from "#minicore"
3
3
  import { LIMITS } from "../constants.ts"
4
4
  import { atomicWriteText } from "../lib/atomic-write.ts"
5
5
  import { assertSafeWriteTarget, resolveSafePath, safeReadFile } from "../lib/safe-open.ts"
6
- import { requireToolCwd } from "./context.ts"
6
+ import { contextUnrestricted, requireToolCwd } from "./context.ts"
7
7
  import { flexibleMatch } from "./edit.ts"
8
8
 
9
9
  // Apply SEARCH/REPLACE block (a la Aider) ke file. Search block harus match
@@ -40,16 +40,17 @@ export const applyPatchTool: Tool = {
40
40
  ctx.signal.throwIfAborted()
41
41
  const p = path as string
42
42
  const root = requireToolCwd(ctx)
43
+ const relaxed = contextUnrestricted(ctx)
43
44
  // Verifikasi path terpusat (logis + target nyata) — detail di safe-open.ts.
44
- const { abs, real: realAbs } = await resolveSafePath(p, root)
45
+ const { abs, real: realAbs } = await resolveSafePath(p, root, relaxed)
45
46
  // Tolak menimpa symlink final (swap antara cek dan tulis gagal tutup).
46
- await assertSafeWriteTarget(abs, root)
47
+ await assertSafeWriteTarget(abs, root, relaxed)
47
48
  const st = await stat(realAbs).catch(() => null)
48
49
  if (!st) throw new Error(`file not found: ${p}`)
49
50
  if (st.size > LIMITS.READ_FILE_MAX_BYTES) throw new Error(`file too large: ${p} (${st.size})`)
50
51
 
51
52
  // Pakai safeReadFile (O_NOFOLLOW) agar swap symlink di antara cek dan baca gagal ELOOP.
52
- let content = await safeReadFile(abs, root)
53
+ let content = await safeReadFile(abs, root, relaxed)
53
54
  const patchList = patches as { search: string; replace: string }[]
54
55
  if (patchList.length > 50) throw new Error(`too many patches: ${patchList.length} (max 50)`)
55
56
  const applied: string[] = []
@@ -4,7 +4,7 @@ import type { Tool } from "#minicore"
4
4
  import { LIMITS } from "../constants.ts"
5
5
  import { safeOpenRead } from "../lib/safe-open.ts"
6
6
  import { scrubSecrets } from "../policy/scrub.ts"
7
- import { requireToolCwd } from "./context.ts"
7
+ import { contextUnrestricted, requireToolCwd } from "./context.ts"
8
8
 
9
9
  // defense-in-depth: also jail inside tool (permission layer is primary)
10
10
 
@@ -168,13 +168,14 @@ export const readFileTool: Tool = {
168
168
  ctx.signal.throwIfAborted()
169
169
  const p = path as string
170
170
  const root = requireToolCwd(ctx)
171
+ const relaxed = contextUnrestricted(ctx)
171
172
  const abs = isAbsolute(p) ? resolve(p) : resolve(root, p)
172
173
  // Semua verifikasi path (jail + sensitif + O_NOFOLLOW) terjadi di SATU
173
174
  // titik saat open — detail di safe-open.ts. Tidak ada resolve/stat
174
175
  // terpisah: handle dipakai untuk stat (cap ukuran) lalu baca.
175
176
  let handle: Awaited<ReturnType<typeof safeOpenRead>>["handle"]
176
177
  try {
177
- ;({ handle } = await safeOpenRead(abs, root))
178
+ ;({ handle } = await safeOpenRead(abs, root, relaxed))
178
179
  } catch (e) {
179
180
  // ENOENT → pesan seragam; sisanya (jail/sensitif/ELOOP/raw IO) apa adanya
180
181
  const msg = (e as Error).message ?? ""
@@ -3,7 +3,7 @@ import type { Tool } from "#minicore"
3
3
  import { LIMITS } from "../constants.ts"
4
4
  import { safeOpenRead } from "../lib/safe-open.ts"
5
5
  import { estimateImageTokens } from "../policy/context.ts"
6
- import { requireToolCwd } from "./context.ts"
6
+ import { contextUnrestricted, requireToolCwd } from "./context.ts"
7
7
 
8
8
  // Batas b64 = batas truncate kernel yang sebenarnya: toolResultMaxTokens
9
9
  // (default 4096) × DEFAULT_CHARS_PER_TOKEN (4) = 16.384 chars, dengan margin
@@ -27,13 +27,14 @@ export const readImageTool: Tool = {
27
27
  ctx.signal.throwIfAborted()
28
28
  const p = path as string
29
29
  const root = requireToolCwd(ctx)
30
+ const relaxed = contextUnrestricted(ctx)
30
31
  const abs = isAbsolute(p) ? resolve(p) : resolve(root, p)
31
32
  // TOCTOU-safe: safeOpenRead = realpath(abs) → cek jail+sensitif di dalam
32
33
  // root → open(preReal, O_NOFOLLOW). Bukan open(abs) yang bisa di-swap jadi
33
34
  // symlink luar di antara cek dan open — semua verifikasi ada di titik ini.
34
35
  let handle: Awaited<ReturnType<typeof safeOpenRead>>["handle"]
35
36
  try {
36
- ;({ handle } = await safeOpenRead(abs, root))
37
+ ;({ handle } = await safeOpenRead(abs, root, relaxed))
37
38
  } catch (e) {
38
39
  // ENOENT → pesan seragam; sisanya (jail/sensitif/ELOOP/raw IO) apa adanya
39
40
  const msg = (e as Error).message ?? ""
package/src/tools/task.ts CHANGED
@@ -316,6 +316,7 @@ export const delegateTaskTool: Tool = {
316
316
  "bash_output",
317
317
  "bash_kill",
318
318
  "git_commit",
319
+ "git_push",
319
320
  "submit_result",
320
321
  ].includes(t.name),
321
322
  )
package/src/tools/todo.ts CHANGED
@@ -416,7 +416,7 @@ export function renderTodos(todos: TodoItem[]): string {
416
416
  * kebenaran; kebijakan hanya berlaku di jalur tulis (`todo_write`) dan di
417
417
  * rekonsiliasi eksplisit (`reconcileCompletionEvidence`) yang menulis balik.
418
418
  */
419
- export async function loadTodos(sessionId: string, cwd = process.cwd()): Promise<TodoItem[]> {
419
+ export async function loadTodos(sessionId: string, cwd: string): Promise<TodoItem[]> {
420
420
  // N2: try the canonical name first, then the legacy name. A file written by an
421
421
  // older process only exists at the legacy path, so without this fallback a
422
422
  // workspace that was upgraded but never ran `todo_write` again would lose its
@@ -479,11 +479,7 @@ export async function reconcileCompletionEvidence(
479
479
  }
480
480
  }
481
481
 
482
- export async function saveTodos(
483
- sessionId: string,
484
- todos: TodoItem[],
485
- cwd = process.cwd(),
486
- ): Promise<void> {
482
+ export async function saveTodos(sessionId: string, todos: TodoItem[], cwd: string): Promise<void> {
487
483
  const p = todoPath(sessionId, cwd)
488
484
  await mkdir(resolve(cwd, ".minicode", "todos"), { recursive: true }).catch(() => {})
489
485
  await atomicWriteText(p, JSON.stringify({ sessionId, updatedAt: Date.now(), todos }, null, 2))
@@ -527,7 +523,7 @@ export function renderPlan(sessionId: string, todos: TodoItem[]): string {
527
523
  export async function savePlanSnapshot(
528
524
  sessionId: string,
529
525
  todos: TodoItem[],
530
- cwd = process.cwd(),
526
+ cwd: string,
531
527
  ): Promise<string> {
532
528
  const p = planPath(sessionId, cwd)
533
529
  await mkdir(resolve(cwd, ".minicode", "plans"), { recursive: true }).catch(() => {})
@@ -535,7 +531,7 @@ export async function savePlanSnapshot(
535
531
  return p
536
532
  }
537
533
 
538
- export async function loadPlan(sessionId: string, cwd = process.cwd()): Promise<string | null> {
534
+ export async function loadPlan(sessionId: string, cwd: string): Promise<string | null> {
539
535
  try {
540
536
  return await readFile(planPath(sessionId, cwd), "utf8")
541
537
  } catch {
@@ -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
  }