minicode-ai 0.9.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +935 -0
- package/LICENSE +21 -0
- package/README.md +200 -0
- package/cli/args.ts +195 -0
- package/cli/auto-update.ts +108 -0
- package/cli/commands/auth.ts +166 -0
- package/cli/commands/config.ts +382 -0
- package/cli/commands/doctor.ts +128 -0
- package/cli/commands/exec.ts +179 -0
- package/cli/commands/mcp.ts +35 -0
- package/cli/commands/memory.ts +107 -0
- package/cli/commands/pricing.ts +100 -0
- package/cli/commands/providers.ts +162 -0
- package/cli/commands/sessions.ts +128 -0
- package/cli/commands/skills.ts +61 -0
- package/cli/commands/stats.ts +82 -0
- package/cli/commands.ts +317 -0
- package/cli/index.ts +539 -0
- package/cli/model-manager.ts +112 -0
- package/cli/provider-manager.ts +111 -0
- package/cli/repl.ts +734 -0
- package/cli/router.ts +124 -0
- package/cli/setup.ts +780 -0
- package/cli/wizard.ts +21 -0
- package/docs/ARCHITECTURE.html +1222 -0
- package/docs/README.md +109 -0
- package/docs/architecture.md +44 -0
- package/docs/changelog.md +3 -0
- package/package.json +91 -0
- package/src/agents/pool.ts +43 -0
- package/src/app/mentions.ts +50 -0
- package/src/app/provider-layer.ts +118 -0
- package/src/app/rag-layer.ts +105 -0
- package/src/app/session.ts +154 -0
- package/src/app/tool-layer.ts +56 -0
- package/src/config.ts +372 -0
- package/src/constants.ts +119 -0
- package/src/hooks/run.ts +89 -0
- package/src/lib/atomic-write.ts +88 -0
- package/src/lib/db-path.ts +36 -0
- package/src/lib/git-hardening.ts +91 -0
- package/src/lib/ignore.ts +58 -0
- package/src/lib/keystore.ts +202 -0
- package/src/lib/net.ts +70 -0
- package/src/lib/safe-open.ts +138 -0
- package/src/lib/session-id.ts +23 -0
- package/src/lib/trash.ts +38 -0
- package/src/lib/trusted-exec.ts +81 -0
- package/src/lsp/client.ts +395 -0
- package/src/mcp/client.ts +400 -0
- package/src/mcp/http-transport.ts +344 -0
- package/src/mcp/server.ts +538 -0
- package/src/mcp/transport.ts +150 -0
- package/src/memory/files.ts +159 -0
- package/src/memory/vector.ts +775 -0
- package/src/policy/allowlist.ts +67 -0
- package/src/policy/bash-guard.ts +465 -0
- package/src/policy/compaction.ts +271 -0
- package/src/policy/context.ts +161 -0
- package/src/policy/executor.ts +199 -0
- package/src/policy/jail.ts +127 -0
- package/src/policy/permission.ts +517 -0
- package/src/policy/pricing.ts +336 -0
- package/src/policy/ratelimit.ts +54 -0
- package/src/policy/sandbox-policy.ts +157 -0
- package/src/policy/scrub.ts +138 -0
- package/src/policy/update-check.ts +200 -0
- package/src/policy/usage.ts +292 -0
- package/src/policy/verifier.ts +181 -0
- package/src/providers/anthropic.ts +401 -0
- package/src/providers/auth-store.ts +139 -0
- package/src/providers/build.ts +136 -0
- package/src/providers/detect.ts +126 -0
- package/src/providers/effort.ts +165 -0
- package/src/providers/guards.ts +107 -0
- package/src/providers/oauth.ts +326 -0
- package/src/providers/presets.ts +122 -0
- package/src/providers/provision.ts +298 -0
- package/src/providers/responses.ts +371 -0
- package/src/providers/router.ts +247 -0
- package/src/repo/repomap.ts +470 -0
- package/src/sandbox/docker.ts +129 -0
- package/src/sandbox/os.ts +193 -0
- package/src/session/checkpoint.ts +543 -0
- package/src/session/journal.ts +1347 -0
- package/src/session/persistence.ts +446 -0
- package/src/session/shadow-git.ts +351 -0
- package/src/session/turn-marker.ts +118 -0
- package/src/skills/loader.ts +117 -0
- package/src/telemetry/trace.ts +283 -0
- package/src/tools/ask_user.ts +54 -0
- package/src/tools/bash.ts +400 -0
- package/src/tools/code_run.ts +96 -0
- package/src/tools/delete_file.ts +31 -0
- package/src/tools/edit.ts +204 -0
- package/src/tools/git.ts +301 -0
- package/src/tools/glob.ts +90 -0
- package/src/tools/grep.ts +281 -0
- package/src/tools/hashline.ts +66 -0
- package/src/tools/index.ts +103 -0
- package/src/tools/lsp.ts +346 -0
- package/src/tools/mcp_call.ts +163 -0
- package/src/tools/memory.ts +144 -0
- package/src/tools/move_file.ts +47 -0
- package/src/tools/patch.ts +86 -0
- package/src/tools/read_file.ts +130 -0
- package/src/tools/read_image.ts +80 -0
- package/src/tools/submit_result.ts +49 -0
- package/src/tools/task.ts +346 -0
- package/src/tools/todo.ts +201 -0
- package/src/tools/web_fetch.ts +161 -0
- package/src/tools/web_search.ts +156 -0
- package/src/tools/write_file.ts +42 -0
- package/src/ui/approval/prompt.ts +76 -0
- package/src/ui/assistant/simple.ts +568 -0
- package/src/ui/assistant/turn-status.ts +303 -0
- package/src/ui/contract.ts +55 -0
- package/src/ui/footer.ts +105 -0
- package/src/ui/input/input.ts +805 -0
- package/src/ui/input/prompt-engine.ts +606 -0
- package/src/ui/render/collapse.ts +84 -0
- package/src/ui/render/detail.ts +24 -0
- package/src/ui/render/diff.ts +181 -0
- package/src/ui/render/errors.ts +239 -0
- package/src/ui/render/format.ts +54 -0
- package/src/ui/render/highlight.ts +294 -0
- package/src/ui/render/markdown.ts +120 -0
- package/src/ui/render/money.ts +12 -0
- package/src/ui/render/reasoning.ts +20 -0
- package/src/ui/render/sanitize.ts +80 -0
- package/src/ui/render/table.ts +88 -0
- package/src/ui/render/theme.ts +339 -0
- package/src/ui/render/width.ts +256 -0
- package/src/ui/render/wrap.ts +120 -0
- package/src/ui/runtime/bus-debug.ts +83 -0
- package/src/ui/runtime/chrome.ts +301 -0
- package/src/ui/runtime/spinner.ts +77 -0
- package/src/ui/runtime/statusline.ts +227 -0
- package/src/ui/screens/model-manager.ts +434 -0
- package/src/ui/screens/overlay.ts +61 -0
- package/src/ui/screens/picker.ts +307 -0
- package/src/ui/screens/provider-manager.ts +450 -0
- package/src/ui/screens/wizard.ts +132 -0
- package/vendor/minicore/VENDOR.md +29 -0
- package/vendor/minicore/package.json +21 -0
- package/vendor/minicore/src/core/budget.ts +26 -0
- package/vendor/minicore/src/core/compact.ts +76 -0
- package/vendor/minicore/src/core/errors.ts +60 -0
- package/vendor/minicore/src/core/events.ts +74 -0
- package/vendor/minicore/src/core/executor.ts +139 -0
- package/vendor/minicore/src/core/history.ts +32 -0
- package/vendor/minicore/src/core/index.ts +42 -0
- package/vendor/minicore/src/core/loop.ts +344 -0
- package/vendor/minicore/src/core/permission.ts +24 -0
- package/vendor/minicore/src/core/provider.ts +39 -0
- package/vendor/minicore/src/core/recovery.ts +34 -0
- package/vendor/minicore/src/core/session.ts +327 -0
- package/vendor/minicore/src/core/snapshot.ts +142 -0
- package/vendor/minicore/src/core/tokens.ts +111 -0
- package/vendor/minicore/src/core/tool.ts +118 -0
- package/vendor/minicore/src/core/types.ts +50 -0
- package/vendor/minicore/src/providers/openai-compat.ts +366 -0
|
@@ -0,0 +1,805 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises"
|
|
2
|
+
import { homedir } from "node:os"
|
|
3
|
+
import { join } from "node:path"
|
|
4
|
+
import { createInterface } from "node:readline"
|
|
5
|
+
import { stripAnsi } from "../render/theme.ts"
|
|
6
|
+
import { displayWidth, escapeLength, truncateToWidth } from "../render/width.ts"
|
|
7
|
+
import { footerReserveRows } from "../runtime/chrome.ts"
|
|
8
|
+
import {
|
|
9
|
+
applyKey,
|
|
10
|
+
buildRenderSpec,
|
|
11
|
+
createDecoderState,
|
|
12
|
+
createState,
|
|
13
|
+
type DecoderState,
|
|
14
|
+
decodeKeysStream,
|
|
15
|
+
MAX_VISIBLE,
|
|
16
|
+
type PromptKey,
|
|
17
|
+
pointLength,
|
|
18
|
+
toGraphemes,
|
|
19
|
+
} from "./prompt-engine.ts"
|
|
20
|
+
|
|
21
|
+
const HISTORY_FILE = join(homedir(), ".minicode", "history")
|
|
22
|
+
const MAX_HISTORY = 1000
|
|
23
|
+
|
|
24
|
+
export async function loadHistory(file = HISTORY_FILE): Promise<string[]> {
|
|
25
|
+
try {
|
|
26
|
+
const content = await readFile(file, "utf8")
|
|
27
|
+
const out: string[] = []
|
|
28
|
+
for (const line of content.split("\n")) {
|
|
29
|
+
if (!line) continue
|
|
30
|
+
// Format baru: satu JSON string per baris (mendukung newline di entri
|
|
31
|
+
// multiline). Format lama: baris plain — tetap dibaca apa adanya.
|
|
32
|
+
if (line.startsWith('"')) {
|
|
33
|
+
try {
|
|
34
|
+
const v: unknown = JSON.parse(line)
|
|
35
|
+
if (typeof v === "string" && v) {
|
|
36
|
+
out.push(v)
|
|
37
|
+
continue
|
|
38
|
+
}
|
|
39
|
+
} catch {
|
|
40
|
+
// Bukan JSON valid — jatuh ke plain di bawah.
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const t = line.trim()
|
|
44
|
+
if (t) out.push(t)
|
|
45
|
+
}
|
|
46
|
+
return out.slice(-MAX_HISTORY)
|
|
47
|
+
} catch {
|
|
48
|
+
return []
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function appendHistory(entry: string, file = HISTORY_FILE): Promise<void> {
|
|
53
|
+
const clean = entry.trim()
|
|
54
|
+
if (!clean) return
|
|
55
|
+
try {
|
|
56
|
+
const existing = await loadHistory(file)
|
|
57
|
+
const filtered = existing.filter((e) => e !== clean)
|
|
58
|
+
filtered.push(clean)
|
|
59
|
+
const capped = filtered.slice(-MAX_HISTORY)
|
|
60
|
+
await mkdir(join(homedir(), ".minicode"), { recursive: true }).catch(() => {})
|
|
61
|
+
await writeFile(file, `${capped.map((e) => JSON.stringify(e)).join("\n")}\n`, "utf8")
|
|
62
|
+
} catch {}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ── ANSI support detection (sekali per process, cached) ──
|
|
66
|
+
// Semua console modern (Windows Terminal, VS Code, conhost Windows 10+,
|
|
67
|
+
// macOS/Linux TTY) memproses VT sequences. JANGAN menggantungkan dropdown
|
|
68
|
+
// pada probe DSR - conhost PS5.1 tidak selalu membalas \x1b[6n padahal VT
|
|
69
|
+
// bekerja (itulah kenapa dropdown 'hilang' kembali ke inline).
|
|
70
|
+
// Opt-out eksplisit: MINICODE_DROPDOWN=0 (console benar-benar legacy).
|
|
71
|
+
let ansiCache: Promise<boolean> | undefined
|
|
72
|
+
|
|
73
|
+
export async function detectAnsi(): Promise<boolean> {
|
|
74
|
+
if (process.env.MINICODE_DROPDOWN === "0") return false
|
|
75
|
+
if (!process.stdin.isTTY) return false
|
|
76
|
+
ansiCache ??= Promise.resolve(true)
|
|
77
|
+
return ansiCache
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface AskLineOptions {
|
|
81
|
+
/**
|
|
82
|
+
* Prefix prompt: string statis ATAU fungsi yang dipanggil setiap render.
|
|
83
|
+
* Bentuk fungsi membuat perubahan eksternal — mis. cycle mode REPL via
|
|
84
|
+
* Shift+Tab — langsung terlihat tanpa mengulang askLine.
|
|
85
|
+
*/
|
|
86
|
+
prompt?: string | (() => string)
|
|
87
|
+
hints?: (line: string) => string[]
|
|
88
|
+
groupOf?: (text: string) => string // opsional: label grup (commands/skills)
|
|
89
|
+
/**
|
|
90
|
+
* Riwayat eksplisit (menggantikan loadHistory dari file). Dipakai test agar
|
|
91
|
+
* hermetic tanpa menyentuh ~/.minicode/history milik mesin.
|
|
92
|
+
*/
|
|
93
|
+
history?: string[]
|
|
94
|
+
/**
|
|
95
|
+
* Batas idle tanpa keypress (ms); lewat = batal sendiri (null). Default
|
|
96
|
+
* 90.000 seperti picker/manager — raw-mode yang digenggam tanpa input
|
|
97
|
+
* rawan macet/segfault saat ConPTY mati. `0` = mati, dipakai prompt utama
|
|
98
|
+
* REPL: null di sana dihitung Ctrl+C (2x = exit), jadi auto-batal akan
|
|
99
|
+
* mengeluarkan user yang diam 3 menit.
|
|
100
|
+
*/
|
|
101
|
+
idleMs?: number
|
|
102
|
+
/**
|
|
103
|
+
* Dipanggil untuk setiap keypress SEBELUM logika bawaan (history, applyKey).
|
|
104
|
+
* Return truthy = key sudah ditangani pemanggil; askLine melewatkan handling
|
|
105
|
+
* default dan tetap me-render ulang. Dipakai REPL linier untuk Shift+Tab
|
|
106
|
+
* (cycle mode), Tab kosong (toggle plan/build), dan Ctrl+O (toggle compact).
|
|
107
|
+
* `line` = isi baris saat ini (untuk Tab kosong).
|
|
108
|
+
*/
|
|
109
|
+
onKey?: (key: PromptKey, line: string) => boolean
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Input interaktif satu baris + floating dropdown suggestions (dimmed).
|
|
113
|
+
// - ANSI (Windows Terminal/VS Code/macOS/Linux): dropdown baris di bawah prompt,
|
|
114
|
+
// seleksi › hijau, navigasi ↑/↓, Tab = complete tetap editing, Enter = complete + submit.
|
|
115
|
+
// - Legacy console (tanpa VT): fallback inline hints di baris yang sama.
|
|
116
|
+
// Semua logika transisi ada di prompt-engine.ts (pure) - di sini hanya IO + render.
|
|
117
|
+
export async function askLine(opts: AskLineOptions = {}): Promise<string | null> {
|
|
118
|
+
const { glyphs } = await import("../render/theme.ts")
|
|
119
|
+
// Diselesaikan per pemakaian (bukan sekali di awal) supaya prompt berbentuk
|
|
120
|
+
// fungsi — mis. prefix mode REPL yang berubah lewat Shift+Tab — tergambar baru.
|
|
121
|
+
const promptOf = (): string =>
|
|
122
|
+
typeof opts.prompt === "function" ? opts.prompt() : (opts.prompt ?? `${glyphs.prompt} `)
|
|
123
|
+
|
|
124
|
+
if (!process.stdin.isTTY) {
|
|
125
|
+
return new Promise((resolve) => {
|
|
126
|
+
let settled = false
|
|
127
|
+
const done = (v: string | null) => {
|
|
128
|
+
if (settled) return
|
|
129
|
+
settled = true
|
|
130
|
+
resolve(v)
|
|
131
|
+
}
|
|
132
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout })
|
|
133
|
+
// Pipe EOF tanpa newline: rl.question tak pernah memanggil balik —
|
|
134
|
+
// tanpa ini REPL gantung selamanya menunggu input yang tak datang.
|
|
135
|
+
rl.on("close", () => done(null))
|
|
136
|
+
rl.question(promptOf(), (a) => {
|
|
137
|
+
rl.close()
|
|
138
|
+
done(a.trim())
|
|
139
|
+
})
|
|
140
|
+
})
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const ansi = await detectAnsi()
|
|
144
|
+
const { c } = await import("../render/theme.ts")
|
|
145
|
+
const DIM = "\x1b[2m",
|
|
146
|
+
RESTORE = "\x1b[22m",
|
|
147
|
+
CLEAR = "\x1b[2K",
|
|
148
|
+
SYNC_START = "\x1b[?2026h",
|
|
149
|
+
SYNC_END = "\x1b[?2026l"
|
|
150
|
+
const hints = (l: string) => opts.hints?.(l) ?? []
|
|
151
|
+
|
|
152
|
+
// History navigation via Up/Down when menu not open (append mode)
|
|
153
|
+
const historyCache = opts.history ?? (await loadHistory())
|
|
154
|
+
let historyIdx = -1
|
|
155
|
+
let savedLine = ""
|
|
156
|
+
|
|
157
|
+
// Reverse-i-search ala readline (Ctrl+R): filter substring historyCache,
|
|
158
|
+
// tampil inline sebagai prompt pengganti — tanpa overlay/picker. Dulu
|
|
159
|
+
// Ctrl+R di-decode prompt-engine tapi tak dipakai ("bekas picker history
|
|
160
|
+
// fullscreen"). Hasil ditampilkan sebagai state.line sementara; draf asli
|
|
161
|
+
// kembali utuh bila pencarian dibatalkan (Esc/Ctrl+C).
|
|
162
|
+
let search: { query: string; idx: number; saved: string } | null = null
|
|
163
|
+
const searchMatches = (): string[] => {
|
|
164
|
+
if (!search) return []
|
|
165
|
+
const q = search.query.toLowerCase()
|
|
166
|
+
const out: string[] = []
|
|
167
|
+
for (let i = historyCache.length - 1; i >= 0; i--) {
|
|
168
|
+
const h = historyCache[i]!
|
|
169
|
+
if (!q || h.toLowerCase().includes(q)) out.push(h)
|
|
170
|
+
}
|
|
171
|
+
return out
|
|
172
|
+
}
|
|
173
|
+
const effPrompt = (): string => {
|
|
174
|
+
const base = promptOf()
|
|
175
|
+
if (!search) return base
|
|
176
|
+
const ok = searchMatches().length > 0
|
|
177
|
+
return `${ok ? "(reverse-i-search)" : "(failed reverse-i-search)"}\`${search.query}': `
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return new Promise((resolve, reject) => {
|
|
181
|
+
// Raw mode harus dikembalikan BAGI BAGIAN body yang error: bila renderAnsi
|
|
182
|
+
// melempar (mis. lebar terminal abnormal), terminal tidak boleh tertinggal
|
|
183
|
+
// dalam raw + listener lama menumpuk (dulu REPL catch{continue} lalu
|
|
184
|
+
// askLine berikutnya memasang listener kedua → MaxListenersExceeded).
|
|
185
|
+
const decoder: DecoderState = createDecoderState()
|
|
186
|
+
let done = false
|
|
187
|
+
let onData!: (chunk: Buffer) => void
|
|
188
|
+
let idleTimer: ReturnType<typeof setTimeout> | undefined
|
|
189
|
+
const clearIdle = () => {
|
|
190
|
+
if (idleTimer) clearTimeout(idleTimer)
|
|
191
|
+
idleTimer = undefined
|
|
192
|
+
}
|
|
193
|
+
const cleanup = () => {
|
|
194
|
+
if (done) return
|
|
195
|
+
done = true
|
|
196
|
+
clearIdle()
|
|
197
|
+
try {
|
|
198
|
+
process.stdin.setRawMode(false)
|
|
199
|
+
} catch {}
|
|
200
|
+
// SENGAJA tanpa pause(): stdin TTY mengalir seumur proses — siklus
|
|
201
|
+
// pause→resume berulang mematikan pengiriman 'data' selamanya di
|
|
202
|
+
// Bun Windows (list tampil tapi semua tombol mati, bahkan Ctrl+C).
|
|
203
|
+
// Kepemilikan = siapa yang memegang listener; melepas listener cukup.
|
|
204
|
+
// Pause hanya di teardown sesi (close()) agar one-shot bisa exit.
|
|
205
|
+
if (onData) process.stdin.removeListener("data", onData)
|
|
206
|
+
}
|
|
207
|
+
const finish = (v: string | null) => {
|
|
208
|
+
cleanup()
|
|
209
|
+
resolve(v)
|
|
210
|
+
}
|
|
211
|
+
const fail = (e: unknown) => {
|
|
212
|
+
cleanup()
|
|
213
|
+
reject(e)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
try {
|
|
217
|
+
process.stdin.setRawMode(true)
|
|
218
|
+
process.stdin.resume()
|
|
219
|
+
} catch (e) {
|
|
220
|
+
reject(e)
|
|
221
|
+
return
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
let state = createState()
|
|
225
|
+
let prevRows = 0 // jumlah baris dropdown yang tergambar (untuk clear)
|
|
226
|
+
let prevInputRows = 1 // jumlah baris input visual frame lalu (multiline)
|
|
227
|
+
let prevCursorRow = 0 // baris kursor frame lalu (0 = anchor)
|
|
228
|
+
let printedW = 0 // lebar teks yang ditulis (fallback inline)
|
|
229
|
+
|
|
230
|
+
const matches = (): string[] => hints(state.line)
|
|
231
|
+
|
|
232
|
+
// ── render ANSI: dropdown floating di bawah prompt ──
|
|
233
|
+
// Horizontal scroll mengikuti KURSOR, bukan hanya ujung baris: saat user
|
|
234
|
+
// menyunting di tengah prompt panjang, bagian yang sedang diedit harus
|
|
235
|
+
// terlihat. Semua ukuran dalam KOLOM terminal — CJK/emoji dua kolom.
|
|
236
|
+
// Sebelumnya memakai `.length` (karakter), sehingga baris CJK 53 kolom
|
|
237
|
+
// dianggap "muat" di terminal 30 kolom lalu membungkus sendiri.
|
|
238
|
+
// Ambil run SGR di awal baris (biasanya gaya prompt): potongan tengah
|
|
239
|
+
// memang plain (teks user), tapi jendela dari awal harus mempertahankan
|
|
240
|
+
// warna prompt. Tanpa ini stripAnsi membuat prompt pudar begitu baris
|
|
241
|
+
// lebih panjang dari terminal.
|
|
242
|
+
const takeLeadSgr = (s: string): string => {
|
|
243
|
+
let out = ""
|
|
244
|
+
let i = 0
|
|
245
|
+
while (s[i] === "\x1b") {
|
|
246
|
+
const len = escapeLength(s, i)
|
|
247
|
+
if (len <= 0) break
|
|
248
|
+
const seq = s.slice(i, i + len)
|
|
249
|
+
if (!seq.endsWith("m")) break
|
|
250
|
+
out += seq
|
|
251
|
+
i += len
|
|
252
|
+
}
|
|
253
|
+
return out
|
|
254
|
+
}
|
|
255
|
+
const scrollableLine = (line: string, cursorCol: number): { text: string; col: number } => {
|
|
256
|
+
const cols = process.stdout.columns || 80
|
|
257
|
+
if (displayWidth(line) <= cols - 1) return { text: line, col: cursorCol }
|
|
258
|
+
// Bekerja pada teks bersih: potongan tengah tidak bisa mempertahankan
|
|
259
|
+
// sekuens ANSI dengan benar tanpa melacak state warna.
|
|
260
|
+
const lead = takeLeadSgr(line)
|
|
261
|
+
const clean = stripAnsi(line)
|
|
262
|
+
const pts = toGraphemes(clean)
|
|
263
|
+
// Lebar kumulatif per posisi karakter.
|
|
264
|
+
const colAt: number[] = [0]
|
|
265
|
+
for (const ch of pts) colAt.push(colAt[colAt.length - 1]! + displayWidth(ch))
|
|
266
|
+
// Jendela scroll tidak boleh melebihi terminal sendiri: `max(8, cols-4)`
|
|
267
|
+
// di cols=5 menghasilkan keep 8 > cols → baris membungkus lagi.
|
|
268
|
+
const keep = Math.min(Math.max(8, cols - 4), Math.max(4, cols - 1))
|
|
269
|
+
// Cari indeks awal terkecil yang membuat kursor masuk jendela `keep`.
|
|
270
|
+
let start = 0
|
|
271
|
+
while (start < pts.length && cursorCol - colAt[start]! >= keep) start++
|
|
272
|
+
const ell = start > 0 ? "…" : ""
|
|
273
|
+
const body = truncateToWidth(pts.slice(start).join(""), keep - displayWidth(ell), "")
|
|
274
|
+
return {
|
|
275
|
+
// Awalan SGR (nol kolom) hanya relevan saat jendela dari awal —
|
|
276
|
+
// saat start>0 prompt sudah tergulir keluar dan body memang plain.
|
|
277
|
+
text: (start > 0 ? c.dim(ell) : lead) + body,
|
|
278
|
+
col: displayWidth(ell) + (cursorCol - colAt[start]!),
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Pindahkan kursor terminal ke kolom logis (1-based di ANSI). */
|
|
283
|
+
const placeCursor = (col: number) => {
|
|
284
|
+
process.stdout.write(`\x1b[${Math.max(1, col + 1)}G`)
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Render input multiline (Ctrl+J): tiap baris visual digambar di baris
|
|
288
|
+
// terminal sendiri; kursor diposisikan di baris+kolom logisnya. Baris
|
|
289
|
+
// non-kursor digambar dari awal (cukup, karena teks user plain); baris
|
|
290
|
+
// kursor lewat scrollableLine (jendela + warna prompt bila di baris 0).
|
|
291
|
+
const scrollableMultiline = (
|
|
292
|
+
prompt: string,
|
|
293
|
+
line: string,
|
|
294
|
+
cursor: number,
|
|
295
|
+
): { texts: string[]; cursorRow: number; cursorCol: number } => {
|
|
296
|
+
const segs = line.split("\n")
|
|
297
|
+
let acc = 0
|
|
298
|
+
let cursorRow = 0
|
|
299
|
+
let cursorInRow = 0
|
|
300
|
+
for (let r = 0; r < segs.length; r++) {
|
|
301
|
+
const glen = pointLength(segs[r]!)
|
|
302
|
+
if (cursor <= acc + glen) {
|
|
303
|
+
cursorRow = r
|
|
304
|
+
cursorInRow = cursor - acc
|
|
305
|
+
break
|
|
306
|
+
}
|
|
307
|
+
acc += glen + 1
|
|
308
|
+
if (r === segs.length - 1) {
|
|
309
|
+
cursorRow = r
|
|
310
|
+
cursorInRow = glen
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
const promptW = displayWidth(prompt)
|
|
314
|
+
const texts: string[] = []
|
|
315
|
+
let cursorCol = 0
|
|
316
|
+
for (let r = 0; r < segs.length; r++) {
|
|
317
|
+
const full = r === 0 ? prompt + segs[r]! : segs[r]!
|
|
318
|
+
if (r === cursorRow) {
|
|
319
|
+
const colW = displayWidth(toGraphemes(segs[r]!).slice(0, cursorInRow).join(""))
|
|
320
|
+
const v = scrollableLine(full, (r === 0 ? promptW : 0) + colW)
|
|
321
|
+
texts.push(v.text)
|
|
322
|
+
cursorCol = v.col
|
|
323
|
+
} else {
|
|
324
|
+
texts.push(scrollableLine(full, 0).text)
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
return { texts, cursorRow, cursorCol }
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const renderAnsi = () => {
|
|
331
|
+
// Satu frame = satu unit sinkron: terminal menahan tampil sampai SYNC_END,
|
|
332
|
+
// sehingga navigasi dropdown (atas/bawah) tak berkedip/robek. Terminal
|
|
333
|
+
// tanpa dukungan mengabaikan sekuens ini (sudah dipakai clearOverlay).
|
|
334
|
+
process.stdout.write(SYNC_START)
|
|
335
|
+
const rows = process.stdout.rows || 24
|
|
336
|
+
// Baris input visual ikut memakan tinggi: kurangi jatah dropdown agar
|
|
337
|
+
// blok input + dropdown tetap muat di terminal pendek.
|
|
338
|
+
const nInGuess = state.line.split("\n").length
|
|
339
|
+
// Sisakan ruang untuk prompt + 1 baris status + jatah footer lengket
|
|
340
|
+
// (chrome sticky = 3 baris dasar) agar dropdown tidak membungkus maupun
|
|
341
|
+
// menimpa footer di terminal pendek.
|
|
342
|
+
const maxVisible = Math.max(
|
|
343
|
+
1,
|
|
344
|
+
Math.min(MAX_VISIBLE, rows - 3 - footerReserveRows() - (nInGuess - 1)),
|
|
345
|
+
)
|
|
346
|
+
const spec = buildRenderSpec(state, effPrompt(), matches(), opts.groupOf, maxVisible)
|
|
347
|
+
const view = scrollableMultiline(effPrompt(), state.line, state.cursor)
|
|
348
|
+
const nIn = view.texts.length
|
|
349
|
+
const maxRows = Math.max(prevRows, spec.totalRows)
|
|
350
|
+
const maxIn = Math.max(prevInputRows, nIn)
|
|
351
|
+
// Kembali ke anchor: render lalu menaruh kursor di baris R.
|
|
352
|
+
if (prevCursorRow > 0) process.stdout.write(`\x1b[${prevCursorRow}A`)
|
|
353
|
+
// Blok input (anchor + lanjutan), bersihkan sisa frame lama yang susut.
|
|
354
|
+
process.stdout.write(`\r${CLEAR}${view.texts[0]}`)
|
|
355
|
+
for (let k = 1; k < maxIn; k++)
|
|
356
|
+
process.stdout.write(`\r\n${CLEAR}${k < nIn ? view.texts[k]! : ""}`)
|
|
357
|
+
// Turun ke bawah-blok-input aktual (bukan sisa frame lama yang susut).
|
|
358
|
+
const gapUp = maxIn - nIn
|
|
359
|
+
if (gapUp > 0) process.stdout.write(`\x1b[${gapUp}A`)
|
|
360
|
+
// Blok dropdown di bawah input, bersihkan sisa frame lama.
|
|
361
|
+
for (let k = 0; k < maxRows; k++) process.stdout.write(`\r\n${CLEAR}`)
|
|
362
|
+
if (maxRows > 0) process.stdout.write(`\x1b[${maxRows}A`)
|
|
363
|
+
|
|
364
|
+
if (spec.rows.length > 0) {
|
|
365
|
+
const cols = process.stdout.columns || 80
|
|
366
|
+
process.stdout.write("\r\n")
|
|
367
|
+
for (let i = 0; i < spec.rows.length; i++) {
|
|
368
|
+
const row = spec.rows[i]!
|
|
369
|
+
if (row.kind === "header") {
|
|
370
|
+
process.stdout.write(
|
|
371
|
+
CLEAR + c.accent(c.bold(truncateToWidth(row.text, cols))) + RESTORE,
|
|
372
|
+
)
|
|
373
|
+
} else {
|
|
374
|
+
const isPicked = row.picked
|
|
375
|
+
const prefix = isPicked ? ` ${c.accent("›")} ` : " "
|
|
376
|
+
// Item dropdown juga dipotong ke lebar terminal.
|
|
377
|
+
const label = truncateToWidth(row.text, Math.max(4, cols - 4))
|
|
378
|
+
const text = isPicked ? c.accent(c.bold(label)) : label
|
|
379
|
+
if (isPicked) {
|
|
380
|
+
process.stdout.write(CLEAR + prefix + text + RESTORE)
|
|
381
|
+
} else {
|
|
382
|
+
process.stdout.write(CLEAR + DIM + prefix + text + RESTORE)
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
if (i < spec.rows.length - 1) process.stdout.write("\r\n")
|
|
386
|
+
}
|
|
387
|
+
if (spec.moreCount > 0) {
|
|
388
|
+
process.stdout.write("\r\n")
|
|
389
|
+
process.stdout.write(`${CLEAR + DIM} … ${spec.moreCount} more${RESTORE}`)
|
|
390
|
+
}
|
|
391
|
+
// Kembali ke anchor (melewati dropdown + baris input lanjutan).
|
|
392
|
+
process.stdout.write(`\x1b[${spec.totalRows + (nIn - 1)}A`)
|
|
393
|
+
// Gambar ulang blok input (pastikan bersih setelah naik).
|
|
394
|
+
process.stdout.write(`\r${CLEAR}${view.texts[0]}`)
|
|
395
|
+
for (let k = 1; k < nIn; k++) process.stdout.write(`\r\n${CLEAR}${view.texts[k]!}`)
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// Naik dari baris input terakhir ke baris kursor, lalu ke kolom logis.
|
|
399
|
+
const upToCursor = nIn - 1 - view.cursorRow
|
|
400
|
+
if (upToCursor > 0) process.stdout.write(`\x1b[${upToCursor}A`)
|
|
401
|
+
// Kursor sungguhan di posisi logis — bukan selalu di ujung baris.
|
|
402
|
+
placeCursor(view.cursorCol)
|
|
403
|
+
process.stdout.write(SYNC_END)
|
|
404
|
+
prevRows = spec.totalRows
|
|
405
|
+
prevInputRows = nIn
|
|
406
|
+
prevCursorRow = view.cursorRow
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// ── render inline (legacy console, tanpa ANSI) ──
|
|
410
|
+
const renderInline = () => {
|
|
411
|
+
const hs = matches()
|
|
412
|
+
const prompt = effPrompt()
|
|
413
|
+
// Konsol legacy tak menghitung baris: gepengkan multiline untuk display
|
|
414
|
+
// (nilai submit tetap utuh ber-newline).
|
|
415
|
+
const flat =
|
|
416
|
+
state.line.indexOf("\n") === -1
|
|
417
|
+
? state.line
|
|
418
|
+
: `${state.line.replace(/\n/g, " ")} (+${state.line.split("\n").length - 1} lines)`
|
|
419
|
+
const content = hs.length
|
|
420
|
+
? `${prompt}${flat} ${hs.slice(0, 5).join(" ")}`
|
|
421
|
+
: `${prompt}${flat}`
|
|
422
|
+
// Fallback non-ANSI tetap harus mengukur lebar per KOLOM terminal.
|
|
423
|
+
// Jika memakai .length, CJK/emoji meninggalkan jejak saat baris memendek.
|
|
424
|
+
const contentW = displayWidth(content)
|
|
425
|
+
const pad = printedW - contentW
|
|
426
|
+
process.stdout.write(`\r${" ".repeat(printedW)}\r${content}${pad > 0 ? " ".repeat(pad) : ""}`)
|
|
427
|
+
printedW = contentW
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const render = ansi ? renderAnsi : renderInline
|
|
431
|
+
|
|
432
|
+
// Hapus overlay dropdown sepenuhnya (delete lines, bukan clear) supaya
|
|
433
|
+
// tidak menyisakan gap kosong. Cursor kembali ke baris anchor.
|
|
434
|
+
const clearOverlay = () => {
|
|
435
|
+
if (prevRows <= 0) return
|
|
436
|
+
process.stdout.write(SYNC_START)
|
|
437
|
+
// turun ke baris overlay pertama, hapus satu per satu (baris bawah
|
|
438
|
+
// shift-up otomatis tiap \x1b[1M), lalu naik balik ke anchor.
|
|
439
|
+
process.stdout.write("\r\n")
|
|
440
|
+
for (let k = 0; k < prevRows; k++) {
|
|
441
|
+
process.stdout.write(CLEAR)
|
|
442
|
+
process.stdout.write("\x1b[1M")
|
|
443
|
+
}
|
|
444
|
+
process.stdout.write("\x1b[1A")
|
|
445
|
+
process.stdout.write(SYNC_END)
|
|
446
|
+
prevRows = 0
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// Tampilkan cocokkan pencarian sebagai baris (sementara; draf asli di
|
|
450
|
+
// search.saved dan kembali utuh bila dibatalkan).
|
|
451
|
+
const searchShow = () => {
|
|
452
|
+
const ms = searchMatches()
|
|
453
|
+
const m = ms.length ? ms[Math.min(search!.idx, ms.length - 1)]! : ""
|
|
454
|
+
state = { ...state, line: m, cursor: pointLength(m), sel: -1, menuOpen: false }
|
|
455
|
+
render()
|
|
456
|
+
}
|
|
457
|
+
// Echo baris final ke scrollback lalu selesaikan askLine. Multiline:
|
|
458
|
+
// kursor bisa di baris R>0 — naik ke anchor dulu agar clearOverlay (yang
|
|
459
|
+
// mengasumsikan kursor di anchor) dan echo menimpa blok input tepat.
|
|
460
|
+
const doSubmit = (cancelled: boolean) => {
|
|
461
|
+
const v = cancelled ? null : state.line.trim()
|
|
462
|
+
if (ansi) {
|
|
463
|
+
const segs = state.line.split("\n")
|
|
464
|
+
let crow = 0
|
|
465
|
+
let acc = 0
|
|
466
|
+
for (let r = 0; r < segs.length; r++) {
|
|
467
|
+
const glen = pointLength(segs[r]!)
|
|
468
|
+
if (state.cursor <= acc + glen) {
|
|
469
|
+
crow = r
|
|
470
|
+
break
|
|
471
|
+
}
|
|
472
|
+
acc += glen + 1
|
|
473
|
+
crow = r
|
|
474
|
+
}
|
|
475
|
+
if (crow > 0) process.stdout.write(`\x1b[${crow}A`)
|
|
476
|
+
clearOverlay()
|
|
477
|
+
const cols = process.stdout.columns || 80
|
|
478
|
+
const prompt = effPrompt()
|
|
479
|
+
// Baris pertama lewat scrollableLine (jendela horizontal, sama
|
|
480
|
+
// seperti dulu); baris lanjutan cukup dipotong ke lebar terminal.
|
|
481
|
+
const first = scrollableLine(`${prompt}${segs[0]!}`, 0).text
|
|
482
|
+
process.stdout.write(`\r${CLEAR}${first}\r\n`)
|
|
483
|
+
for (let k = 1; k < segs.length; k++)
|
|
484
|
+
process.stdout.write(`${CLEAR + truncateToWidth(segs[k]!, cols)}\r\n`)
|
|
485
|
+
} else {
|
|
486
|
+
process.stdout.write(`\r${CLEAR}${effPrompt()}${state.line}\r\n`)
|
|
487
|
+
}
|
|
488
|
+
finish(v)
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
// Idle-timeout: nol keypress selama idleMs = batal sendiri via jalur
|
|
492
|
+
// submit normal (draf ikut ter-echo ke scrollback, tak hilang bisu).
|
|
493
|
+
// Reset di tiap chunk — mengetik/menahan tombol apa pun memperpanjang.
|
|
494
|
+
const resetIdle = () => {
|
|
495
|
+
const ms = opts.idleMs ?? 90_000
|
|
496
|
+
if (done || !ms) return
|
|
497
|
+
clearIdle()
|
|
498
|
+
idleTimer = setTimeout(() => {
|
|
499
|
+
doSubmit(true)
|
|
500
|
+
}, ms)
|
|
501
|
+
// Jangan tahan process hidup hanya karena timer ini.
|
|
502
|
+
try {
|
|
503
|
+
;(idleTimer as unknown as { unref?: () => void }).unref?.()
|
|
504
|
+
} catch {}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
onData = (chunk: Buffer) => {
|
|
508
|
+
resetIdle()
|
|
509
|
+
const keys = decodeKeysStream(chunk, decoder)
|
|
510
|
+
for (const d of keys) {
|
|
511
|
+
// Hook pemanggil: key yang ditangani sendiri (return truthy) dilewati
|
|
512
|
+
// dari logika bawaan; render() di akhir chunk tetap menggambar efeknya.
|
|
513
|
+
// SAAT SEARCH AKTIF hook DILEWATI: tanpa ini Tab/Shift+Tab/Ctrl+O yang
|
|
514
|
+
// dicegat REPL (cycle mode/compact) membajak keypad pencarian — user
|
|
515
|
+
// yang search-nya gagal lalu menekan Tab malah mengganti mode.
|
|
516
|
+
if (!search && opts.onKey?.(d.key, state.line)) continue
|
|
517
|
+
// Reverse-i-search: Ctrl+R masuk/putar, sisanya dikelola di bawah.
|
|
518
|
+
if (d.key.type === "ctrl-r") {
|
|
519
|
+
if (historyCache.length === 0) continue
|
|
520
|
+
if (!search) {
|
|
521
|
+
search = { query: "", idx: 0, saved: state.line }
|
|
522
|
+
historyIdx = -1
|
|
523
|
+
searchShow()
|
|
524
|
+
} else {
|
|
525
|
+
const ms = searchMatches()
|
|
526
|
+
if (ms.length) {
|
|
527
|
+
search.idx = (search.idx + 1) % ms.length
|
|
528
|
+
searchShow()
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
continue
|
|
532
|
+
}
|
|
533
|
+
if (search) {
|
|
534
|
+
if (d.key.type === "enter") {
|
|
535
|
+
// Bash: Enter mengeksekusi baris hasil pencarian.
|
|
536
|
+
search = null
|
|
537
|
+
historyIdx = -1
|
|
538
|
+
savedLine = ""
|
|
539
|
+
doSubmit(false)
|
|
540
|
+
return
|
|
541
|
+
}
|
|
542
|
+
if (d.key.type === "esc" || d.key.type === "ctrl-c" || d.key.type === "ctrl-d") {
|
|
543
|
+
// Batal cari saja (bukan batal baris): kembalikan draf. Ctrl+D ikut
|
|
544
|
+
// agar konsisten dengan Ctrl+C — tanpa ini Ctrl+D saat search
|
|
545
|
+
// membuang draf (beda dari perilaku readline).
|
|
546
|
+
const back = search.saved
|
|
547
|
+
search = null
|
|
548
|
+
state = { ...state, line: back, cursor: pointLength(back), sel: -1, menuOpen: false }
|
|
549
|
+
historyIdx = -1
|
|
550
|
+
render()
|
|
551
|
+
continue
|
|
552
|
+
}
|
|
553
|
+
if (d.key.type === "char") {
|
|
554
|
+
search.query += d.key.ch
|
|
555
|
+
search.idx = 0
|
|
556
|
+
searchShow()
|
|
557
|
+
continue
|
|
558
|
+
}
|
|
559
|
+
if (d.key.type === "ctrl-u") {
|
|
560
|
+
// Hapus query — jangan auto-accept hasil lalu clear baris, karena
|
|
561
|
+
// itu membuang draf asli (search.saved) yang seharusnya pulang.
|
|
562
|
+
search.query = ""
|
|
563
|
+
search.idx = 0
|
|
564
|
+
searchShow()
|
|
565
|
+
continue
|
|
566
|
+
}
|
|
567
|
+
if (d.key.type === "backspace") {
|
|
568
|
+
const q = toGraphemes(search.query)
|
|
569
|
+
q.pop()
|
|
570
|
+
search.query = q.join("")
|
|
571
|
+
search.idx = 0
|
|
572
|
+
searchShow()
|
|
573
|
+
continue
|
|
574
|
+
}
|
|
575
|
+
if (d.key.type === "up") {
|
|
576
|
+
const ms = searchMatches()
|
|
577
|
+
if (search.idx < ms.length - 1) {
|
|
578
|
+
search.idx++
|
|
579
|
+
searchShow()
|
|
580
|
+
}
|
|
581
|
+
continue
|
|
582
|
+
}
|
|
583
|
+
if (d.key.type === "down") {
|
|
584
|
+
if (search.idx > 0) {
|
|
585
|
+
search.idx--
|
|
586
|
+
searchShow()
|
|
587
|
+
}
|
|
588
|
+
continue
|
|
589
|
+
}
|
|
590
|
+
// Tombol lain: terima hasil ke baris lalu proses normal di bawah.
|
|
591
|
+
const ms = searchMatches()
|
|
592
|
+
const m = ms.length ? ms[Math.min(search.idx, ms.length - 1)]! : search.saved
|
|
593
|
+
search = null
|
|
594
|
+
state = { ...state, line: m, cursor: pointLength(m), sel: -1, menuOpen: false }
|
|
595
|
+
historyIdx = -1
|
|
596
|
+
}
|
|
597
|
+
// Esc pada baris KOSONG tanpa menu = batal prompt (null) — dipakai
|
|
598
|
+
// dialog (Provider >, Base URL >, dsb.) agar Esc konsisten dengan
|
|
599
|
+
// picker/manager. Esc pada baris berisi TIDAK batal: draf tidak boleh
|
|
600
|
+
// hilang karena salah tekan (menu yang terbuka tetap ditutup applyKey).
|
|
601
|
+
if (!search && d.key.type === "esc" && !state.menuOpen && state.line === "") {
|
|
602
|
+
doSubmit(true)
|
|
603
|
+
return
|
|
604
|
+
}
|
|
605
|
+
// Navigasi history saat dropdown tertutup.
|
|
606
|
+
//
|
|
607
|
+
// Sebelumnya entri history DIGABUNGKAN ke teks yang sedang ditulis
|
|
608
|
+
// ("halo" + panah atas -> "halo <entri>"), yang menghancurkan prompt
|
|
609
|
+
// yang sedang disusun. Semua shell mengganti baris; kita ikut. Baris
|
|
610
|
+
// yang sedang ditulis disimpan dan kembali saat user turun melewati
|
|
611
|
+
// entri terbaru.
|
|
612
|
+
if ((d.key.type === "up" || d.key.type === "down") && !state.menuOpen) {
|
|
613
|
+
const setLine = (line: string) => {
|
|
614
|
+
state = { ...state, line, cursor: pointLength(line), sel: -1, menuOpen: false }
|
|
615
|
+
render()
|
|
616
|
+
}
|
|
617
|
+
if (d.key.type === "up") {
|
|
618
|
+
if (historyIdx < historyCache.length - 1) {
|
|
619
|
+
if (historyIdx === -1) savedLine = state.line
|
|
620
|
+
historyIdx++
|
|
621
|
+
setLine(historyCache[historyCache.length - 1 - historyIdx] ?? "")
|
|
622
|
+
}
|
|
623
|
+
} else if (historyIdx > 0) {
|
|
624
|
+
historyIdx--
|
|
625
|
+
setLine(historyCache[historyCache.length - 1 - historyIdx] ?? "")
|
|
626
|
+
} else if (historyIdx === 0) {
|
|
627
|
+
historyIdx = -1
|
|
628
|
+
setLine(savedLine)
|
|
629
|
+
}
|
|
630
|
+
continue
|
|
631
|
+
}
|
|
632
|
+
// Mengetik/menghapus/memindah kursor setelah menjelajah history
|
|
633
|
+
// memutus mode history — semua shell begitu (setiap edit = edit baris
|
|
634
|
+
// baru, bukan lanjut navigasi). Sebelumnya ctrl-w/ctrl-u/tab/panah
|
|
635
|
+
// tidak me-reset historyIdx, jadi setelah recall history lalu Ctrl+W
|
|
636
|
+
// panah bawah tetap kembali ke entri history lain.
|
|
637
|
+
if (
|
|
638
|
+
d.key.type === "char" ||
|
|
639
|
+
d.key.type === "ctrl-j" ||
|
|
640
|
+
d.key.type === "backspace" ||
|
|
641
|
+
d.key.type === "delete" ||
|
|
642
|
+
d.key.type === "ctrl-w" ||
|
|
643
|
+
d.key.type === "ctrl-u" ||
|
|
644
|
+
d.key.type === "tab" ||
|
|
645
|
+
d.key.type === "left" ||
|
|
646
|
+
d.key.type === "right"
|
|
647
|
+
) {
|
|
648
|
+
historyIdx = -1
|
|
649
|
+
savedLine = ""
|
|
650
|
+
}
|
|
651
|
+
const r = applyKey(state, d.key, hints)
|
|
652
|
+
state = r.state
|
|
653
|
+
if (r.action === "submit" || r.action === "cancel") {
|
|
654
|
+
// Empty Enter = "" (not null) - REPL continues; null = cancel (break)
|
|
655
|
+
doSubmit(r.action === "cancel")
|
|
656
|
+
return
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
// Satu render per chunk - paste 50+ char tidak meng-redraw 50 kali.
|
|
660
|
+
try {
|
|
661
|
+
render()
|
|
662
|
+
} catch (e) {
|
|
663
|
+
fail(e)
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
process.stdin.on("data", onData)
|
|
668
|
+
resetIdle()
|
|
669
|
+
try {
|
|
670
|
+
render()
|
|
671
|
+
} catch (e) {
|
|
672
|
+
fail(e)
|
|
673
|
+
}
|
|
674
|
+
})
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/**
|
|
678
|
+
* Prompt rahasia (tanpa echo). Return null = DIBATALKAN user (Esc/Ctrl+C/
|
|
679
|
+
* Ctrl+D) — beda dari submit kosong (""), supaya pemanggil bisa membedakan
|
|
680
|
+
* "batal" dari "Enter tanpa isi" (yang dulu sama-sama jatuh ke pesan
|
|
681
|
+
* "required", membuat batal dikira error).
|
|
682
|
+
*/
|
|
683
|
+
export async function askSecret(
|
|
684
|
+
promptText: string,
|
|
685
|
+
opts: { idleMs?: number } = {},
|
|
686
|
+
): Promise<string | null> {
|
|
687
|
+
if (!process.stdin.isTTY) return null
|
|
688
|
+
|
|
689
|
+
return new Promise((resolve, reject) => {
|
|
690
|
+
const decoder: DecoderState = createDecoderState()
|
|
691
|
+
let done = false
|
|
692
|
+
let onData!: (chunk: Buffer) => void
|
|
693
|
+
let idleTimer: ReturnType<typeof setTimeout> | undefined
|
|
694
|
+
const clearIdle = () => {
|
|
695
|
+
if (idleTimer) clearTimeout(idleTimer)
|
|
696
|
+
idleTimer = undefined
|
|
697
|
+
}
|
|
698
|
+
const cleanup = () => {
|
|
699
|
+
if (done) return
|
|
700
|
+
done = true
|
|
701
|
+
clearIdle()
|
|
702
|
+
try {
|
|
703
|
+
process.stdin.setRawMode(false)
|
|
704
|
+
} catch {}
|
|
705
|
+
// Tanpa pause — lihat cleanup askLine (stdin mengalir seumur proses).
|
|
706
|
+
if (onData) process.stdin.removeListener("data", onData)
|
|
707
|
+
}
|
|
708
|
+
const finish = (value: string | null) => {
|
|
709
|
+
cleanup()
|
|
710
|
+
process.stdout.write("\n")
|
|
711
|
+
resolve(value)
|
|
712
|
+
}
|
|
713
|
+
const fail = (e: unknown) => {
|
|
714
|
+
cleanup()
|
|
715
|
+
reject(e)
|
|
716
|
+
}
|
|
717
|
+
// Sama seperti askLine: idle tanpa keypress = batal (null), bukan
|
|
718
|
+
// gantung dengan raw-mode digenggam.
|
|
719
|
+
const resetIdle = () => {
|
|
720
|
+
const ms = opts.idleMs ?? 90_000
|
|
721
|
+
if (done || !ms) return
|
|
722
|
+
clearIdle()
|
|
723
|
+
idleTimer = setTimeout(() => {
|
|
724
|
+
finish(null)
|
|
725
|
+
}, ms)
|
|
726
|
+
try {
|
|
727
|
+
;(idleTimer as unknown as { unref?: () => void }).unref?.()
|
|
728
|
+
} catch {}
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
process.stdout.write(promptText)
|
|
732
|
+
let secret = ""
|
|
733
|
+
|
|
734
|
+
onData = (chunk: Buffer) => {
|
|
735
|
+
resetIdle()
|
|
736
|
+
try {
|
|
737
|
+
for (const d of decodeKeysStream(chunk, decoder)) {
|
|
738
|
+
const k = d.key
|
|
739
|
+
if (k.type === "enter") {
|
|
740
|
+
finish(secret.trim())
|
|
741
|
+
return
|
|
742
|
+
} else if (k.type === "esc" || k.type === "ctrl-c" || k.type === "ctrl-d") {
|
|
743
|
+
// Esc/Ctrl+C/Ctrl+D = BATALKAN PROMPT, bukan matikan proses.
|
|
744
|
+
//
|
|
745
|
+
// Dulu di sini `process.exit(130)`. Di raw mode Ctrl+C tidak
|
|
746
|
+
// menghasilkan SIGINT, jadi itu emulasi manual — tapi `askSecret`
|
|
747
|
+
// dipanggil dari `runProviderManager`, sebuah dialog di dalam REPL
|
|
748
|
+
// yang hidup. Menekan Ctrl+C saat salah ketik API key mematikan
|
|
749
|
+
// seluruh sesi beserta riwayatnya, bukan menutup dialognya.
|
|
750
|
+
finish(null)
|
|
751
|
+
return
|
|
752
|
+
} else if (k.type === "backspace") {
|
|
753
|
+
// Hapus satu GRAPHEME (bukan code point/UTF-16 unit): emoji ZWJ
|
|
754
|
+
// dan flag tidak meninggalkan setengah.
|
|
755
|
+
const graphemes = toGraphemes(secret)
|
|
756
|
+
if (graphemes.length > 0) {
|
|
757
|
+
graphemes.pop()
|
|
758
|
+
secret = graphemes.join("")
|
|
759
|
+
process.stdout.write("\b \b")
|
|
760
|
+
}
|
|
761
|
+
} else if (k.type === "ctrl-u") {
|
|
762
|
+
// Hapus SEMUA (mis. salah paste API key) — tanpa ini satu-satunya
|
|
763
|
+
// jalan adalah Backspace satu-satu.
|
|
764
|
+
const n = toGraphemes(secret).length
|
|
765
|
+
secret = ""
|
|
766
|
+
if (n > 0) process.stdout.write(`${"\b \b".repeat(n)}`)
|
|
767
|
+
} else if (k.type === "ctrl-w") {
|
|
768
|
+
// Hapus satu "kata" (sampai spasi terakhir) — sama dengan prompt
|
|
769
|
+
// teks biasa.
|
|
770
|
+
const graphemes = toGraphemes(secret)
|
|
771
|
+
const cut = secret.replace(/\S+\s*$/, "")
|
|
772
|
+
const removed = graphemes.length - toGraphemes(cut).length
|
|
773
|
+
if (removed > 0) {
|
|
774
|
+
secret = cut
|
|
775
|
+
process.stdout.write(`${"\b \b".repeat(removed)}`)
|
|
776
|
+
}
|
|
777
|
+
} else if (k.type === "char") {
|
|
778
|
+
// Sekuens kontrol dari paste dibuang — secret tidak boleh
|
|
779
|
+
// mengandung newline/C0 (Enter adalah satu-satunya terminasi).
|
|
780
|
+
const clean = k.ch
|
|
781
|
+
.replace(/\r\n|\r|\n|\t/g, "")
|
|
782
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: membuang kontrol dari paste
|
|
783
|
+
.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "")
|
|
784
|
+
if (clean) {
|
|
785
|
+
secret += clean
|
|
786
|
+
process.stdout.write("*".repeat(toGraphemes(clean).length))
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
} catch (e) {
|
|
791
|
+
fail(e)
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
process.stdin.resume()
|
|
796
|
+
try {
|
|
797
|
+
process.stdin.setRawMode(true)
|
|
798
|
+
} catch (e) {
|
|
799
|
+
fail(e)
|
|
800
|
+
return
|
|
801
|
+
}
|
|
802
|
+
process.stdin.on("data", onData)
|
|
803
|
+
resetIdle()
|
|
804
|
+
})
|
|
805
|
+
}
|