minicode-ai 0.22.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 (100) hide show
  1. package/README.md +2 -2
  2. package/cli/commands.ts +10 -0
  3. package/cli/index.ts +11 -0
  4. package/cli/setup.ts +64 -33
  5. package/cli/tui.ts +29 -3
  6. package/docs/README.md +2 -2
  7. package/docs/SUMMARY.md +10 -19
  8. package/docs/TERMINAL_CONTRACT.md +119 -32
  9. package/docs/architecture.md +1 -1
  10. package/docs/autonomous-scheduler.md +283 -2
  11. package/docs/choosing-mode.md +4 -4
  12. package/docs/concepts.md +39 -3
  13. package/docs/config.md +90 -4
  14. package/docs/environment.md +6 -0
  15. package/docs/getting-started.md +58 -2
  16. package/docs/repl.md +1 -1
  17. package/docs/security.md +49 -2
  18. package/docs/tools.md +2 -1
  19. package/package.json +2 -36
  20. package/src/app/provider-layer.ts +1 -1
  21. package/src/app/session.ts +129 -20
  22. package/src/config.ts +102 -2
  23. package/src/constants.ts +32 -4
  24. package/src/lib/safe-open.ts +21 -12
  25. package/src/memory/vector.ts +0 -31
  26. package/src/policy/compaction.ts +27 -0
  27. package/src/policy/context-budget.ts +132 -0
  28. package/src/policy/context-escalation.ts +140 -0
  29. package/src/policy/context-window.ts +14 -9
  30. package/src/policy/context.ts +10 -1
  31. package/src/policy/microcompact.ts +162 -0
  32. package/src/policy/no-progress.ts +1 -1
  33. package/src/policy/permission.ts +5 -0
  34. package/src/policy/scrub.ts +15 -2
  35. package/src/policy/tool-contract.ts +11 -9
  36. package/src/presentation/reducer.ts +1 -0
  37. package/src/providers/anthropic.ts +17 -3
  38. package/src/providers/detect.ts +155 -13
  39. package/src/providers/provision.ts +92 -1
  40. package/src/providers/responses.ts +13 -1
  41. package/src/session/persistence.ts +56 -0
  42. package/src/task/autonomous-policy.ts +7 -0
  43. package/src/task/graph-validate.ts +1 -1
  44. package/src/task/session-authority.ts +0 -5
  45. package/src/task/store.ts +0 -4
  46. package/src/tools/ask_user.ts +14 -1
  47. package/src/tools/bash.ts +57 -9
  48. package/src/tools/context.ts +10 -0
  49. package/src/tools/delete_file.ts +3 -2
  50. package/src/tools/edit.ts +5 -4
  51. package/src/tools/git.ts +70 -12
  52. package/src/tools/glob.ts +13 -5
  53. package/src/tools/grep.ts +26 -10
  54. package/src/tools/index.ts +3 -2
  55. package/src/tools/lsp.ts +15 -9
  56. package/src/tools/move_file.ts +4 -3
  57. package/src/tools/patch.ts +5 -4
  58. package/src/tools/read_file.ts +3 -2
  59. package/src/tools/read_image.ts +3 -2
  60. package/src/tools/task.ts +1 -0
  61. package/src/tools/todo.ts +4 -8
  62. package/src/tools/write_file.ts +4 -3
  63. package/src/ui/approval/prompt.ts +226 -77
  64. package/src/ui/assistant/simple.ts +1 -1
  65. package/src/ui/footer.ts +41 -29
  66. package/src/ui/i18n/en.ts +23 -4
  67. package/src/ui/i18n/id.ts +25 -4
  68. package/src/ui/input/input.ts +2 -2
  69. package/src/ui/render/activity-group.ts +1 -0
  70. package/src/ui/render/activity-panel.ts +21 -3
  71. package/src/ui/render/hint.ts +28 -0
  72. package/src/ui/render/ledger.ts +1 -9
  73. package/src/ui/render/logo.ts +86 -0
  74. package/src/ui/render/markdown-table.ts +0 -3
  75. package/src/ui/render/session-summary.ts +22 -1
  76. package/src/ui/render/table-grid.ts +0 -3
  77. package/src/ui/render/theme.ts +36 -5
  78. package/src/ui/runtime/screen.ts +11 -3
  79. package/src/ui/screens/dialog.ts +45 -81
  80. package/src/ui/screens/form.ts +29 -33
  81. package/src/ui/screens/lifecycle.ts +80 -0
  82. package/src/ui/screens/model-manager.ts +84 -91
  83. package/src/ui/screens/picker.ts +36 -33
  84. package/src/ui/screens/provider-manager.ts +50 -59
  85. package/src/ui/screens/watchdog.ts +27 -0
  86. package/src/ui/screens/wizard.ts +3 -20
  87. package/src/ui/tui/app.ts +97 -11
  88. package/src/ui/tui/transcript.ts +55 -16
  89. package/vendor/minicore/src/core/compact.ts +10 -0
  90. package/vendor/minicore/src/core/errors.ts +11 -1
  91. package/vendor/minicore/src/core/executor.ts +6 -1
  92. package/vendor/minicore/src/core/loop.ts +92 -2
  93. package/vendor/minicore/src/core/session.ts +8 -0
  94. package/vendor/minicore/src/providers/openai-compat.ts +15 -2
  95. package/docs/P14_OPEN_WORK.md +0 -290
  96. package/docs/config-providers.md +0 -87
  97. package/docs/glossary.md +0 -39
  98. package/docs/quickstart.md +0 -60
  99. package/docs/security-model.md +0 -96
  100. package/docs/terminal.md +0 -91
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
  }
