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
package/cli/repl.ts
ADDED
|
@@ -0,0 +1,734 @@
|
|
|
1
|
+
// REPL linier — Minicode sebagai agentic Unix shell.
|
|
2
|
+
//
|
|
3
|
+
// Loop `askLine` + printer linier (src/ui/assistant/simple.ts, dipasang di
|
|
4
|
+
// cli/setup.ts) + spinner turn-status. Output append-only di scrollback:
|
|
5
|
+
// tanpa alternate screen, tanpa redraw penuh, tanpa overlay modal. Saat agen
|
|
6
|
+
// bekerja terminal "dipakai" sampai selesai atau dibatalkan Ctrl+C — persis
|
|
7
|
+
// seperti menjalankan perintah shell.
|
|
8
|
+
//
|
|
9
|
+
// Semantik interupsi:
|
|
10
|
+
// - busy: stdin tidak raw, jadi Ctrl+C menjadi SIGINT → abort turn.
|
|
11
|
+
// Listener byte \x03 dipasang sebagai cadangan untuk konsol yang
|
|
12
|
+
// tidak mengirim SIGINT (conhost legacy).
|
|
13
|
+
// - idle: askLine menangkap Ctrl+C/Ctrl+D → null → cetak ^C; null dua kali
|
|
14
|
+
// beruntun → keluar. `/exit` tetap cara utama.
|
|
15
|
+
|
|
16
|
+
import { resolve as resolvePath } from "node:path"
|
|
17
|
+
import { expandMentions } from "../src/app/mentions.ts"
|
|
18
|
+
import { saveLastModel } from "../src/config.ts"
|
|
19
|
+
import { budgetStatus } from "../src/policy/usage.ts"
|
|
20
|
+
import { redoLastCheckpoint, undoLastCheckpoint } from "../src/session/checkpoint.ts"
|
|
21
|
+
import { listSessions, loadSession } from "../src/session/persistence.ts"
|
|
22
|
+
import { renderSkill } from "../src/skills/loader.ts"
|
|
23
|
+
import {
|
|
24
|
+
formatError,
|
|
25
|
+
getLastTurnText,
|
|
26
|
+
takePendingError,
|
|
27
|
+
writeClipboardOsc52,
|
|
28
|
+
} from "../src/ui/assistant/simple.ts"
|
|
29
|
+
import { appendHistory, askLine } from "../src/ui/input/input.ts"
|
|
30
|
+
import type { PromptKey } from "../src/ui/input/prompt-engine.ts"
|
|
31
|
+
import {
|
|
32
|
+
type CollapseSection,
|
|
33
|
+
collapse,
|
|
34
|
+
getBufferedSections,
|
|
35
|
+
resetBufferedSections,
|
|
36
|
+
sectionMinimized,
|
|
37
|
+
setSectionMinimized,
|
|
38
|
+
} from "../src/ui/render/collapse.ts"
|
|
39
|
+
import { setCompactMode } from "../src/ui/render/detail.ts"
|
|
40
|
+
import { formatUsd } from "../src/ui/render/money.ts"
|
|
41
|
+
import { setReasoningVisible } from "../src/ui/render/reasoning.ts"
|
|
42
|
+
import { c, glyphs } from "../src/ui/render/theme.ts"
|
|
43
|
+
import { createFooterChrome, type FooterChrome } from "../src/ui/runtime/chrome.ts"
|
|
44
|
+
import { paintWrite } from "../src/ui/runtime/statusline.ts"
|
|
45
|
+
import {
|
|
46
|
+
BUILTIN_COMMANDS,
|
|
47
|
+
type CommandContext,
|
|
48
|
+
DRIVER_HELP_COMMANDS,
|
|
49
|
+
handleBuiltinCommand,
|
|
50
|
+
} from "./commands.ts"
|
|
51
|
+
import type { CliSession } from "./setup.ts"
|
|
52
|
+
|
|
53
|
+
const MODES = ["auto", "ask", "plan", "allowlist", "allow-all"] as const
|
|
54
|
+
|
|
55
|
+
// Jarak edit untuk did-you-mean — cukup untuk typo 1-2 huruf (/modle,
|
|
56
|
+
// /sessons), cukup ketat untuk tidak menebak perintah yang memang asing.
|
|
57
|
+
function editDistance(a: string, b: string): number {
|
|
58
|
+
const dp = Array.from({ length: a.length + 1 }, (_, i) => i)
|
|
59
|
+
for (let j = 1; j <= b.length; j++) {
|
|
60
|
+
let prev = dp[0]!
|
|
61
|
+
dp[0] = j
|
|
62
|
+
for (let i = 1; i <= a.length; i++) {
|
|
63
|
+
const cur = dp[i]!
|
|
64
|
+
dp[i] = Math.min(dp[i]! + 1, dp[i - 1]! + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1))
|
|
65
|
+
prev = cur
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return dp[a.length]!
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Saran perintah terdekat untuk typo slash; undefined bila tak ada yang dekat.
|
|
72
|
+
* Diekspor untuk test. */
|
|
73
|
+
export function suggestSimilar(name: string, candidates: string[]): string | undefined {
|
|
74
|
+
let best: string | undefined
|
|
75
|
+
let bestD = 3 // ambang: >2 dianggap perintah asing, bukan typo
|
|
76
|
+
for (const cand of candidates) {
|
|
77
|
+
if (cand === name) return cand
|
|
78
|
+
const d = editDistance(name.toLowerCase(), cand.toLowerCase())
|
|
79
|
+
if (d < bestD) {
|
|
80
|
+
bestD = d
|
|
81
|
+
best = cand
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return best
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Terapkan pilihan model + ingat untuk sesi berikutnya (global,
|
|
88
|
+
* fire-and-forget). Diekspor untuk test. */
|
|
89
|
+
export function persistModelChoice(m: string, modelRef: { current?: string }): void {
|
|
90
|
+
modelRef.current = m
|
|
91
|
+
void saveLastModel(m).catch(() => {})
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Perintah REPL yang ditangani driver sendiri DAN ikut di dropdown completion.
|
|
95
|
+
// Yang hanya ditampilkan di /help (bukan dropdown) tinggal di commands.ts
|
|
96
|
+
// (DRIVER_HELP_COMMANDS) — dropdown tetap pendek. /mode pindah ke sana:
|
|
97
|
+
// Tab/Shift+Tab sudah memutar mode tanpa baris baru, jadi /mode tak perlu
|
|
98
|
+
// memenuhi dropdown. /thinking = toggle TAMPILAN reasoning (expand/minimize),
|
|
99
|
+
// bukan effort — effort diatur lewat picker /model (Enter).
|
|
100
|
+
const DRIVER_COMMANDS = ["/compact", "/thinking", "/expand", "/minimize"]
|
|
101
|
+
|
|
102
|
+
// Pemetaan byte tombol yang ditangkap SELAMA turn (raw mode). Dipisah agar
|
|
103
|
+
// bisa di-unit-test murni. `+`/`=` expand section aktif, `-`/`_` minimize,
|
|
104
|
+
// Ctrl+T toggle thinking, Ctrl+C abort.
|
|
105
|
+
export type BusyKeyAction =
|
|
106
|
+
| { action: "abort" }
|
|
107
|
+
| { action: "toggle-section"; kind: CollapseSection; expand: boolean }
|
|
108
|
+
| { action: "toggle-thinking" }
|
|
109
|
+
| null
|
|
110
|
+
|
|
111
|
+
export function applyBusyKey(byte: number, active: CollapseSection | null): BusyKeyAction {
|
|
112
|
+
if (byte === 0x03) return { action: "abort" }
|
|
113
|
+
if (byte === 0x2b || byte === 0x3d)
|
|
114
|
+
return { action: "toggle-section", kind: active ?? "tool", expand: true }
|
|
115
|
+
if (byte === 0x2d || byte === 0x5f)
|
|
116
|
+
return { action: "toggle-section", kind: active ?? "tool", expand: false }
|
|
117
|
+
if (byte === 0x14) return { action: "toggle-thinking" }
|
|
118
|
+
return null
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export async function runRepl(ctx: CliSession): Promise<void> {
|
|
122
|
+
const {
|
|
123
|
+
cfg,
|
|
124
|
+
cwd,
|
|
125
|
+
sessionId,
|
|
126
|
+
modelRef,
|
|
127
|
+
permissionMode,
|
|
128
|
+
permissions,
|
|
129
|
+
sessionTools,
|
|
130
|
+
allLoadedSkills,
|
|
131
|
+
allowLocalConfig,
|
|
132
|
+
usage,
|
|
133
|
+
budget,
|
|
134
|
+
budgetStrict,
|
|
135
|
+
persistCurrent,
|
|
136
|
+
runPromptWithVerify,
|
|
137
|
+
close,
|
|
138
|
+
} = ctx
|
|
139
|
+
// Kontrak control-plane (Phase 6): sumber kebenaran konteks = kernel.
|
|
140
|
+
const { session } = ctx
|
|
141
|
+
|
|
142
|
+
// Kernel tidak mengekspos `config`, jadi handle permission datang dari
|
|
143
|
+
// createMinicodeSession lewat CliSession. Tanpa ini Shift+Tab hanya mengubah
|
|
144
|
+
// label prompt sementara mode sebenarnya tidak berubah.
|
|
145
|
+
let mode: string = permissions?.getMode() ?? permissionMode ?? "auto"
|
|
146
|
+
// REPL default ringkas (minimize): output tool minimize, bisa di-expand via
|
|
147
|
+
// /compact atau Ctrl+O. Env eksplisit selalu menang; one-shot/exec/CI tak
|
|
148
|
+
// tersentuh (tetap expanded). Lihat detail.compact.
|
|
149
|
+
if (process.env.MINICODE_COMPACT === undefined) setCompactMode(true)
|
|
150
|
+
// Section collapse default MINIMIZE untuk tool: bash/edit/content jadi
|
|
151
|
+
// satu baris ` + label`, isi di-buffer. `+`/`-` saat turn atau /expand
|
|
152
|
+
// membuka. Jawaban model SENGAJA default expanded (streaming penuh) —
|
|
153
|
+
// minimize-default membuatnya "bisu" tanpa off-switch; yang mau rapi
|
|
154
|
+
// tinggal /minimize. Env eksplisit selalu menang untuk keduanya.
|
|
155
|
+
if (process.env.MINICODE_MINIMIZE_TOOL === undefined) setSectionMinimized("tool", true)
|
|
156
|
+
let nullStreak = 0
|
|
157
|
+
let warned80 = false
|
|
158
|
+
// Non-null selama turn berjalan — target abort SIGINT/Ctrl+C.
|
|
159
|
+
let abort: AbortController | null = null
|
|
160
|
+
|
|
161
|
+
const commandCtx: CommandContext = {
|
|
162
|
+
cwd,
|
|
163
|
+
sessionId,
|
|
164
|
+
allowLocalConfig,
|
|
165
|
+
get currentModel() {
|
|
166
|
+
return modelRef.current ?? cfg.providers[0]?.models[0]
|
|
167
|
+
},
|
|
168
|
+
set currentModel(v) {
|
|
169
|
+
modelRef.current = v
|
|
170
|
+
},
|
|
171
|
+
usage,
|
|
172
|
+
skills: allLoadedSkills,
|
|
173
|
+
toolsCount: sessionTools.length,
|
|
174
|
+
providerHint: cfg.providers[0]?.providerHint,
|
|
175
|
+
setModelOverride: (m) => {
|
|
176
|
+
persistModelChoice(m, modelRef)
|
|
177
|
+
},
|
|
178
|
+
// Kontrak control-plane (Phase 6): angka konteks dari sumber kebenaran
|
|
179
|
+
// kernel (estimateSessionContext) — bukan usage kumulatif.
|
|
180
|
+
getContextTokens: () => session.contextTokens,
|
|
181
|
+
budgetState: () => {
|
|
182
|
+
const u = usage.getSession()
|
|
183
|
+
return budgetStatus(budget, u.cost, budgetStrict ?? false, u.totalTokens)
|
|
184
|
+
},
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const suggestions = (line: string): string[] => {
|
|
188
|
+
if (!line.startsWith("/")) return []
|
|
189
|
+
const all = [
|
|
190
|
+
...BUILTIN_COMMANDS.map((b) => `/${b.name}`),
|
|
191
|
+
...DRIVER_COMMANDS,
|
|
192
|
+
...allLoadedSkills.map((s) => `/${s.name}`),
|
|
193
|
+
]
|
|
194
|
+
return all.filter((t) => t.startsWith(line))
|
|
195
|
+
}
|
|
196
|
+
const groupOf = (text: string): string =>
|
|
197
|
+
BUILTIN_COMMANDS.some((b) => `/${b.name}` === text) || DRIVER_COMMANDS.includes(text)
|
|
198
|
+
? "commands"
|
|
199
|
+
: "skills"
|
|
200
|
+
|
|
201
|
+
// Prompt steril: tanpa status apa pun (mode/model/cwd pindah ke footer).
|
|
202
|
+
// Bentuk fungsi dipertahankan karena askLine menerima string|fungsi.
|
|
203
|
+
const promptPrefix = (): string => {
|
|
204
|
+
return `${c.dim("minicode")} › `
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Notifikasi satu baris saat prompt masih aktif: bersihkan baris berjalan,
|
|
208
|
+
// cetak, lalu askLine menggambar ulang prompt di baris bawahnya.
|
|
209
|
+
const notify = (msg: string) => process.stdout.write(`\r\x1b[2K${msg}\n`)
|
|
210
|
+
|
|
211
|
+
const cycleMode = () => {
|
|
212
|
+
const idx = MODES.indexOf(mode as (typeof MODES)[number])
|
|
213
|
+
// allow-all hanya via flag --allow-all, tidak di-cycle tombol
|
|
214
|
+
// — mencegah aktivasi tak sengaja mode paling permisif.
|
|
215
|
+
let next = MODES[(idx + 1) % MODES.length]!
|
|
216
|
+
if (next === "allow-all") next = MODES[(idx + 2) % MODES.length]!
|
|
217
|
+
mode = next
|
|
218
|
+
if (permissions) permissions.setMode(mode as (typeof MODES)[number])
|
|
219
|
+
else mode = permissionMode ?? mode // tak ada handle: jangan tampilkan label palsu
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const onKey = (key: PromptKey, _line: string): boolean => {
|
|
223
|
+
// Ganti mode TANPA baris scrollback baru: askLine me-render ulang baris
|
|
224
|
+
// berjalan setelah onKey (lihat input.ts); mode baru terlihat di footer
|
|
225
|
+
// yang dicetak pada idle berikutnya. notify() di sini hanya menambah
|
|
226
|
+
// histori "mode: x" tiap tekan tombol.
|
|
227
|
+
// (compact di bawah tetap notify: statusnya tak ada di prefiks.)
|
|
228
|
+
if (key.type === "shift-tab") {
|
|
229
|
+
cycleMode()
|
|
230
|
+
// Mode baru langsung terlihat di footer (repaint di tempat, tanpa
|
|
231
|
+
// memindahkan kursor) — bukan menunggu idle berikutnya.
|
|
232
|
+
footer.refresh()
|
|
233
|
+
return true
|
|
234
|
+
}
|
|
235
|
+
// Tab SELALU putar mode (keputusan user: tanpa peduli baris kosong/isi).
|
|
236
|
+
// Completion dropdown tidak lagi pakai Tab — user pilih via ↑/↓ lalu
|
|
237
|
+
// Enter. Tanpa ini Tab saat mengetik tidak bisa ganti mode (keluhan nyata).
|
|
238
|
+
if (key.type === "tab") {
|
|
239
|
+
cycleMode()
|
|
240
|
+
footer.refresh()
|
|
241
|
+
return true
|
|
242
|
+
}
|
|
243
|
+
if (key.type === "ctrl-o") {
|
|
244
|
+
const compact = setCompactMode()
|
|
245
|
+
notify(c.muted(`tool call: ${compact ? "compact" : "expanded"}`))
|
|
246
|
+
return true
|
|
247
|
+
}
|
|
248
|
+
if (key.type === "ctrl-t") {
|
|
249
|
+
const vis = setReasoningVisible()
|
|
250
|
+
notify(c.muted(`thinking: ${vis ? "expanded" : "minimized"}`))
|
|
251
|
+
return true
|
|
252
|
+
}
|
|
253
|
+
return false
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function respawnWithResume(id: string): Promise<void> {
|
|
257
|
+
// Lepas region footer sebelum spawn anak stdio-inherit — anak tidak boleh
|
|
258
|
+
// mewarisi terminal yang region-nya terkunci milik parent.
|
|
259
|
+
footer.detach()
|
|
260
|
+
await close()
|
|
261
|
+
const { spawn } = await import("node:child_process")
|
|
262
|
+
const { waitChildExit } = await import("./auto-update.ts")
|
|
263
|
+
const entry = resolvePath(import.meta.dir, "index.ts")
|
|
264
|
+
const child = spawn(
|
|
265
|
+
process.execPath,
|
|
266
|
+
[entry, `--resume=${id}`, ...(cwd ? [`--cwd=${cwd}`] : [])],
|
|
267
|
+
{ stdio: "inherit", env: { ...process.env, MINICODE_RESUME_NEW: "1" } },
|
|
268
|
+
)
|
|
269
|
+
void waitChildExit(child).then((code) => process.exit(code ?? 0))
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// `/sessions` tanpa argumen: builtin mencetak daftar bernomor, lalu satu
|
|
273
|
+
// askLine linier meminta pilihan — pengganti picker modal lama.
|
|
274
|
+
async function pickSession(): Promise<void> {
|
|
275
|
+
await handleBuiltinCommand("/sessions", commandCtx)
|
|
276
|
+
const rows = listSessions(cwd).slice(0, 25)
|
|
277
|
+
if (rows.length === 0) return
|
|
278
|
+
const choice = await askLine({ prompt: "resume (number/id, empty = cancel) › " })
|
|
279
|
+
const pick = choice?.trim()
|
|
280
|
+
if (!pick) return
|
|
281
|
+
const asNum = Number(pick)
|
|
282
|
+
const id =
|
|
283
|
+
Number.isInteger(asNum) && asNum >= 0 && asNum < rows.length
|
|
284
|
+
? (rows[asNum]?.id ?? pick)
|
|
285
|
+
: pick
|
|
286
|
+
const sess = loadSession(id, cwd)
|
|
287
|
+
if (!sess?.messages.length) {
|
|
288
|
+
console.log(`Session "${id}" not found or empty.`)
|
|
289
|
+
return
|
|
290
|
+
}
|
|
291
|
+
await respawnWithResume(id)
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// Salin teks turn terakhir ke clipboard (OSC 52). Dipakai /copy DAN Ctrl+C
|
|
295
|
+
// sekali saat idle. Mengembalikan true bila ada yang disalin.
|
|
296
|
+
function copyLastTurn(): boolean {
|
|
297
|
+
const txt = getLastTurnText().trim()
|
|
298
|
+
if (!txt) {
|
|
299
|
+
console.log(c.dim("(nothing to copy yet — run a prompt first)"))
|
|
300
|
+
return false
|
|
301
|
+
}
|
|
302
|
+
// OSC 52 diblokir default di banyak terminal; sampaikan jujur.
|
|
303
|
+
if (writeClipboardOsc52(txt))
|
|
304
|
+
console.log(
|
|
305
|
+
c.dim(`copied ${txt.length} chars (OSC 52 — allow clipboard access in terminal if empty)`),
|
|
306
|
+
)
|
|
307
|
+
else console.log(c.dim("(clipboard needs a TTY terminal)"))
|
|
308
|
+
return true
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// Jalankan satu prompt user sebagai turn agen. Budget diperiksa di sini
|
|
312
|
+
// (dipindah dari UI ke driver): prompt baru ditolak setelah batas terlampaui,
|
|
313
|
+
// peringatan 80% dicetak sekali.
|
|
314
|
+
async function runTurn(finalPrompt: string, original: string): Promise<void> {
|
|
315
|
+
const spent = usage.getSession(modelRef.current)
|
|
316
|
+
const preStatus = budgetStatus(budget, spent.cost, budgetStrict ?? false, spent.totalTokens)
|
|
317
|
+
if (preStatus === "over" && spent.cost != null && budget != null) {
|
|
318
|
+
console.log(
|
|
319
|
+
c.red(
|
|
320
|
+
`[budget] ${formatUsd(spent.cost)} > ${formatUsd(budget)} — over budget, new prompts rejected. /exit to quit.`,
|
|
321
|
+
),
|
|
322
|
+
)
|
|
323
|
+
return
|
|
324
|
+
}
|
|
325
|
+
if (preStatus === "unknown-strict") {
|
|
326
|
+
console.log(
|
|
327
|
+
c.red(
|
|
328
|
+
`[budget] cost unknown (model without pricing) with ${spent.totalTokens} tokens spent — over budget, new prompts rejected. /exit to quit.`,
|
|
329
|
+
),
|
|
330
|
+
)
|
|
331
|
+
return
|
|
332
|
+
}
|
|
333
|
+
await appendHistory(original)
|
|
334
|
+
let prompt = finalPrompt
|
|
335
|
+
if (finalPrompt.includes("@")) {
|
|
336
|
+
const expanded = await expandMentions(finalPrompt, cwd ?? process.cwd())
|
|
337
|
+
prompt = expanded.prompt
|
|
338
|
+
for (const n of expanded.notes) process.stderr.write(` [@mention] ${n}\n`)
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
footer.setBusy(true)
|
|
342
|
+
const ctrl = new AbortController()
|
|
343
|
+
abort = ctrl
|
|
344
|
+
// Raw mode selama turn: tombol + / - / Ctrl+T dibaca live (section
|
|
345
|
+
// collapse), Ctrl+C tetap abort via byte 0x03. Di luar turn stdin tidak
|
|
346
|
+
// raw — askLine mengelola mode raw sendiri. Bukan TTY (pipe/CI) = tanpa
|
|
347
|
+
// raw, tanpa tombol live (perilaku lama: hanya Ctrl+C via sinyal).
|
|
348
|
+
const ttyStdin = !!process.stdin.isTTY
|
|
349
|
+
if (ttyStdin) {
|
|
350
|
+
try {
|
|
351
|
+
process.stdin.setRawMode(true)
|
|
352
|
+
} catch {}
|
|
353
|
+
}
|
|
354
|
+
const busyFeedback = (msg: string) => {
|
|
355
|
+
try {
|
|
356
|
+
paintWrite(`\r\x1b[2K✦ ${msg}`)
|
|
357
|
+
} catch {}
|
|
358
|
+
}
|
|
359
|
+
// Esc sendirian = abort. 0x1b juga awal SEMUA escape sequence (panah,
|
|
360
|
+
// F-key, mouse), jadi kita tunggu ~50ms: kalau ada byte lanjutan, itu
|
|
361
|
+
// sekuens — bukan Esc; kalau tidak ada, Esc asli → abort.
|
|
362
|
+
let escTimer: ReturnType<typeof setTimeout> | undefined
|
|
363
|
+
const armEsc = (): void => {
|
|
364
|
+
if (escTimer) clearTimeout(escTimer)
|
|
365
|
+
escTimer = setTimeout(() => {
|
|
366
|
+
escTimer = undefined
|
|
367
|
+
ctrl.abort()
|
|
368
|
+
}, 50)
|
|
369
|
+
}
|
|
370
|
+
const onBusyKey = ttyStdin
|
|
371
|
+
? (chunk: Buffer) => {
|
|
372
|
+
if (chunk.length === 1 && chunk[0] === 0x1b) {
|
|
373
|
+
armEsc()
|
|
374
|
+
return
|
|
375
|
+
}
|
|
376
|
+
if (escTimer) {
|
|
377
|
+
clearTimeout(escTimer)
|
|
378
|
+
escTimer = undefined
|
|
379
|
+
}
|
|
380
|
+
for (const b of chunk) {
|
|
381
|
+
const act = applyBusyKey(b, collapse.activeSection)
|
|
382
|
+
if (!act) continue
|
|
383
|
+
if (act.action === "abort") {
|
|
384
|
+
ctrl.abort()
|
|
385
|
+
continue
|
|
386
|
+
}
|
|
387
|
+
if (act.action === "toggle-thinking") {
|
|
388
|
+
busyFeedback(
|
|
389
|
+
`thinking: ${setSectionMinimized("thinking") ? "minimized" : "expanded"}`,
|
|
390
|
+
)
|
|
391
|
+
continue
|
|
392
|
+
}
|
|
393
|
+
const minimized = setSectionMinimized(act.kind, !act.expand)
|
|
394
|
+
busyFeedback(`${act.kind}: ${minimized ? "minimized" : "expanded"}`)
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
: // Pipe/CI: input bisa berisi byte + / - apa pun — jangan sentuh state.
|
|
398
|
+
// Perilaku lama: hanya abort via Ctrl+C (sinyal maupun byte).
|
|
399
|
+
(chunk: Buffer) => {
|
|
400
|
+
if (chunk.includes(0x03)) ctrl.abort()
|
|
401
|
+
}
|
|
402
|
+
process.stdin.resume()
|
|
403
|
+
process.stdin.on("data", onBusyKey)
|
|
404
|
+
const turnStart = Date.now()
|
|
405
|
+
try {
|
|
406
|
+
await runPromptWithVerify(prompt, ctrl.signal)
|
|
407
|
+
if (ctrl.signal.aborted) console.log(c.yellow("\n(stopped)"))
|
|
408
|
+
} catch (e) {
|
|
409
|
+
if (ctrl.signal.aborted) console.log(c.yellow("\n(stopped)"))
|
|
410
|
+
else {
|
|
411
|
+
// Audit #04 P1: turn gagal SETELAH delegasi committed = efek anak
|
|
412
|
+
// tetap ada sementara riwayat bersih. Model (dan retry berikut)
|
|
413
|
+
// buta terhadapnya tanpa peringatan ini — blind re-delegation =
|
|
414
|
+
// duplikat side effect. Best-effort, tak pernah blokir throw.
|
|
415
|
+
try {
|
|
416
|
+
const { committedDelegatesSince } = await import("../src/session/journal.ts")
|
|
417
|
+
const done = await committedDelegatesSince(sessionId, cwd, turnStart)
|
|
418
|
+
for (const d of done) {
|
|
419
|
+
console.log(
|
|
420
|
+
c.yellow(
|
|
421
|
+
`[recovery] turn failed after sub-agent ${d.childSessionId} completed — its effects stand; verify before re-delegating\n`,
|
|
422
|
+
),
|
|
423
|
+
)
|
|
424
|
+
}
|
|
425
|
+
} catch {}
|
|
426
|
+
throw e
|
|
427
|
+
}
|
|
428
|
+
} finally {
|
|
429
|
+
footer.setBusy(false)
|
|
430
|
+
if (escTimer) {
|
|
431
|
+
clearTimeout(escTimer)
|
|
432
|
+
escTimer = undefined
|
|
433
|
+
}
|
|
434
|
+
process.stdin.removeListener("data", onBusyKey)
|
|
435
|
+
// Tanpa pause — stdin mengalir seumur proses (lihat cleanup askLine);
|
|
436
|
+
// pause→resume berulang mematikan 'data' selamanya di Bun Windows.
|
|
437
|
+
if (ttyStdin) {
|
|
438
|
+
try {
|
|
439
|
+
process.stdin.setRawMode(false)
|
|
440
|
+
} catch {}
|
|
441
|
+
}
|
|
442
|
+
abort = null
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
const u = usage.get(modelRef.current)
|
|
446
|
+
await persistCurrent(u)
|
|
447
|
+
usage.reset()
|
|
448
|
+
const session = usage.getSession(modelRef.current)
|
|
449
|
+
if (
|
|
450
|
+
budget != null &&
|
|
451
|
+
session.cost != null &&
|
|
452
|
+
session.cost > budget * 0.8 &&
|
|
453
|
+
session.cost <= budget &&
|
|
454
|
+
!warned80
|
|
455
|
+
) {
|
|
456
|
+
warned80 = true
|
|
457
|
+
console.log(c.yellow(`[budget] ${formatUsd(session.cost)} / ${formatUsd(budget)} (80% used)`))
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// true = minta keluar (loop berhenti, lalu close + exit).
|
|
462
|
+
async function dispatchLine(q: string): Promise<boolean> {
|
|
463
|
+
if (q.startsWith("/")) {
|
|
464
|
+
const spaceIdx = q.indexOf(" ")
|
|
465
|
+
const name = (spaceIdx === -1 ? q.slice(1) : q.slice(1, spaceIdx)).toLowerCase()
|
|
466
|
+
const args = spaceIdx === -1 ? "" : q.slice(spaceIdx + 1).trim()
|
|
467
|
+
|
|
468
|
+
// Slash sendirian = minta daftar perintah, bukan unknown command.
|
|
469
|
+
if (name === "") {
|
|
470
|
+
return handleBuiltinCommand("/help", commandCtx).then((r) => !!r.shouldExit)
|
|
471
|
+
}
|
|
472
|
+
if (name === "mode") {
|
|
473
|
+
if (args) {
|
|
474
|
+
if (!(MODES as readonly string[]).includes(args)) {
|
|
475
|
+
console.log(c.yellow(`unknown mode: ${args} — choices: ${MODES.join(", ")}`))
|
|
476
|
+
return false
|
|
477
|
+
}
|
|
478
|
+
mode = args
|
|
479
|
+
permissions?.setMode(args as (typeof MODES)[number])
|
|
480
|
+
} else {
|
|
481
|
+
cycleMode()
|
|
482
|
+
}
|
|
483
|
+
console.log(c.muted(`mode: ${mode}`))
|
|
484
|
+
return false
|
|
485
|
+
}
|
|
486
|
+
if (name === "compact") {
|
|
487
|
+
const next = args === "" ? undefined : args === "on" || args === "1"
|
|
488
|
+
const compact = setCompactMode(next)
|
|
489
|
+
console.log(c.muted(`tool call: ${compact ? "compact" : "expanded"}`))
|
|
490
|
+
return false
|
|
491
|
+
}
|
|
492
|
+
if (name === "thinking") {
|
|
493
|
+
const next = args === "" ? undefined : args === "on" || args === "1"
|
|
494
|
+
const vis = setReasoningVisible(next)
|
|
495
|
+
console.log(c.muted(`thinking: ${vis ? "expanded" : "minimized"}`))
|
|
496
|
+
return false
|
|
497
|
+
}
|
|
498
|
+
if (name === "expand") {
|
|
499
|
+
// Buka isi section yang dikecilkan pada turn terakhir (buffer).
|
|
500
|
+
// Stream asal dipertahankan: answer → stdout, sisanya stderr.
|
|
501
|
+
// Ringkasan/kontrol = stdout.
|
|
502
|
+
const sections = getBufferedSections()
|
|
503
|
+
if (sections.length === 0) {
|
|
504
|
+
console.log(
|
|
505
|
+
c.dim(
|
|
506
|
+
"(nothing to expand — all sections were visible; press + during the turn to collapse)",
|
|
507
|
+
),
|
|
508
|
+
)
|
|
509
|
+
return false
|
|
510
|
+
}
|
|
511
|
+
for (const s of sections) {
|
|
512
|
+
const out = s.stream === "stdout" ? process.stdout : process.stderr
|
|
513
|
+
out.write(`${c.muted(` ── ${s.label} ──`)}\n`)
|
|
514
|
+
out.write(s.text.endsWith("\n") ? s.text : `${s.text}\n`)
|
|
515
|
+
}
|
|
516
|
+
// Sudah dibuka = selesai; cetak ulang butuh buffer baru dari turn baru.
|
|
517
|
+
resetBufferedSections()
|
|
518
|
+
return false
|
|
519
|
+
}
|
|
520
|
+
if (name === "minimize") {
|
|
521
|
+
// Saklar tunggal "rapi ⇄ penuh" seperti /compact dan /thinking:
|
|
522
|
+
// bare = flip (keduanya minimize → expand keduanya; selain itu →
|
|
523
|
+
// minimize keduanya); on|1 / off|0 = set eksplisit keduanya.
|
|
524
|
+
const arg = args.trim().toLowerCase()
|
|
525
|
+
let next: boolean | undefined
|
|
526
|
+
if (arg === "") next = !(sectionMinimized("tool") && sectionMinimized("answer"))
|
|
527
|
+
else if (arg === "on" || arg === "1") next = true
|
|
528
|
+
else if (arg === "off" || arg === "0") next = false
|
|
529
|
+
else {
|
|
530
|
+
console.log(c.muted("usage: /minimize [on|off]"))
|
|
531
|
+
return false
|
|
532
|
+
}
|
|
533
|
+
setSectionMinimized("tool", next)
|
|
534
|
+
setSectionMinimized("answer", next)
|
|
535
|
+
console.log(
|
|
536
|
+
c.muted(
|
|
537
|
+
next
|
|
538
|
+
? "sections: minimized (press + / - during the turn to expand/collapse)"
|
|
539
|
+
: "sections: expanded",
|
|
540
|
+
),
|
|
541
|
+
)
|
|
542
|
+
return false
|
|
543
|
+
}
|
|
544
|
+
if (name === "undo") {
|
|
545
|
+
const res = await undoLastCheckpoint(sessionId, cwd)
|
|
546
|
+
console.log(res.message)
|
|
547
|
+
if (res.restoredFiles.length) console.log(res.restoredFiles.join("\n"))
|
|
548
|
+
return false
|
|
549
|
+
}
|
|
550
|
+
if (name === "redo") {
|
|
551
|
+
const res = await redoLastCheckpoint(sessionId, cwd)
|
|
552
|
+
console.log(res.message)
|
|
553
|
+
if (res.reappliedFiles.length) console.log(res.reappliedFiles.join("\n"))
|
|
554
|
+
return false
|
|
555
|
+
}
|
|
556
|
+
if (name === "cost" || name === "usage") {
|
|
557
|
+
// Opsi A: /cost tidak punya tampilan sendiri lagi — arahkan ke /status
|
|
558
|
+
// (satu-satunya sumber biaya sesi: input/output/total/cost).
|
|
559
|
+
return handleBuiltinCommand("/status", commandCtx).then((r) => !!r.shouldExit)
|
|
560
|
+
}
|
|
561
|
+
if (name === "resume") {
|
|
562
|
+
// Opsi A: /resume = pintas /sessions (daftar + picker, atau respawn <id>).
|
|
563
|
+
if (!args) {
|
|
564
|
+
await pickSession()
|
|
565
|
+
return false
|
|
566
|
+
}
|
|
567
|
+
return handleBuiltinCommand(`/sessions ${args}`, commandCtx).then((r) => !!r.shouldExit)
|
|
568
|
+
}
|
|
569
|
+
if (name === "clear") {
|
|
570
|
+
// Shell-first: scrollback adalah transcript — jangan hapus, tandai saja.
|
|
571
|
+
console.log(c.dim("--- cleared (scrollback preserved) ---"))
|
|
572
|
+
return false
|
|
573
|
+
}
|
|
574
|
+
if (name === "copy") {
|
|
575
|
+
copyLastTurn()
|
|
576
|
+
return false
|
|
577
|
+
}
|
|
578
|
+
if (name === "history") {
|
|
579
|
+
const { loadHistory } = await import("../src/ui/input/input.ts")
|
|
580
|
+
console.log((await loadHistory()).slice(-20).join("\n"))
|
|
581
|
+
return false
|
|
582
|
+
}
|
|
583
|
+
if (name === "models")
|
|
584
|
+
return handleBuiltinCommand("/model", commandCtx).then((r) => !!r.shouldExit)
|
|
585
|
+
if (name === "providers")
|
|
586
|
+
return handleBuiltinCommand("/provider", commandCtx).then((r) => !!r.shouldExit)
|
|
587
|
+
if (name === "sessions" && !args) {
|
|
588
|
+
await pickSession()
|
|
589
|
+
return false
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// Builtin mengalir langsung ke scrollback (console.log) — tanpa
|
|
593
|
+
// penangkap output/overlay. Manajer /model & /provider transient:
|
|
594
|
+
// menghapus diri sendiri dan tidak menyentuh scrollback.
|
|
595
|
+
const builtin = await handleBuiltinCommand(q, commandCtx)
|
|
596
|
+
if (builtin.handled) return !!builtin.shouldExit
|
|
597
|
+
|
|
598
|
+
const skill = allLoadedSkills.find((s) => s.name === name)
|
|
599
|
+
if (!skill) {
|
|
600
|
+
const hint = suggestSimilar(name, [
|
|
601
|
+
...BUILTIN_COMMANDS.map((b) => b.name),
|
|
602
|
+
...DRIVER_COMMANDS.map((d) => d.slice(1)),
|
|
603
|
+
// Alias yang diarahkan ke perintah lain tetap dikenali sebagai typo
|
|
604
|
+
// (mis. /cst → /cost → /status), walau tak muncul di dropdown.
|
|
605
|
+
...DRIVER_HELP_COMMANDS.map((b) => b.name),
|
|
606
|
+
"cost",
|
|
607
|
+
"usage",
|
|
608
|
+
"resume",
|
|
609
|
+
...allLoadedSkills.map((s) => s.name),
|
|
610
|
+
])
|
|
611
|
+
console.log(
|
|
612
|
+
c.yellow(`Unknown command: /${name}.${hint ? ` Did you mean /${hint}?` : " Try /help."}`),
|
|
613
|
+
)
|
|
614
|
+
return false
|
|
615
|
+
}
|
|
616
|
+
await runTurn(await renderSkill(skill, args), q)
|
|
617
|
+
return false
|
|
618
|
+
}
|
|
619
|
+
await runTurn(q, q)
|
|
620
|
+
return false
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
const onSigint = () => {
|
|
624
|
+
if (abort) abort.abort()
|
|
625
|
+
else {
|
|
626
|
+
// Idle: jangan biarkan SIGINT bocor ke PowerShell batch (Terminate batch job)
|
|
627
|
+
// Kirim byte Ctrl+C ke stdin agar askLine tangani sebagai null (idle) — konsisten dengan raw mode
|
|
628
|
+
try {
|
|
629
|
+
process.stdin.emit("data", Buffer.from([0x03]))
|
|
630
|
+
} catch {}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
process.on("SIGINT", onSigint)
|
|
634
|
+
// Baris konteks startup (model/mode/dir + hint) dihapus: status kini milik
|
|
635
|
+
// footer yang dicetak fresh tiap idle — startup tetap steril seperti prompt.
|
|
636
|
+
|
|
637
|
+
// Footer status (mode • model • cwd • konteks): lengket di dasar terminal
|
|
638
|
+
// bila terminal mampu (DECSTBM), jatuh ke cetak bila tidak, mati total di
|
|
639
|
+
// pipe. Diresolve per present/refresh agar mode/model/cwd/konteks selalu
|
|
640
|
+
// aktual (Shift+Tab, /model, cwd berubah, konteks live). Reset region
|
|
641
|
+
// dijamin pada semua jalur keluar. Mode di-pad agar teks kanan tak bergeser
|
|
642
|
+
// (lihat footer.ts MODE_WIDTH), garis = faint tipis hampir tak terlihat.
|
|
643
|
+
const fmtCtx = (n: number): string | undefined => {
|
|
644
|
+
if (!Number.isFinite(n) || n <= 0) return undefined
|
|
645
|
+
if (n < 1000) return String(n)
|
|
646
|
+
if (n < 10000) return `${(n / 1000).toFixed(1)}k`
|
|
647
|
+
if (n < 1000000) return `${Math.round(n / 1000)}k`
|
|
648
|
+
return `${(n / 1000000).toFixed(1)}m`
|
|
649
|
+
}
|
|
650
|
+
const footer: FooterChrome = createFooterChrome({
|
|
651
|
+
enabled: true,
|
|
652
|
+
status: () => {
|
|
653
|
+
return {
|
|
654
|
+
mode,
|
|
655
|
+
model: modelRef.current ?? cfg.providers[0]?.models[0] ?? "no model",
|
|
656
|
+
cwd: cwd ?? process.cwd(),
|
|
657
|
+
// Kontrak control-plane (Phase 6): angka footer = UKURAN JENDELA
|
|
658
|
+
// saat ini (kernel contextTokens, estimateSessionContext) — bukan
|
|
659
|
+
// totalTokens kumulatif provider (dulu salah konsep; sama dengan
|
|
660
|
+
// /status yang kini membedakan keduanya).
|
|
661
|
+
context: fmtCtx(session.contextTokens),
|
|
662
|
+
}
|
|
663
|
+
},
|
|
664
|
+
})
|
|
665
|
+
process.on("exit", () => footer.detach())
|
|
666
|
+
|
|
667
|
+
let shouldExit = false
|
|
668
|
+
// Akumulasi baris yang diakhiri `\` — shell-like continuation di driver
|
|
669
|
+
// (bukan di askLine) agar hanya prompt REPL yang punya, tidak semua pemanggil askLine.
|
|
670
|
+
// Sesuai USAGE.md "akhiri baris dengan \ untuk menyambung".
|
|
671
|
+
let pending = ""
|
|
672
|
+
const contPrompt = () => c.dim("··· › ")
|
|
673
|
+
try {
|
|
674
|
+
for (;;) {
|
|
675
|
+
let line: string | null
|
|
676
|
+
try {
|
|
677
|
+
const usePrompt = pending ? contPrompt : promptPrefix
|
|
678
|
+
// Footer di-print/repaint tepat sebelum prompt idle: sticky → pastikan
|
|
679
|
+
// region + posisikan kursor di baris input; print → baris scrollback.
|
|
680
|
+
footer.present()
|
|
681
|
+
// idleMs mati DI SINI saja: prompt utama adalah home state proses —
|
|
682
|
+
// null dihitung Ctrl+C (2x = exit), sehingga auto-batal akan
|
|
683
|
+
// mengeluarkan user yang diam. Dialog transient (approval, add/edit,
|
|
684
|
+
// wizard) tetap pakai default 90 dtk.
|
|
685
|
+
line = await askLine({ prompt: usePrompt, hints: suggestions, groupOf, onKey, idleMs: 0 })
|
|
686
|
+
} catch (e) {
|
|
687
|
+
console.log(`${c.red(glyphs.cross)} ${formatError(e)}`)
|
|
688
|
+
continue
|
|
689
|
+
}
|
|
690
|
+
if (line == null) {
|
|
691
|
+
if (pending) {
|
|
692
|
+
pending = ""
|
|
693
|
+
console.log("^C")
|
|
694
|
+
nullStreak = 0
|
|
695
|
+
continue
|
|
696
|
+
}
|
|
697
|
+
// Ctrl+C sekali saat idle = SALIN teks turn terakhir (keputusan user);
|
|
698
|
+
// dua kali beruntun = keluar. Esc/Ctrl+D juga resolve null — diperlakukan
|
|
699
|
+
// sama: tekan pertama copy, kedua keluar.
|
|
700
|
+
nullStreak++
|
|
701
|
+
if (nullStreak >= 2) {
|
|
702
|
+
shouldExit = true
|
|
703
|
+
break
|
|
704
|
+
}
|
|
705
|
+
copyLastTurn()
|
|
706
|
+
continue
|
|
707
|
+
}
|
|
708
|
+
nullStreak = 0
|
|
709
|
+
// Baris berakhir `\` → sambung, tanpa dispatch.
|
|
710
|
+
if (line.endsWith("\\")) {
|
|
711
|
+
pending += `${line.slice(0, -1)}\n`
|
|
712
|
+
continue
|
|
713
|
+
}
|
|
714
|
+
const full = pending ? `${pending}${line}` : line
|
|
715
|
+
pending = ""
|
|
716
|
+
const q = full.trim()
|
|
717
|
+
if (!q) continue
|
|
718
|
+
try {
|
|
719
|
+
shouldExit = await dispatchLine(q)
|
|
720
|
+
} catch (e) {
|
|
721
|
+
const shown = takePendingError()
|
|
722
|
+
console.log(`${c.red(glyphs.cross)} ${shown ?? formatError(e)}`)
|
|
723
|
+
}
|
|
724
|
+
if (shouldExit) break
|
|
725
|
+
}
|
|
726
|
+
} finally {
|
|
727
|
+
process.off("SIGINT", onSigint)
|
|
728
|
+
}
|
|
729
|
+
// Reset region + cetak footer terakhir SEBELUM process.exit — jalur keluar
|
|
730
|
+
// normal; jalur crash dilindungi handler on("exit") di atas (idempotent).
|
|
731
|
+
footer.detach()
|
|
732
|
+
await close()
|
|
733
|
+
process.exit(0)
|
|
734
|
+
}
|