@@ -615,7 +615,7 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
615
615
  const lines = renderActivityPanel(snap.activities, { maxRows: 10 })
616
616
  if (lines.length > 0) {
617
617
  wErr(c.muted(`${t("panel.header")}\n`))
618
- for (const line of lines) wErr(c.muted(`${line}\n`))
618
+ for (const line of lines) wErr(`${line}\n`)
619
619
  }
620
620
  }
621
621
  }
package/src/ui/footer.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  // dengan spasi dan warna, tanpa bullet separator. Work Mode ada di kiri;
9
9
  // Permission Mode berwarna cyan di sisi kanan, dekat penggunaan konteks.
10
10
  import { sanitizeAnsiLine } from "./render/sanitize.ts"
11
- import { c, glyphs, themeCapabilityKey } from "./render/theme.ts"
11
+ import { c, glyphs, supportsUtf8, themeCapabilityKey } from "./render/theme.ts"
12
12
  import { displayWidth, truncateToWidth } from "./render/width.ts"
13
13
 
14
14
  export type TimerHighlight = "seconds" | "minutes" | "hours"
@@ -36,6 +36,11 @@ export interface FooterStatus {
36
36
  * memetakan frame โ†’ glyph berwarna.
37
37
  */
38
38
  sparkFrame?: number
39
+ /** Jumlah job bash background hidup (dihitung di cli โ€” batas lapisan).
40
+ * >= 1 = badge `โ—ท N` berputar; 0/undefined = tanpa badge. */
41
+ backgroundJobs?: number
42
+ /** Frame animasi badge job (dinaikkan clock idle di app.ts, bukan turn). */
43
+ backgroundFrame?: number
39
44
  activity?: string
40
45
  timer?: string
41
46
  timerActive?: boolean
@@ -43,8 +48,6 @@ export interface FooterStatus {
43
48
  }
44
49
 
45
50
  /** Lebar tetap kolom agar perubahan WorkMode tidak menggeser model/CWD. */
46
- const WORK_MODE_WIDTH = 18
47
- const WORK_MODE_COMPACT_WIDTH = 13
48
51
  const WORK_MODE_VALUE_WIDTH = 7
49
52
 
50
53
  /** Buang prefix provider (`acme::deepseek-v4` โ†’ `deepseek-v4`). */
@@ -73,41 +76,30 @@ function workModeValue(workMode?: string): string {
73
76
 
74
77
  type ModeLabelStyle = "full" | "compact" | "value"
75
78
 
76
- /** Work Mode memakai warna semantik; label/nilai memakai title case. */
77
- export function paintWorkMode(workMode?: string, style: ModeLabelStyle = "full"): string {
79
+ /** Work Mode memakai warna semantik; nilai title case tanpa label (v0.24:
80
+ * footer lebih lega โ€” nilai saja, pembeda sumbu = warna). */
81
+ export function paintWorkMode(workMode?: string, _style: ModeLabelStyle = "full"): string {
78
82
  const value = workModeValue(workMode)
79
83
  const normalized = sanitizeAnsiLine(workMode || "DISCUSS").toUpperCase()
80
- const prefix = style === "full" ? "Work Mode: " : style === "compact" ? "Work: " : ""
81
- const width =
82
- style === "full"
83
- ? WORK_MODE_WIDTH
84
- : style === "compact"
85
- ? WORK_MODE_COMPACT_WIDTH
86
- : WORK_MODE_VALUE_WIDTH
87
- const labelWidth = displayWidth(sanitizeAnsiLine(`${prefix}${value}`))
84
+ const labelWidth = displayWidth(sanitizeAnsiLine(value))
88
85
  const colorValue = normalized === "DISCUSS" || normalized === "PLAN" ? c.warning : c.success
89
- return `${prefix ? c.gray(prefix) : ""}${colorValue(value)}${" ".repeat(
90
- Math.max(0, width - labelWidth),
91
- )}`
86
+ return `${colorValue(value)}${" ".repeat(Math.max(0, WORK_MODE_VALUE_WIDTH - labelWidth))}`
92
87
  }
93
88
 
94
- /** Permission Mode selalu cyan agar terpisah secara visual dari Work Mode.
95
- * `unrestricted` (full akses, /unrestric): label disembunyikan โ€” cukup gembok
96
- * terbuka ๐Ÿ”“ sebagai indikator satu-satunya (lihat paintBashStrict). */
97
- export function paintPermissionMode(mode: string, style: ModeLabelStyle = "full"): string {
89
+ /** Permission Mode selalu cyan agar terpisah dari Work Mode. `unrestricted`:
90
+ * label disembunyikan โ€” cukup titik terbuka โ—‹ (lihat paintBashStrict). */
91
+ export function paintPermissionMode(mode: string, _style: ModeLabelStyle = "full"): string {
98
92
  if (mode === "unrestricted") return ""
99
93
  const value = titleCaseMode(mode, "Auto")
100
- if (style === "value") return c.info(value)
101
- const prefix = style === "full" ? "Permission Mode: " : "Permission: "
102
- return `${c.gray(prefix)}${c.info(value)}`
94
+ return c.info(value)
103
95
  }
104
96
 
105
- /** Badge pembatas bash allow-list: gembok selalu tampil โ€” terang saat aktif,
106
- * redup saat nonaktif (lapis kapabilitas, terpisah dari mode persetujuan).
107
- * Saat `unrestricted` aktif, gembok jadi TERBUKA (๐Ÿ”“) โ€” satu-satunya penanda,
108
- * jadi dirender jelas (bukan redup). */
97
+ /** Badge pembatas bash allow-list: titik selalu tampil โ€” terang/kuning saat
98
+ * aktif, redup/abu saat nonaktif (lapis kapabilitas, terpisah dari mode
99
+ * persetujuan). Saat `unrestricted` aktif, titik jadi โ—‹ MERAH โ€” satu-satunya
100
+ * penanda mode itu, jadi dirender jelas (bukan redup). */
109
101
  export function paintBashStrict(strictBash?: boolean, unrestricted = false): string {
110
- if (unrestricted) return c.info(glyphs.unlock)
102
+ if (unrestricted) return c.red(glyphs.unlock)
111
103
  return strictBash ? c.yellow(glyphs.lock) : c.gray(glyphs.lock)
112
104
  }
113
105
 
@@ -118,6 +110,20 @@ function sparkGlyph(frame: number): string {
118
110
  return frame % 2 === 0 ? c.white(g) : c.gray(g)
119
111
  }
120
112
 
113
+ // Badge job background: jam flat berputar PELAN (fase beda dari spark),
114
+ // monokrom; fallback ASCII `[BG:n]`.
115
+ const WAITING_GLYPHS = ["โ—ท", "โ—ถ", "โ—ต", "โ—ด"] as const
116
+ const WAITING_ASCII = ["[BG:", "|", "/", "-"] as const
117
+
118
+ /** Frame -> glyph badge tunggu. `count` = jumlah job hidup; 0 = string kosong. */
119
+ export function waitingGlyph(count: number, frame = 0): string {
120
+ if (count <= 0) return ""
121
+ const n = Math.max(1, Math.floor(count))
122
+ if (!supportsUtf8()) return `${WAITING_ASCII[0]}${n}]`
123
+ const phase = Math.abs(Math.floor(frame)) % WAITING_GLYPHS.length
124
+ return `${WAITING_GLYPHS[phase]} ${n}`
125
+ }
126
+
121
127
  function paintTimer(text: string, active: boolean, highlight: TimerHighlight = "seconds"): string {
122
128
  if (!active) return c.gray(text)
123
129
  const parts = text.split(".")
@@ -168,6 +174,8 @@ function footerCacheKey(s: FooterStatus, cols: number): string {
168
174
  s.context ?? "",
169
175
  s.metrics ?? "",
170
176
  s.sparkFrame ?? 0,
177
+ s.backgroundJobs ?? 0,
178
+ s.backgroundFrame ?? 0,
171
179
  s.activity ?? "",
172
180
  s.timer ?? "",
173
181
  s.timerActive === true,
@@ -194,11 +202,15 @@ export function renderFooter(s: FooterStatus, columns: number): string[] {
194
202
 
195
203
  function buildFooterLine(s: FooterStatus, cols: number): string {
196
204
  const spark = sparkGlyph(s.sparkFrame ?? 0)
205
+ const badge =
206
+ s.backgroundJobs != null && s.backgroundJobs >= 1
207
+ ? `${c.muted(waitingGlyph(s.backgroundJobs, s.backgroundFrame ?? 0))} `
208
+ : ""
197
209
  const timerText = s.timer ? sanitizeAnsiLine(s.timer) : ""
198
210
  const timer = timerText
199
211
  ? `${paintTimer(timerText, s.timerActive === true, s.timerHighlight)} `
200
212
  : ""
201
- const lead = `${spark} ${timer}`
213
+ const lead = `${spark} ${badge}${timer}`
202
214
  const fieldGap = " "
203
215
  // Satu-baris: cwd/model bisa berisi newline (nama dir) โ€” sanitizeAnsiLine
204
216
  // agar \n tak memecah frame lengket ke scrollback (displayWidth menghitung
package/src/ui/i18n/en.ts CHANGED
@@ -25,6 +25,7 @@ export const en = {
25
25
  "appr.decAllow": "allow",
26
26
  "appr.decAlways": "always",
27
27
  "appr.decDeny": "deny",
28
+ "appr.keyHint": "โ†‘โ†“ move ยท Enter pick ยท Esc cancel",
28
29
  "appr.askTitle": "Agent asks",
29
30
  "appr.a11y": "[approval required: {name}]",
30
31
  "appr.answerPrompt": "Your answer (empty = cancel): ",
@@ -37,9 +38,15 @@ export const en = {
37
38
  "appr.tier.unknown": "unknown effect",
38
39
  "dlg.more": "โ€ฆ {n} more",
39
40
  "ts.compacted": "โ€ฆ compacted: {reason}",
41
+ "ts.compactedNoOp": "โ€ฆ compacted: nothing evictable ({reason}) โ€” context did not shrink",
42
+ "ts.compactedFixpoint": "โ€ฆ compaction stopped: target unreachable with only {kept} messages left",
43
+ "ts.compactedImpossible":
44
+ "โ€ฆ compaction impossible: fixed instructions + tool schemas ({fixed}) already exceed the {trigger} threshold",
45
+ "ts.compactedLlmFailed": "โ€ฆ LLM summary failed ({reason}), using mechanical summary",
46
+ "ts.contextWindowSource": "context {tokens} tokens ({source})",
40
47
  "ts.providerAttemptDiscarded": "provider attempt {attempt} failed; partial output was discarded",
41
48
  "ts.thinking": "โ€ฆ thinking",
42
- "ts.evictMarker": "โ€ฆ {n} early lines outside viewport โ€” full history in model",
49
+ "ts.evictMarker": "โ€ฆ {n} early lines outside viewport",
43
50
  "ts.statusRunning": "running",
44
51
  "ts.statusCompleted": "completed",
45
52
  "ts.statusFailed": "failed",
@@ -72,7 +79,7 @@ export const en = {
72
79
  "model.del": 'Delete model "{id}"?',
73
80
  "model.failOpen": "model manager failed to open: {msg}",
74
81
  "effort.title": "Thinking effort",
75
- "effort.saved": "Thinking: {effort} (next session)",
82
+ "effort.saved": "Thinking effort: {effort} (next session)",
76
83
  "prov.empty": "No providers",
77
84
  "prov.addTitle": "Add provider",
78
85
  "prov.customUrl": "Custom URL",
@@ -128,11 +135,20 @@ export const en = {
128
135
  "st.input": " Input: {v} (provider usage)",
129
136
  "st.output": " Output: {v} (provider usage)",
130
137
  "st.total": " Total: {v} (session cumulative)",
138
+ "st.cache": " Cache: {read} hit ยท {write} write (prompt cache)",
131
139
  "st.cost": " Cost: {v} (estimated from price table)",
132
140
  "st.budget": " Budget: {v}{extra}",
133
141
  "st.costUnknown": " (cost unknown โ€” model without pricing)",
134
142
  "help.head": "Commands:",
135
143
  "help.keysLine": "Mouse wheel/PgUp/PgDn scroll (Shift = half) ยท /help keys = all shortcuts",
144
+ "hint.move": "move",
145
+ "hint.select": "select",
146
+ "hint.close": "close",
147
+ "hint.filter": "filter",
148
+ "hint.delete": "delete",
149
+ "hint.edit": "edit",
150
+ "hint.add": "add",
151
+ "hint.effort": "effort",
136
152
  "help.cHead": "Commands:",
137
153
  "help.cKeys":
138
154
  "Keys: Tab work-mode ยท Shift+Tab permission ยท โ†‘โ†“ history ยท Mouse wheel/PgUp/PgDn scroll ยท Ctrl+R search ยท Ctrl+D exit",
@@ -239,8 +255,11 @@ export const en = {
239
255
  "tui.workModeLine": "work mode: {m}",
240
256
  "tui.workModeUsage": "usage: /work-mode <DISCUSS|PLAN|BUILD> โ€” current: {m}",
241
257
  "tui.workModeUnavailable": "work mode is not available in this session",
242
- "tui.unrestrictedOn": "๐Ÿ”“ unrestricted mode enabled - full access",
243
- "tui.unrestrictedOff": "๐Ÿ”“ unrestricted disabled โ€” permission mode restored to {m}",
258
+ "tui.unrestrictedOn": "unrestricted mode enabled - full access",
259
+ "tui.unrestrictedOff": "unrestricted disabled โ€” permission mode restored to {m}",
260
+ "tui.bgFinished": "background job {id} finished (exit {code})",
261
+ "tui.bgFinishedAuto":
262
+ "background job {id} finished with exit code {code}. Continue the work you were doing before without waiting for me: collect the job output with bash_output if relevant, verify the result, then finish the remaining tasks.",
244
263
  "tui.langLine": "lang: {v}",
245
264
  "tui.toolCall": "tool call: {v}",
246
265
  "tui.modelSet": "model: {v}",