aegiscode 7.0.14 → 7.0.16
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/SOURCE-OFFER.txt +9 -0
- package/package.json +4 -7
- package/scripts/check.mjs +1 -52
- package/scripts/demo.mjs +1 -94
- package/scripts/predist.mjs +1 -75
- package/scripts/runtests.mjs +1 -56
- package/scripts/seal-gate.mjs +1 -74
- package/src/agents.js +1 -139
- package/src/app.js +1 -2932
- package/src/art.js +1 -289
- package/src/chatflow.js +1 -3020
- package/src/checkpoint.js +1 -90
- package/src/clipboard.js +1 -424
- package/src/cloudsync.js +1 -528
- package/src/commands.js +1 -4003
- package/src/config.js +1 -581
- package/src/connect.js +1 -349
- package/src/credentials.js +1 -33
- package/src/deps.js +1 -232
- package/src/devrun.js +1 -187
- package/src/diff.js +1 -333
- package/src/diffview.js +1 -296
- package/src/engine.js +1 -297
- package/src/entitlement.js +1 -355
- package/src/events.js +1 -707
- package/src/export.js +1 -67
- package/src/fingerprint.js +1 -592
- package/src/format.js +1 -259
- package/src/fuzzy.js +1 -119
- package/src/history.js +1 -401
- package/src/init.js +1 -175
- package/src/input.js +1 -139
- package/src/keys.js +1 -183
- package/src/markdown.js +1 -306
- package/src/models.js +1 -487
- package/src/naming.js +1 -229
- package/src/overlays.js +1 -461
- package/src/panels.js +1 -1418
- package/src/ping.js +1 -226
- package/src/presence.js +1 -238
- package/src/render.js +1 -515
- package/src/screen.js +1 -518
- package/src/screens.js +1 -896
- package/src/secret.js +1 -59
- package/src/securefs.js +1 -359
- package/src/settings.js +1 -155
- package/src/shared.js +1 -52
- package/src/sharedpaths.js +1 -53
- package/src/signup.js +1 -156
- package/src/summarize.js +1 -95
- package/src/sysdiag.js +1 -585
- package/src/system.js +1 -40
- package/src/theme.js +1 -570
- package/src/title.js +1 -220
- package/src/todos.js +1 -115
- package/src/tokens.js +1 -263
- package/src/topup.js +1 -210
- package/src/update.js +1 -181
- package/vendor/client/aegis.js +1 -2179
- package/vendor/client/attest.js +1 -442
- package/vendor/client/authorship-key.js +1 -410
- package/vendor/client/auto-provision.js +1 -134
- package/vendor/client/brain-catalog.js +1 -268
- package/vendor/client/byok-catalog.js +1 -230
- package/vendor/client/credentials.js +1 -494
- package/vendor/client/device-fingerprint.js +1 -141
- package/vendor/client/drive-connect.js +1 -110
- package/vendor/client/drive-upload.js +1 -174
- package/vendor/client/env-file.js +1 -1273
- package/vendor/client/fingerprint.js +1 -1064
- package/vendor/client/foreign-memory.js +1 -669
- package/vendor/client/google-signin.js +1 -133
- package/vendor/client/hooks.js +1 -430
- package/vendor/client/model-discovery.js +1 -373
- package/vendor/client/platform.js +1 -937
- package/vendor/client/prefs.js +1 -351
- package/vendor/client/presence-constants.js +1 -107
- package/vendor/client/presence.js +1 -438
- package/vendor/client/record-vault.js +3 -1055
- package/vendor/client/session-store.js +1 -548
- package/vendor/client/topup.js +1 -297
- package/vendor/client/touch.js +1 -458
- package/vendor/client/update.js +1 -704
- package/vendor/client/user-models.js +1 -381
- package/vendor/desktop/lib/local/agents.js +1 -105
- package/vendor/desktop/lib/local/autonomous.js +1 -1045
- package/vendor/desktop/lib/local/claude-pro.js +1 -993
- package/vendor/desktop/lib/local/context.js +1 -95
- package/vendor/desktop/lib/local/engine.js +1 -3301
- package/vendor/desktop/lib/local/entitlement.js +1 -660
- package/vendor/desktop/lib/local/git-scope.js +1 -228
- package/vendor/desktop/lib/local/local.js +1 -2135
- package/vendor/desktop/lib/local/prompt.js +1 -275
- package/vendor/desktop/lib/local/queue.js +1 -560
- package/vendor/desktop/lib/local/session-rounds.js +1 -208
- package/vendor/desktop/lib/local/shell.js +1 -680
- package/vendor/desktop/lib/local/tools.js +1 -1238
- package/vendor/desktop/lib/local/turn-guard.js +1 -300
- package/vendor/desktop/lib/local/worktree-lock.js +1 -235
- package/vendor/desktop/lib/settings.js +1 -890
- package/vendor/desktop/renderer/usage.js +1 -1239
- package/vendor/hosts/install.js +1 -638
- package/vendor/hosts/openai-shim.js +1 -515
- package/vendor/hosts/spec.js +1 -164
- package/vendor/hosts/targets.js +1 -346
- package/vendor/mcp/server.js +1 -221
- package/vendor/mcp/tools.js +1 -408
- package/vendor/one/src/child.js +1 -285
- package/vendor/one/src/permissions.js +1 -369
package/src/chatflow.js
CHANGED
|
@@ -1,3022 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
// AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
|
|
4
|
-
// Conveying a modified copy, or running one as a network service, owes the
|
|
5
|
-
// corresponding source under this licence (§5/§13) — see LICENSING.md.
|
|
6
|
-
'use strict';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* The chatflow — the full-screen session loop, and the row/render helpers it
|
|
10
|
-
* runs on.
|
|
11
|
-
*
|
|
12
|
-
* This is the upstream engine session loop: an alternate-screen frame of
|
|
13
|
-
*
|
|
14
|
-
* ╭──── AEGIS Code v6.2.0 ────╮ header rule
|
|
15
|
-
* …transcript viewport… user rows, assistant markdown, tool rows
|
|
16
|
-
* ✻ Tempering… (3s · ↓412 tokens) spinner, or the effort line when idle
|
|
17
|
-
* ─────────────────────────────
|
|
18
|
-
* ❯ what should I fix? input line, with history + completion
|
|
19
|
-
* ─────────────────────────────
|
|
20
|
-
* ⏸ manual mode on · ? for shortcuts status line (→ switches the mode)
|
|
21
|
-
*
|
|
22
|
-
* driven by a raw key stream, with the turn lifecycle of the reference: a user
|
|
23
|
-
* row, a live assistant row that grows as the model streams, tool rows that
|
|
24
|
-
* resolve from "Running 1 shell command…" to "Ran 1 shell command", a
|
|
25
|
-
* `✻ Churned/Worked for Ns` completion row, `(stopped)` on Esc and
|
|
26
|
-
* `(backend error: …)` on failure.
|
|
27
|
-
*
|
|
28
|
-
* The split from `app.js` is the reference's split: this module owns the frame,
|
|
29
|
-
* the rows, the keys and the turn; `app.js` owns the transport, the tool
|
|
30
|
-
* registry, the command table and the session tallies. Everything this module
|
|
31
|
-
* needs from the app arrives through the small `host` interface documented on
|
|
32
|
-
* `runSession` — which is what lets the whole loop be driven from a test with a
|
|
33
|
-
* stub host and no TTY.
|
|
34
|
-
*
|
|
35
|
-
* Pure helpers are exported at module scope (`resolveToolDone`,
|
|
36
|
-
* `finalizeTurnText`, `transcriptLines`, …) so a regression test can drive the
|
|
37
|
-
* exact pairing, marker and viewport logic without a terminal.
|
|
38
|
-
*/
|
|
39
|
-
|
|
40
|
-
const {
|
|
41
|
-
getSize, span, padLine, paint, w, wrapBlock,
|
|
42
|
-
hideCursor, showCursor, moveTo, clearScreen,
|
|
43
|
-
enterAltScreen, leaveAltScreen,
|
|
44
|
-
enableBracketedPaste, disableBracketedPaste,
|
|
45
|
-
enableMouseTracking, disableMouseTracking,
|
|
46
|
-
selectionRange, selectionText, applySelection,
|
|
47
|
-
} = require('./screen.js');
|
|
48
|
-
const {
|
|
49
|
-
KEY, STREAM_END, attachKeyStream, nextKey, nextKeyTimeout, requeueKeys, resetKeyStream,
|
|
50
|
-
markSessionStart, isKeyStreamSuspended,
|
|
51
|
-
} = require('./events.js');
|
|
52
|
-
const { GLYPH, VERBS, DONE_VERBS, BOLD, BOLD_OFF, themeOf, RGB } = require('./theme.js');
|
|
53
|
-
const { LineEditor } = require('./input.js');
|
|
54
|
-
const { renderMarkdown } = require('./markdown.js');
|
|
55
|
-
const overlays = require('./overlays.js');
|
|
56
|
-
const models = require('./models.js');
|
|
57
|
-
const { resolveShared } = require('./sharedpaths.js');
|
|
58
|
-
const { validateApiKey } = require(resolveShared(require('node:path').join('client', 'credentials.js')));
|
|
59
|
-
const claudePro = require(resolveShared(require('node:path').join('desktop', 'lib', 'local', 'claude-pro.js')));
|
|
60
|
-
const fuzzy = require('./fuzzy.js');
|
|
61
|
-
const { fmtTokens, fmtEur, fmtElapsed, fmtUsageSplit, displayTokens, pathName, feeBillable } = require('./format.js');
|
|
62
|
-
const { editPreview } = require('./diff.js');
|
|
63
|
-
const { renderDiffBlock, defaultOpen } = require('./diffview.js');
|
|
64
|
-
const { copyToClipboard, describeCopy, readClipboardText, readClipboardImage } = require('./clipboard.js');
|
|
65
|
-
const { transcriptToMarkdown } = require('./export.js');
|
|
66
|
-
const fs = require('node:fs');
|
|
67
|
-
const path = require('node:path');
|
|
68
|
-
const { aegisDir, loadConfig } = require('./config.js');
|
|
69
|
-
const { effortRung } = require('./engine.js');
|
|
70
|
-
// The shared usage normaliser, reached through the CLI's own accounting module
|
|
71
|
-
// rather than by hand-rolling `input_tokens ?? prompt_tokens` at each render
|
|
72
|
-
// site (see the meta row's comment). tokens.js re-exports it, so chatflow does
|
|
73
|
-
// not have to resolve the desktop bundle itself — and deps.js, which already
|
|
74
|
-
// carries it, would pull the engine, the client and the tool registry into the
|
|
75
|
-
// renderer's require graph.
|
|
76
|
-
const { usageBuckets, estimateTokensFromCells } = require('./tokens.js');
|
|
77
|
-
// /ping — the terminal's half of the desktop's "reply ready" alert. Pure, so
|
|
78
|
-
// the loop only has to supply the stream and the elapsed time.
|
|
79
|
-
const { pingTurn } = require('./ping.js');
|
|
80
|
-
|
|
81
|
-
/** The rotating placeholder shown on an empty input line. */
|
|
82
|
-
const SUGGESTIONS = [
|
|
83
|
-
'edit <filepath> to...',
|
|
84
|
-
'refactor <filepath>',
|
|
85
|
-
'how do I log an error?',
|
|
86
|
-
'write a test for <filepath>',
|
|
87
|
-
'create a util logging.py that...',
|
|
88
|
-
];
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Terminal title spinner while a turn runs (the reference's frames). Owned by
|
|
92
|
-
* `title.js`, which also derives the topic the title carries; re-exported here
|
|
93
|
-
* because this module's export list is part of the tested surface.
|
|
94
|
-
*/
|
|
95
|
-
const { TITLE_SPIN, titleText, topicFrom, adoptTopic, titleEnabled, writeTitle } = require('./title.js');
|
|
96
|
-
const { GENERIC_TITLE, isGenericTitle } = require('./naming.js');
|
|
97
|
-
|
|
98
|
-
const FRAME_MS = 33; // ~30fps cap for streaming repaints
|
|
99
|
-
|
|
100
|
-
// ── pure turn helpers ───────────────────────────────────────────────────────
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* The shipped engine's shell tool is `exec` and its subagent tool is `task`
|
|
104
|
-
* (desktop/lib/local/tools.js). `Bash`/`Task` are Claude Code's names for the
|
|
105
|
-
* same two capabilities — this file was written against the reference's
|
|
106
|
-
* registry, so every branch below keyed on the reference's spelling and missed
|
|
107
|
-
* the tools that actually arrive: a shell row read "exec command" instead of
|
|
108
|
-
* "shell command", and a subagent row read "task command". Both spellings are
|
|
109
|
-
* accepted so either registry renders identically.
|
|
110
|
-
*/
|
|
111
|
-
function isShellTool(name) {
|
|
112
|
-
return name === 'exec' || name === 'Bash';
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
function isAgentTool(name) {
|
|
116
|
-
return name === 'task' || name === 'Task';
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/** The noun a tool row uses: "shell command", "subagent", "read command"… */
|
|
120
|
-
function toolLabel(name, n) {
|
|
121
|
-
const base =
|
|
122
|
-
isShellTool(name) ? 'shell command'
|
|
123
|
-
: isAgentTool(name) ? 'subagent'
|
|
124
|
-
: `${String(name).toLowerCase()} command`;
|
|
125
|
-
return n > 1 ? base + 's' : base;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* Resolve a tool "done" event to its running transcript row.
|
|
130
|
-
*
|
|
131
|
-
* Ids pair events exactly (parallel same-name calls, nested subagent rows);
|
|
132
|
-
* id-less streams fall back to name + agent matching. Mutates and returns the
|
|
133
|
-
* row, or null when nothing matches.
|
|
134
|
-
*/
|
|
135
|
-
function resolveToolDone(transcript, t) {
|
|
136
|
-
let idx = -1;
|
|
137
|
-
if (t.id !== undefined) {
|
|
138
|
-
for (let i = transcript.length - 1; i >= 0; i--) {
|
|
139
|
-
const m = transcript[i];
|
|
140
|
-
if (m.role === 'tool' && m.phase === 'run' && m.id === t.id) {
|
|
141
|
-
idx = i;
|
|
142
|
-
break;
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
if (idx === -1) {
|
|
147
|
-
for (let i = transcript.length - 1; i >= 0; i--) {
|
|
148
|
-
const m = transcript[i];
|
|
149
|
-
if (m.role === 'tool' && m.phase === 'run' && m.name === t.name && m.agent === t.agent) {
|
|
150
|
-
idx = i;
|
|
151
|
-
break;
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
if (idx === -1) return null;
|
|
156
|
-
const m = transcript[idx];
|
|
157
|
-
const n = transcript.filter(
|
|
158
|
-
(x, i) => x.role === 'tool' && x.name === t.name && x.agent === t.agent && i <= idx
|
|
159
|
-
).length;
|
|
160
|
-
m.phase = 'done';
|
|
161
|
-
m.elapsed = t.elapsed;
|
|
162
|
-
m.ok = t.ok;
|
|
163
|
-
m.label = `Ran ${n} ${m.agent ? `${m.agent} ▸ ` : ''}${toolLabel(t.name, n)}`;
|
|
164
|
-
return m;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
/**
|
|
168
|
-
* Tool names whose `file_path` means the file was WRITTEN, not read.
|
|
169
|
-
*
|
|
170
|
-
* The summary used to collect `args.file_path || args.path || args.notebook_path`
|
|
171
|
-
* from every tool, so any read-only call that names a file counted as a change:
|
|
172
|
-
* a turn that only looked at the home folder (`Read`, `Grep`, `Glob`, `List`)
|
|
173
|
-
* ended with "N files changed" under an answer that wrote nothing. The reader
|
|
174
|
-
* is asked to trust that line, so it may only fire on a tool that can mutate a
|
|
175
|
-
* file. `editFile`/`writeFile` are this host's spellings; `Write`/`Edit`/
|
|
176
|
-
* `MultiEdit`/`NotebookEdit` are the engine's — `cli/src/diff.js` accepts both,
|
|
177
|
-
* and this list must stay in step with it.
|
|
178
|
-
*/
|
|
179
|
-
const MUTATING_FILES = new Set([
|
|
180
|
-
'Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'editFile', 'writeFile',
|
|
181
|
-
]);
|
|
182
|
-
|
|
183
|
-
/**
|
|
184
|
-
* Fold one turn's tool events into the counts the end-of-turn summary prints.
|
|
185
|
-
*
|
|
186
|
-
* Deterministic and purely local, on purpose. The tail of every turn is the
|
|
187
|
-
* wrong place to spend a model call: it would bill the reader for a restatement
|
|
188
|
-
* of work they have already paid to have done, and it would arrive after a
|
|
189
|
-
* network round-trip instead of at the instant the turn ends. The data needed
|
|
190
|
-
* is already in the tool events — the engine hands us `ok` on every call and
|
|
191
|
-
* the args name every file and command — so the summary is arithmetic, not
|
|
192
|
-
* inference.
|
|
193
|
-
*
|
|
194
|
-
* @param {Array<{ok?:boolean,args?:object}>} tools This turn's tool events, in order.
|
|
195
|
-
* @returns {{tools:number,failed:number,files:string[],names:string[],more:number,commands:string[]}}
|
|
196
|
-
*/
|
|
197
|
-
function summarizeTurnTools(tools, { maxNames = 3 } = {}) {
|
|
198
|
-
const files = [];
|
|
199
|
-
const commands = [];
|
|
200
|
-
let failed = 0;
|
|
201
|
-
for (const tool of tools || []) {
|
|
202
|
-
if (!tool) continue;
|
|
203
|
-
if (tool.ok === false) failed += 1;
|
|
204
|
-
const args = tool.args;
|
|
205
|
-
if (!args || typeof args !== 'object') continue;
|
|
206
|
-
const writes = MUTATING_FILES.has(tool.name);
|
|
207
|
-
const file = writes ? args.file_path || args.path || args.notebook_path : null;
|
|
208
|
-
if (typeof file === 'string' && file && !files.includes(file)) files.push(file);
|
|
209
|
-
const cmd = args.command;
|
|
210
|
-
if (typeof cmd === 'string' && cmd.trim()) {
|
|
211
|
-
// First word only — the binary or builtin that ran, not its whole argv.
|
|
212
|
-
// "node /a/b/c.mjs --flag" reports as "node", which is what a one-line
|
|
213
|
-
// summary has room for.
|
|
214
|
-
const head = pathName(cmd.trim().split(/\s+/)[0]);
|
|
215
|
-
if (head && !commands.includes(head)) commands.push(head);
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
return {
|
|
219
|
-
tools: (tools || []).length,
|
|
220
|
-
failed,
|
|
221
|
-
files,
|
|
222
|
-
names: files.slice(0, maxNames).map((f) => pathName(f)),
|
|
223
|
-
more: Math.max(0, files.length - maxNames),
|
|
224
|
-
commands,
|
|
225
|
-
};
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
/**
|
|
229
|
-
* Finalize an assistant message's text: append a "(backend error: …)" marker
|
|
230
|
-
* when the turn failed mid-stream, a single "(stopped)" marker on abort, and
|
|
231
|
-
* fall back to "(no response)" for empty text. An abort wins over an error so
|
|
232
|
-
* Esc-cancel never produces the doubled marker.
|
|
233
|
-
*/
|
|
234
|
-
function finalizeTurnText(text, { aborted, error, reasoned } = {}) {
|
|
235
|
-
let t = String(text == null ? '' : text);
|
|
236
|
-
if (error && !aborted && error !== 'stopped') {
|
|
237
|
-
const err = `(backend error: ${error})`;
|
|
238
|
-
t = t.trim() ? `${t.trimEnd()}\n\n${err}` : err;
|
|
239
|
-
}
|
|
240
|
-
if (aborted) t = t.trim() ? `${t.trimEnd()} (stopped)` : '(stopped)';
|
|
241
|
-
if (!t.trim()) {
|
|
242
|
-
// A reasoning model that spends its whole token budget on hidden
|
|
243
|
-
// chain-of-thought finishes with empty content and no error. "(no
|
|
244
|
-
// response)" reads as a broken client for what is really an exhausted
|
|
245
|
-
// budget, and sends you looking for a bug that is not there.
|
|
246
|
-
t = reasoned
|
|
247
|
-
? '(no answer — the model used its whole budget on hidden reasoning before writing one; retry, or raise the budget with /effort)'
|
|
248
|
-
: '(no response)';
|
|
249
|
-
}
|
|
250
|
-
return t;
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
/** Every prior user/assistant pair, for the engine's conversation history. */
|
|
254
|
-
function historyPairs(rows) {
|
|
255
|
-
return rows
|
|
256
|
-
.filter((m) => m.role === 'user' || m.role === 'assistant')
|
|
257
|
-
.map((m) => ({ role: m.role, content: m.text }));
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
// A byok "anthropic:<model>" id's model half → the PRO_MODELS alias it reads
|
|
261
|
-
// closest to. 'default' when nothing matches, which is every dated/snapshot
|
|
262
|
-
// id (`claude-sonnet-4-20250514`) as much as a name this table has not been
|
|
263
|
-
// taught — the subscription's own default is a safer landing than guessing
|
|
264
|
-
// wrong.
|
|
265
|
-
const PRO_ALIAS_KEYWORDS = Object.freeze(['opus', 'haiku', 'sonnet']);
|
|
266
|
-
|
|
267
|
-
/**
|
|
268
|
-
* A picked "anthropic:<model>" byok row this machine has no console key for,
|
|
269
|
-
* but IS already signed into Claude Code Pro/Max for, is better served by the
|
|
270
|
-
* subscription it already pays for than by a prompt for a second credential
|
|
271
|
-
* it does not have — `engine.js`'s own refusal message for this exact state
|
|
272
|
-
* already says so ("Use the subscription instead: /class pro"); this is that
|
|
273
|
-
* suggestion applied at pick time instead of left for the user to notice in
|
|
274
|
-
* an error and type a second command.
|
|
275
|
-
*
|
|
276
|
-
* A row with a real console key already stored takes that key, unchanged —
|
|
277
|
-
* the override only fires when `modelKeyPlan` would otherwise have to ask for
|
|
278
|
-
* one. Pure and unit-testable: every fact it needs (whether a key is already
|
|
279
|
-
* stored, whether the subscription is signed in, the PRO_MODELS table) is
|
|
280
|
-
* injected rather than read from a live host/environment.
|
|
281
|
-
*
|
|
282
|
-
* @param {object} chosen a picker row ({id, cls, ...})
|
|
283
|
-
* @param {object} o
|
|
284
|
-
* @param {boolean} o.hasStored the byok provider store already holds an
|
|
285
|
-
* anthropic key (desktop Provider settings / `/byok-key anthropic`)
|
|
286
|
-
* @param {boolean} o.proLoggedIn this machine is signed into Claude Code Pro
|
|
287
|
-
* @param {boolean} o.proEnabled the `pro` class is enabled for this install
|
|
288
|
-
* (`/class pro on`); anything but `true` leaves the byok row untouched, so a
|
|
289
|
-
* disabled subscription can never be reached by this reroute
|
|
290
|
-
* @param {Array<{id:string,label:string,note:string}>} o.proModels
|
|
291
|
-
* `claudePro.PRO_MODELS`, injected rather than required here
|
|
292
|
-
* @returns {{row:object, message:string|null}} the row to actually pin (the
|
|
293
|
-
* original, unchanged, when the override does not apply) and a note to
|
|
294
|
-
* surface when it does
|
|
295
|
-
*/
|
|
296
|
-
function overrideAnthropicByokWithPro(chosen, o = {}) {
|
|
297
|
-
if (!chosen || chosen.cls !== 'byok') return { row: chosen, message: null };
|
|
298
|
-
const id = String(chosen.id || '');
|
|
299
|
-
const colon = id.indexOf(':');
|
|
300
|
-
if (colon < 0 || id.slice(0, colon).trim().toLowerCase() !== 'anthropic') {
|
|
301
|
-
return { row: chosen, message: null };
|
|
302
|
-
}
|
|
303
|
-
if (!o.needsKey) return { row: chosen, message: null }; // a real console key is already usable
|
|
304
|
-
if (!o.proLoggedIn) return { row: chosen, message: null }; // no subscription either — the normal prompt stands
|
|
305
|
-
// The `pro` class ships disabled (config.js `proEnabled`, `/class pro on`).
|
|
306
|
-
// This override silently MOVES a byok pick onto the subscription, so it must
|
|
307
|
-
// obey the same gate the picker and `/class` do — otherwise the one path a
|
|
308
|
-
// user never asked for is the path that still routes turns onto a
|
|
309
|
-
// subscription whose Claude Code access may be revoked, failing the turn with
|
|
310
|
-
// `oauth_org_not_allowed` after the pick already looked successful. Absent
|
|
311
|
-
// means "not stated" and is treated as disabled: fail closed.
|
|
312
|
-
if (o.proEnabled !== true) return { row: chosen, message: null };
|
|
313
|
-
const modelPart = id.slice(colon + 1).toLowerCase();
|
|
314
|
-
const proModels = Array.isArray(o.proModels) && o.proModels.length ? o.proModels : [{ id: 'default', label: 'Default', note: '' }];
|
|
315
|
-
const aliasId = PRO_ALIAS_KEYWORDS.find((kw) => modelPart.includes(kw)) || 'default';
|
|
316
|
-
const row = proModels.find((m) => m.id === aliasId) || proModels[0];
|
|
317
|
-
return {
|
|
318
|
-
row: { id: row.id, label: row.label, note: row.note, cls: 'pro' },
|
|
319
|
-
message:
|
|
320
|
-
`${id} has no Anthropic console key on this machine, but Claude Code Pro is signed in — ` +
|
|
321
|
-
`using the subscription instead (claude --model ${row.id}). Add a real console key any ` +
|
|
322
|
-
`time with /byok-key anthropic <key> to run this row directly.`,
|
|
323
|
-
};
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
/**
|
|
327
|
-
* Palette ranking query for a typed command line: "/memory tiers" must keep
|
|
328
|
-
* ranking on "memory" so the command stays listed while the user finishes the
|
|
329
|
-
* line; the ENTER branch passes the remainder as args. Single words unchanged.
|
|
330
|
-
*/
|
|
331
|
-
function paletteQuery(q) {
|
|
332
|
-
const t = String(q || '').trim();
|
|
333
|
-
return t.includes(' ') ? t.split(/\s+/)[0] : t;
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
// ── the frame ───────────────────────────────────────────────────────────────
|
|
337
|
-
|
|
338
|
-
/** The rounded header rule: `╭──── AEGIS Code v6.2.0 ────╮`. */
|
|
339
|
-
function headerLine(version, cols, ctx) {
|
|
340
|
-
const t = themeOf(ctx);
|
|
341
|
-
const label = ` AEGIS Code v${version} `;
|
|
342
|
-
const fill = Math.max(0, cols - [...label].length - 2);
|
|
343
|
-
const left = Math.floor(fill / 2);
|
|
344
|
-
return [span(t.coral, `╭${'─'.repeat(left)}${label}${'─'.repeat(fill - left)}╮`)];
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
const separatorLine = (cols, ctx) => [span(themeOf(ctx).dim, '─'.repeat(cols))];
|
|
348
|
-
|
|
349
|
-
/** The idle bottom-left line: which effort level the next turn runs at.
|
|
350
|
-
* Always one of the three rungs — `high` when the session has no stored rung,
|
|
351
|
-
* which is the value the request will actually carry (see effortRung). */
|
|
352
|
-
function effortLine(ctx, cols) {
|
|
353
|
-
const t = themeOf(ctx);
|
|
354
|
-
const txt = `● ${effortRung(ctx.effort)} · /effort`;
|
|
355
|
-
const pad = ' '.repeat(Math.max(0, cols - [...txt].length - 4));
|
|
356
|
-
return [span(t.gray, pad + txt)];
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
/**
|
|
360
|
-
* The non-peak colour of the shimmer that runs through the working verb,
|
|
361
|
-
* taken verbatim from the reference engine's spinner
|
|
362
|
-
* (`aegiscodex-dev/src/main.js`: `(i + frame) % 3 === 0 ? C.coral :
|
|
363
|
-
* RGB2(235, 159, 127)`).
|
|
364
|
-
*
|
|
365
|
-
* It is deliberately NOT a palette role, because the reference does not make it
|
|
366
|
-
* one either: `test/cli-conformance.test.mjs` pins this theme's roles to exactly
|
|
367
|
-
* the reference's set, so adding a `salmon` role would fail that guard for a
|
|
368
|
-
* colour the palette never owned.
|
|
369
|
-
*
|
|
370
|
-
* The previous value here was `gray`, and that is what made the live spinner
|
|
371
|
-
* read as washed out: two of every three shimmering characters were the same
|
|
372
|
-
* dim grey as finished output, so the one row that means "a turn is in flight"
|
|
373
|
-
* was painted in the colour of settled chrome. The tint is a warm salmon, one
|
|
374
|
-
* step lighter than `coral`, so the shimmer reads as motion at a glance.
|
|
375
|
-
*/
|
|
376
|
-
const SPINNER_TINT = RGB(235, 159, 127);
|
|
377
|
-
|
|
378
|
-
/**
|
|
379
|
-
* The working line: the `✻`-family spinner with a shimmering verb, the elapsed
|
|
380
|
-
* time and a token count — the reference's
|
|
381
|
-
* `✻ Tempering… (3s · ↓412 tokens)`.
|
|
382
|
-
*/
|
|
383
|
-
function spinnerLine(state, ctx) {
|
|
384
|
-
const t = themeOf(ctx);
|
|
385
|
-
const secs = Math.max(1, Math.round((state.elapsedMs || 0) / 1000));
|
|
386
|
-
const shimmer = [...(state.verb || VERBS[0])];
|
|
387
|
-
const frame = Math.floor((state.frame || 0) / 2) % 3;
|
|
388
|
-
const tinted = shimmer.map((ch, i) =>
|
|
389
|
-
span((i + frame) % 3 === 0 ? t.coral : SPINNER_TINT, ch)
|
|
390
|
-
);
|
|
391
|
-
// The tail is keyed on the thinking flag, NOT on whether anything has
|
|
392
|
-
// streamed yet. The reference branches the same way
|
|
393
|
-
// (`aegiscodex-dev/src/main.js`: `if (ctx.thinking) … else … ↓N tokens`).
|
|
394
|
-
// Gating on `state.streamed` instead meant every turn opened on
|
|
395
|
-
// `(0s · thinking)` — a tokenless tail that announced reasoning whether or not
|
|
396
|
-
// extended thinking was on — which is why the live token count was missing
|
|
397
|
-
// from the spinner while the model was working.
|
|
398
|
-
const tail = ctx && ctx.thinking
|
|
399
|
-
? span(t.gray, ` (${secs}s · thinking)`)
|
|
400
|
-
: span(t.gray, ` (${secs}s · ↓${state.streamedFloor ? '≥' : ''}${fmtTokens(state.streamed || 0)} tokens)`);
|
|
401
|
-
const glyph = GLYPH.spin[(state.frame || 0) % GLYPH.spin.length];
|
|
402
|
-
return [span(t.coral, glyph), ...tinted, span(t.white, '… '), tail];
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
/**
|
|
406
|
-
* The idle/modifier status line at the bottom of the frame.
|
|
407
|
-
*
|
|
408
|
-
* The idle form advertises `→`, the chord that switches the approval mode
|
|
409
|
-
* (manual ⇄ auto) — see the RIGHT branch in `handleKey`. It replaces the
|
|
410
|
-
* reference's "← for agents" hint, which this host printed on every idle frame
|
|
411
|
-
* while binding nothing to it: LEFT was wired only to `editor.left()`, so the
|
|
412
|
-
* one chord the status line offered did nothing. A hint for a key with no
|
|
413
|
-
* handler is worse than no hint, and the agents panel is reachable by the
|
|
414
|
-
* `/agents` command it was really standing in for.
|
|
415
|
-
*/
|
|
416
|
-
function statusLine(state, cols, ctx) {
|
|
417
|
-
const t = themeOf(ctx);
|
|
418
|
-
let left;
|
|
419
|
-
if (state.inputPrompt) {
|
|
420
|
-
left = [span(t.gray, 'enter to confirm · esc to cancel')];
|
|
421
|
-
} else if (state.working) {
|
|
422
|
-
left = [span(t.gray, ` ${GLYPH.bullet} esc to interrupt`)];
|
|
423
|
-
} else if (state.streamJob) {
|
|
424
|
-
left = [span(t.gray, `${GLYPH.bullet} esc to stop`)];
|
|
425
|
-
} else if (state.keyNotice) {
|
|
426
|
-
left = [span(t.gray, ` ${GLYPH.bullet} no AEGIS key: ${state.keyNotice} ${GLYPH.bullet} /key register to retry`)];
|
|
427
|
-
} else if (state.yolo) {
|
|
428
|
-
left = [span(t.gray, `${GLYPH.bullet} automode on ${GLYPH.bullet} ${autoContinueLimit()} rounds then it asks ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for manual mode`)];
|
|
429
|
-
} else {
|
|
430
|
-
left = [span(t.gray, `${GLYPH.pause} manual mode on ${GLYPH.bullet} ? for shortcuts ${GLYPH.bullet} ${GLYPH.rightarrow} for auto mode`)];
|
|
431
|
-
}
|
|
432
|
-
return padLine(left, cols);
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
/**
|
|
436
|
-
* The `?` shortcuts grid. Every row advertised here is a key this CLI actually
|
|
437
|
-
* handles — the reference sheet also lists chords this host never wired up
|
|
438
|
-
* (shift+tab, `\`+return, `@`, ctrl+z/v/g…), and a cheat-sheet of dead keys is
|
|
439
|
-
* worse than none. Add a row only alongside its handler in `handleKey`.
|
|
440
|
-
*/
|
|
441
|
-
function shortcutsGrid(cols, ctx) {
|
|
442
|
-
const t = themeOf(ctx);
|
|
443
|
-
const cell = (a, b, c, d) => [
|
|
444
|
-
span('', ' '), span(t.white, a), span(t.gray, ' ' + b),
|
|
445
|
-
span('', ' '), span(t.white, c), span(t.gray, ' ' + d),
|
|
446
|
-
];
|
|
447
|
-
return [
|
|
448
|
-
cell('/', 'for commands', '?', 'for shortcuts'),
|
|
449
|
-
cell('ctrl + c', 'to quit', 'ctrl + o', 'for permissions'),
|
|
450
|
-
cell('alt + p', 'to switch model', 'alt + t', 'to toggle thinking'),
|
|
451
|
-
// The shift chords the two pickers commit with. They are on the sheet for
|
|
452
|
-
// the same reason every other row is: `handleOverlayKey` handles them now,
|
|
453
|
-
// and a key a user cannot read about is a key that does not exist.
|
|
454
|
-
cell('shift + ↑/↓', 'pins as it moves', 'shift + enter', 'runs the row'),
|
|
455
|
-
cell('esc', 'to interrupt a turn', 'ctrl + l', 'to clear the screen'),
|
|
456
|
-
cell('ctrl + t', 'to show tokens', 'ctrl + r', 'to resume a session'),
|
|
457
|
-
cell('↑ / ↓', 'for history', 'tab', 'to complete a command'),
|
|
458
|
-
];
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
/**
|
|
462
|
-
* The engine's approval vocabulary — and the ONLY tokens that survive
|
|
463
|
-
* `respondApproval` (see cli/vendor/desktop/lib/local/engine.js). It accepts
|
|
464
|
-
* 'once' and 'session' and coerces EVERYTHING ELSE to 'deny'.
|
|
465
|
-
*
|
|
466
|
-
* This overlay used to answer 'allow': the desktop renderer's word for "yes",
|
|
467
|
-
* not the engine's. So a user who pressed "1. Yes" was denied anyway — silently,
|
|
468
|
-
* on every mutating tool, every time. The model then read "the user denied the
|
|
469
|
-
* request" and retried with a different command, which was denied too, and the
|
|
470
|
-
* turn burned several rounds of tokens to accomplish nothing. Emitting the
|
|
471
|
-
* engine's own words is the whole fix; `test/cli-approval.test.mjs` pins it so
|
|
472
|
-
* the two vocabularies cannot drift apart again.
|
|
473
|
-
*/
|
|
474
|
-
const APPROVE_ONCE = 'once';
|
|
475
|
-
const APPROVE_SESSION = 'session';
|
|
476
|
-
const DENY_TOKEN = 'deny';
|
|
477
|
-
|
|
478
|
-
/** Choice labels, in overlay order. Index maps 1:1 onto DECISIONS. */
|
|
479
|
-
const APPROVAL_CHOICES = ['Yes', 'Yes, allow for this session', 'No'];
|
|
480
|
-
const APPROVAL_DECISIONS = [APPROVE_ONCE, APPROVE_SESSION, DENY_TOKEN];
|
|
481
|
-
|
|
482
|
-
/** The tool-approval dialog body. */
|
|
483
|
-
function confirmLines(overlay, cols, ctx) {
|
|
484
|
-
const t = themeOf(ctx);
|
|
485
|
-
const lines = [];
|
|
486
|
-
lines.push([span(t.gray, '─'.repeat(Math.min(Math.max(10, cols - 4), 80)))]);
|
|
487
|
-
lines.push([span(t.white, `${isShellTool(overlay.name) ? 'shell' : overlay.name} command`)]);
|
|
488
|
-
lines.push([span('', '')]);
|
|
489
|
-
// `exec` carries its subject in `command`; readFile/writeFile/editFile in
|
|
490
|
-
// `file_path`; glob/grep in `pattern`. Keying this on the reference's `Bash`
|
|
491
|
-
// sent every shell approval into the file branch, so the dialog that asks
|
|
492
|
-
// "Do you want to proceed?" showed an empty body — you were approving a
|
|
493
|
-
// command you could not see.
|
|
494
|
-
const subject =
|
|
495
|
-
isShellTool(overlay.name)
|
|
496
|
-
? String((overlay.args && overlay.args.command) || '')
|
|
497
|
-
: String((overlay.args && (overlay.args.file_path || overlay.args.pattern)) || '');
|
|
498
|
-
for (const l of wrapBlock(subject, Math.max(8, cols - 4))) lines.push([span(t.gray, l)]);
|
|
499
|
-
lines.push([span('', '')]);
|
|
500
|
-
lines.push([span(t.white, 'Do you want to proceed?')]);
|
|
501
|
-
const opt = (i, label) => {
|
|
502
|
-
const active = overlay.sel === i;
|
|
503
|
-
const left = active ? span(t.lavender, GLYPH.cursor) : span('', ' ');
|
|
504
|
-
return [left, span(t.gray, ` ${i + 1}. `), span(active ? t.lavender : t.white, label)];
|
|
505
|
-
};
|
|
506
|
-
const toolName = overlay.name || 'this tool';
|
|
507
|
-
APPROVAL_CHOICES.forEach((label, i) => {
|
|
508
|
-
// The session option names the tool it will stop asking about, so the
|
|
509
|
-
// blanket allow is never something the user has to infer.
|
|
510
|
-
const text = i === 1 ? `Yes, and allow ${toolName} for this session` : label;
|
|
511
|
-
lines.push(opt(i, text));
|
|
512
|
-
});
|
|
513
|
-
lines.push([span('', '')]);
|
|
514
|
-
lines.push([span(t.gray, 'Esc to cancel')]);
|
|
515
|
-
return lines;
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
/**
|
|
519
|
-
* Automatic round-budget continuations automode may take before it has to
|
|
520
|
-
* ask for real — mirrors the upstream engine's `autoContinuePlan`
|
|
521
|
-
* (aegiscodex-dev's src/autonomous.js). Not "run forever": after `limit`
|
|
522
|
-
* silent yeses the real dialog is shown, so a turn that is genuinely stuck
|
|
523
|
-
* still puts a human in the loop. Pure, and exported, so the policy itself
|
|
524
|
-
* (not just the dialog it feeds) is directly testable.
|
|
525
|
-
*
|
|
526
|
-
* { auto: true, used: n } → answer the ask with "continue", no dialog
|
|
527
|
-
* { auto: false, used: 0 } → show the real dialog (allowance just spent)
|
|
528
|
-
* { auto: false, used: n } → show the real dialog (automode is off)
|
|
529
|
-
*/
|
|
530
|
-
const AUTO_CONTINUE_LIMIT = 3;
|
|
531
|
-
/**
|
|
532
|
-
* The allowance, honouring `AEGIS_AUTO_CONTINUE_MAX` exactly as the upstream
|
|
533
|
-
* engine's `autoContinueLimit` does (aegiscodex-dev's src/autonomous.js). Read
|
|
534
|
-
* per call, not frozen at module load, so a test or a wrapper can move the
|
|
535
|
-
* allowance without a reload — and so the number the status line advertises
|
|
536
|
-
* ("N rounds then it asks") is the number the plan will actually spend.
|
|
537
|
-
*/
|
|
538
|
-
function autoContinueLimit(env = process.env) {
|
|
539
|
-
const n = Number.parseInt(env && env.AEGIS_AUTO_CONTINUE_MAX, 10);
|
|
540
|
-
return Number.isFinite(n) && n > 0 ? n : AUTO_CONTINUE_LIMIT;
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
function autoContinuePlan({ on = false, used = 0, limit = autoContinueLimit() } = {}) {
|
|
544
|
-
const cap = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : AUTO_CONTINUE_LIMIT;
|
|
545
|
-
const spent = Number.isFinite(used) && used > 0 ? Math.floor(used) : 0;
|
|
546
|
-
if (!on) return { auto: false, used: spent, cap };
|
|
547
|
-
if (spent >= cap) return { auto: false, used: 0, cap };
|
|
548
|
-
return { auto: true, used: spent + 1, cap };
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
/** The round-budget extension dialog body — same shape as confirmLines, but
|
|
552
|
-
* the subject is a round budget rather than a tool call. */
|
|
553
|
-
function roundsLines(overlay, cols, ctx) {
|
|
554
|
-
const t = themeOf(ctx);
|
|
555
|
-
const lines = [];
|
|
556
|
-
lines.push([span(t.gray, '─'.repeat(Math.min(Math.max(10, cols - 4), 80)))]);
|
|
557
|
-
lines.push([span(t.white, `${overlay.spent}-round tool limit reached`)]);
|
|
558
|
-
lines.push([span('', '')]);
|
|
559
|
-
for (const l of wrapBlock(
|
|
560
|
-
'The turn is still working — it ended its last round on a tool call instead of an answer.',
|
|
561
|
-
Math.max(8, cols - 4)
|
|
562
|
-
)) {
|
|
563
|
-
lines.push([span(t.gray, l)]);
|
|
564
|
-
}
|
|
565
|
-
lines.push([span('', '')]);
|
|
566
|
-
const opt = (i, label) => {
|
|
567
|
-
const active = overlay.sel === i;
|
|
568
|
-
const left = active ? span(t.lavender, GLYPH.cursor) : span('', ' ');
|
|
569
|
-
return [left, span(t.gray, ` ${i + 1}. `), span(active ? t.lavender : t.white, label)];
|
|
570
|
-
};
|
|
571
|
-
lines.push(opt(0, `Yes, continue with ${overlay.size} more rounds`));
|
|
572
|
-
lines.push(opt(1, 'No, stop here and answer with what I have'));
|
|
573
|
-
lines.push([span('', '')]);
|
|
574
|
-
lines.push([span(t.gray, `extension ${overlay.extensions} of ${overlay.max} · Esc to stop`)]);
|
|
575
|
-
return lines;
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
/**
|
|
579
|
-
* The accounting bits for a turn — model, tokens, the in/out split, €, elapsed
|
|
580
|
-
* and call count. Shared by the standalone `meta` row and the folded footer, so
|
|
581
|
-
* the two can never drift apart.
|
|
582
|
-
*
|
|
583
|
-
* `omitMs` drops the client-call time: when the bits ride on the `✻ Churned for
|
|
584
|
-
* 6s` row, that row already states the wall time, and printing a second,
|
|
585
|
-
* slightly different duration beside it reads as a discrepancy.
|
|
586
|
-
*/
|
|
587
|
-
function metaBits(m, t, { omitMs = false } = {}) {
|
|
588
|
-
const bits = [];
|
|
589
|
-
if (m.model) bits.push(span(t.blue, m.model));
|
|
590
|
-
// Same figure as the standalone meta row, from the one helper both call:
|
|
591
|
-
// OUTPUT only, in `white`, the token the total used to get. The
|
|
592
|
-
// input-inclusive total is not printed beside it — on a cached turn it is the
|
|
593
|
-
// prompt restated, and showing `156,189 tok` next to `5,014 tokens` is what made
|
|
594
|
-
// the row read as a runaway. When no output figure arrived the row states
|
|
595
|
-
// NOTHING rather than the total: `m.tokens` is input + output, so falling back
|
|
596
|
-
// to it put the input half back under an unlabelled figure — the leak the
|
|
597
|
-
// desktop closed in `displayTokens`, closed here the same way. A row with no
|
|
598
|
-
// measurable output is better empty than stating a total the reader cannot tell
|
|
599
|
-
// from the answer's size.
|
|
600
|
-
const parts = fmtUsageSplit(m);
|
|
601
|
-
if (parts) bits.push(span(t.white, parts.output));
|
|
602
|
-
else {
|
|
603
|
-
const produced = displayTokens(m);
|
|
604
|
-
if (produced != null) bits.push(span(t.white, `${fmtTokens(produced)} tokens`));
|
|
605
|
-
}
|
|
606
|
-
// No money on a tier AEGIS bills no fee to, nor from an unproven snapshot
|
|
607
|
-
// (`feeBillable`) — the desktop's rule, and the same one the standalone meta
|
|
608
|
-
// row uses, so the two renderers of this row cannot disagree about a fee.
|
|
609
|
-
if (m.eur != null && feeBillable()) bits.push(span(m.eur > 0 ? t.coral : t.green, fmtEur(m.eur)));
|
|
610
|
-
if (m.ms != null && !omitMs) bits.push(span(t.gray, fmtElapsed(m.ms)));
|
|
611
|
-
if (m.calls > 1) bits.push(span(t.gray, `${m.calls} calls`));
|
|
612
|
-
return bits;
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
/** Interleave accounting bits with the `·` separator. */
|
|
616
|
-
function joinBits(bits, t) {
|
|
617
|
-
const line = [];
|
|
618
|
-
bits.forEach((b, i) => {
|
|
619
|
-
if (i) line.push(span(t.dim, ` ${GLYPH.bullet} `));
|
|
620
|
-
line.push(b);
|
|
621
|
-
});
|
|
622
|
-
return line;
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
/** Longest directory a row prints before it is contracted from the front. */
|
|
626
|
-
const DIR_MAX = 40;
|
|
627
|
-
|
|
628
|
-
/**
|
|
629
|
-
* A row's working directory, contracted for display: the home prefix becomes
|
|
630
|
-
* `~`, and a path still too long keeps its tail — the leaf is what identifies
|
|
631
|
-
* the checkout, the ancestors are the part a reader can spare. Returns '' when
|
|
632
|
-
* the host didn't say, so a row never implies a directory it doesn't know.
|
|
633
|
-
*/
|
|
634
|
-
function shortDir(dir) {
|
|
635
|
-
let p = String(dir == null ? '' : dir).trim().replace(/\/+$/, '');
|
|
636
|
-
if (!p) return '';
|
|
637
|
-
const home = String(process.env.HOME || process.env.USERPROFILE || '').replace(/\/+$/, '');
|
|
638
|
-
if (home && (p === home || p.startsWith(`${home}/`))) p = `~${p.slice(home.length)}`;
|
|
639
|
-
if (p.length > DIR_MAX) p = `${GLYPH.ellipse}${p.slice(-(DIR_MAX - 1))}`;
|
|
640
|
-
return p;
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
/** Render one transcript row to span lines. */
|
|
644
|
-
function rowLines(msg, cols, ctx, now = Date.now()) {
|
|
645
|
-
const t = themeOf(ctx);
|
|
646
|
-
const out = [];
|
|
647
|
-
if (msg.role === 'tool') {
|
|
648
|
-
// One ellipsis per row. The label already ends in one ("Running 1 shell
|
|
649
|
-
// command…") and this appended a second after the seconds, so the row read
|
|
650
|
-
// "Running 1 shell command… · 3s…" — two ellipses on one line. Normalising
|
|
651
|
-
// the label here rather than at the call site means the row stays correct
|
|
652
|
-
// whatever a host puts in `label`.
|
|
653
|
-
const label = String(msg.label || '').replace(/(?:…|\.\.\.)+$/, '');
|
|
654
|
-
// Where it runs. A tool row's args are the command or the path, so without
|
|
655
|
-
// this the transcript cannot answer "where is it working in".
|
|
656
|
-
const where = msg.cwd ? ` · ${shortDir(msg.cwd)}` : '';
|
|
657
|
-
if (msg.phase === 'run') {
|
|
658
|
-
const secs = msg.start ? Math.max(1, Math.round((now - msg.start) / 1000)) : 0;
|
|
659
|
-
// No leading `●` bullet on a running-command row: the label plus its
|
|
660
|
-
// elapsed seconds already say what is happening, and the bullet made a
|
|
661
|
-
// live turn read as a list of bullets. It also kept the running row one
|
|
662
|
-
// column right of the finished row it collapses into, so the transcript
|
|
663
|
-
// shifted sideways the moment the command completed.
|
|
664
|
-
out.push([span(t.gray, `${label}${GLYPH.ellipse} · ${secs}s${where}`)]);
|
|
665
|
-
} else {
|
|
666
|
-
out.push([span(t.gray, `${label}${where}`)]);
|
|
667
|
-
}
|
|
668
|
-
// An editFile/writeFile row carries a diff preview (built from the tool's
|
|
669
|
-
// `run` frame, before the executor reads/writes). Paint the colored block —
|
|
670
|
-
// summary always, body when open — instead of the gray `$ {args}` row, so
|
|
671
|
-
// the transcript shows *what* changed. renderDiffBlock emits ANSI strings,
|
|
672
|
-
// so each becomes one pre-styled span whose visible width padLine still
|
|
673
|
-
// measures and pads correctly.
|
|
674
|
-
if (msg.diff) {
|
|
675
|
-
for (const l of renderDiffBlock(msg.diff, ctx, cols, { open: !!msg.diffOpen })) {
|
|
676
|
-
out.push([span('', l)]);
|
|
677
|
-
}
|
|
678
|
-
return out;
|
|
679
|
-
}
|
|
680
|
-
const argsStr =
|
|
681
|
-
typeof msg.args === 'string'
|
|
682
|
-
? msg.args
|
|
683
|
-
: msg.args && typeof msg.args === 'object'
|
|
684
|
-
? msg.args.command ?? msg.args.file_path ?? msg.args.description ??
|
|
685
|
-
Object.values(msg.args).find((v) => typeof v === 'string') ?? ''
|
|
686
|
-
: '';
|
|
687
|
-
if (argsStr) out.push([span(t.gray, ` ${GLYPH.hook} $ ${String(argsStr)}`)]);
|
|
688
|
-
return out;
|
|
689
|
-
}
|
|
690
|
-
if (msg.role === 'note') {
|
|
691
|
-
out.push([span(t.gray, `· ${msg.text}`)]);
|
|
692
|
-
return out;
|
|
693
|
-
}
|
|
694
|
-
if (msg.role === 'tip') {
|
|
695
|
-
for (const l of wrapBlock(String(msg.text), cols)) out.push([span(t.gray, l)]);
|
|
696
|
-
return out;
|
|
697
|
-
}
|
|
698
|
-
if (msg.role === 'done') {
|
|
699
|
-
// Real 2.1.211: "✻ Churned for 6s" — bloom glyph + gray text. The turn's
|
|
700
|
-
// accounting rides on this same row (see the turn's finally block): one
|
|
701
|
-
// footer per turn instead of a done row plus a second `⎿` row beneath it.
|
|
702
|
-
const line = [span(t.gray, GLYPH.bloom), span(t.gray, ` ${msg.text}`)];
|
|
703
|
-
if (msg.meta) {
|
|
704
|
-
const bits = metaBits(msg.meta, t, { omitMs: true });
|
|
705
|
-
if (bits.length) line.push(span(t.dim, ' '), ...joinBits(bits, t));
|
|
706
|
-
}
|
|
707
|
-
out.push(line);
|
|
708
|
-
return out;
|
|
709
|
-
}
|
|
710
|
-
if (msg.role === 'summary') {
|
|
711
|
-
// The end-of-turn delta line. Rendered as the LAST row of the turn so the
|
|
712
|
-
// bottom of the screen answers "what did that actually do?" without the
|
|
713
|
-
// reader scrolling back up through the tool rows that produced it.
|
|
714
|
-
const s = msg.counts || {};
|
|
715
|
-
if (!s.tools) return out;
|
|
716
|
-
const line = [span(t.dim, GLYPH.hook), span('', ' ')];
|
|
717
|
-
const bits = [
|
|
718
|
-
span(t.white, String(s.tools)),
|
|
719
|
-
span(t.gray, ` ${s.tools === 1 ? 'command' : 'commands'}`),
|
|
720
|
-
];
|
|
721
|
-
if (s.files && s.files.length) {
|
|
722
|
-
bits.push(span(t.gray, ` ${GLYPH.bullet} `));
|
|
723
|
-
bits.push(
|
|
724
|
-
span(t.white, String(s.files.length)),
|
|
725
|
-
span(t.gray, ` ${s.files.length === 1 ? 'file changed' : 'files changed'}`)
|
|
726
|
-
);
|
|
727
|
-
}
|
|
728
|
-
if (s.failed) {
|
|
729
|
-
bits.push(span(t.gray, ` ${GLYPH.bullet} `));
|
|
730
|
-
bits.push(span(t.coral, `${s.failed} failed`));
|
|
731
|
-
}
|
|
732
|
-
if (s.names && s.names.length) {
|
|
733
|
-
const more = s.more ? ` +${s.more}` : '';
|
|
734
|
-
bits.push(span(t.dim, ` ${s.names.join(', ')}${more}`));
|
|
735
|
-
}
|
|
736
|
-
line.push(...bits);
|
|
737
|
-
out.push(line);
|
|
738
|
-
return out;
|
|
739
|
-
}
|
|
740
|
-
if (msg.role === 'meta') {
|
|
741
|
-
// Deliberate divergence from the reference: this client's reason to exist
|
|
742
|
-
// is showing what a turn consumed, so the accounting line is a transcript
|
|
743
|
-
// row rather than something only /cost can reveal. Kept for rows that have
|
|
744
|
-
// no `done` row to fold into (and for hosts that emit it standalone).
|
|
745
|
-
const bits = metaBits(msg.meta || {}, t);
|
|
746
|
-
if (bits.length) out.push([span(t.dim, `${GLYPH.hook} `), ...joinBits(bits, t)]);
|
|
747
|
-
return out;
|
|
748
|
-
}
|
|
749
|
-
if (msg.role === 'panel') {
|
|
750
|
-
for (const l of msg.lines || []) out.push(padLine(l, cols));
|
|
751
|
-
out.push([span('', '')]);
|
|
752
|
-
return out;
|
|
753
|
-
}
|
|
754
|
-
if (msg.role === 'error') {
|
|
755
|
-
out.push([span(t.red, `✗ ${msg.text}`)]);
|
|
756
|
-
return out;
|
|
757
|
-
}
|
|
758
|
-
if (msg.role === 'user') {
|
|
759
|
-
const body = wrapBlock(String(msg.text), Math.max(8, cols - 2));
|
|
760
|
-
body.forEach((l, i) => {
|
|
761
|
-
if (i === 0) out.push([span(t.gray, GLYPH.cursor), span('', ' '), span(t.white, l)]);
|
|
762
|
-
else out.push([span('', ' '), span(t.white, l)]);
|
|
763
|
-
});
|
|
764
|
-
return out;
|
|
765
|
-
}
|
|
766
|
-
// assistant (and anything else textual)
|
|
767
|
-
const rendered = msg.role === 'assistant'
|
|
768
|
-
? renderMarkdown(String(msg.text == null ? '' : msg.text), cols, ctx)
|
|
769
|
-
: wrapBlock(String(msg.text == null ? '' : msg.text), cols).map((l) => [span(t.white, l)]);
|
|
770
|
-
const segment = rendered.length ? rendered : [[span('', '')]];
|
|
771
|
-
for (let i = 0; i < segment.length; i++) {
|
|
772
|
-
const line = segment[i].slice();
|
|
773
|
-
if (i === 0) line.unshift(span(t.white, GLYPH.block), span('', ' '));
|
|
774
|
-
out.push(line);
|
|
775
|
-
}
|
|
776
|
-
// No trailing cursor glyph. This used to append a second `●` to the last line
|
|
777
|
-
// of a still-growing answer whenever the message occupied more than one row,
|
|
778
|
-
// which made the glyph count a function of how the text WRAPPED: a one-line
|
|
779
|
-
// answer was `● Working`, a two-line answer was `● Working●`. Two dots where
|
|
780
|
-
// the reader expects one, and the asymmetry landed on exactly the long answers
|
|
781
|
-
// a person is most likely to read — the marker is the message's opening
|
|
782
|
-
// gutter, not a bracket. A streaming turn is already advertised by the working
|
|
783
|
-
// line below (`renderWorking`) and by the head marker being the same one the
|
|
784
|
-
// finished row keeps, so the tail glyph carried no information the reader did
|
|
785
|
-
// not already have.
|
|
786
|
-
return out;
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
/**
|
|
790
|
-
* Build the visible transcript window.
|
|
791
|
-
*
|
|
792
|
-
* Two things here are load-bearing:
|
|
793
|
-
*
|
|
794
|
-
* · finished rows are cached by identity + text + cols, because re-running
|
|
795
|
-
* markdown over the whole transcript on every frame during a streaming burst
|
|
796
|
-
* is an O(transcript) reparse up to 30x/sec and freezes input;
|
|
797
|
-
* · while scrolled up the window anchors to an ABSOLUTE line index
|
|
798
|
-
* (`anchorEnd`) rather than a bottom-relative offset, so rows appended below
|
|
799
|
-
* the window (streaming deltas, tool rows — `total` grows every frame) leave
|
|
800
|
-
* the reader's position alone instead of sliding it toward the bottom.
|
|
801
|
-
*
|
|
802
|
-
* @returns {{lines:Array, scroll:number, anchorEnd:number|null}}
|
|
803
|
-
*/
|
|
804
|
-
function transcriptLines(rows, view, ctx, now = Date.now(), cache = null) {
|
|
805
|
-
const { cols, rows: termRows } = view;
|
|
806
|
-
const avail = Math.max(1, termRows - 6);
|
|
807
|
-
const out = [];
|
|
808
|
-
// Which transcript row produced each line, in lockstep with `out`. The frame
|
|
809
|
-
// builder needs it to map a clicked screen row back to the row it toggles.
|
|
810
|
-
const owners = [];
|
|
811
|
-
for (const msg of rows) {
|
|
812
|
-
const key = cache || null;
|
|
813
|
-
// Rows whose rendering depends on the CLOCK cannot be cached on their text.
|
|
814
|
-
// A streaming assistant row grows (`isGrower`), and a running tool row
|
|
815
|
-
// carries `${label} · ${secs}s` — its text is fixed while `now - start`
|
|
816
|
-
// climbs, so caching it froze the row at the second it first painted and a
|
|
817
|
-
// long-running tool read `· 1s` for as long as it ran. The same entry then
|
|
818
|
-
// survived the run → done collapse (resolveToolDone mutates the row in
|
|
819
|
-
// place and leaves `text` undefined, so the cache key still matched) and the
|
|
820
|
-
// finished row kept saying "Running 1 shell command… · 1s" for a command
|
|
821
|
-
// that had already returned. Neither row is cached; both are cheap to
|
|
822
|
-
// re-render, and the expensive rows (markdown answers) still are.
|
|
823
|
-
const isLive =
|
|
824
|
-
(msg.role === 'assistant' && msg.streaming) ||
|
|
825
|
-
(msg.role === 'tool' && msg.phase === 'run');
|
|
826
|
-
if (key && !isLive) {
|
|
827
|
-
const hit = key.get(msg);
|
|
828
|
-
// diffOpen is part of the cache key: a toggled edit block must re-render.
|
|
829
|
-
if (hit && hit.text === msg.text && hit.cols === cols && hit.diffOpen === msg.diffOpen) {
|
|
830
|
-
for (const l of hit.segment) {
|
|
831
|
-
out.push(l);
|
|
832
|
-
owners.push(msg);
|
|
833
|
-
}
|
|
834
|
-
continue;
|
|
835
|
-
}
|
|
836
|
-
const segment = rowLines(msg, cols, ctx, now);
|
|
837
|
-
key.set(msg, { text: msg.text, cols, diffOpen: msg.diffOpen, segment });
|
|
838
|
-
for (const l of segment) {
|
|
839
|
-
out.push(l);
|
|
840
|
-
owners.push(msg);
|
|
841
|
-
}
|
|
842
|
-
continue;
|
|
843
|
-
}
|
|
844
|
-
for (const l of rowLines(msg, cols, ctx, now)) {
|
|
845
|
-
out.push(l);
|
|
846
|
-
owners.push(msg);
|
|
847
|
-
}
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
let scroll = view.scroll || 0;
|
|
851
|
-
let anchorEnd = view.anchorEnd == null ? null : view.anchorEnd;
|
|
852
|
-
const total = out.length;
|
|
853
|
-
const maxScroll = Math.max(0, total - avail);
|
|
854
|
-
if (scroll > maxScroll) scroll = maxScroll;
|
|
855
|
-
let end;
|
|
856
|
-
if (scroll === 0) {
|
|
857
|
-
anchorEnd = null;
|
|
858
|
-
end = total;
|
|
859
|
-
} else {
|
|
860
|
-
if (anchorEnd === null) anchorEnd = Math.max(0, total - scroll);
|
|
861
|
-
end = Math.min(anchorEnd, total);
|
|
862
|
-
}
|
|
863
|
-
if (total <= avail) {
|
|
864
|
-
scroll = 0;
|
|
865
|
-
anchorEnd = null;
|
|
866
|
-
end = total;
|
|
867
|
-
}
|
|
868
|
-
const start = Math.max(0, end - avail);
|
|
869
|
-
return { lines: out.slice(start, end), owners: owners.slice(start, end), scroll, anchorEnd };
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
// ── the input line ──────────────────────────────────────────────────────────
|
|
873
|
-
|
|
874
|
-
/**
|
|
875
|
-
* The visible text of the input row. A pasted multi-line buffer collapses to a
|
|
876
|
-
* one-line preview ("head … (+N lines)") while `editor.buf` keeps the full
|
|
877
|
-
* text, so submit still sends everything — a raw '\n' painted into a one-row
|
|
878
|
-
* input would move the terminal to a new line mid-paint.
|
|
879
|
-
*/
|
|
880
|
-
function inputPreviewText(buf) {
|
|
881
|
-
const nl = buf.indexOf('\n');
|
|
882
|
-
if (nl === -1) return buf;
|
|
883
|
-
const n = buf.split('\n').length - 1;
|
|
884
|
-
return `${buf.slice(0, nl)} … (+${n} line${n === 1 ? '' : 's'})`;
|
|
885
|
-
}
|
|
886
|
-
|
|
887
|
-
/** Cells available to the input buffer (2 for "❯ ", 1 spare). */
|
|
888
|
-
const inputRowCells = (cols) => Math.max(1, cols - 3);
|
|
889
|
-
|
|
890
|
-
const bufCells = (buf) => [...buf].reduce((a, ch) => a + w(ch), 0);
|
|
891
|
-
|
|
892
|
-
function cursorCells(buf, cursor) {
|
|
893
|
-
const arr = [...buf];
|
|
894
|
-
let n = 0;
|
|
895
|
-
for (let i = 0; i < Math.min(cursor, arr.length); i++) n += w(arr[i]);
|
|
896
|
-
return n;
|
|
897
|
-
}
|
|
898
|
-
|
|
899
|
-
/**
|
|
900
|
-
* Horizontal viewport for the input row, so the buffer scrolls once it is wider
|
|
901
|
-
* than the row instead of running off the right edge while the user types.
|
|
902
|
-
*/
|
|
903
|
-
function inputScroll(buf, cursor, cols) {
|
|
904
|
-
const avail = inputRowCells(cols);
|
|
905
|
-
const bw = bufCells(buf);
|
|
906
|
-
if (bw <= avail) return 0;
|
|
907
|
-
// The '…' indicator occupies a cell, so the visible window is one narrower
|
|
908
|
-
// once scrolling starts; without this the cursor parks past the last glyph.
|
|
909
|
-
const vis = avail - 1;
|
|
910
|
-
return Math.max(0, Math.min(cursorCells(buf, cursor) - vis, bw - vis));
|
|
911
|
-
}
|
|
912
|
-
|
|
913
|
-
/** First codepoint index of the visible window for a scroll offset. */
|
|
914
|
-
function inputStart(buf, scroll) {
|
|
915
|
-
const arr = [...buf];
|
|
916
|
-
let cells = 0;
|
|
917
|
-
for (let i = 0; i < arr.length; i++) {
|
|
918
|
-
if (cells >= scroll) return i;
|
|
919
|
-
cells += w(arr[i]);
|
|
920
|
-
}
|
|
921
|
-
return arr.length;
|
|
922
|
-
}
|
|
923
|
-
|
|
924
|
-
/**
|
|
925
|
-
* The input row as span lines.
|
|
926
|
-
* @returns {{line:Array, cursorCol:number}}
|
|
927
|
-
*/
|
|
928
|
-
function inputLine(state, cols, ctx) {
|
|
929
|
-
const t = themeOf(ctx);
|
|
930
|
-
// Two cells ("❯ "), matching the reference. The cursor columns below are all
|
|
931
|
-
// `3 + w(text before the caret)`, which is only correct if the typed text
|
|
932
|
-
// starts in cell 3 — a third prefix cell pushed the text to cell 4 and left
|
|
933
|
-
// the caret one cell short, i.e. sitting *on* the last typed character.
|
|
934
|
-
const line = [span(t.gray, GLYPH.cursor), span('', ' ')];
|
|
935
|
-
if (state.inputPrompt) {
|
|
936
|
-
line.push(span(t.white, `${state.inputPrompt.title}: `));
|
|
937
|
-
for (const ch of [...state.inputPrompt.buf]) line.push(span(t.white, ch));
|
|
938
|
-
const col = Math.min(3 + w(state.inputPrompt.title) + 2 + w(state.inputPrompt.buf), cols);
|
|
939
|
-
return { line: padLine(line, cols), cursorCol: col };
|
|
940
|
-
}
|
|
941
|
-
if (state.working) {
|
|
942
|
-
// During generation the input line stays empty (the spinner lives above).
|
|
943
|
-
return { line: padLine(line, cols), cursorCol: 3 };
|
|
944
|
-
}
|
|
945
|
-
const buf = state.buf || '';
|
|
946
|
-
if (!buf.length) {
|
|
947
|
-
if (state.insertMode) return { line: padLine(line, cols), cursorCol: 3 };
|
|
948
|
-
const sug = SUGGESTIONS[(state.suggestionIdx || 0) % SUGGESTIONS.length];
|
|
949
|
-
line.push(span(t.white + BOLD, `Try "${sug}"`), span(BOLD_OFF, ''));
|
|
950
|
-
return { line: padLine(line, cols), cursorCol: 3 };
|
|
951
|
-
}
|
|
952
|
-
if (buf.includes('\n')) {
|
|
953
|
-
const preview = inputPreviewText(buf);
|
|
954
|
-
for (const ch of [...preview]) line.push(span(t.white, ch));
|
|
955
|
-
return { line: padLine(line, cols), cursorCol: Math.min(3 + w(preview), cols) };
|
|
956
|
-
}
|
|
957
|
-
const scroll = inputScroll(buf, state.cursor, cols);
|
|
958
|
-
const start = inputStart(buf, scroll);
|
|
959
|
-
if (scroll > 0) line.push(span(t.dim, '…'));
|
|
960
|
-
const chars = [...buf];
|
|
961
|
-
for (let i = start; i < chars.length; i++) line.push(span(t.white, chars[i]));
|
|
962
|
-
const visBefore = chars.slice(start, Math.min(state.cursor, chars.length)).join('');
|
|
963
|
-
const col = Math.min(3 + (scroll > 0 ? 1 : 0) + w(visBefore), cols);
|
|
964
|
-
return { line: padLine(line, cols), cursorCol: col };
|
|
965
|
-
}
|
|
966
|
-
|
|
967
|
-
// ── the session ─────────────────────────────────────────────────────────────
|
|
968
|
-
|
|
969
|
-
/**
|
|
970
|
-
* Drive a full-screen chat session.
|
|
971
|
-
*
|
|
972
|
-
* `host` — the app's side of the contract:
|
|
973
|
-
* ctx live mutable session context ({model, effort, vim, light, …})
|
|
974
|
-
* version string
|
|
975
|
-
* transcript the shared row array (also the engine's history source)
|
|
976
|
-
* session live tallies ({turns, calls, tokens, inputTokens, outputTokens, cost, balance})
|
|
977
|
-
* client the thin transport
|
|
978
|
-
* ask(prompt, {history, presenter}) -> Promise<{text, usage, model, ms, interrupted}>
|
|
979
|
-
* makeCommandContext() -> the frozen `c` (this loop overrides the IO fields)
|
|
980
|
-
* buildState() -> a snapshot for panels.js
|
|
981
|
-
* dispatchLine(line, c) -> Promise<false|void>; false ends the session
|
|
982
|
-
* refreshSpend() -> Promise<{balance, lastCost}|null>
|
|
983
|
-
* updateConfig(patch)
|
|
984
|
-
* wantsExit() -> bool (set by a handler's c.exit())
|
|
985
|
-
*
|
|
986
|
-
* @returns {Promise<number>} exit code
|
|
987
|
-
*/
|
|
988
|
-
async function runSession(host) {
|
|
989
|
-
const ctx = host.ctx;
|
|
990
|
-
|
|
991
|
-
const editor = new LineEditor();
|
|
992
|
-
const transcript = host.transcript;
|
|
993
|
-
const lineCache = new WeakMap();
|
|
994
|
-
|
|
995
|
-
let overlay = null;
|
|
996
|
-
|
|
997
|
-
/**
|
|
998
|
-
* The palette's rows: the ONE ranking the frame draws and the key handlers
|
|
999
|
-
* act on. Tab and Enter each wrote this expression out in full, which is two
|
|
1000
|
-
* chances for the row that is completed or run to be a different row than the
|
|
1001
|
-
* one highlighted. A function declaration so `render`'s closure can call it
|
|
1002
|
-
* whatever order the definitions are initialised in.
|
|
1003
|
-
*/
|
|
1004
|
-
function paletteRows(query) {
|
|
1005
|
-
const q = paletteQuery(query == null ? (overlay && overlay.query) || '' : query);
|
|
1006
|
-
return fuzzy.fuzzyRankWithAliases(q, host.visibleCommands(), (c) => c.name, (c) => c.aliases || []);
|
|
1007
|
-
}
|
|
1008
|
-
// Automode's running tally of silent "continue" answers to the round-budget
|
|
1009
|
-
// dialog (see autoContinuePlan above). Cleared whenever the human is
|
|
1010
|
-
// actually asked (autoContinuePlan resets it once the allowance is spent),
|
|
1011
|
-
// so it is "N automatic continuations per block", never a life-of-session
|
|
1012
|
-
// total that a long build could quietly exhaust.
|
|
1013
|
-
let autoContinues = 0;
|
|
1014
|
-
let working = false;
|
|
1015
|
-
let abort = null;
|
|
1016
|
-
let spinnerFrame = 0;
|
|
1017
|
-
let spinnerTimer = null;
|
|
1018
|
-
let startedAt = 0;
|
|
1019
|
-
let verb = VERBS[0];
|
|
1020
|
-
let turnCount = 0;
|
|
1021
|
-
let toolSeq = 0;
|
|
1022
|
-
// This turn's raw tool events, kept so the end-of-turn summary can report the
|
|
1023
|
-
// deltas (commands run, files touched, failures) without re-reading the
|
|
1024
|
-
// transcript — the rows are display state, the events are the record.
|
|
1025
|
-
let turnTools = [];
|
|
1026
|
-
let suggestionIdx = 0;
|
|
1027
|
-
let scroll = 0;
|
|
1028
|
-
let anchorEnd = null;
|
|
1029
|
-
// Grid row (0-based, as the frame indexes `lines`) → the transcript message
|
|
1030
|
-
// painted there, tool rows only. Rebuilt on every frame so it follows
|
|
1031
|
-
// scrolling; a click reads it to find which edit block to toggle. The wire's
|
|
1032
|
-
// 1-based row is converted once, in mouseGesture(), so both sides of this map
|
|
1033
|
-
// speak grid rows — keying it by screen row instead (the `1 +` that used to
|
|
1034
|
-
// read `2 +`) toggles the row ABOVE the one the reader clicked.
|
|
1035
|
-
const clickHits = new Map();
|
|
1036
|
-
// ── mouse marking (text selection) ────────────────────────────────────────
|
|
1037
|
-
// The terminal's own selection can't see the alternate screen, so a drag is
|
|
1038
|
-
// rebuilt here from the SGR stream (events.js) against the grid the last
|
|
1039
|
-
// frame painted. `frameLines` is that grid — kept so selectionText() can read
|
|
1040
|
-
// the cells the reader actually pointed at, not the transcript (which is
|
|
1041
|
-
// re-wrapped, scrolled and clipped differently every frame).
|
|
1042
|
-
let mark = null; // { anchor:{col,row}, head:{col,row} } — grid, 0-based
|
|
1043
|
-
let pendingClick = null; // press awaiting its release: a click or a marking
|
|
1044
|
-
let frameLines = [];
|
|
1045
|
-
let insertMode = false;
|
|
1046
|
-
let hintUntil = 0;
|
|
1047
|
-
let hintText = '';
|
|
1048
|
-
let inputPrompt = null;
|
|
1049
|
-
let streamJob = null;
|
|
1050
|
-
let streamStartedAt = 0;
|
|
1051
|
-
let tabCycle = null;
|
|
1052
|
-
// The terminal title's topic — what this session is about. Derived locally
|
|
1053
|
-
// from the user's own prompts (title.js) until the model names the
|
|
1054
|
-
// conversation (naming.js), after which the model's name is the topic and is
|
|
1055
|
-
// NOT re-derived per prompt: a follow-up must not rename the session away
|
|
1056
|
-
// from what it is about.
|
|
1057
|
-
let topic = '';
|
|
1058
|
-
let sessionTitle = '';
|
|
1059
|
-
let namingStarted = false;
|
|
1060
|
-
let titleBar = true;
|
|
1061
|
-
try {
|
|
1062
|
-
titleBar = titleEnabled(process.env, host.loadConfig ? host.loadConfig() : host.config || {});
|
|
1063
|
-
} catch {
|
|
1064
|
-
titleBar = true;
|
|
1065
|
-
}
|
|
1066
|
-
|
|
1067
|
-
// ── rendering ──
|
|
1068
|
-
let renderPending = false;
|
|
1069
|
-
let lastPaintAt = 0;
|
|
1070
|
-
|
|
1071
|
-
/**
|
|
1072
|
-
* Point the terminal title at the session's topic, spinning while a turn
|
|
1073
|
-
* runs. Replaces the static "AEGIS Code" this used to write on every frame:
|
|
1074
|
-
* that left every tab of every session reading identically, which is the one
|
|
1075
|
-
* job a terminal title has.
|
|
1076
|
-
*/
|
|
1077
|
-
const setTitle = (spinning) => {
|
|
1078
|
-
if (!titleBar) return;
|
|
1079
|
-
const frame = spinning ? TITLE_SPIN[Math.floor(spinnerFrame / 2) % TITLE_SPIN.length] : null;
|
|
1080
|
-
writeTitle(titleText({ topic, frame }), process.stdout);
|
|
1081
|
-
};
|
|
1082
|
-
|
|
1083
|
-
/**
|
|
1084
|
-
* Ask the model to name the conversation (naming.js), off the critical path.
|
|
1085
|
-
*
|
|
1086
|
-
* Fire-and-forget by construction: the turn is already streaming, and a name
|
|
1087
|
-
* that arrives a moment late is a name — a name that blocks the first frame
|
|
1088
|
-
* is a regression. `host.nameConversation` is the app's own model seam, so
|
|
1089
|
-
* the round runs on the session's model through the session's own client and
|
|
1090
|
-
* key; a host without that seam (tests, demo) simply keeps the local topic
|
|
1091
|
-
* from title.js.
|
|
1092
|
-
*
|
|
1093
|
-
* A greeting is answered locally by naming.js with GENERIC_TITLE and the
|
|
1094
|
-
* ladder is re-run on later turns, so a session opened with "heey" gets its
|
|
1095
|
-
* real name once the user says what they actually want.
|
|
1096
|
-
*/
|
|
1097
|
-
const ensureNamed = (prompt) => {
|
|
1098
|
-
if (typeof host.nameConversation !== 'function') return;
|
|
1099
|
-
namingStarted = true;
|
|
1100
|
-
let p;
|
|
1101
|
-
try {
|
|
1102
|
-
p = Promise.resolve(host.nameConversation(prompt, { signal: abort ? abort.signal : null }));
|
|
1103
|
-
} catch {
|
|
1104
|
-
return;
|
|
1105
|
-
}
|
|
1106
|
-
p.then((name) => {
|
|
1107
|
-
const clean = String(name || '').trim();
|
|
1108
|
-
if (!clean) return;
|
|
1109
|
-
sessionTitle = clean;
|
|
1110
|
-
topic = clean;
|
|
1111
|
-
setTitle(!!working);
|
|
1112
|
-
render();
|
|
1113
|
-
}).catch(() => { /* naming is best-effort */ });
|
|
1114
|
-
};
|
|
1115
|
-
|
|
1116
|
-
/** Re-ask only while the session is still wearing the generic name. */
|
|
1117
|
-
const maybeName = (prompt) => {
|
|
1118
|
-
if (!sessionTitle) {
|
|
1119
|
-
if (!namingStarted) ensureNamed(prompt);
|
|
1120
|
-
return;
|
|
1121
|
-
}
|
|
1122
|
-
if (!isGenericTitle(sessionTitle)) return;
|
|
1123
|
-
ensureNamed(prompt);
|
|
1124
|
-
};
|
|
1125
|
-
|
|
1126
|
-
// ── clipboard paste (Ctrl+V) and transcript copy (Ctrl+B) ────────────────
|
|
1127
|
-
// Neither chord existed here: `\x16` and `\x02` had no case in keys.js, so
|
|
1128
|
-
// they fell into its "any other control char → ESC" branch — Ctrl+V did
|
|
1129
|
-
// nothing at all (the terminal's own bracketed paste, and its own
|
|
1130
|
-
// Ctrl+Shift+V, are the only ways text ever arrived), and Ctrl+B aborted a
|
|
1131
|
-
// running turn. Both are real keys now (`KEY.CTRL_V` / `KEY.CTRL_B`).
|
|
1132
|
-
//
|
|
1133
|
-
// Ctrl+V pastes the clipboard's image when it holds one — written under the
|
|
1134
|
-
// data dir and inserted as its PATH, which is what every file-reading tool
|
|
1135
|
-
// here accepts and what the reference CLI hands the model for a screenshot —
|
|
1136
|
-
// and its text otherwise. Both land in the input line, so nothing is sent
|
|
1137
|
-
// until Enter.
|
|
1138
|
-
const flash = (text) => {
|
|
1139
|
-
hintText = text;
|
|
1140
|
-
hintUntil = Date.now() + 2500;
|
|
1141
|
-
setTimeout(() => { if (Date.now() >= hintUntil) render(); }, 2600);
|
|
1142
|
-
render();
|
|
1143
|
-
};
|
|
1144
|
-
const pasteClipboard = () => {
|
|
1145
|
-
const img = readClipboardImage({ env: process.env });
|
|
1146
|
-
if (img.ok) {
|
|
1147
|
-
try {
|
|
1148
|
-
const dir = path.join(aegisDir(), 'clipboard');
|
|
1149
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
1150
|
-
const ext = img.mime === 'image/jpeg' ? 'jpg' : 'png';
|
|
1151
|
-
const file = path.join(dir, `pasted-${new Date().toISOString().replace(/[:.]/g, '-')}.${ext}`);
|
|
1152
|
-
fs.writeFileSync(file, img.data, { mode: 0o600 });
|
|
1153
|
-
const lead = editor.buf && !/\s$/.test(editor.buf) ? ' ' : '';
|
|
1154
|
-
editor.insert(lead + file);
|
|
1155
|
-
flash(`Pasted image → ${file}`);
|
|
1156
|
-
return;
|
|
1157
|
-
} catch (e) {
|
|
1158
|
-
flash(`Could not save the pasted image: ${(e && e.message) || e}`);
|
|
1159
|
-
return;
|
|
1160
|
-
}
|
|
1161
|
-
}
|
|
1162
|
-
const txt = readClipboardText({ env: process.env });
|
|
1163
|
-
if (txt.ok && txt.text) {
|
|
1164
|
-
editor.insert(txt.text);
|
|
1165
|
-
flash(`Pasted ${txt.text.length} character${txt.text.length === 1 ? '' : 's'} from the clipboard`);
|
|
1166
|
-
return;
|
|
1167
|
-
}
|
|
1168
|
-
// Honest failure: say WHICH side is missing. "Nothing to paste" when the
|
|
1169
|
-
// host simply has no clipboard reader sends the user looking for an empty
|
|
1170
|
-
// clipboard instead of a missing tool.
|
|
1171
|
-
flash(txt.ok
|
|
1172
|
-
? 'Clipboard is empty — nothing to paste'
|
|
1173
|
-
: `Cannot read the clipboard here (${txt.error}) — use your terminal's own paste shortcut instead`);
|
|
1174
|
-
};
|
|
1175
|
-
// Ctrl+B: the whole conversation onto the clipboard, so it can be pasted into
|
|
1176
|
-
// an issue, a chat or a file without a marking drag or a /export round trip
|
|
1177
|
-
// through the disk.
|
|
1178
|
-
const copyTranscript = () => {
|
|
1179
|
-
if (!transcript.length) { flash('Nothing to copy yet'); return; }
|
|
1180
|
-
const res = copyToClipboard(transcriptToMarkdown(transcript), { stdout: process.stdout, env: process.env });
|
|
1181
|
-
flash(describeCopy(res, 'Copied the conversation'));
|
|
1182
|
-
};
|
|
1183
|
-
|
|
1184
|
-
const buildFrame = () => {
|
|
1185
|
-
const { cols, rows } = getSize();
|
|
1186
|
-
const lines = [];
|
|
1187
|
-
lines.push(headerLine(host.version, cols, ctx));
|
|
1188
|
-
const avail = Math.max(1, rows - 6);
|
|
1189
|
-
const view = transcriptLines(transcript, { cols, rows, scroll, anchorEnd }, ctx, Date.now(), lineCache);
|
|
1190
|
-
scroll = view.scroll;
|
|
1191
|
-
anchorEnd = view.anchorEnd;
|
|
1192
|
-
// The header is frame line 0 (grid row 0), so the transcript window's first
|
|
1193
|
-
// painted line is grid row 1; each painted line carries its source row in
|
|
1194
|
-
// view.owners.
|
|
1195
|
-
clickHits.clear();
|
|
1196
|
-
for (let i = 0; i < view.lines.length; i++) clickHits.set(1 + i, view.owners[i]);
|
|
1197
|
-
for (const l of view.lines) lines.push(l);
|
|
1198
|
-
// Exactly `avail` transcript rows, so the frame is exactly `rows` lines:
|
|
1199
|
-
// header(1) + transcript(avail) + spinner/effort + rule + input + rule +
|
|
1200
|
-
// status = rows. The input row's 1-based position is therefore rows - 2.
|
|
1201
|
-
while (lines.length < avail + 1) lines.push([span('', '')]);
|
|
1202
|
-
const t = themeOf(ctx);
|
|
1203
|
-
if (working) {
|
|
1204
|
-
lines.push(
|
|
1205
|
-
spinnerLine(
|
|
1206
|
-
{
|
|
1207
|
-
verb,
|
|
1208
|
-
frame: spinnerFrame,
|
|
1209
|
-
elapsedMs: Date.now() - startedAt,
|
|
1210
|
-
// `streamedChars` is a display width — the accumulated `w(delta)` of
|
|
1211
|
-
// the stream — so it is converted to tokens HERE, at the producer.
|
|
1212
|
-
// Both spinner renderers label this field `tokens`, so handing them
|
|
1213
|
-
// cells printed the character count as a token count and the live
|
|
1214
|
-
// figure read ~4x high.
|
|
1215
|
-
streamed: estimateTokensFromCells(streamedCells()) + thinkingTokens,
|
|
1216
|
-
streamedFloor: thinkingTokens > 0,
|
|
1217
|
-
},
|
|
1218
|
-
ctx
|
|
1219
|
-
)
|
|
1220
|
-
);
|
|
1221
|
-
} else if (Date.now() < hintUntil) {
|
|
1222
|
-
lines.push([span(t.gray, ` ${hintText}`)]);
|
|
1223
|
-
} else if (streamJob) {
|
|
1224
|
-
const secs = Math.max(1, Math.round((Date.now() - streamStartedAt) / 1000));
|
|
1225
|
-
lines.push([span(t.gray, ` ${streamJob.label || 'running'}… (${secs}s · esc to stop)`)]);
|
|
1226
|
-
} else {
|
|
1227
|
-
lines.push(effortLine(ctx, cols));
|
|
1228
|
-
}
|
|
1229
|
-
lines.push(separatorLine(cols, ctx));
|
|
1230
|
-
const inp = inputLine(
|
|
1231
|
-
{ buf: editor.buf, cursor: editor.cursor, working, insertMode, suggestionIdx, inputPrompt },
|
|
1232
|
-
cols,
|
|
1233
|
-
ctx
|
|
1234
|
-
);
|
|
1235
|
-
lines.push(inp.line);
|
|
1236
|
-
lines.push(separatorLine(cols, ctx));
|
|
1237
|
-
lines.push(statusLine({ working, inputPrompt, streamJob, yolo: host.isYolo && host.isYolo(), keyNotice: host.keyNotice && host.keyNotice() }, cols, ctx));
|
|
1238
|
-
return { lines, inputCol: inp.cursorCol, rows, inputRow: rows - 2 };
|
|
1239
|
-
};
|
|
1240
|
-
|
|
1241
|
-
const render = () => {
|
|
1242
|
-
if (isKeyStreamSuspended()) return;
|
|
1243
|
-
const cols = getSize().cols;
|
|
1244
|
-
const { lines, inputCol, rows, inputRow } = buildFrame();
|
|
1245
|
-
if (overlay) applyOverlay(lines, rows, cols);
|
|
1246
|
-
// A marking paints over the grid the reader is dragging on; frameLines is
|
|
1247
|
-
// kept for the copy on release (selectionText in screen.js). Assigned from
|
|
1248
|
-
// the UNMARKED lines so the copied text is the text, not the reverse-video
|
|
1249
|
-
// spans applySelection adds.
|
|
1250
|
-
frameLines = lines;
|
|
1251
|
-
paint(mark ? applySelection(lines, selectionRange(mark.anchor, mark.head), cols) : lines);
|
|
1252
|
-
lastPaintAt = Date.now();
|
|
1253
|
-
if (overlay) {
|
|
1254
|
-
hideCursor();
|
|
1255
|
-
return;
|
|
1256
|
-
}
|
|
1257
|
-
if (inputPrompt || !working) {
|
|
1258
|
-
moveTo(inputRow, inputCol);
|
|
1259
|
-
showCursor();
|
|
1260
|
-
} else {
|
|
1261
|
-
hideCursor();
|
|
1262
|
-
}
|
|
1263
|
-
};
|
|
1264
|
-
|
|
1265
|
-
const scheduleRender = () => {
|
|
1266
|
-
if (renderPending) return;
|
|
1267
|
-
renderPending = true;
|
|
1268
|
-
const wait = Math.max(0, FRAME_MS - (Date.now() - lastPaintAt));
|
|
1269
|
-
setTimeout(() => {
|
|
1270
|
-
renderPending = false;
|
|
1271
|
-
render();
|
|
1272
|
-
}, wait);
|
|
1273
|
-
};
|
|
1274
|
-
|
|
1275
|
-
const applyOverlay = (lines, termRows, cols) => {
|
|
1276
|
-
if (!overlay) return;
|
|
1277
|
-
let ol = null;
|
|
1278
|
-
if (overlay.type === 'palette') {
|
|
1279
|
-
ol = overlays.renderPalette(host.visibleCommands(), { query: paletteQuery(overlay.query), sel: overlay.sel }, cols, termRows);
|
|
1280
|
-
} else if (overlay.type === 'model') {
|
|
1281
|
-
// The class rides on the overlay (set where it was opened, commands.js
|
|
1282
|
-
// /model) with the live ctx as the fallback, and the label comes from the
|
|
1283
|
-
// engine's table via the host — so this path and app.js's renderOverlay
|
|
1284
|
-
// paint the same title, subtitle and row semantics for the same overlay.
|
|
1285
|
-
ol = overlays.renderModelPicker(
|
|
1286
|
-
overlay.items || [], overlay.sel || 0, cols, termRows, overlay.current,
|
|
1287
|
-
overlay.cls || ctx.modelClass,
|
|
1288
|
-
typeof host.classLabel === 'function' ? host.classLabel : null
|
|
1289
|
-
);
|
|
1290
|
-
} else if (overlay.type === 'effort') {
|
|
1291
|
-
ol = overlays.renderEffortPicker(overlay.sel || 0, cols, ctx.effort);
|
|
1292
|
-
} else if (overlay.type === 'class') {
|
|
1293
|
-
ol = overlays.renderClassPicker(
|
|
1294
|
-
overlay.items || [], overlay.sel || 0, cols, overlay.current || ctx.modelClass,
|
|
1295
|
-
typeof host.classLabel === 'function' ? host.classLabel : null
|
|
1296
|
-
);
|
|
1297
|
-
} else if (overlay.type === 'provider') {
|
|
1298
|
-
// The BYOK provider picker (/byok-set with no argument, /byok-key with
|
|
1299
|
-
// no argument). Same overlay machinery as /model and /class — arrow or
|
|
1300
|
-
// Tab to move, Enter to pick — so choosing WHICH vendor a key belongs to
|
|
1301
|
-
// is a highlight rather than a provider id retyped from memory.
|
|
1302
|
-
ol = overlays.renderProviderPicker(
|
|
1303
|
-
overlay.items || [], overlay.sel || 0, cols, overlay.current, overlay.hint
|
|
1304
|
-
);
|
|
1305
|
-
} else if (overlay.type === 'resume') {
|
|
1306
|
-
ol = overlays.renderResumeList(overlay.items || [], overlay.sel || 0, cols, termRows);
|
|
1307
|
-
} else if (overlay.type === 'shortcuts') {
|
|
1308
|
-
ol = shortcutsGrid(cols, ctx);
|
|
1309
|
-
} else if (overlay.type === 'confirm') {
|
|
1310
|
-
ol = confirmLines(overlay, cols, ctx);
|
|
1311
|
-
} else if (overlay.type === 'rounds') {
|
|
1312
|
-
ol = roundsLines(overlay, cols, ctx);
|
|
1313
|
-
} else if (overlay.type === 'panel') {
|
|
1314
|
-
ol = overlay.lines || [];
|
|
1315
|
-
}
|
|
1316
|
-
if (!ol) return;
|
|
1317
|
-
if (overlay.type === 'shortcuts') {
|
|
1318
|
-
const start = Math.max(2, termRows - ol.length - 1);
|
|
1319
|
-
for (let i = 0; i < ol.length; i++) lines[start + i] = padLine(ol[i], cols);
|
|
1320
|
-
hideCursor();
|
|
1321
|
-
return;
|
|
1322
|
-
}
|
|
1323
|
-
const start = Math.max(2, Math.floor((termRows - ol.length) / 2));
|
|
1324
|
-
for (let i = 0; i < ol.length; i++) lines[start + i] = padLine(ol[i], cols);
|
|
1325
|
-
hideCursor();
|
|
1326
|
-
};
|
|
1327
|
-
|
|
1328
|
-
// ── transcript rows ──
|
|
1329
|
-
|
|
1330
|
-
const push = (msg, o) => {
|
|
1331
|
-
transcript.push(msg);
|
|
1332
|
-
if (!o || o.follow !== false) {
|
|
1333
|
-
scroll = 0;
|
|
1334
|
-
anchorEnd = null;
|
|
1335
|
-
}
|
|
1336
|
-
return msg;
|
|
1337
|
-
};
|
|
1338
|
-
|
|
1339
|
-
/**
|
|
1340
|
-
* Append a turn's tool row *before* the still-streaming answer row instead of
|
|
1341
|
-
* after it.
|
|
1342
|
-
*
|
|
1343
|
-
* The answer row is created empty when the turn opens and grows in place as
|
|
1344
|
-
* text streams, while each tool call appends a row of its own. Appending the
|
|
1345
|
-
* tool rows after it left the growing answer ABOVE a run of tool rows: once
|
|
1346
|
-
* the turn outgrew the window, the follow-the-bottom viewport showed only the
|
|
1347
|
-
* newest tool row and the answer the reader was waiting for sat off the top
|
|
1348
|
-
* of the window — "I have to scroll up to read the result". Inserting the
|
|
1349
|
-
* tools ahead of the answer keeps the answer as the last row of the turn, so
|
|
1350
|
-
* the bottom of the screen always holds the thing being waited for.
|
|
1351
|
-
*
|
|
1352
|
-
* `follow` is deliberately not re-applied: the rows this replaces were pushed
|
|
1353
|
-
* with `{ follow: false }`, and a raw append never re-engaged the bottom.
|
|
1354
|
-
*
|
|
1355
|
-
* Known limit: a turn's text is already flattened into one `msg.text` (see
|
|
1356
|
-
* the presenter's `text` hook), so text emitted *before* a tool call can't be
|
|
1357
|
-
* split from text emitted after it. This trades that unrepresentable
|
|
1358
|
-
* interleaving for the answer being on screen.
|
|
1359
|
-
*/
|
|
1360
|
-
const pushToolRow = (msg, before) => {
|
|
1361
|
-
const at = before ? transcript.indexOf(before) : -1;
|
|
1362
|
-
if (at < 0) transcript.push(msg);
|
|
1363
|
-
else transcript.splice(at, 0, msg);
|
|
1364
|
-
return msg;
|
|
1365
|
-
};
|
|
1366
|
-
|
|
1367
|
-
const note = (text) => push({ role: 'note', text }, { follow: false });
|
|
1368
|
-
|
|
1369
|
-
// The live figure's input: the display width of what the turn has PRODUCED so
|
|
1370
|
-
// far — the answer's deltas AND the thinking trace's — because that is the
|
|
1371
|
-
// billed output and the quantity the desktop's bubble reports (see the
|
|
1372
|
-
// `reasoning` presenter below). It feeds the spinner and nothing else: it is
|
|
1373
|
-
// reset per turn and never reaches the accounting row, which is built from
|
|
1374
|
-
// what the provider measured.
|
|
1375
|
-
let streamedChars = 0;
|
|
1376
|
-
// Thinking tokens the PROVIDER measured, added verbatim. `streamedChars` is a
|
|
1377
|
-
// display width that becomes tokens at 4:1, which cannot express this: a
|
|
1378
|
-
// subscription turn sends `thinking_delta.thinking` as the empty string and
|
|
1379
|
-
// reports progress in `estimated_tokens` instead, so the char counter stayed
|
|
1380
|
-
// at 0 for the entire thinking phase while thousands of tokens were billed.
|
|
1381
|
-
let thinkingTokens = 0;
|
|
1382
|
-
const streamedCells = () => streamedChars;
|
|
1383
|
-
// ── the turn ──
|
|
1384
|
-
|
|
1385
|
-
const confirmTool = (info) =>
|
|
1386
|
-
new Promise((resolve) => {
|
|
1387
|
-
overlay = { type: 'confirm', name: info.tool || info.name || 'tool', args: info.args || {}, sel: 0, info };
|
|
1388
|
-
render();
|
|
1389
|
-
(async () => {
|
|
1390
|
-
const choose = (decision) => {
|
|
1391
|
-
overlay = null;
|
|
1392
|
-
render();
|
|
1393
|
-
resolve(decision);
|
|
1394
|
-
};
|
|
1395
|
-
for (;;) {
|
|
1396
|
-
const key = await nextKey();
|
|
1397
|
-
if (key.name === KEY.UP || key.name === KEY.DOWN || key.name === KEY.TAB) {
|
|
1398
|
-
const step = key.name === KEY.UP ? -1 : 1;
|
|
1399
|
-
overlay.sel = (overlay.sel + step + APPROVAL_CHOICES.length) % APPROVAL_CHOICES.length;
|
|
1400
|
-
render();
|
|
1401
|
-
} else if (key.name === KEY.ENTER) {
|
|
1402
|
-
choose(APPROVAL_DECISIONS[overlay.sel] || DENY_TOKEN);
|
|
1403
|
-
return;
|
|
1404
|
-
} else if (key.name === KEY.ESC || key.name === KEY.CTRL_C) {
|
|
1405
|
-
choose(DENY_TOKEN);
|
|
1406
|
-
return;
|
|
1407
|
-
} else if (key.name === 'char') {
|
|
1408
|
-
const ch = String(key.ch).trim();
|
|
1409
|
-
const idx = Number(ch) - 1;
|
|
1410
|
-
if (Number.isInteger(idx) && idx >= 0 && idx < APPROVAL_DECISIONS.length) {
|
|
1411
|
-
choose(APPROVAL_DECISIONS[idx]);
|
|
1412
|
-
return;
|
|
1413
|
-
}
|
|
1414
|
-
}
|
|
1415
|
-
}
|
|
1416
|
-
})();
|
|
1417
|
-
});
|
|
1418
|
-
|
|
1419
|
-
// The round-budget extension dialog (engine.js requestRoundsAsk, surfaced
|
|
1420
|
-
// here as `chunk.rounds` → `presenter.rounds`). Same own-nextKey-loop shape
|
|
1421
|
-
// as confirmTool above. The cursor starts on "No" deliberately: an Enter on
|
|
1422
|
-
// an untouched dialog must not spend another block of rounds, so a
|
|
1423
|
-
// declined dialog is bit-for-bit the engine's own hard stop.
|
|
1424
|
-
const confirmRoundsExtension = (info) =>
|
|
1425
|
-
new Promise((resolve) => {
|
|
1426
|
-
// ── automode: the first AUTO_CONTINUE_LIMIT asks are answered for the
|
|
1427
|
-
// human ───────────────────────────────────────────────────────────────
|
|
1428
|
-
// This is the "fund a few blocks automatically, then ask for real"
|
|
1429
|
-
// contract: with automode on, a turn that reaches its horizon is
|
|
1430
|
-
// extended silently a few times, and the ask after that is the real
|
|
1431
|
-
// dialog again — so automode is "don't make me answer the same budget
|
|
1432
|
-
// question every time", not "run forever with no one watching".
|
|
1433
|
-
const yolo = Boolean(host.isYolo && host.isYolo());
|
|
1434
|
-
const plan = autoContinuePlan({ on: yolo, used: autoContinues });
|
|
1435
|
-
autoContinues = plan.used;
|
|
1436
|
-
if (plan.auto) {
|
|
1437
|
-
note(
|
|
1438
|
-
`auto: ${info.spent}-round limit reached — continuing automatically` +
|
|
1439
|
-
` (${plan.used}/${plan.cap}, then it asks).`
|
|
1440
|
-
);
|
|
1441
|
-
render();
|
|
1442
|
-
resolve(true);
|
|
1443
|
-
return;
|
|
1444
|
-
}
|
|
1445
|
-
if (yolo) {
|
|
1446
|
-
// The allowance is spent: this IS the ask. Say so, or the dialog reads
|
|
1447
|
-
// as automode having silently switched itself off.
|
|
1448
|
-
note(`auto: ${plan.cap} automatic continuations used — asking you now (answering restarts the block).`);
|
|
1449
|
-
render();
|
|
1450
|
-
}
|
|
1451
|
-
overlay = {
|
|
1452
|
-
type: 'rounds',
|
|
1453
|
-
spent: Number(info.spent) || 0,
|
|
1454
|
-
extensions: Number(info.extensions) || 1,
|
|
1455
|
-
max: Number(info.max) || 8,
|
|
1456
|
-
size: Number(info.size) || Number(info.spent) || 0,
|
|
1457
|
-
sel: 1,
|
|
1458
|
-
};
|
|
1459
|
-
render();
|
|
1460
|
-
(async () => {
|
|
1461
|
-
const choose = (yes) => {
|
|
1462
|
-
overlay = null;
|
|
1463
|
-
render();
|
|
1464
|
-
resolve(yes);
|
|
1465
|
-
};
|
|
1466
|
-
for (;;) {
|
|
1467
|
-
const key = await nextKey();
|
|
1468
|
-
if (key.name === KEY.UP || key.name === KEY.DOWN || key.name === KEY.TAB) {
|
|
1469
|
-
overlay.sel = 1 - overlay.sel;
|
|
1470
|
-
render();
|
|
1471
|
-
} else if (key.name === KEY.ENTER) {
|
|
1472
|
-
choose(overlay.sel === 0);
|
|
1473
|
-
return;
|
|
1474
|
-
} else if (key.name === KEY.ESC || key.name === KEY.CTRL_C) {
|
|
1475
|
-
choose(false);
|
|
1476
|
-
return;
|
|
1477
|
-
} else if (key.name === 'char') {
|
|
1478
|
-
const c = String(key.ch).trim();
|
|
1479
|
-
if (c === '1') { choose(true); return; }
|
|
1480
|
-
if (c === '2') { choose(false); return; }
|
|
1481
|
-
}
|
|
1482
|
-
}
|
|
1483
|
-
})();
|
|
1484
|
-
});
|
|
1485
|
-
|
|
1486
|
-
const startResponse = async (prompt) => {
|
|
1487
|
-
working = true;
|
|
1488
|
-
spinnerFrame = 0;
|
|
1489
|
-
startedAt = Date.now();
|
|
1490
|
-
streamedChars = 0;
|
|
1491
|
-
thinkingTokens = 0;
|
|
1492
|
-
toolSeq = 0;
|
|
1493
|
-
turnTools = [];
|
|
1494
|
-
verb = VERBS[turnCount % VERBS.length];
|
|
1495
|
-
// Adopt the ask as this session's topic (kept when it is a follow-up), so
|
|
1496
|
-
// the tab reads what is being worked on from the first frame of the turn.
|
|
1497
|
-
// A model-given name outranks the local derivation — that is the whole
|
|
1498
|
-
// point of asking the model — and ask the model to name the conversation
|
|
1499
|
-
// off the critical path until it has a real one.
|
|
1500
|
-
topic = sessionTitle || adoptTopic(topic, prompt);
|
|
1501
|
-
maybeName(prompt);
|
|
1502
|
-
abort = new AbortController();
|
|
1503
|
-
spinnerTimer = setInterval(() => {
|
|
1504
|
-
spinnerFrame++;
|
|
1505
|
-
setTitle(true);
|
|
1506
|
-
if (spinnerFrame % 3 === 0) render();
|
|
1507
|
-
}, 100);
|
|
1508
|
-
if (spinnerTimer.unref) spinnerTimer.unref();
|
|
1509
|
-
setTitle(true);
|
|
1510
|
-
push({ role: 'user', text: prompt });
|
|
1511
|
-
const msg = push({ role: 'assistant', text: '', streaming: true });
|
|
1512
|
-
let sawReasoning = false;
|
|
1513
|
-
|
|
1514
|
-
const presenter = {
|
|
1515
|
-
text: (delta) => {
|
|
1516
|
-
msg.text += delta;
|
|
1517
|
-
streamedChars += w(delta);
|
|
1518
|
-
scheduleRender();
|
|
1519
|
-
},
|
|
1520
|
-
// Not rendered (deliberation is not an answer), but counted and recorded.
|
|
1521
|
-
// Counted, because the live figure is the turn's BILLED output — the
|
|
1522
|
-
// answer plus the thinking trace it is charged for — which is the same
|
|
1523
|
-
// quantity the desktop's bubble reports (`desktop/renderer/app.js` sums
|
|
1524
|
-
// reply AND reasoning cells at this same 4:1 ratio). Consuming the delta
|
|
1525
|
-
// here without adding it left the counter at 0 for the whole thinking
|
|
1526
|
-
// phase, so the spinner read `↓0 tokens` while a reasoning model — the
|
|
1527
|
-
// default in this build — thought: the one row that means "a turn is in
|
|
1528
|
-
// flight" reported nothing happening.
|
|
1529
|
-
// Recorded separately, because a turn that reasoned and then produced
|
|
1530
|
-
// nothing needs a different explanation from one that produced nothing at
|
|
1531
|
-
// all.
|
|
1532
|
-
reasoning: (delta) => { sawReasoning = true; streamedChars += w(delta); },
|
|
1533
|
-
// Provider-measured thinking progress, in tokens. Separate from
|
|
1534
|
-
// `reasoning` above because that one is TEXT (accumulated as display
|
|
1535
|
-
// width, converted at 4:1) and this is already a token count. On a
|
|
1536
|
-
// subscription turn this is the only live signal that arrives during the
|
|
1537
|
-
// thinking phase — the text channel sends empty strings throughout.
|
|
1538
|
-
thinkingTokens: (n) => { sawReasoning = true; thinkingTokens += n; scheduleRender(); },
|
|
1539
|
-
tool: (tool) => {
|
|
1540
|
-
// One entry per tool call, not one per frame. The engine opens a `run`
|
|
1541
|
-
// frame before the tool executes and closes it with a `done` frame
|
|
1542
|
-
// after (see desktop/lib/local/engine.js), so pushing both made the
|
|
1543
|
-
// turn summary report every tool twice. An id-bearing done frame
|
|
1544
|
-
// replaces the run frame it closes; frames with no id keep the old
|
|
1545
|
-
// push-every-frame behaviour, so a host that reports a tool once is
|
|
1546
|
-
// unaffected.
|
|
1547
|
-
if (tool && tool.id !== undefined) {
|
|
1548
|
-
const at = turnTools.findIndex((x) => x && x.id !== undefined && x.id === tool.id);
|
|
1549
|
-
if (at >= 0) turnTools[at] = tool;
|
|
1550
|
-
else turnTools.push(tool);
|
|
1551
|
-
} else {
|
|
1552
|
-
turnTools.push(tool);
|
|
1553
|
-
}
|
|
1554
|
-
if (tool.phase === 'run') {
|
|
1555
|
-
const n = ++toolSeq;
|
|
1556
|
-
const prefix = tool.agent ? `${tool.agent} ▸ ` : '';
|
|
1557
|
-
// Built on the `run` frame, before the executor writes — a writeFile
|
|
1558
|
-
// preview built any later would diff the file against itself. The
|
|
1559
|
-
// row this lands on persists through resolveToolDone (same object,
|
|
1560
|
-
// found by id), so the diff set here is still there once the tool
|
|
1561
|
-
// reports `done` and the row repaints.
|
|
1562
|
-
const diff = editPreview(tool.name, tool.args, { cwd: tool.cwd });
|
|
1563
|
-
pushToolRow(
|
|
1564
|
-
{
|
|
1565
|
-
role: 'tool',
|
|
1566
|
-
phase: 'run',
|
|
1567
|
-
name: tool.name,
|
|
1568
|
-
args: tool.args,
|
|
1569
|
-
agent: tool.agent,
|
|
1570
|
-
id: tool.id,
|
|
1571
|
-
label: `Running ${n} ${prefix}${toolLabel(tool.name, n)}…`,
|
|
1572
|
-
start: Date.now(),
|
|
1573
|
-
diff,
|
|
1574
|
-
diffOpen: defaultOpen(diff),
|
|
1575
|
-
},
|
|
1576
|
-
msg
|
|
1577
|
-
);
|
|
1578
|
-
} else if (!resolveToolDone(transcript, tool)) {
|
|
1579
|
-
// A host that reports a tool once, after it ran, never opens a
|
|
1580
|
-
// `phase: 'run'` row for resolveToolDone to close — the vendored
|
|
1581
|
-
// local engine does exactly this (one `tool: {name,args,ok}` frame
|
|
1582
|
-
// post-execution). Falling through left the row unwritten, so the
|
|
1583
|
-
// turn silently showed no tool activity at all. Record the finished
|
|
1584
|
-
// tool directly instead.
|
|
1585
|
-
// No `run` frame means no pre-write read either, so a writeFile's
|
|
1586
|
-
// diff here can only compare the file against its own post-write
|
|
1587
|
-
// content (reads clean) — a limitation of this fallback, not of the
|
|
1588
|
-
// normal run→done path above.
|
|
1589
|
-
const n = ++toolSeq;
|
|
1590
|
-
const diff = editPreview(tool.name, tool.args, { cwd: tool.cwd });
|
|
1591
|
-
pushToolRow(
|
|
1592
|
-
{
|
|
1593
|
-
role: 'tool',
|
|
1594
|
-
phase: 'done',
|
|
1595
|
-
name: tool.name,
|
|
1596
|
-
args: tool.args,
|
|
1597
|
-
agent: tool.agent,
|
|
1598
|
-
id: tool.id,
|
|
1599
|
-
ok: tool.ok,
|
|
1600
|
-
label: `Ran ${n} ${tool.agent ? `${tool.agent} ▸ ` : ''}${toolLabel(tool.name, n)}`,
|
|
1601
|
-
diff,
|
|
1602
|
-
diffOpen: defaultOpen(diff),
|
|
1603
|
-
},
|
|
1604
|
-
msg
|
|
1605
|
-
);
|
|
1606
|
-
}
|
|
1607
|
-
scheduleRender();
|
|
1608
|
-
},
|
|
1609
|
-
approval: (info) => confirmTool(info),
|
|
1610
|
-
rounds: (info) => confirmRoundsExtension(info),
|
|
1611
|
-
};
|
|
1612
|
-
|
|
1613
|
-
let result = null;
|
|
1614
|
-
try {
|
|
1615
|
-
result = await host.ask(prompt, {
|
|
1616
|
-
history: historyPairs(transcript),
|
|
1617
|
-
presenter,
|
|
1618
|
-
signal: abort.signal,
|
|
1619
|
-
});
|
|
1620
|
-
} catch (err) {
|
|
1621
|
-
result = { error: (err && err.message) || String(err) };
|
|
1622
|
-
} finally {
|
|
1623
|
-
msg.streaming = false;
|
|
1624
|
-
// The row is built from streamed deltas, but the transport is the
|
|
1625
|
-
// authority on what the turn actually produced. A provider that emits
|
|
1626
|
-
// no incremental content — a non-streaming fallback, a gateway that
|
|
1627
|
-
// only sends the finished message, a reasoning model whose visible
|
|
1628
|
-
// answer arrives in one final frame — left this row empty and the user
|
|
1629
|
-
// read "(no response)" for a turn that was answered and billed.
|
|
1630
|
-
if (!String(msg.text || '').trim() && result && typeof result.text === 'string' && result.text.trim()) {
|
|
1631
|
-
msg.text = result.text;
|
|
1632
|
-
}
|
|
1633
|
-
working = false;
|
|
1634
|
-
clearInterval(spinnerTimer);
|
|
1635
|
-
spinnerTimer = null;
|
|
1636
|
-
setTitle(false);
|
|
1637
|
-
const secs = Math.max(1, Math.round((Date.now() - startedAt) / 1000));
|
|
1638
|
-
const abortedFlag = !!(abort && abort.signal.aborted);
|
|
1639
|
-
msg.text = finalizeTurnText(msg.text, {
|
|
1640
|
-
aborted: abortedFlag,
|
|
1641
|
-
error: result && result.error,
|
|
1642
|
-
reasoned: sawReasoning,
|
|
1643
|
-
});
|
|
1644
|
-
const footer = push(
|
|
1645
|
-
{ role: 'done', text: `${toolSeq > 0 ? DONE_VERBS[1] : DONE_VERBS[0]} for ${secs}s` },
|
|
1646
|
-
{ follow: false }
|
|
1647
|
-
);
|
|
1648
|
-
suggestionIdx = turnCount + 1;
|
|
1649
|
-
turnCount++;
|
|
1650
|
-
abort = null;
|
|
1651
|
-
|
|
1652
|
-
// /ping — the same notice the desktop raises from
|
|
1653
|
-
// `notifyReplyIfUnfocused()`, re-derived for a terminal that has no
|
|
1654
|
-
// `isFocused()`: the proxy is TIME (a turn the user walked away from is
|
|
1655
|
-
// one that took longer than `pingMinSeconds`), and the gate is
|
|
1656
|
-
// `process.stdout.isTTY` (a piped or headless run has no one to notify).
|
|
1657
|
-
// Written to `process.stdout` rather than through the renderer on
|
|
1658
|
-
// purpose: a notification escape goes past the screen buffer, so it works
|
|
1659
|
-
// while the renderer still owns the terminal. Guarded, and last, so a
|
|
1660
|
-
// notice can never break the turn it is reporting on.
|
|
1661
|
-
try {
|
|
1662
|
-
const pingCfg = loadConfig();
|
|
1663
|
-
const notice = pingTurn({
|
|
1664
|
-
stream: process.stdout,
|
|
1665
|
-
mode: pingCfg.ping,
|
|
1666
|
-
minSeconds: pingCfg.pingMinSeconds,
|
|
1667
|
-
elapsedMs: Date.now() - startedAt,
|
|
1668
|
-
isTTY: !!process.stdout.isTTY,
|
|
1669
|
-
aborted: abortedFlag,
|
|
1670
|
-
});
|
|
1671
|
-
if (notice) push({ role: 'note', text: notice }, { follow: false });
|
|
1672
|
-
} catch {
|
|
1673
|
-
/* a notice must never break a turn */
|
|
1674
|
-
}
|
|
1675
|
-
|
|
1676
|
-
// Accounting: fold the turn's usage into the session tallies, ask the
|
|
1677
|
-
// ledger what it settled at, and show both — tokens beside €.
|
|
1678
|
-
host.recordTurn(result);
|
|
1679
|
-
// Ask the ledger what this turn settled at BEFORE persisting it. Order
|
|
1680
|
-
// matters: the charge is the server's number (margin and prompt-cache
|
|
1681
|
-
// discount included) and only it can answer "what did that cost". The
|
|
1682
|
-
// turn used to be written first, with no charge attached, which left
|
|
1683
|
-
// /cost recomputing from a local rate table that knows about neither —
|
|
1684
|
-
// so the figure a user read never matched the bill they paid.
|
|
1685
|
-
let lastCost = null;
|
|
1686
|
-
try {
|
|
1687
|
-
const spend = await host.refreshSpend();
|
|
1688
|
-
lastCost = spend ? spend.lastCost : null;
|
|
1689
|
-
} catch {
|
|
1690
|
-
/* accounting must never break a turn */
|
|
1691
|
-
}
|
|
1692
|
-
// Persist the finished exchange for /resume. Guarded: the test host stub
|
|
1693
|
-
// deliberately omits persistTurn, and the accounting below must still run.
|
|
1694
|
-
if (host.persistTurn) {
|
|
1695
|
-
host.persistTurn(
|
|
1696
|
-
prompt,
|
|
1697
|
-
result,
|
|
1698
|
-
abortedFlag ? 'stopped' : (result && result.error) ? 'error' : 'done',
|
|
1699
|
-
lastCost
|
|
1700
|
-
);
|
|
1701
|
-
}
|
|
1702
|
-
const usage = result && result.usage;
|
|
1703
|
-
const tokens = host.tokensFor ? host.tokensFor(usage) : null;
|
|
1704
|
-
// The in/out split on this row is the miss/hit split the ledger row,
|
|
1705
|
-
// /cost, /context and the desktop roll all carry — not the raw wire
|
|
1706
|
-
// fields. `usage.input_tokens ?? usage.prompt_tokens` is not a spelling
|
|
1707
|
-
// preference: Anthropic's `input_tokens` EXCLUDES cached reads while
|
|
1708
|
-
// OpenAI's and DeepSeek's `prompt_tokens` INCLUDES the hit, so reading
|
|
1709
|
-
// the raw field printed the entire prompt as fresh input on a cached
|
|
1710
|
-
// turn. On a resumed session that is most of the prompt, which is why
|
|
1711
|
-
// this row's token figure ran so far above the engine's for the same
|
|
1712
|
-
// turn. `usageBuckets` resolves both to the miss half.
|
|
1713
|
-
const buckets = usage ? usageBuckets(usage) : null;
|
|
1714
|
-
push(
|
|
1715
|
-
{
|
|
1716
|
-
role: 'meta',
|
|
1717
|
-
meta: {
|
|
1718
|
-
model: result && result.model,
|
|
1719
|
-
tokens,
|
|
1720
|
-
input: buckets ? buckets.input : null,
|
|
1721
|
-
output: buckets ? buckets.output : null,
|
|
1722
|
-
eur: lastCost,
|
|
1723
|
-
ms: result && result.ms,
|
|
1724
|
-
calls: (result && result.calls) || 1,
|
|
1725
|
-
},
|
|
1726
|
-
},
|
|
1727
|
-
{ follow: false }
|
|
1728
|
-
);
|
|
1729
|
-
// The turn's last row: a one-line delta of what the tools actually did.
|
|
1730
|
-
// Without it the tail of a tool-heavy turn was the accounting row, and
|
|
1731
|
-
// the answer to "what did that change?" was only reachable by scrolling
|
|
1732
|
-
// back up through the tool rows. Follows the viewport EXCEPT when the
|
|
1733
|
-
// reader has scrolled up themselves — scroll is non-zero exactly when
|
|
1734
|
-
// they are mid-read, and yanking them to the bottom then would undo the
|
|
1735
|
-
// scroll they asked for.
|
|
1736
|
-
const counts = summarizeTurnTools(turnTools);
|
|
1737
|
-
if (counts.tools > 0) {
|
|
1738
|
-
push({ role: 'summary', counts }, { follow: scroll === 0 });
|
|
1739
|
-
}
|
|
1740
|
-
render();
|
|
1741
|
-
}
|
|
1742
|
-
};
|
|
1743
|
-
|
|
1744
|
-
// ── inline input (askInput) ──
|
|
1745
|
-
|
|
1746
|
-
const askInput = (title) =>
|
|
1747
|
-
new Promise((resolve) => {
|
|
1748
|
-
inputPrompt = { title, buf: '' };
|
|
1749
|
-
render();
|
|
1750
|
-
(async () => {
|
|
1751
|
-
for (;;) {
|
|
1752
|
-
const key = await nextKey();
|
|
1753
|
-
if (!inputPrompt) {
|
|
1754
|
-
resolve(null);
|
|
1755
|
-
return;
|
|
1756
|
-
}
|
|
1757
|
-
if (key.name === KEY.ESC || key.name === KEY.CTRL_C || key.name === KEY.CTRL_D) {
|
|
1758
|
-
inputPrompt = null;
|
|
1759
|
-
render();
|
|
1760
|
-
resolve(null);
|
|
1761
|
-
return;
|
|
1762
|
-
}
|
|
1763
|
-
if (key.name === KEY.ENTER) {
|
|
1764
|
-
const value = inputPrompt.buf;
|
|
1765
|
-
inputPrompt = null;
|
|
1766
|
-
render();
|
|
1767
|
-
resolve(value);
|
|
1768
|
-
return;
|
|
1769
|
-
}
|
|
1770
|
-
if (key.name === KEY.BACKSPACE) {
|
|
1771
|
-
inputPrompt.buf = [...inputPrompt.buf].slice(0, -1).join('');
|
|
1772
|
-
} else if (key.name === 'char') {
|
|
1773
|
-
inputPrompt.buf += key.ch;
|
|
1774
|
-
} else if (key.name === 'paste') {
|
|
1775
|
-
inputPrompt.buf += String(key.text).replace(/\n/g, ' ');
|
|
1776
|
-
}
|
|
1777
|
-
render();
|
|
1778
|
-
}
|
|
1779
|
-
})();
|
|
1780
|
-
});
|
|
1781
|
-
|
|
1782
|
-
const withWorking = async (fn) => {
|
|
1783
|
-
const prev = abort;
|
|
1784
|
-
working = true;
|
|
1785
|
-
spinnerFrame = 0;
|
|
1786
|
-
startedAt = Date.now();
|
|
1787
|
-
verb = VERBS[turnCount % VERBS.length];
|
|
1788
|
-
abort = new AbortController();
|
|
1789
|
-
spinnerTimer = setInterval(() => {
|
|
1790
|
-
spinnerFrame++;
|
|
1791
|
-
// A slash command that runs long (an export, a compaction) is still this
|
|
1792
|
-
// session working, so the tab spins for it too and keeps the topic it
|
|
1793
|
-
// already had — no prompt here to derive a new one from.
|
|
1794
|
-
setTitle(true);
|
|
1795
|
-
if (spinnerFrame % 3 === 0) render();
|
|
1796
|
-
}, 100);
|
|
1797
|
-
if (spinnerTimer.unref) spinnerTimer.unref();
|
|
1798
|
-
setTitle(true);
|
|
1799
|
-
try {
|
|
1800
|
-
return await fn(abort.signal);
|
|
1801
|
-
} finally {
|
|
1802
|
-
working = false;
|
|
1803
|
-
clearInterval(spinnerTimer);
|
|
1804
|
-
spinnerTimer = null;
|
|
1805
|
-
abort = prev;
|
|
1806
|
-
setTitle(false);
|
|
1807
|
-
render();
|
|
1808
|
-
}
|
|
1809
|
-
};
|
|
1810
|
-
|
|
1811
|
-
// ── the command context this loop owns ──
|
|
1812
|
-
|
|
1813
|
-
const makeContext = () => {
|
|
1814
|
-
const c = host.makeCommandContext();
|
|
1815
|
-
Object.assign(c, {
|
|
1816
|
-
push: (row, o) => {
|
|
1817
|
-
push(row, o);
|
|
1818
|
-
render();
|
|
1819
|
-
},
|
|
1820
|
-
note: (text) => {
|
|
1821
|
-
push({ role: 'note', text });
|
|
1822
|
-
render();
|
|
1823
|
-
},
|
|
1824
|
-
panel: (lines) => {
|
|
1825
|
-
push({ role: 'panel', lines: lines || [] });
|
|
1826
|
-
render();
|
|
1827
|
-
},
|
|
1828
|
-
render: () => render(),
|
|
1829
|
-
openOverlay: (o) => {
|
|
1830
|
-
overlay = o;
|
|
1831
|
-
render();
|
|
1832
|
-
},
|
|
1833
|
-
closeOverlay: () => {
|
|
1834
|
-
overlay = null;
|
|
1835
|
-
showCursor();
|
|
1836
|
-
render();
|
|
1837
|
-
},
|
|
1838
|
-
askInput: (title) => askInput(title),
|
|
1839
|
-
withWorking: (fn) => withWorking(fn),
|
|
1840
|
-
runPrompt: async (text) => {
|
|
1841
|
-
await startResponse(text);
|
|
1842
|
-
},
|
|
1843
|
-
state: () => host.buildState(),
|
|
1844
|
-
setInput: (text) => {
|
|
1845
|
-
editor.buf = String(text == null ? '' : text);
|
|
1846
|
-
editor.end();
|
|
1847
|
-
render();
|
|
1848
|
-
},
|
|
1849
|
-
exit: () => host.requestExit(),
|
|
1850
|
-
openStream: (job) => {
|
|
1851
|
-
streamJob = job || null;
|
|
1852
|
-
streamStartedAt = Date.now();
|
|
1853
|
-
render();
|
|
1854
|
-
},
|
|
1855
|
-
closeStream: (job) => {
|
|
1856
|
-
if (!job || streamJob === job) streamJob = null;
|
|
1857
|
-
render();
|
|
1858
|
-
},
|
|
1859
|
-
showThemePicker: () => {
|
|
1860
|
-
// The app owns the real picker (the 7-row onboarding screen on a TTY,
|
|
1861
|
-
// the light/dark toggle off one). The loop only repaints after it — the
|
|
1862
|
-
// old inline toggle hardcoded themeIndex 0/1, which no longer names
|
|
1863
|
-
// Light/Dark in theme.js's THEME_TABLE (2 is "Light mode").
|
|
1864
|
-
if (host.showThemePicker) host.showThemePicker();
|
|
1865
|
-
render();
|
|
1866
|
-
},
|
|
1867
|
-
});
|
|
1868
|
-
return c;
|
|
1869
|
-
};
|
|
1870
|
-
|
|
1871
|
-
/**
|
|
1872
|
-
* Toggle the edit block painted at a grid row (0-based — the same row
|
|
1873
|
-
* mouseGesture() resolves from the wire). Split out of the click branch so
|
|
1874
|
-
* the gesture resolver can call it for a press that never swept a cell — the
|
|
1875
|
-
* click path and the marking path must agree on what a click is.
|
|
1876
|
-
* Returns true when a block was toggled.
|
|
1877
|
-
*/
|
|
1878
|
-
const toggleAtRow = (row) => {
|
|
1879
|
-
const msg = clickHits.get(row);
|
|
1880
|
-
if (msg && msg.diff) {
|
|
1881
|
-
msg.diffOpen = !msg.diffOpen;
|
|
1882
|
-
return true;
|
|
1883
|
-
}
|
|
1884
|
-
return false;
|
|
1885
|
-
};
|
|
1886
|
-
|
|
1887
|
-
// ── mouse gestures: click-to-toggle vs. drag-to-mark ──────────────────────
|
|
1888
|
-
// With DECSET 1002 (see screen.js enableMouseTracking) the terminal reports
|
|
1889
|
-
// every cell of a sweep, so the SAME left press can end as a click or as a
|
|
1890
|
-
// text marking — the press alone doesn't say which. The gesture is therefore
|
|
1891
|
-
// resolved on RELEASE:
|
|
1892
|
-
//
|
|
1893
|
-
// press → remember the cell; repaint nothing
|
|
1894
|
-
// drag → the press became a marking: anchor at the press, follow the
|
|
1895
|
-
// pointer (the reverse-video paint is the feedback)
|
|
1896
|
-
// release → marking swept more than one cell? copy it, drop it. Otherwise
|
|
1897
|
-
// it was a click: toggle the edit block under the press.
|
|
1898
|
-
//
|
|
1899
|
-
// Toggling on the press instead would flip an edit block open and shut as a
|
|
1900
|
-
// side effect of every drag that started inside one — the block would
|
|
1901
|
-
// collapse the moment the reader tried to select its contents.
|
|
1902
|
-
//
|
|
1903
|
-
// Coordinates arrive 1-based on the wire and grid rows are 0-based, hence the
|
|
1904
|
-
// -1 on both axes. `cell.row` is also the key toggleAtRow() looks up in
|
|
1905
|
-
// clickHits, which buildFrame() fills from the same 0-based frame, so the two
|
|
1906
|
-
// conversions have to agree: a map built one row off toggles the row above the
|
|
1907
|
-
// one the reader clicked, with everything else still looking right.
|
|
1908
|
-
// Selection is read from `frameLines` (the last painted grid), NOT the
|
|
1909
|
-
// transcript, so the copied cells are the ones the reader pointed at.
|
|
1910
|
-
const mouseGesture = (key) => {
|
|
1911
|
-
const cell = { col: key.col - 1, row: key.row - 1 };
|
|
1912
|
-
if (key.name === 'click') { pendingClick = cell; return false; }
|
|
1913
|
-
if (key.name === 'drag') {
|
|
1914
|
-
// A drag with no recorded press (the button went down before the stream
|
|
1915
|
-
// was attached, or a multiplexer dropped the press) still marks: DECSET
|
|
1916
|
-
// 1002 only reports motion while a button is held, so the anchor can be
|
|
1917
|
-
// seeded from the report itself.
|
|
1918
|
-
if (mark) mark.head = cell;
|
|
1919
|
-
else mark = { anchor: pendingClick || cell, head: cell };
|
|
1920
|
-
pendingClick = null;
|
|
1921
|
-
return true;
|
|
1922
|
-
}
|
|
1923
|
-
// release
|
|
1924
|
-
const pressed = pendingClick;
|
|
1925
|
-
pendingClick = null;
|
|
1926
|
-
const sel = mark ? selectionRange(mark.anchor, mark.head) : null;
|
|
1927
|
-
// A press that never swept a cell is a click, not a one-character marking:
|
|
1928
|
-
// an unsteady hand shouldn't leave a glyph on the clipboard.
|
|
1929
|
-
const swept = !!sel && !(sel.startRow === sel.endRow && sel.startCol === sel.endCol);
|
|
1930
|
-
mark = null;
|
|
1931
|
-
if (!swept) return toggleAtRow((pressed || cell).row);
|
|
1932
|
-
const text = selectionText(frameLines, sel);
|
|
1933
|
-
if (!text) return true;
|
|
1934
|
-
// Confirm in the transient hint slot (the line the Tab tip uses) rather
|
|
1935
|
-
// than in the transcript: a copy is a UI action, not a turn, and pushing a
|
|
1936
|
-
// note would edit the conversation the reader is copying FROM.
|
|
1937
|
-
//
|
|
1938
|
-
// The sentence comes from describeCopy() and is therefore honest about
|
|
1939
|
-
// WHERE the text went: on a host with a tool or a terminal that answers
|
|
1940
|
-
// OSC 52 it says the clipboard, and when neither exists it names the file
|
|
1941
|
-
// instead of claiming a copy that never happened. Before, every drag said
|
|
1942
|
-
// "Marked N lines" whether or not anything reached a clipboard.
|
|
1943
|
-
const res = copyToClipboard(text, { stdout: process.stdout, env: process.env });
|
|
1944
|
-
const n = text.split('\n').length;
|
|
1945
|
-
hintText = describeCopy(res, `Marked ${n} line${n === 1 ? '' : 's'}`);
|
|
1946
|
-
hintUntil = Date.now() + 2500;
|
|
1947
|
-
setTimeout(() => { if (Date.now() >= hintUntil) render(); }, 2600);
|
|
1948
|
-
return true;
|
|
1949
|
-
};
|
|
1950
|
-
|
|
1951
|
-
// ── live scroll while a turn runs ──
|
|
1952
|
-
|
|
1953
|
-
const applyLiveScroll = (key) => {
|
|
1954
|
-
let d = null;
|
|
1955
|
-
if (key.name === KEY.PAGE_UP) d = +5;
|
|
1956
|
-
else if (key.name === KEY.PAGE_DOWN) d = -5;
|
|
1957
|
-
else if (key.name === 'wheel') d = key.dir === 'up' ? +3 : -3;
|
|
1958
|
-
// A click mid-turn toggles the same blocks it does when idle, and a drag
|
|
1959
|
-
// marks text mid-turn too: the transcript is already scrollable while the
|
|
1960
|
-
// model works, so it has to stay clickable and markable there — the answer
|
|
1961
|
-
// being streamed is exactly what a reader wants to copy. Resolved through
|
|
1962
|
-
// the shared gesture handler so the click/drag/release triplet can't be
|
|
1963
|
-
// handled two different ways depending on whether a turn happens to run.
|
|
1964
|
-
else if (key.name === 'click' || key.name === 'drag' || key.name === 'release') {
|
|
1965
|
-
if (!mouseGesture(key)) return true; // press: consumed, no repaint
|
|
1966
|
-
scheduleRender();
|
|
1967
|
-
return true;
|
|
1968
|
-
}
|
|
1969
|
-
else if (key.name === 'char' && ctx.vim && !insertMode && !editor.buf) {
|
|
1970
|
-
if (key.ch === 'j') d = +1;
|
|
1971
|
-
else if (key.ch === 'k') d = -1;
|
|
1972
|
-
}
|
|
1973
|
-
if (d === null) return false;
|
|
1974
|
-
scroll = Math.max(0, scroll + d);
|
|
1975
|
-
anchorEnd = null;
|
|
1976
|
-
scheduleRender();
|
|
1977
|
-
return true;
|
|
1978
|
-
};
|
|
1979
|
-
|
|
1980
|
-
// ── mid-turn key drain ──
|
|
1981
|
-
// The loop awaits a turn inline, so it is NOT parked on nextKey() while the
|
|
1982
|
-
// model works. drainWhileWorking keeps it alive by polling for keys: Esc /
|
|
1983
|
-
// Ctrl-C abort the active controller, scroll keys act live, everything else
|
|
1984
|
-
// is replayed into the queue afterwards so typed-ahead text still lands.
|
|
1985
|
-
const drainWhileWorking = (promise, getAbort) => {
|
|
1986
|
-
const replay = [];
|
|
1987
|
-
let settled = false;
|
|
1988
|
-
let result;
|
|
1989
|
-
let error;
|
|
1990
|
-
promise.then(
|
|
1991
|
-
(v) => {
|
|
1992
|
-
settled = true;
|
|
1993
|
-
result = v;
|
|
1994
|
-
},
|
|
1995
|
-
(e) => {
|
|
1996
|
-
settled = true;
|
|
1997
|
-
error = e;
|
|
1998
|
-
}
|
|
1999
|
-
);
|
|
2000
|
-
return (async () => {
|
|
2001
|
-
while (!settled) {
|
|
2002
|
-
if (!working || (overlay && overlay.type === 'confirm')) {
|
|
2003
|
-
await new Promise((r) => setTimeout(r, 60));
|
|
2004
|
-
continue;
|
|
2005
|
-
}
|
|
2006
|
-
const key = await nextKeyTimeout(120);
|
|
2007
|
-
if (key === null) continue;
|
|
2008
|
-
if (key.name === KEY.ESC || key.name === KEY.CTRL_C) {
|
|
2009
|
-
const controller = getAbort && getAbort();
|
|
2010
|
-
if (controller) controller.abort();
|
|
2011
|
-
} else if (!applyLiveScroll(key)) {
|
|
2012
|
-
replay.push(key);
|
|
2013
|
-
}
|
|
2014
|
-
}
|
|
2015
|
-
requeueKeys(replay);
|
|
2016
|
-
if (error) throw error;
|
|
2017
|
-
return result;
|
|
2018
|
-
})();
|
|
2019
|
-
};
|
|
2020
|
-
|
|
2021
|
-
const runGuarded = async (fn, getAbort) => {
|
|
2022
|
-
try {
|
|
2023
|
-
return await drainWhileWorking(fn(), getAbort);
|
|
2024
|
-
} catch (err) {
|
|
2025
|
-
push({ role: 'note', text: `Error: ${(err && err.message) || String(err)}` }, { follow: false });
|
|
2026
|
-
render();
|
|
2027
|
-
return undefined;
|
|
2028
|
-
}
|
|
2029
|
-
};
|
|
2030
|
-
|
|
2031
|
-
// ── key handling on the idle input line ──
|
|
2032
|
-
|
|
2033
|
-
const completeTab = () => {
|
|
2034
|
-
const buf = editor.buf;
|
|
2035
|
-
if (!buf.startsWith('/') || buf.includes(' ')) return false;
|
|
2036
|
-
const q = buf.slice(1);
|
|
2037
|
-
const cands = host
|
|
2038
|
-
.visibleCommands()
|
|
2039
|
-
.flatMap((c) => [c.name, ...(c.aliases || [])])
|
|
2040
|
-
.filter((n) => n.startsWith(q))
|
|
2041
|
-
.sort();
|
|
2042
|
-
if (!cands.length) return false;
|
|
2043
|
-
if (!tabCycle || tabCycle.q !== q) tabCycle = { q, i: -1 };
|
|
2044
|
-
tabCycle.i = (tabCycle.i + 1) % cands.length;
|
|
2045
|
-
editor.buf = '/' + cands[tabCycle.i];
|
|
2046
|
-
editor.end();
|
|
2047
|
-
return true;
|
|
2048
|
-
};
|
|
2049
|
-
|
|
2050
|
-
// The number of rows the active overlay currently renders, so DOWN can clamp
|
|
2051
|
-
// the highlight to the last row instead of running off the end of the list.
|
|
2052
|
-
const overlayRowCount = () => {
|
|
2053
|
-
if (!overlay) return 0;
|
|
2054
|
-
if (overlay.type === 'palette') {
|
|
2055
|
-
return fuzzy.fuzzyRankWithAliases(
|
|
2056
|
-
paletteQuery(overlay.query),
|
|
2057
|
-
host.visibleCommands(),
|
|
2058
|
-
(c) => c.name,
|
|
2059
|
-
(c) => c.aliases || []
|
|
2060
|
-
).length;
|
|
2061
|
-
}
|
|
2062
|
-
if (overlay.type === 'model' || overlay.type === 'resume' || overlay.type === 'class' || overlay.type === 'provider') return (overlay.items || []).length;
|
|
2063
|
-
if (overlay.type === 'effort') return overlays.EFFORT_VALUES.length;
|
|
2064
|
-
return 0;
|
|
2065
|
-
};
|
|
2066
|
-
|
|
2067
|
-
/**
|
|
2068
|
-
* Collect the key a just-picked model needs, when it needs one, and store it
|
|
2069
|
-
* where EVERY host reads it.
|
|
2070
|
-
*
|
|
2071
|
-
* Requirement this exists for: picking a model that has no credential on this
|
|
2072
|
-
* machine must ask for the key there and then, and the answer must be durable
|
|
2073
|
-
* — not a shell export that dies with the terminal, and not a file only this
|
|
2074
|
-
* host knows about. `models.modelKeyPlan` answers "does this row need one?"
|
|
2075
|
-
* through the shared `client/env-file.js` the desktop engine also loads, so
|
|
2076
|
-
* the variable name here and the variable name there cannot drift; that drift
|
|
2077
|
-
* is how the same account ended up holding two private copies of one provider
|
|
2078
|
-
* key and looking unconfigured in whichever host it did not hold.
|
|
2079
|
-
*
|
|
2080
|
-
* Three outcomes, all reported in the transcript rather than swallowed:
|
|
2081
|
-
* stored, already present, or skipped (the row keeps its pin and will fail
|
|
2082
|
-
* with the provider's own error until a key arrives — never a silent no-op).
|
|
2083
|
-
*/
|
|
2084
|
-
const collectKeyFor = async (chosen) => {
|
|
2085
|
-
// EVERY key this row needs, in ask order: the AEGIS account key first (the
|
|
2086
|
-
// pooled route's identity, and what reads the catalog at all), then the
|
|
2087
|
-
// VENDOR key the row is named after when this machine lacks one
|
|
2088
|
-
// (`deepseek` → DEEPSEEK_API_KEY). One prompt was not enough: a pooled row
|
|
2089
|
-
// named after a vendor is billed to the account, but the pool calls that
|
|
2090
|
-
// vendor, so an account key alone left the turn failing upstream with
|
|
2091
|
-
// nothing the user could act on — see models.js modelKeyQueue.
|
|
2092
|
-
//
|
|
2093
|
-
// Both facts about the stores that are NOT the env file are supplied here,
|
|
2094
|
-
// because only the host knows them: `accountConfigured` (credentials.json,
|
|
2095
|
-
// written by /key or `aegiscode login`) and `hasStoredFor` (the
|
|
2096
|
-
// `byok:<provider>` rows the provider store and the desktop's provider
|
|
2097
|
-
// settings share).
|
|
2098
|
-
const queue = models.modelKeyQueue(chosen, {
|
|
2099
|
-
// Never throws: an injected engine may carry no provider store, and a
|
|
2100
|
-
// missing store must read as "no key" rather than break the picker.
|
|
2101
|
-
accountConfigured: host.accountConfigured ? !!host.accountConfigured() : false,
|
|
2102
|
-
hasStoredFor: (vendor) => (host.hasProviderKey ? !!host.hasProviderKey(vendor) : false),
|
|
2103
|
-
});
|
|
2104
|
-
if (!queue.length) {
|
|
2105
|
-
// Quiet on purpose: every key this row needs is already somewhere both
|
|
2106
|
-
// hosts look, and a note per pick would be noise on the common path.
|
|
2107
|
-
return;
|
|
2108
|
-
}
|
|
2109
|
-
let c = null;
|
|
2110
|
-
try { c = host.makeCommandContext(); } catch { c = null; }
|
|
2111
|
-
if (!c || typeof c.readSecret !== 'function') {
|
|
2112
|
-
// No way to ask where the user can answer: name every variable still
|
|
2113
|
-
// missing rather than only the last one, so one round of setup finishes
|
|
2114
|
-
// the job instead of leaving the second key to be discovered by failure.
|
|
2115
|
-
const missing = queue.map((s) => `${s.env}: ${s.why}`).join(' · ');
|
|
2116
|
-
note(`${chosen.id} has no key: ${missing}. Set the ones above and pick it again.`);
|
|
2117
|
-
return;
|
|
2118
|
-
}
|
|
2119
|
-
for (const step of queue) {
|
|
2120
|
-
// Pooled rows bill the account; a vendor step names its provider; the
|
|
2121
|
-
// Claude Code Pro step has neither — it is the subscription's own OAuth
|
|
2122
|
-
// token, minted with `claude setup-token` (or lifted from wherever it is
|
|
2123
|
-
// already set aside). The label says WHICH key is wanted, because two
|
|
2124
|
-
// prompts in a row for the same row must not read as the same question
|
|
2125
|
-
// asked twice.
|
|
2126
|
-
const label = step.role === 'account' ? 'AEGIS account key'
|
|
2127
|
-
: step.role === 'claude-pro' ? 'Claude Code OAuth token (`claude setup-token` mints one)'
|
|
2128
|
-
: `${step.provider} key`;
|
|
2129
|
-
const key = String(
|
|
2130
|
-
(await c.readSecret(`${label} → ${step.env} (kept off screen, Enter to skip): `)) || ''
|
|
2131
|
-
).trim();
|
|
2132
|
-
if (!key) {
|
|
2133
|
-
// Skipping one key must not abandon the rest: the vendor key is still
|
|
2134
|
-
// worth collecting for a row whose account key the user just pasted
|
|
2135
|
-
// elsewhere, and vice versa.
|
|
2136
|
-
note(`no key given — ${step.env} is still unset, so ${chosen.id} will fail until it is.`);
|
|
2137
|
-
continue;
|
|
2138
|
-
}
|
|
2139
|
-
// Shape check before it ever touches disk: this is the same structural
|
|
2140
|
-
// check the account-key login flow has always had (empty / whitespace /
|
|
2141
|
-
// under 16 chars), now applied here too. Without it a truncated paste
|
|
2142
|
-
// (a 2-char clipboard miss, once landed as a literal ANTHROPIC_API_KEY)
|
|
2143
|
-
// writes straight to .env, reads as "configured" to every status check
|
|
2144
|
-
// that only asks `inFile`, and the row fails upstream on every real turn
|
|
2145
|
-
// with an opaque provider error — "key needed" never shows again because
|
|
2146
|
-
// the picker believes it already has one.
|
|
2147
|
-
const shapeLabel = step.role === 'account' ? 'AEGIS'
|
|
2148
|
-
: step.role === 'claude-pro' ? 'Claude Code OAuth'
|
|
2149
|
-
: step.provider || 'that provider';
|
|
2150
|
-
const shape = validateApiKey(key, { label: shapeLabel });
|
|
2151
|
-
if (!shape.ok) {
|
|
2152
|
-
note(`not saved — ${shape.message}. ${step.env} is still unset.`);
|
|
2153
|
-
continue;
|
|
2154
|
-
}
|
|
2155
|
-
// `env: step.env` is what makes a per-step store possible at all: the row
|
|
2156
|
-
// alone cannot say which of its two keys this value is for.
|
|
2157
|
-
const res = models.storeModelKey(chosen, shape.key, { env: step.env });
|
|
2158
|
-
if (!res.ok) {
|
|
2159
|
-
note(`could not save the key: ${res.error || 'unknown error'}`);
|
|
2160
|
-
continue;
|
|
2161
|
-
}
|
|
2162
|
-
// A foreign secret (CLAUDE_CODE_OAUTH_TOKEN) lands in secrets.env, which
|
|
2163
|
-
// is read explicitly by the one transport that needs it — not loaded
|
|
2164
|
-
// ambiently at start-up the way `.env` is — so it gets its own wording
|
|
2165
|
-
// rather than the "both hosts read that file" line, which is true of
|
|
2166
|
-
// `.env` and would overstate what secrets.env actually does.
|
|
2167
|
-
note(res.changed
|
|
2168
|
-
? res.foreign
|
|
2169
|
-
? `${step.env} saved to ${res.file} (0600) — read only by the Claude Code Pro transport, never exported.`
|
|
2170
|
-
: `${step.env} saved to ${res.file} (0600) — both hosts read that file; nothing to export.`
|
|
2171
|
-
: `${step.env} was already set in ${res.file}.`);
|
|
2172
|
-
}
|
|
2173
|
-
};
|
|
2174
|
-
|
|
2175
|
-
/**
|
|
2176
|
-
* Pin a model row — the ONE path a row is applied through, shared by Enter,
|
|
2177
|
-
* shift+enter and the shift+arrow chord. Written out once because applying a
|
|
2178
|
-
* model is not just a config write: it may have to move the class first and
|
|
2179
|
-
* it may have to collect the provider key the row needs. A second apply path
|
|
2180
|
-
* would eventually skip one of those (the reference's own picker pinned the
|
|
2181
|
-
* id and left the class behind), and the user would be running on a model
|
|
2182
|
-
* whose key this machine does not hold.
|
|
2183
|
-
*/
|
|
2184
|
-
const applyModelRow = async (chosen) => {
|
|
2185
|
-
if (!chosen) return;
|
|
2186
|
-
{
|
|
2187
|
-
// Swap an anthropic byok row for the equivalent Claude Code Pro alias
|
|
2188
|
-
// when this machine is signed into the subscription and holds no real
|
|
2189
|
-
// console key — see `overrideAnthropicByokWithPro` (module scope, pure)
|
|
2190
|
-
// for the full reasoning.
|
|
2191
|
-
const plan = models.modelKeyPlan(chosen, {
|
|
2192
|
-
hasStored: host.hasProviderKey ? !!host.hasProviderKey('anthropic') : false,
|
|
2193
|
-
});
|
|
2194
|
-
const { row, message } = overrideAnthropicByokWithPro(chosen, {
|
|
2195
|
-
needsKey: !!(plan && plan.needed),
|
|
2196
|
-
proLoggedIn: models.claudeProLoggedIn(),
|
|
2197
|
-
// The same gate `/class pro on` writes: a disabled subscription is not
|
|
2198
|
-
// reachable by this reroute either.
|
|
2199
|
-
proEnabled: (() => {
|
|
2200
|
-
try {
|
|
2201
|
-
return loadConfig().proEnabled === true;
|
|
2202
|
-
} catch {
|
|
2203
|
-
return false;
|
|
2204
|
-
}
|
|
2205
|
-
})(),
|
|
2206
|
-
proModels: claudePro.PRO_MODELS,
|
|
2207
|
-
});
|
|
2208
|
-
chosen = row;
|
|
2209
|
-
if (message) note(message);
|
|
2210
|
-
}
|
|
2211
|
-
// A row that belongs to another class moves the session to that class
|
|
2212
|
-
// BEFORE the pin is stored, for the same reason byok's row does (and it is
|
|
2213
|
-
// the same one-line rule, not a second copy of it): a pro alias pinned while
|
|
2214
|
-
// the session sits on aegis would be sent to the pool as an AEGIS id, and
|
|
2215
|
-
// an AEGIS id pinned under pro would be handed to `claude --model`. Both
|
|
2216
|
-
// fail on the next turn, with a message about a model rather than the class.
|
|
2217
|
-
if (chosen.cls && chosen.cls !== 'aegis' && ctx.modelClass !== chosen.cls) {
|
|
2218
|
-
await dispatch(`/class ${chosen.cls}`);
|
|
2219
|
-
}
|
|
2220
|
-
ctx.model = chosen.id;
|
|
2221
|
-
host.updateConfig({ model: chosen.id, currentModelId: chosen.id, modelClass: ctx.modelClass });
|
|
2222
|
-
note(`model: ${chosen.id}${chosen.cls === 'byok' ? ' (byok)' : chosen.cls === 'pro' ? ' (Claude Code Pro)' : ''}`);
|
|
2223
|
-
await collectKeyFor(chosen);
|
|
2224
|
-
};
|
|
2225
|
-
|
|
2226
|
-
/**
|
|
2227
|
-
* Switch class from a /class picker row — routed through the `/class`
|
|
2228
|
-
* command itself (not a second copy of switchClass + the byok auto-pin
|
|
2229
|
-
* fallback) so the picker and `/class <id>` typed by hand can never
|
|
2230
|
-
* disagree about what picking a class does.
|
|
2231
|
-
*/
|
|
2232
|
-
const applyClassRow = async (chosen) => {
|
|
2233
|
-
if (!chosen || !chosen.class) return;
|
|
2234
|
-
await dispatch(`/class ${chosen.class}`);
|
|
2235
|
-
};
|
|
2236
|
-
|
|
2237
|
-
/**
|
|
2238
|
-
* Pin an effort rung — the ONE path a rung is applied through, shared by
|
|
2239
|
-
* Enter, shift+enter and the shift+arrow chords.
|
|
2240
|
-
*
|
|
2241
|
-
* It resolves the row through the picker's OWN table (overlays.EFFORT_VALUES),
|
|
2242
|
-
* which is the point: this used to re-declare ['low','medium','high'] at each
|
|
2243
|
-
* commit site while the picker drew its own list, so the row a user picked and
|
|
2244
|
-
* the value the session stored came from two different lists. A rung the
|
|
2245
|
-
* picker does not draw can no longer be stored, and a row it does draw can no
|
|
2246
|
-
* longer store a different value than the one it painted.
|
|
2247
|
-
*/
|
|
2248
|
-
const applyEffortRow = (sel) => {
|
|
2249
|
-
const chosen = overlays.EFFORT_VALUES[sel || 0];
|
|
2250
|
-
overlay = null;
|
|
2251
|
-
ctx.effort = chosen || 'high';
|
|
2252
|
-
host.updateConfig({ effort: ctx.effort });
|
|
2253
|
-
note(`effort: ${ctx.effort}`);
|
|
2254
|
-
render();
|
|
2255
|
-
};
|
|
2256
|
-
|
|
2257
|
-
const handleOverlayKey = async (key) => {
|
|
2258
|
-
const type = overlay.type;
|
|
2259
|
-
if (key.name === KEY.ESC || key.name === KEY.CTRL_C) {
|
|
2260
|
-
overlay = null;
|
|
2261
|
-
render();
|
|
2262
|
-
return;
|
|
2263
|
-
}
|
|
2264
|
-
if (type === 'shortcuts' || type === 'panel') {
|
|
2265
|
-
overlay = null;
|
|
2266
|
-
render();
|
|
2267
|
-
return;
|
|
2268
|
-
}
|
|
2269
|
-
if (key.name === KEY.TAB && type === 'palette') {
|
|
2270
|
-
// Tab completes the query to the highlighted command. The ranking is
|
|
2271
|
-
// `paletteRows()`, the same list the frame drew and Enter runs, so the
|
|
2272
|
-
// row completed is the row highlighted. Nothing highlighted (no matches)
|
|
2273
|
-
// → do nothing.
|
|
2274
|
-
const chosen = paletteRows()[overlay.sel || 0];
|
|
2275
|
-
if (chosen) {
|
|
2276
|
-
overlay.query = chosen.name;
|
|
2277
|
-
overlay.sel = 0;
|
|
2278
|
-
render();
|
|
2279
|
-
}
|
|
2280
|
-
return;
|
|
2281
|
-
}
|
|
2282
|
-
if (key.name === KEY.TAB && (type === 'model' || type === 'effort' || type === 'class' || type === 'provider')) {
|
|
2283
|
-
// Reference parity (aegiscodex-dev/src/main.js's model overlay cycles on
|
|
2284
|
-
// Tab). It is also the one way to walk either picker that survives a link
|
|
2285
|
-
// where arrow escapes are eaten, since Tab is a single control byte.
|
|
2286
|
-
// Both lists are addressed the one way each of them can be: the catalogue
|
|
2287
|
-
// lives in `overlay.items`, while the rungs are the picker's own table —
|
|
2288
|
-
// the same table Enter and shift+enter resolve through.
|
|
2289
|
-
const n = type === 'model' || type === 'class' || type === 'provider'
|
|
2290
|
-
? (overlay.items || []).length
|
|
2291
|
-
: overlays.EFFORT_VALUES.length;
|
|
2292
|
-
if (n) {
|
|
2293
|
-
overlay.sel = ((overlay.sel || 0) + 1) % n;
|
|
2294
|
-
render();
|
|
2295
|
-
}
|
|
2296
|
-
return;
|
|
2297
|
-
}
|
|
2298
|
-
if (key.name === KEY.ENTER) {
|
|
2299
|
-
if (type === 'palette') {
|
|
2300
|
-
// Rank with the same function the palette rendered with, so the row
|
|
2301
|
-
// highlighted is the row Enter runs.
|
|
2302
|
-
const chosen = paletteRows()[overlay.sel || 0];
|
|
2303
|
-
const arg = String(overlay.query || '').trim().split(/\s+/).slice(1).join(' ');
|
|
2304
|
-
overlay = null;
|
|
2305
|
-
render();
|
|
2306
|
-
if (chosen) {
|
|
2307
|
-
await dispatch(arg ? `/${chosen.name} ${arg}` : `/${chosen.name}`);
|
|
2308
|
-
}
|
|
2309
|
-
return;
|
|
2310
|
-
}
|
|
2311
|
-
if (type === 'model') {
|
|
2312
|
-
const chosen = (overlay.items || [])[overlay.sel || 0];
|
|
2313
|
-
overlay = null;
|
|
2314
|
-
render();
|
|
2315
|
-
await applyModelRow(chosen);
|
|
2316
|
-
render();
|
|
2317
|
-
return;
|
|
2318
|
-
}
|
|
2319
|
-
if (type === 'effort') {
|
|
2320
|
-
// The picker's own order, not a second copy of the level names: this
|
|
2321
|
-
// used to re-declare ['low','medium','high'] here while the picker drew
|
|
2322
|
-
// its own table, so the row a user picked and the value it stored were
|
|
2323
|
-
// resolved through different lists. (See applyEffortRow.)
|
|
2324
|
-
applyEffortRow(overlay.sel || 0);
|
|
2325
|
-
return;
|
|
2326
|
-
}
|
|
2327
|
-
if (type === 'class') {
|
|
2328
|
-
const chosen = (overlay.items || [])[overlay.sel || 0];
|
|
2329
|
-
overlay = null;
|
|
2330
|
-
render();
|
|
2331
|
-
await applyClassRow(chosen);
|
|
2332
|
-
render();
|
|
2333
|
-
return;
|
|
2334
|
-
}
|
|
2335
|
-
if (type === 'provider') {
|
|
2336
|
-
// The BYOK provider pick: run the command that opened this picker with
|
|
2337
|
-
// the highlighted provider's own catalog id, so the id that reaches the
|
|
2338
|
-
// store is the id the relay is asked for — never a hand-retyped alias
|
|
2339
|
-
// (the `findByokProvider` loose match this replaces could land on the
|
|
2340
|
-
// wrong vendor, which is the failure the whole path exists to prevent).
|
|
2341
|
-
// `overlay.command` names the command to re-enter: /byok-key stores on
|
|
2342
|
-
// this machine, /byok-set stores on the account.
|
|
2343
|
-
const chosen = (overlay.items || [])[overlay.sel || 0];
|
|
2344
|
-
const cmd = overlay.command || 'byok-key';
|
|
2345
|
-
overlay = null;
|
|
2346
|
-
render();
|
|
2347
|
-
if (chosen && chosen.id) await dispatch(`/${cmd} ${chosen.id}`);
|
|
2348
|
-
return;
|
|
2349
|
-
}
|
|
2350
|
-
if (type === 'resume') {
|
|
2351
|
-
const chosen = (overlay.items || [])[overlay.sel || 0];
|
|
2352
|
-
overlay = null;
|
|
2353
|
-
render();
|
|
2354
|
-
if (chosen && host.resumeSession) await host.resumeSession(chosen);
|
|
2355
|
-
return;
|
|
2356
|
-
}
|
|
2357
|
-
overlay = null;
|
|
2358
|
-
render();
|
|
2359
|
-
return;
|
|
2360
|
-
}
|
|
2361
|
-
if (key.name === KEY.SHIFT_UP || key.name === KEY.SHIFT_DOWN) {
|
|
2362
|
-
// Shift is the one-keystroke commit in the two pickers that write a
|
|
2363
|
-
// setting: it moves the highlight one row in the pressed direction and
|
|
2364
|
-
// applies THAT row immediately, so changing the model is a single key
|
|
2365
|
-
// instead of point-then-Enter. It routes into the same apply paths Enter
|
|
2366
|
-
// uses, so the chord cannot pin a model Enter would refuse to pin, skip
|
|
2367
|
-
// the provider-key prompt a byok row needs, or store an effort level the
|
|
2368
|
-
// picker's own table does not contain.
|
|
2369
|
-
const step = key.name === KEY.SHIFT_UP ? -1 : 1;
|
|
2370
|
-
const max = Math.max(0, overlayRowCount() - 1);
|
|
2371
|
-
overlay.sel = Math.min(max, Math.max(0, (overlay.sel || 0) + step));
|
|
2372
|
-
if (type === 'model') {
|
|
2373
|
-
const chosen = (overlay.items || [])[overlay.sel || 0];
|
|
2374
|
-
overlay = null;
|
|
2375
|
-
render();
|
|
2376
|
-
await applyModelRow(chosen);
|
|
2377
|
-
render();
|
|
2378
|
-
return;
|
|
2379
|
-
}
|
|
2380
|
-
if (type === 'class') {
|
|
2381
|
-
const chosen = (overlay.items || [])[overlay.sel || 0];
|
|
2382
|
-
overlay = null;
|
|
2383
|
-
render();
|
|
2384
|
-
await applyClassRow(chosen);
|
|
2385
|
-
render();
|
|
2386
|
-
return;
|
|
2387
|
-
}
|
|
2388
|
-
if (type === 'provider') {
|
|
2389
|
-
// The BYOK provider pick: run the command that opened this picker with
|
|
2390
|
-
// the highlighted provider's own catalog id, so the id that reaches the
|
|
2391
|
-
// store is the id the relay is asked for — never a hand-retyped alias
|
|
2392
|
-
// (the `findByokProvider` loose match this replaces could land on the
|
|
2393
|
-
// wrong vendor, which is the failure the whole path exists to prevent).
|
|
2394
|
-
// `overlay.command` names the command to re-enter: /byok-key stores on
|
|
2395
|
-
// this machine, /byok-set stores on the account.
|
|
2396
|
-
const chosen = (overlay.items || [])[overlay.sel || 0];
|
|
2397
|
-
const cmd = overlay.command || 'byok-key';
|
|
2398
|
-
overlay = null;
|
|
2399
|
-
render();
|
|
2400
|
-
if (chosen && chosen.id) await dispatch(`/${cmd} ${chosen.id}`);
|
|
2401
|
-
return;
|
|
2402
|
-
}
|
|
2403
|
-
if (type === 'effort') {
|
|
2404
|
-
applyEffortRow(overlay.sel || 0);
|
|
2405
|
-
return;
|
|
2406
|
-
}
|
|
2407
|
-
render();
|
|
2408
|
-
return;
|
|
2409
|
-
}
|
|
2410
|
-
if (key.name === KEY.SHIFT_ENTER) {
|
|
2411
|
-
// The same commit as Enter, in the spelling terminals that have no other
|
|
2412
|
-
// way to send it: on the palette it runs the highlighted command without
|
|
2413
|
-
// the user reaching for the Enter key proper, and in a picker it applies
|
|
2414
|
-
// the highlighted row. Both read the same sel/items every other path
|
|
2415
|
-
// reads, so the chord cannot run a different row than the frame drew.
|
|
2416
|
-
if (type === 'palette') {
|
|
2417
|
-
const chosen = paletteRows()[overlay.sel || 0];
|
|
2418
|
-
overlay = null;
|
|
2419
|
-
render();
|
|
2420
|
-
if (chosen) await dispatch(`/${chosen.name}`);
|
|
2421
|
-
return;
|
|
2422
|
-
}
|
|
2423
|
-
if (type === 'model') {
|
|
2424
|
-
const chosen = (overlay.items || [])[overlay.sel || 0];
|
|
2425
|
-
overlay = null;
|
|
2426
|
-
render();
|
|
2427
|
-
await applyModelRow(chosen);
|
|
2428
|
-
render();
|
|
2429
|
-
return;
|
|
2430
|
-
}
|
|
2431
|
-
if (type === 'class') {
|
|
2432
|
-
const chosen = (overlay.items || [])[overlay.sel || 0];
|
|
2433
|
-
overlay = null;
|
|
2434
|
-
render();
|
|
2435
|
-
await applyClassRow(chosen);
|
|
2436
|
-
render();
|
|
2437
|
-
return;
|
|
2438
|
-
}
|
|
2439
|
-
if (type === 'provider') {
|
|
2440
|
-
// The BYOK provider pick: run the command that opened this picker with
|
|
2441
|
-
// the highlighted provider's own catalog id, so the id that reaches the
|
|
2442
|
-
// store is the id the relay is asked for — never a hand-retyped alias
|
|
2443
|
-
// (the `findByokProvider` loose match this replaces could land on the
|
|
2444
|
-
// wrong vendor, which is the failure the whole path exists to prevent).
|
|
2445
|
-
// `overlay.command` names the command to re-enter: /byok-key stores on
|
|
2446
|
-
// this machine, /byok-set stores on the account.
|
|
2447
|
-
const chosen = (overlay.items || [])[overlay.sel || 0];
|
|
2448
|
-
const cmd = overlay.command || 'byok-key';
|
|
2449
|
-
overlay = null;
|
|
2450
|
-
render();
|
|
2451
|
-
if (chosen && chosen.id) await dispatch(`/${cmd} ${chosen.id}`);
|
|
2452
|
-
return;
|
|
2453
|
-
}
|
|
2454
|
-
if (type === 'effort') {
|
|
2455
|
-
applyEffortRow(overlay.sel || 0);
|
|
2456
|
-
return;
|
|
2457
|
-
}
|
|
2458
|
-
return;
|
|
2459
|
-
}
|
|
2460
|
-
if (key.name === KEY.UP || key.name === KEY.DOWN) {
|
|
2461
|
-
// NAVIGATION ONLY — this is the reference's binding and it has to stay
|
|
2462
|
-
// that way. A plain arrow that applies the row it lands on cannot browse:
|
|
2463
|
-
// the overlay closes on the first press, the model is already changed,
|
|
2464
|
-
// and the other fifteen rows are unreachable. The reference moves the
|
|
2465
|
-
// highlight here and commits on Enter (aegiscodex-dev/src/main.js
|
|
2466
|
-
// navList + the KEY.ENTER branch of its model overlay); the one-keystroke
|
|
2467
|
-
// commit belongs to the shift chords below, which are additive and
|
|
2468
|
-
// explicit, not to the arrow every picker in the app uses to point.
|
|
2469
|
-
// Bounds come from the list being drawn, exactly as navList does it.
|
|
2470
|
-
const n = (overlay.items || []).length || overlayRowCount();
|
|
2471
|
-
const step = key.name === KEY.UP ? -1 : 1;
|
|
2472
|
-
overlay.sel = Math.min(Math.max(0, n - 1), Math.max(0, (overlay.sel || 0) + step));
|
|
2473
|
-
render();
|
|
2474
|
-
return;
|
|
2475
|
-
}
|
|
2476
|
-
if (key.name === 'char') {
|
|
2477
|
-
if (type === 'palette') {
|
|
2478
|
-
overlay.query = (overlay.query || '') + key.ch;
|
|
2479
|
-
overlay.sel = 0;
|
|
2480
|
-
render();
|
|
2481
|
-
return;
|
|
2482
|
-
}
|
|
2483
|
-
// There is deliberately NO shift+w / shift+s chord here. It existed (it
|
|
2484
|
-
// arrived as the bare chars 'W'/'S' — a real signal that survives links
|
|
2485
|
-
// which eat CSI arrow escapes) and it was removed on request: one
|
|
2486
|
-
// navigation binding is all these pickers need, and Tab already is that
|
|
2487
|
-
// binding — a single control byte, so it survives the same transports the
|
|
2488
|
-
// letter chord was there for, without a second way to move that then has
|
|
2489
|
-
// to be kept in step with the first. Tab cycles (above), Enter pins,
|
|
2490
|
-
// shift+↑/↓ pins as it moves for terminals that send CSI modifier 2, and
|
|
2491
|
-
// a plain uppercase letter in a picker now does nothing at all — it falls
|
|
2492
|
-
// through to the row-number branch below, which correctly ignores it.
|
|
2493
|
-
if (type === 'model') {
|
|
2494
|
-
const idx = parseInt(key.ch, 10);
|
|
2495
|
-
const items = overlay.items || [];
|
|
2496
|
-
if (Number.isFinite(idx) && idx >= 1 && idx <= items.length) {
|
|
2497
|
-
overlay.sel = idx - 1;
|
|
2498
|
-
render();
|
|
2499
|
-
}
|
|
2500
|
-
return;
|
|
2501
|
-
}
|
|
2502
|
-
if (type === 'effort' || type === 'resume' || type === 'class' || type === 'provider') {
|
|
2503
|
-
// Bounded by the same row count every other mover is bounded by. A row
|
|
2504
|
-
// number past the end used to be accepted unseen (`sel = idx - 1` with
|
|
2505
|
-
// no upper clamp), so '9' in /effort parked the highlight off the list
|
|
2506
|
-
// and Enter then stored the 'high' fallback for a row that was never
|
|
2507
|
-
// drawn — silently, since nothing was highlighted to contradict it.
|
|
2508
|
-
const idx = parseInt(key.ch, 10);
|
|
2509
|
-
const n = overlayRowCount();
|
|
2510
|
-
if (Number.isFinite(idx) && idx >= 1 && idx <= n) {
|
|
2511
|
-
overlay.sel = idx - 1;
|
|
2512
|
-
render();
|
|
2513
|
-
}
|
|
2514
|
-
return;
|
|
2515
|
-
}
|
|
2516
|
-
}
|
|
2517
|
-
if (key.name === KEY.BACKSPACE && type === 'palette') {
|
|
2518
|
-
overlay.query = String(overlay.query || '').slice(0, -1);
|
|
2519
|
-
render();
|
|
2520
|
-
}
|
|
2521
|
-
};
|
|
2522
|
-
|
|
2523
|
-
const handleKey = async (key) => {
|
|
2524
|
-
// No key is not a key. The pump can legitimately deliver nothing — a reset
|
|
2525
|
-
// during teardown, a stdin that closed before the keystroke landed — and
|
|
2526
|
-
// that used to reach `key.name` and throw, which the loop's catch turned
|
|
2527
|
-
// into a stray note and another park. See the STREAM_END branch in the
|
|
2528
|
-
// session loop for what that cost.
|
|
2529
|
-
if (!key) return;
|
|
2530
|
-
if (overlay) {
|
|
2531
|
-
await handleOverlayKey(key);
|
|
2532
|
-
return;
|
|
2533
|
-
}
|
|
2534
|
-
// A bare '/' opens the palette and a bare '?' the shortcuts grid — the
|
|
2535
|
-
// reference opens both on the keystroke (main.js:1542-1543), not after
|
|
2536
|
-
// Enter. With text already in the line both insert literally, so '/model'
|
|
2537
|
-
// and 'why?' still type.
|
|
2538
|
-
if (key.name === 'char' && !editor.buf) {
|
|
2539
|
-
if (key.ch === '/') {
|
|
2540
|
-
overlay = { type: 'palette', query: '', sel: 0 };
|
|
2541
|
-
render();
|
|
2542
|
-
return;
|
|
2543
|
-
}
|
|
2544
|
-
if (key.ch === '?') {
|
|
2545
|
-
overlay = { type: 'shortcuts' };
|
|
2546
|
-
render();
|
|
2547
|
-
return;
|
|
2548
|
-
}
|
|
2549
|
-
}
|
|
2550
|
-
// vim normal-mode motions (only when the buffer is empty, so j/k do not
|
|
2551
|
-
// fight typed text).
|
|
2552
|
-
if (ctx.vim && !insertMode && !editor.buf && key.name === 'char') {
|
|
2553
|
-
const ch = key.ch;
|
|
2554
|
-
if (ch === 'i' || ch === 'a' || ch === 'o' || ch === 's' || ch === 'S') {
|
|
2555
|
-
if (ch === 's') editor.substChar();
|
|
2556
|
-
if (ch === 'S') editor.substLine();
|
|
2557
|
-
if (ch === 'a') editor.right();
|
|
2558
|
-
insertMode = true;
|
|
2559
|
-
render();
|
|
2560
|
-
return;
|
|
2561
|
-
}
|
|
2562
|
-
if (ch === 'h') {
|
|
2563
|
-
editor.left();
|
|
2564
|
-
render();
|
|
2565
|
-
return;
|
|
2566
|
-
}
|
|
2567
|
-
if (ch === 'l') {
|
|
2568
|
-
editor.right();
|
|
2569
|
-
render();
|
|
2570
|
-
return;
|
|
2571
|
-
}
|
|
2572
|
-
if (ch === '0') {
|
|
2573
|
-
editor.home();
|
|
2574
|
-
render();
|
|
2575
|
-
return;
|
|
2576
|
-
}
|
|
2577
|
-
if (ch === '$') {
|
|
2578
|
-
editor.end();
|
|
2579
|
-
render();
|
|
2580
|
-
return;
|
|
2581
|
-
}
|
|
2582
|
-
if (ch === 'x') {
|
|
2583
|
-
editor.delete();
|
|
2584
|
-
render();
|
|
2585
|
-
return;
|
|
2586
|
-
}
|
|
2587
|
-
if (ch === 'D') {
|
|
2588
|
-
editor.killToEnd();
|
|
2589
|
-
render();
|
|
2590
|
-
return;
|
|
2591
|
-
}
|
|
2592
|
-
if (ch === 'A') {
|
|
2593
|
-
editor.end();
|
|
2594
|
-
insertMode = true;
|
|
2595
|
-
render();
|
|
2596
|
-
return;
|
|
2597
|
-
}
|
|
2598
|
-
if (applyLiveScroll(key)) return;
|
|
2599
|
-
} else if (ctx.vim && insertMode && key.name === KEY.ESC) {
|
|
2600
|
-
insertMode = false;
|
|
2601
|
-
if (editor.cursor > 0) editor.cursor--;
|
|
2602
|
-
render();
|
|
2603
|
-
return;
|
|
2604
|
-
}
|
|
2605
|
-
|
|
2606
|
-
if (key.name === KEY.ENTER) {
|
|
2607
|
-
const text = editor.submit();
|
|
2608
|
-
tabCycle = null;
|
|
2609
|
-
insertMode = false;
|
|
2610
|
-
if (!text) {
|
|
2611
|
-
render();
|
|
2612
|
-
return;
|
|
2613
|
-
}
|
|
2614
|
-
await dispatch(text);
|
|
2615
|
-
return;
|
|
2616
|
-
}
|
|
2617
|
-
if (key.name === KEY.CTRL_V) {
|
|
2618
|
-
pasteClipboard();
|
|
2619
|
-
return;
|
|
2620
|
-
}
|
|
2621
|
-
if (key.name === KEY.CTRL_B) {
|
|
2622
|
-
copyTranscript();
|
|
2623
|
-
return;
|
|
2624
|
-
}
|
|
2625
|
-
if (key.name === 'paste') {
|
|
2626
|
-
if (ctx.vim) insertMode = true;
|
|
2627
|
-
editor.insert(String(key.text));
|
|
2628
|
-
render();
|
|
2629
|
-
return;
|
|
2630
|
-
}
|
|
2631
|
-
if (key.name === 'char') {
|
|
2632
|
-
if (ctx.vim && !insertMode) {
|
|
2633
|
-
// A printable key in normal mode is not typed text; ignore it (the
|
|
2634
|
-
// user must press i/a first), matching the reference keymap.
|
|
2635
|
-
render();
|
|
2636
|
-
return;
|
|
2637
|
-
}
|
|
2638
|
-
editor.insert(key.ch);
|
|
2639
|
-
render();
|
|
2640
|
-
return;
|
|
2641
|
-
}
|
|
2642
|
-
if (key.name === KEY.BACKSPACE) {
|
|
2643
|
-
editor.backspace();
|
|
2644
|
-
render();
|
|
2645
|
-
return;
|
|
2646
|
-
}
|
|
2647
|
-
if (key.name === KEY.DELETE) {
|
|
2648
|
-
editor.delete();
|
|
2649
|
-
render();
|
|
2650
|
-
return;
|
|
2651
|
-
}
|
|
2652
|
-
if (key.name === KEY.LEFT || key.name === KEY.CTRL_LEFT) {
|
|
2653
|
-
if (key.name === KEY.CTRL_LEFT) editor.wordBack();
|
|
2654
|
-
else editor.left();
|
|
2655
|
-
render();
|
|
2656
|
-
return;
|
|
2657
|
-
}
|
|
2658
|
-
// → on an empty line switches the approval mode (manual ⇄ auto) — the chord
|
|
2659
|
-
// the status line advertises. With an empty buffer the cursor already sits
|
|
2660
|
-
// at column 0, so `editor.right()` was a no-op there: the binding costs no
|
|
2661
|
-
// editing behaviour, and a line with text keeps plain cursor movement.
|
|
2662
|
-
if (key.name === KEY.RIGHT && !editor.buf) {
|
|
2663
|
-
await dispatch(!(host.isYolo && host.isYolo()) ? '/automode on' : '/automode off');
|
|
2664
|
-
return;
|
|
2665
|
-
}
|
|
2666
|
-
if (key.name === KEY.RIGHT || key.name === KEY.CTRL_RIGHT) {
|
|
2667
|
-
editor.right();
|
|
2668
|
-
render();
|
|
2669
|
-
return;
|
|
2670
|
-
}
|
|
2671
|
-
if (key.name === KEY.HOME || key.name === KEY.CTRL_A) {
|
|
2672
|
-
editor.home();
|
|
2673
|
-
render();
|
|
2674
|
-
return;
|
|
2675
|
-
}
|
|
2676
|
-
if (key.name === KEY.END || key.name === KEY.CTRL_E) {
|
|
2677
|
-
editor.end();
|
|
2678
|
-
render();
|
|
2679
|
-
return;
|
|
2680
|
-
}
|
|
2681
|
-
if (key.name === KEY.UP) {
|
|
2682
|
-
editor.historyUp();
|
|
2683
|
-
render();
|
|
2684
|
-
return;
|
|
2685
|
-
}
|
|
2686
|
-
if (key.name === KEY.DOWN) {
|
|
2687
|
-
editor.historyDown();
|
|
2688
|
-
render();
|
|
2689
|
-
return;
|
|
2690
|
-
}
|
|
2691
|
-
if (key.name === KEY.TAB) {
|
|
2692
|
-
// completeTab cycles command names; when it finds nothing, flash the
|
|
2693
|
-
// reference's hint in the idle line — the alt+t nudge on an empty buffer,
|
|
2694
|
-
// a "Tab completes" reminder once text is typed (main.js:1598-1606).
|
|
2695
|
-
// hintUntil/hintText were declared and rendered but never set.
|
|
2696
|
-
if (!completeTab()) {
|
|
2697
|
-
hintText = editor.buf ? 'Tab completes commands' : 'Use alt+t to toggle thinking';
|
|
2698
|
-
hintUntil = Date.now() + 2500;
|
|
2699
|
-
setTimeout(() => {
|
|
2700
|
-
if (Date.now() >= hintUntil) render();
|
|
2701
|
-
}, 2600);
|
|
2702
|
-
}
|
|
2703
|
-
render();
|
|
2704
|
-
return;
|
|
2705
|
-
}
|
|
2706
|
-
if (key.name === KEY.CTRL_U) {
|
|
2707
|
-
editor.buf = '';
|
|
2708
|
-
editor.cursor = 0;
|
|
2709
|
-
render();
|
|
2710
|
-
return;
|
|
2711
|
-
}
|
|
2712
|
-
if (key.name === KEY.CTRL_K) {
|
|
2713
|
-
editor.killToEnd();
|
|
2714
|
-
render();
|
|
2715
|
-
return;
|
|
2716
|
-
}
|
|
2717
|
-
if (key.name === KEY.CTRL_W) {
|
|
2718
|
-
// Word-rubout: step the cursor back a word, no deletion — the reference's
|
|
2719
|
-
// Ctrl+W (main.js:1624). LineEditor.wordBack is the method that exists.
|
|
2720
|
-
editor.wordBack();
|
|
2721
|
-
render();
|
|
2722
|
-
return;
|
|
2723
|
-
}
|
|
2724
|
-
if (key.name === KEY.CTRL_L) {
|
|
2725
|
-
clearScreen();
|
|
2726
|
-
render();
|
|
2727
|
-
return;
|
|
2728
|
-
}
|
|
2729
|
-
if (key.name === KEY.CTRL_T) {
|
|
2730
|
-
note(host.tokenSummary ? host.tokenSummary() : 'no token usage yet this session');
|
|
2731
|
-
render();
|
|
2732
|
-
return;
|
|
2733
|
-
}
|
|
2734
|
-
if (key.name === KEY.CTRL_R) {
|
|
2735
|
-
await dispatch('/resume');
|
|
2736
|
-
return;
|
|
2737
|
-
}
|
|
2738
|
-
if (key.name === KEY.CTRL_O) {
|
|
2739
|
-
// Keybinding parity: Ctrl+O opens the permissions panel (main.js:1644),
|
|
2740
|
-
// which /permissions already renders in this CLI.
|
|
2741
|
-
await dispatch('/permissions');
|
|
2742
|
-
return;
|
|
2743
|
-
}
|
|
2744
|
-
if (key.name === 'click' || key.name === 'drag' || key.name === 'release') {
|
|
2745
|
-
// Consumed here: it toggles an edit row's diff block or marks/copies
|
|
2746
|
-
// text, but must never fall through to the input editor. Routed through
|
|
2747
|
-
// applyLiveScroll so the idle path and the mid-turn path share one
|
|
2748
|
-
// gesture resolver — handling only 'click' here left a drag-to-mark
|
|
2749
|
-
// silently dropped at the idle prompt (the release fell through to the
|
|
2750
|
-
// editor, which ignored it), so marking only worked mid-turn.
|
|
2751
|
-
applyLiveScroll(key);
|
|
2752
|
-
return;
|
|
2753
|
-
}
|
|
2754
|
-
if (key.name === KEY.PAGE_UP || key.name === KEY.PAGE_DOWN || key.name === 'wheel') {
|
|
2755
|
-
applyLiveScroll(key);
|
|
2756
|
-
return;
|
|
2757
|
-
}
|
|
2758
|
-
if (key.name === 'alt' && key.ch === 'p') {
|
|
2759
|
-
await dispatch('/model');
|
|
2760
|
-
return;
|
|
2761
|
-
}
|
|
2762
|
-
if (key.name === 'alt' && key.ch === 't') {
|
|
2763
|
-
// Toggle extended thinking, using the same shape/value as /thinking so
|
|
2764
|
-
// the chord and the command cannot disagree (commands.js: thinking).
|
|
2765
|
-
const want = !(ctx.thinking === true);
|
|
2766
|
-
ctx.thinking = want;
|
|
2767
|
-
host.updateConfig({ thinking: want });
|
|
2768
|
-
note(`Thinking blocks: ${want ? 'expanded' : 'collapsed'}`);
|
|
2769
|
-
render();
|
|
2770
|
-
return;
|
|
2771
|
-
}
|
|
2772
|
-
if (key.name === KEY.ESC) {
|
|
2773
|
-
// A bare Esc on an idle line clears it (readline's rule; the reference
|
|
2774
|
-
// clears the buffer, main.js:1675). The vim insert-mode Esc above is a
|
|
2775
|
-
// distinct motion and must not be shadowed by this.
|
|
2776
|
-
if (editor.buf) {
|
|
2777
|
-
editor.buf = '';
|
|
2778
|
-
editor.cursor = 0;
|
|
2779
|
-
render();
|
|
2780
|
-
}
|
|
2781
|
-
return;
|
|
2782
|
-
}
|
|
2783
|
-
if (key.name === KEY.CTRL_C) {
|
|
2784
|
-
if (editor.buf) {
|
|
2785
|
-
editor.buf = '';
|
|
2786
|
-
editor.cursor = 0;
|
|
2787
|
-
render();
|
|
2788
|
-
return;
|
|
2789
|
-
}
|
|
2790
|
-
await endSession();
|
|
2791
|
-
return;
|
|
2792
|
-
}
|
|
2793
|
-
if (key.name === KEY.CTRL_D) {
|
|
2794
|
-
// Ctrl+D is EOF: it ends the session only on an empty line. With text in
|
|
2795
|
-
// the buffer the reference never deletes-forward (main.js:1673), so a
|
|
2796
|
-
// stray Ctrl+D must neither drop a character nor kill the session.
|
|
2797
|
-
if (!editor.buf) await endSession();
|
|
2798
|
-
return;
|
|
2799
|
-
}
|
|
2800
|
-
};
|
|
2801
|
-
|
|
2802
|
-
// ── dispatch ──
|
|
2803
|
-
|
|
2804
|
-
const dispatch = async (line) => {
|
|
2805
|
-
const trimmed = String(line || '').trim();
|
|
2806
|
-
if (trimmed === '?') {
|
|
2807
|
-
overlay = { type: 'shortcuts' };
|
|
2808
|
-
render();
|
|
2809
|
-
return;
|
|
2810
|
-
}
|
|
2811
|
-
const keep = await runGuarded(async () => {
|
|
2812
|
-
if (trimmed.startsWith('/')) {
|
|
2813
|
-
const c = makeContext();
|
|
2814
|
-
return host.dispatchLine(trimmed, c);
|
|
2815
|
-
}
|
|
2816
|
-
await startResponse(trimmed);
|
|
2817
|
-
return true;
|
|
2818
|
-
}, () => abort);
|
|
2819
|
-
if (keep === false || host.wantsExit()) await endSession();
|
|
2820
|
-
};
|
|
2821
|
-
|
|
2822
|
-
// ── lifecycle ──
|
|
2823
|
-
|
|
2824
|
-
let ended = false;
|
|
2825
|
-
let resolveExit = null;
|
|
2826
|
-
const endSession = () => {
|
|
2827
|
-
if (ended) return;
|
|
2828
|
-
ended = true;
|
|
2829
|
-
if (resolveExit) resolveExit(0);
|
|
2830
|
-
};
|
|
2831
|
-
|
|
2832
|
-
const cleanup = () => {
|
|
2833
|
-
hideCursor();
|
|
2834
|
-
// Blank the alt screen so the shell we hand back is not left holding a
|
|
2835
|
-
// half-painted frame if the terminal ignores the leave sequence.
|
|
2836
|
-
paint([]);
|
|
2837
|
-
try {
|
|
2838
|
-
process.stdout.write('\x1b[0m');
|
|
2839
|
-
} catch {
|
|
2840
|
-
/* not a TTY */
|
|
2841
|
-
}
|
|
2842
|
-
try {
|
|
2843
|
-
// Clear the title we wrote, so the shell that gets the terminal back is
|
|
2844
|
-
// not left wearing this app's title. Same OSC 0 writer as every other
|
|
2845
|
-
// title write, so there is exactly one place user text meets the bar —
|
|
2846
|
-
// and skipped entirely when the bar was never ours to write.
|
|
2847
|
-
if (titleBar) writeTitle('', process.stdout);
|
|
2848
|
-
} catch {
|
|
2849
|
-
/* not a TTY */
|
|
2850
|
-
}
|
|
2851
|
-
try {
|
|
2852
|
-
process.stdin.setRawMode(false);
|
|
2853
|
-
} catch {
|
|
2854
|
-
/* not a TTY */
|
|
2855
|
-
}
|
|
2856
|
-
disableBracketedPaste();
|
|
2857
|
-
disableMouseTracking();
|
|
2858
|
-
leaveAltScreen();
|
|
2859
|
-
};
|
|
2860
|
-
|
|
2861
|
-
// …and it must not depend on the session resolving to run. Anything that ends
|
|
2862
|
-
// the process — a turn parked on a stream that will never produce a key, a
|
|
2863
|
-
// future early `return`, another `process.exit` added above this line —
|
|
2864
|
-
// otherwise hands the user back a terminal still sitting in the alternate
|
|
2865
|
-
// screen with mouse reporting enabled. That is precisely the exit frame the
|
|
2866
|
-
// parity test caught. Once-only, and unregistered in the `finally` so a host
|
|
2867
|
-
// that runs several sessions in one process does not stack handlers.
|
|
2868
|
-
let cleanedUp = false;
|
|
2869
|
-
const cleanupOnce = () => {
|
|
2870
|
-
if (cleanedUp) return;
|
|
2871
|
-
cleanedUp = true;
|
|
2872
|
-
try {
|
|
2873
|
-
cleanup();
|
|
2874
|
-
} catch {
|
|
2875
|
-
/* the terminal is already gone; nothing left to restore */
|
|
2876
|
-
}
|
|
2877
|
-
};
|
|
2878
|
-
process.once('exit', cleanupOnce);
|
|
2879
|
-
|
|
2880
|
-
// Enter the alternate screen and take over the terminal. `host.stdin` exists
|
|
2881
|
-
// so the loop can be driven from a test with a synthetic key stream.
|
|
2882
|
-
const stdin = host.stdin || process.stdin;
|
|
2883
|
-
// Claim the queue BEFORE attaching. Everything queued up to this instant was
|
|
2884
|
-
// typed at a terminal no session owned yet — it survived onboarding's pump
|
|
2885
|
-
// teardown only because the pump knew no session had started (`drainQueue`),
|
|
2886
|
-
// and this is the line that ends that grace period: from here the queue is
|
|
2887
|
-
// this session's, and a later teardown may clear it. Order matters — after
|
|
2888
|
-
// `attachKeyStream` would be too late for the keys already held.
|
|
2889
|
-
markSessionStart();
|
|
2890
|
-
attachKeyStream(stdin);
|
|
2891
|
-
enableBracketedPaste();
|
|
2892
|
-
enableMouseTracking();
|
|
2893
|
-
enterAltScreen();
|
|
2894
|
-
clearScreen();
|
|
2895
|
-
hideCursor();
|
|
2896
|
-
setTitle(false);
|
|
2897
|
-
|
|
2898
|
-
const onResize = () => render();
|
|
2899
|
-
if (process.platform !== 'win32') process.on('SIGWINCH', onResize);
|
|
2900
|
-
else process.stdout.on('resize', onResize);
|
|
2901
|
-
|
|
2902
|
-
const onSigint = () => {
|
|
2903
|
-
if (working && abort) {
|
|
2904
|
-
abort.abort();
|
|
2905
|
-
return;
|
|
2906
|
-
}
|
|
2907
|
-
endSession();
|
|
2908
|
-
};
|
|
2909
|
-
process.on('SIGINT', onSigint);
|
|
2910
|
-
|
|
2911
|
-
const crash = (err) => {
|
|
2912
|
-
cleanup();
|
|
2913
|
-
try {
|
|
2914
|
-
process.stderr.write(
|
|
2915
|
-
`\nAEGIS Code hit an unexpected error. Your transcript is saved; rerun to continue.\n${
|
|
2916
|
-
(err && err.stack) || err
|
|
2917
|
-
}\n`
|
|
2918
|
-
);
|
|
2919
|
-
} catch {
|
|
2920
|
-
/* ignore */
|
|
2921
|
-
}
|
|
2922
|
-
process.exit(1);
|
|
2923
|
-
};
|
|
2924
|
-
process.on('uncaughtException', crash);
|
|
2925
|
-
process.on('unhandledRejection', crash);
|
|
2926
|
-
|
|
2927
|
-
render();
|
|
2928
|
-
|
|
2929
|
-
try {
|
|
2930
|
-
const code = await new Promise((resolve) => {
|
|
2931
|
-
resolveExit = resolve;
|
|
2932
|
-
(async () => {
|
|
2933
|
-
while (!ended) {
|
|
2934
|
-
const key = await nextKey();
|
|
2935
|
-
if (ended) break;
|
|
2936
|
-
// The pump was reset underneath us (another session tore down, or a
|
|
2937
|
-
// child-process handover): stop looping rather than spinning on a
|
|
2938
|
-
// stream that no longer exists. Without this a session parked on
|
|
2939
|
-
// nextKey() at reset time never wakes, and the loop outlives its
|
|
2940
|
-
// terminal — repainting into whatever stdout it captured.
|
|
2941
|
-
//
|
|
2942
|
-
// `nextKey()` maps STREAM_END to null (`events.js`: "this call's
|
|
2943
|
-
// contract is a key or null, and STREAM_END is not a key"), so a
|
|
2944
|
-
// reset arrives here as `null`, not as STREAM_END. Testing for
|
|
2945
|
-
// STREAM_END alone therefore missed every real reset: the loop fed
|
|
2946
|
-
// `null` to handleKey, which threw, and re-parked on a pump that had
|
|
2947
|
-
// been cleared — leaving the promise unsettled. The event loop then
|
|
2948
|
-
// drained on its own and Node exited WITHOUT this function's
|
|
2949
|
-
// `finally`, so `cleanup()` never ran: the alternate screen was never
|
|
2950
|
-
// left, bracketed paste and mouse tracking stayed enabled in the
|
|
2951
|
-
// user's shell, and the "aegiscode --continue" hint never printed.
|
|
2952
|
-
// Measured as two different exit frames from the SAME host — 9561
|
|
2953
|
-
// bytes with teardown, 9120 without — which is what surfaced as
|
|
2954
|
-
// `cli-platform-parity.test.mjs` reporting "linux and darwin wrote
|
|
2955
|
-
// different bytes": a coin flip, not a platform difference.
|
|
2956
|
-
//
|
|
2957
|
-
// Ending the session here is the fix: it resolves the promise so the
|
|
2958
|
-
// teardown below runs on every exit, not only on a clean /exit.
|
|
2959
|
-
if (key === STREAM_END || !key) {
|
|
2960
|
-
endSession();
|
|
2961
|
-
break;
|
|
2962
|
-
}
|
|
2963
|
-
try {
|
|
2964
|
-
await handleKey(key);
|
|
2965
|
-
} catch (err) {
|
|
2966
|
-
push({ role: 'note', text: `Error: ${(err && err.message) || String(err)}` }, { follow: false });
|
|
2967
|
-
render();
|
|
2968
|
-
}
|
|
2969
|
-
}
|
|
2970
|
-
})();
|
|
2971
|
-
});
|
|
2972
|
-
return code;
|
|
2973
|
-
} finally {
|
|
2974
|
-
ended = true;
|
|
2975
|
-
process.off('SIGINT', onSigint);
|
|
2976
|
-
if (process.platform !== 'win32') process.off('SIGWINCH', onResize);
|
|
2977
|
-
else process.stdout.off('resize', onResize);
|
|
2978
|
-
process.off('uncaughtException', crash);
|
|
2979
|
-
process.off('unhandledRejection', crash);
|
|
2980
|
-
process.off('exit', cleanupOnce);
|
|
2981
|
-
cleanupOnce();
|
|
2982
|
-
resetKeyStream();
|
|
2983
|
-
}
|
|
2984
|
-
}
|
|
2985
|
-
|
|
2986
|
-
module.exports = {
|
|
2987
|
-
// pure helpers (unit-testable without a TTY)
|
|
2988
|
-
SUGGESTIONS,
|
|
2989
|
-
TITLE_SPIN,
|
|
2990
|
-
FRAME_MS,
|
|
2991
|
-
toolLabel,
|
|
2992
|
-
resolveToolDone,
|
|
2993
|
-
summarizeTurnTools,
|
|
2994
|
-
finalizeTurnText,
|
|
2995
|
-
historyPairs,
|
|
2996
|
-
overrideAnthropicByokWithPro,
|
|
2997
|
-
paletteQuery,
|
|
2998
|
-
headerLine,
|
|
2999
|
-
separatorLine,
|
|
3000
|
-
effortLine,
|
|
3001
|
-
spinnerLine,
|
|
3002
|
-
statusLine,
|
|
3003
|
-
shortcutsGrid,
|
|
3004
|
-
confirmLines,
|
|
3005
|
-
// The approval vocabulary, exported so a test can assert the CLI only ever
|
|
3006
|
-
// answers with tokens the engine actually honours (see APPROVAL_CHOICES).
|
|
3007
|
-
APPROVAL_CHOICES,
|
|
3008
|
-
APPROVAL_DECISIONS,
|
|
3009
|
-
roundsLines,
|
|
3010
|
-
autoContinuePlan,
|
|
3011
|
-
autoContinueLimit,
|
|
3012
|
-
AUTO_CONTINUE_LIMIT,
|
|
3013
|
-
rowLines,
|
|
3014
|
-
transcriptLines,
|
|
3015
|
-
inputPreviewText,
|
|
3016
|
-
inputRowCells,
|
|
3017
|
-
inputScroll,
|
|
3018
|
-
inputStart,
|
|
3019
|
-
inputLine,
|
|
3020
|
-
// the loop
|
|
3021
|
-
runSession,
|
|
3022
|
-
};
|
|
3
|
+
const{getSize:e,span:t,padLine:n,paint:r,w:o,wrapBlock:s,hideCursor:i,showCursor:a,moveTo:l,clearScreen:u,enterAltScreen:c,leaveAltScreen:d,enableBracketedPaste:f,disableBracketedPaste:m,enableMouseTracking:h,disableMouseTracking:p,selectionRange:g,selectionText:y,applySelection:w}=require("./screen.js"),{KEY:v,STREAM_END:b,attachKeyStream:$,nextKey:k,nextKeyTimeout:C,requeueKeys:S,resetKeyStream:T,markSessionStart:x,isKeyStreamSuspended:E}=require("./events.js"),{GLYPH:M,VERBS:L,DONE_VERBS:P,BOLD:R,BOLD_OFF:I,themeOf:N,RGB:_}=require("./theme.js"),{LineEditor:O}=require("./input.js"),{renderMarkdown:A}=require("./markdown.js"),D=require("./overlays.js"),q=require("./models.js"),{resolveShared:j}=require("./sharedpaths.js"),{validateApiKey:F}=require(j(require("node:path").join("client","credentials.js"))),B=require(j(require("node:path").join("desktop","lib","local","claude-pro.js"))),G=require("./fuzzy.js"),{fmtTokens:U,fmtEur:K,fmtElapsed:W,fmtUsageSplit:z,displayTokens:Y,pathName:H,feeBillable:V}=require("./format.js"),{editPreview:J}=require("./diff.js"),{renderDiffBlock:Q,defaultOpen:X}=require("./diffview.js"),{copyToClipboard:Z,describeCopy:ee,readClipboardText:te,readClipboardImage:ne}=require("./clipboard.js"),{transcriptToMarkdown:re}=require("./export.js"),oe=require("node:fs"),se=require("node:path"),{aegisDir:ie,loadConfig:ae}=require("./config.js"),{effortRung:le}=require("./engine.js"),{usageBuckets:ue,estimateTokensFromCells:ce}=require("./tokens.js"),{pingTurn:de}=require("./ping.js"),fe=["edit <filepath> to...","refactor <filepath>","how do I log an error?","write a test for <filepath>","create a util logging.py that..."],{TITLE_SPIN:me,titleText:he,topicFrom:pe,adoptTopic:ge,titleEnabled:ye,writeTitle:we}=require("./title.js"),{GENERIC_TITLE:ve,isGenericTitle:be}=require("./naming.js");function $e(e){return"exec"===e||"Bash"===e}function ke(e,t){const n=$e(e)?"shell command":function(e){return"task"===e||"Task"===e}(e)?"subagent":`${String(e).toLowerCase()} command`;return t>1?n+"s":n}function Ce(e,t){let n=-1;if(void 0!==t.id)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.id===t.id){n=r;break}}if(-1===n)for(let r=e.length-1;r>=0;r--){const o=e[r];if("tool"===o.role&&"run"===o.phase&&o.name===t.name&&o.agent===t.agent){n=r;break}}if(-1===n)return null;const r=e[n],o=e.filter(((e,r)=>"tool"===e.role&&e.name===t.name&&e.agent===t.agent&&r<=n)).length;return r.phase="done",r.elapsed=t.elapsed,r.ok=t.ok,r.label=`Ran ${o} ${r.agent?`${r.agent} ▸ `:""}${ke(t.name,o)}`,r}const Se=new Set(["Edit","Write","MultiEdit","NotebookEdit","editFile","writeFile"]);function Te(e,{maxNames:t=3}={}){const n=[],r=[];let o=0;for(const t of e||[]){if(!t)continue;!1===t.ok&&(o+=1);const e=t.args;if(!e||"object"!=typeof e)continue;const s=Se.has(t.name)?e.file_path||e.path||e.notebook_path:null;"string"==typeof s&&s&&!n.includes(s)&&n.push(s);const i=e.command;if("string"==typeof i&&i.trim()){const e=H(i.trim().split(/\s+/)[0]);e&&!r.includes(e)&&r.push(e)}}return{tools:(e||[]).length,failed:o,files:n,names:n.slice(0,t).map((e=>H(e))),more:Math.max(0,n.length-t),commands:r}}function xe(e,{aborted:t,error:n,reasoned:r}={}){let o=String(null==e?"":e);if(n&&!t&&"stopped"!==n){const e=`(backend error: ${n})`;o=o.trim()?`${o.trimEnd()}\n\n${e}`:e}return t&&(o=o.trim()?`${o.trimEnd()} (stopped)`:"(stopped)"),o.trim()||(o=r?"(no answer — the model used its whole budget on hidden reasoning before writing one; retry, or raise the budget with /effort)":"(no response)"),o}function Ee(e){return e.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})))}const Me=Object.freeze(["opus","haiku","sonnet"]);function Le(e,t={}){if(!e||"byok"!==e.cls)return{row:e,message:null};const n=String(e.id||""),r=n.indexOf(":");if(r<0||"anthropic"!==n.slice(0,r).trim().toLowerCase())return{row:e,message:null};if(!t.needsKey)return{row:e,message:null};if(!t.proLoggedIn)return{row:e,message:null};if(!0!==t.proEnabled)return{row:e,message:null};const o=n.slice(r+1).toLowerCase(),s=Array.isArray(t.proModels)&&t.proModels.length?t.proModels:[{id:"default",label:"Default",note:""}],i=Me.find((e=>o.includes(e)))||"default",a=s.find((e=>e.id===i))||s[0];return{row:{id:a.id,label:a.label,note:a.note,cls:"pro"},message:`${n} has no Anthropic console key on this machine, but Claude Code Pro is signed in — using the subscription instead (claude --model ${a.id}). Add a real console key any time with /byok-key anthropic <key> to run this row directly.`}}function Pe(e){const t=String(e||"").trim();return t.includes(" ")?t.split(/\s+/)[0]:t}function Re(e,n,r){const o=N(r),s=` AEGIS Code v${e} `,i=Math.max(0,n-[...s].length-2),a=Math.floor(i/2);return[t(o.coral,`╭${"─".repeat(a)}${s}${"─".repeat(i-a)}╮`)]}const Ie=(e,n)=>[t(N(n).dim,"─".repeat(e))];function Ne(e,n){const r=N(e),o=`● ${le(e.effort)} · /effort`,s=" ".repeat(Math.max(0,n-[...o].length-4));return[t(r.gray,s+o)]}const _e=_(235,159,127);function Oe(e,n){const r=N(n),o=Math.max(1,Math.round((e.elapsedMs||0)/1e3)),s=[...e.verb||L[0]],i=Math.floor((e.frame||0)/2)%3,a=s.map(((e,n)=>t((n+i)%3==0?r.coral:_e,e))),l=n&&n.thinking?t(r.gray,` (${o}s · thinking)`):t(r.gray,` (${o}s · ↓${e.streamedFloor?"≥":""}${U(e.streamed||0)} tokens)`),u=M.spin[(e.frame||0)%M.spin.length];return[t(r.coral,u),...a,t(r.white,"… "),l]}function Ae(e,r,o){const s=N(o);let i;return i=e.inputPrompt?[t(s.gray,"enter to confirm · esc to cancel")]:e.working?[t(s.gray,` ${M.bullet} esc to interrupt`)]:e.streamJob?[t(s.gray,`${M.bullet} esc to stop`)]:e.keyNotice?[t(s.gray,` ${M.bullet} no AEGIS key: ${e.keyNotice} ${M.bullet} /key register to retry`)]:e.yolo?[t(s.gray,`${M.bullet} automode on ${M.bullet} ${Ue()} rounds then it asks ${M.bullet} ? for shortcuts ${M.bullet} ${M.rightarrow} for manual mode`)]:[t(s.gray,`${M.pause} manual mode on ${M.bullet} ? for shortcuts ${M.bullet} ${M.rightarrow} for auto mode`)],n(i,r)}function De(e,n){const r=N(n),o=(e,n,o,s)=>[t(""," "),t(r.white,e),t(r.gray," "+n),t(""," "),t(r.white,o),t(r.gray," "+s)];return[o("/","for commands","?","for shortcuts"),o("ctrl + c","to quit","ctrl + o","for permissions"),o("alt + p","to switch model","alt + t","to toggle thinking"),o("shift + ↑/↓","pins as it moves","shift + enter","runs the row"),o("esc","to interrupt a turn","ctrl + l","to clear the screen"),o("ctrl + t","to show tokens","ctrl + r","to resume a session"),o("↑ / ↓","for history","tab","to complete a command")]}const qe="deny",je=["Yes","Yes, allow for this session","No"],Fe=["once","session",qe];function Be(e,n,r){const o=N(r),i=[];i.push([t(o.gray,"─".repeat(Math.min(Math.max(10,n-4),80)))]),i.push([t(o.white,`${$e(e.name)?"shell":e.name} command`)]),i.push([t("","")]);const a=$e(e.name)?String(e.args&&e.args.command||""):String(e.args&&(e.args.file_path||e.args.pattern)||"");for(const e of s(a,Math.max(8,n-4)))i.push([t(o.gray,e)]);i.push([t("","")]),i.push([t(o.white,"Do you want to proceed?")]);const l=e.name||"this tool";return je.forEach(((n,r)=>{const s=1===r?`Yes, and allow ${l} for this session`:n;i.push(((n,r)=>{const s=e.sel===n;return[s?t(o.lavender,M.cursor):t(""," "),t(o.gray,` ${n+1}. `),t(s?o.lavender:o.white,r)]})(r,s))})),i.push([t("","")]),i.push([t(o.gray,"Esc to cancel")]),i}const Ge=3;function Ue(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:Ge}function Ke({on:e=!1,used:t=0,limit:n=Ue()}={}){const r=Number.isFinite(n)&&n>0?Math.floor(n):Ge,o=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?o>=r?{auto:!1,used:0,cap:r}:{auto:!0,used:o+1,cap:r}:{auto:!1,used:o,cap:r}}function We(e,n,r){const o=N(r),i=[];i.push([t(o.gray,"─".repeat(Math.min(Math.max(10,n-4),80)))]),i.push([t(o.white,`${e.spent}-round tool limit reached`)]),i.push([t("","")]);for(const e of s("The turn is still working — it ended its last round on a tool call instead of an answer.",Math.max(8,n-4)))i.push([t(o.gray,e)]);i.push([t("","")]);const a=(n,r)=>{const s=e.sel===n;return[s?t(o.lavender,M.cursor):t(""," "),t(o.gray,` ${n+1}. `),t(s?o.lavender:o.white,r)]};return i.push(a(0,`Yes, continue with ${e.size} more rounds`)),i.push(a(1,"No, stop here and answer with what I have")),i.push([t("","")]),i.push([t(o.gray,`extension ${e.extensions} of ${e.max} · Esc to stop`)]),i}function ze(e,n,{omitMs:r=!1}={}){const o=[];e.model&&o.push(t(n.blue,e.model));const s=z(e);if(s)o.push(t(n.white,s.output));else{const r=Y(e);null!=r&&o.push(t(n.white,`${U(r)} tokens`))}return null!=e.eur&&V()&&o.push(t(e.eur>0?n.coral:n.green,K(e.eur))),null==e.ms||r||o.push(t(n.gray,W(e.ms))),e.calls>1&&o.push(t(n.gray,`${e.calls} calls`)),o}function Ye(e,n){const r=[];return e.forEach(((e,o)=>{o&&r.push(t(n.dim,` ${M.bullet} `)),r.push(e)})),r}const He=40;function Ve(e,r,o,i=Date.now()){const a=N(o),l=[];if("tool"===e.role){const n=String(e.label||"").replace(/(?:…|\.\.\.)+$/,""),s=e.cwd?` · ${function(e){let t=String(null==e?"":e).trim().replace(/\/+$/,"");if(!t)return"";const n=String(process.env.HOME||process.env.USERPROFILE||"").replace(/\/+$/,"");return n&&(t===n||t.startsWith(`${n}/`))&&(t=`~${t.slice(n.length)}`),t.length>He&&(t=`${M.ellipse}${t.slice(-(He-1))}`),t}(e.cwd)}`:"";if("run"===e.phase){const r=e.start?Math.max(1,Math.round((i-e.start)/1e3)):0;l.push([t(a.gray,`${n}${M.ellipse} · ${r}s${s}`)])}else l.push([t(a.gray,`${n}${s}`)]);if(e.diff){for(const n of Q(e.diff,o,r,{open:!!e.diffOpen}))l.push([t("",n)]);return l}const u="string"==typeof e.args?e.args:e.args&&"object"==typeof e.args?e.args.command??e.args.file_path??e.args.description??Object.values(e.args).find((e=>"string"==typeof e))??"":"";return u&&l.push([t(a.gray,` ${M.hook} $ ${String(u)}`)]),l}if("note"===e.role)return l.push([t(a.gray,`· ${e.text}`)]),l;if("tip"===e.role){for(const n of s(String(e.text),r))l.push([t(a.gray,n)]);return l}if("done"===e.role){const n=[t(a.gray,M.bloom),t(a.gray,` ${e.text}`)];if(e.meta){const r=ze(e.meta,a,{omitMs:!0});r.length&&n.push(t(a.dim," "),...Ye(r,a))}return l.push(n),l}if("summary"===e.role){const n=e.counts||{};if(!n.tools)return l;const r=[t(a.dim,M.hook),t(""," ")],o=[t(a.white,String(n.tools)),t(a.gray," "+(1===n.tools?"command":"commands"))];if(n.files&&n.files.length&&(o.push(t(a.gray,` ${M.bullet} `)),o.push(t(a.white,String(n.files.length)),t(a.gray," "+(1===n.files.length?"file changed":"files changed")))),n.failed&&(o.push(t(a.gray,` ${M.bullet} `)),o.push(t(a.coral,`${n.failed} failed`))),n.names&&n.names.length){const e=n.more?` +${n.more}`:"";o.push(t(a.dim,` ${n.names.join(", ")}${e}`))}return r.push(...o),l.push(r),l}if("meta"===e.role){const n=ze(e.meta||{},a);return n.length&&l.push([t(a.dim,`${M.hook} `),...Ye(n,a)]),l}if("panel"===e.role){for(const t of e.lines||[])l.push(n(t,r));return l.push([t("","")]),l}if("error"===e.role)return l.push([t(a.red,`✗ ${e.text}`)]),l;if("user"===e.role)return s(String(e.text),Math.max(8,r-2)).forEach(((e,n)=>{0===n?l.push([t(a.gray,M.cursor),t(""," "),t(a.white,e)]):l.push([t(""," "),t(a.white,e)])})),l;const u="assistant"===e.role?A(String(null==e.text?"":e.text),r,o):s(String(null==e.text?"":e.text),r).map((e=>[t(a.white,e)])),c=u.length?u:[[t("","")]];for(let e=0;e<c.length;e++){const n=c[e].slice();0===e&&n.unshift(t(a.white,M.block),t(""," ")),l.push(n)}return l}function Je(e,t,n,r=Date.now(),o=null){const{cols:s,rows:i}=t,a=Math.max(1,i-6),l=[],u=[];for(const t of e){const e=o||null,i="assistant"===t.role&&t.streaming||"tool"===t.role&&"run"===t.phase;if(!e||i)for(const e of Ve(t,s,n,r))l.push(e),u.push(t);else{const o=e.get(t);if(o&&o.text===t.text&&o.cols===s&&o.diffOpen===t.diffOpen){for(const e of o.segment)l.push(e),u.push(t);continue}const i=Ve(t,s,n,r);e.set(t,{text:t.text,cols:s,diffOpen:t.diffOpen,segment:i});for(const e of i)l.push(e),u.push(t)}}let c=t.scroll||0,d=null==t.anchorEnd?null:t.anchorEnd;const f=l.length,m=Math.max(0,f-a);let h;c>m&&(c=m),0===c?(d=null,h=f):(null===d&&(d=Math.max(0,f-c)),h=Math.min(d,f)),f<=a&&(c=0,d=null,h=f);const p=Math.max(0,h-a);return{lines:l.slice(p,h),owners:u.slice(p,h),scroll:c,anchorEnd:d}}function Qe(e){const t=e.indexOf("\n");if(-1===t)return e;const n=e.split("\n").length-1;return`${e.slice(0,t)} … (+${n} line${1===n?"":"s"})`}const Xe=e=>Math.max(1,e-3),Ze=e=>[...e].reduce(((e,t)=>e+o(t)),0);function et(e,t,n){const r=Xe(n),s=Ze(e);if(s<=r)return 0;const i=r-1;return Math.max(0,Math.min(function(e,t){const n=[...e];let r=0;for(let e=0;e<Math.min(t,n.length);e++)r+=o(n[e]);return r}(e,t)-i,s-i))}function tt(e,t){const n=[...e];let r=0;for(let e=0;e<n.length;e++){if(r>=t)return e;r+=o(n[e])}return n.length}function nt(e,r,s){const i=N(s),a=[t(i.gray,M.cursor),t(""," ")];if(e.inputPrompt){a.push(t(i.white,`${e.inputPrompt.title}: `));for(const n of[...e.inputPrompt.buf])a.push(t(i.white,n));const s=Math.min(3+o(e.inputPrompt.title)+2+o(e.inputPrompt.buf),r);return{line:n(a,r),cursorCol:s}}if(e.working)return{line:n(a,r),cursorCol:3};const l=e.buf||"";if(!l.length){if(e.insertMode)return{line:n(a,r),cursorCol:3};const o=fe[(e.suggestionIdx||0)%fe.length];return a.push(t(i.white+R,`Try "${o}"`),t(I,"")),{line:n(a,r),cursorCol:3}}if(l.includes("\n")){const e=Qe(l);for(const n of[...e])a.push(t(i.white,n));return{line:n(a,r),cursorCol:Math.min(3+o(e),r)}}const u=et(l,e.cursor,r),c=tt(l,u);u>0&&a.push(t(i.dim,"…"));const d=[...l];for(let e=c;e<d.length;e++)a.push(t(i.white,d[e]));const f=d.slice(c,Math.min(e.cursor,d.length)).join(""),m=Math.min(3+(u>0?1:0)+o(f),r);return{line:n(a,r),cursorCol:m}}module.exports={SUGGESTIONS:fe,TITLE_SPIN:me,FRAME_MS:33,toolLabel:ke,resolveToolDone:Ce,summarizeTurnTools:Te,finalizeTurnText:xe,historyPairs:Ee,overrideAnthropicByokWithPro:Le,paletteQuery:Pe,headerLine:Re,separatorLine:Ie,effortLine:Ne,spinnerLine:Oe,statusLine:Ae,shortcutsGrid:De,confirmLines:Be,APPROVAL_CHOICES:je,APPROVAL_DECISIONS:Fe,roundsLines:We,autoContinuePlan:Ke,autoContinueLimit:Ue,AUTO_CONTINUE_LIMIT:Ge,rowLines:Ve,transcriptLines:Je,inputPreviewText:Qe,inputRowCells:Xe,inputScroll:et,inputStart:tt,inputLine:nt,runSession:async function(s){const M=s.ctx,R=new O,I=s.transcript,_=new WeakMap;let A=null;function j(e){const t=Pe(null==e?A&&A.query||"":e);return G.fuzzyRankWithAliases(t,s.visibleCommands(),(e=>e.name),(e=>e.aliases||[]))}let U=0,K=!1,W=null,z=0,Y=null,H=0,V=L[0],Q=0,le=0,fe=[],pe=0,ve=0,$e=null;const Se=new Map;let Me=null,_e=null,Ge=[],Ue=!1,ze=0,Ye="",He=null,Ve=null,Qe=0,Xe=null,Ze="",et="",tt=!1,rt=!0;try{rt=ye(process.env,s.loadConfig?s.loadConfig():s.config||{})}catch{rt=!0}let ot=!1,st=0;const it=e=>{if(!rt)return;const t=e?me[Math.floor(z/2)%me.length]:null;we(he({topic:Ze,frame:t}),process.stdout)},at=e=>{if("function"!=typeof s.nameConversation)return;let t;tt=!0;try{t=Promise.resolve(s.nameConversation(e,{signal:W?W.signal:null}))}catch{return}t.then((e=>{const t=String(e||"").trim();t&&(et=t,Ze=t,it(!!K),ut())})).catch((()=>{}))},lt=e=>{Ye=e,ze=Date.now()+2500,setTimeout((()=>{Date.now()>=ze&&ut()}),2600),ut()},ut=()=>{if(E())return;const n=e().cols,{lines:o,inputCol:u,rows:c,inputRow:d}=(()=>{const{cols:n,rows:r}=e(),o=[];o.push(Re(s.version,n,M));const i=Math.max(1,r-6),a=Je(I,{cols:n,rows:r,scroll:ve,anchorEnd:$e},M,Date.now(),_);ve=a.scroll,$e=a.anchorEnd,Se.clear();for(let e=0;e<a.lines.length;e++)Se.set(1+e,a.owners[e]);for(const e of a.lines)o.push(e);for(;o.length<i+1;)o.push([t("","")]);const l=N(M);if(K)o.push(Oe({verb:V,frame:z,elapsedMs:Date.now()-H,streamed:ce(yt())+gt,streamedFloor:gt>0},M));else if(Date.now()<ze)o.push([t(l.gray,` ${Ye}`)]);else if(Ve){const e=Math.max(1,Math.round((Date.now()-Qe)/1e3));o.push([t(l.gray,` ${Ve.label||"running"}… (${e}s · esc to stop)`)])}else o.push(Ne(M,n));o.push(Ie(n,M));const u=nt({buf:R.buf,cursor:R.cursor,working:K,insertMode:Ue,suggestionIdx:pe,inputPrompt:He},n,M);return o.push(u.line),o.push(Ie(n,M)),o.push(Ae({working:K,inputPrompt:He,streamJob:Ve,yolo:s.isYolo&&s.isYolo(),keyNotice:s.keyNotice&&s.keyNotice()},n,M)),{lines:o,inputCol:u.cursorCol,rows:r,inputRow:r-2}})();A&&dt(o,c,n),Ge=o,r(Me?w(o,g(Me.anchor,Me.head),n):o),st=Date.now(),A?i():He||!K?(l(d,u),a()):i()},ct=()=>{if(ot)return;ot=!0;const e=Math.max(0,33-(Date.now()-st));setTimeout((()=>{ot=!1,ut()}),e)},dt=(e,t,r)=>{if(!A)return;let o=null;if("palette"===A.type?o=D.renderPalette(s.visibleCommands(),{query:Pe(A.query),sel:A.sel},r,t):"model"===A.type?o=D.renderModelPicker(A.items||[],A.sel||0,r,t,A.current,A.cls||M.modelClass,"function"==typeof s.classLabel?s.classLabel:null):"effort"===A.type?o=D.renderEffortPicker(A.sel||0,r,M.effort):"class"===A.type?o=D.renderClassPicker(A.items||[],A.sel||0,r,A.current||M.modelClass,"function"==typeof s.classLabel?s.classLabel:null):"provider"===A.type?o=D.renderProviderPicker(A.items||[],A.sel||0,r,A.current,A.hint):"resume"===A.type?o=D.renderResumeList(A.items||[],A.sel||0,r,t):"shortcuts"===A.type?o=De(0,M):"confirm"===A.type?o=Be(A,r,M):"rounds"===A.type?o=We(A,r,M):"panel"===A.type&&(o=A.lines||[]),!o)return;if("shortcuts"===A.type){const s=Math.max(2,t-o.length-1);for(let t=0;t<o.length;t++)e[s+t]=n(o[t],r);return void i()}const a=Math.max(2,Math.floor((t-o.length)/2));for(let t=0;t<o.length;t++)e[a+t]=n(o[t],r);i()},ft=(e,t)=>(I.push(e),t&&!1===t.follow||(ve=0,$e=null),e),mt=(e,t)=>{const n=t?I.indexOf(t):-1;return n<0?I.push(e):I.splice(n,0,e),e},ht=e=>ft({role:"note",text:e},{follow:!1});let pt=0,gt=0;const yt=()=>pt,wt=async e=>{K=!0,z=0,H=Date.now(),pt=0,gt=0,le=0,fe=[],V=L[Q%L.length],Ze=et||ge(Ze,e),(e=>{et?be(et)&&at(e):tt||at(e)})(e),W=new AbortController,Y=setInterval((()=>{z++,it(!0),z%3==0&&ut()}),100),Y.unref&&Y.unref(),it(!0),ft({role:"user",text:e});const t=ft({role:"assistant",text:"",streaming:!0});let n=!1;const r={text:e=>{t.text+=e,pt+=o(e),ct()},reasoning:e=>{n=!0,pt+=o(e)},thinkingTokens:e=>{n=!0,gt+=e,ct()},tool:e=>{if(e&&void 0!==e.id){const t=fe.findIndex((t=>t&&void 0!==t.id&&t.id===e.id));t>=0?fe[t]=e:fe.push(e)}else fe.push(e);if("run"===e.phase){const n=++le,r=e.agent?`${e.agent} ▸ `:"",o=J(e.name,e.args,{cwd:e.cwd});mt({role:"tool",phase:"run",name:e.name,args:e.args,agent:e.agent,id:e.id,label:`Running ${n} ${r}${ke(e.name,n)}…`,start:Date.now(),diff:o,diffOpen:X(o)},t)}else if(!Ce(I,e)){const n=++le,r=J(e.name,e.args,{cwd:e.cwd});mt({role:"tool",phase:"done",name:e.name,args:e.args,agent:e.agent,id:e.id,ok:e.ok,label:`Ran ${n} ${e.agent?`${e.agent} ▸ `:""}${ke(e.name,n)}`,diff:r,diffOpen:X(r)},t)}ct()},approval:e=>(e=>new Promise((t=>{A={type:"confirm",name:e.tool||e.name||"tool",args:e.args||{},sel:0,info:e},ut(),(async()=>{const e=e=>{A=null,ut(),t(e)};for(;;){const t=await k();if(t.name===v.UP||t.name===v.DOWN||t.name===v.TAB){const e=t.name===v.UP?-1:1;A.sel=(A.sel+e+je.length)%je.length,ut()}else{if(t.name===v.ENTER)return void e(Fe[A.sel]||qe);if(t.name===v.ESC||t.name===v.CTRL_C)return void e(qe);if("char"===t.name){const n=String(t.ch).trim(),r=Number(n)-1;if(Number.isInteger(r)&&r>=0&&r<Fe.length)return void e(Fe[r])}}}})()})))(e),rounds:e=>(e=>new Promise((t=>{const n=Boolean(s.isYolo&&s.isYolo()),r=Ke({on:n,used:U});if(U=r.used,r.auto)return ht(`auto: ${e.spent}-round limit reached — continuing automatically (${r.used}/${r.cap}, then it asks).`),ut(),void t(!0);n&&(ht(`auto: ${r.cap} automatic continuations used — asking you now (answering restarts the block).`),ut()),A={type:"rounds",spent:Number(e.spent)||0,extensions:Number(e.extensions)||1,max:Number(e.max)||8,size:Number(e.size)||Number(e.spent)||0,sel:1},ut(),(async()=>{const e=e=>{A=null,ut(),t(e)};for(;;){const t=await k();if(t.name===v.UP||t.name===v.DOWN||t.name===v.TAB)A.sel=1-A.sel,ut();else{if(t.name===v.ENTER)return void e(0===A.sel);if(t.name===v.ESC||t.name===v.CTRL_C)return void e(!1);if("char"===t.name){const n=String(t.ch).trim();if("1"===n)return void e(!0);if("2"===n)return void e(!1)}}}})()})))(e)};let i=null;try{i=await s.ask(e,{history:Ee(I),presenter:r,signal:W.signal})}catch(e){i={error:e&&e.message||String(e)}}finally{t.streaming=!1,!String(t.text||"").trim()&&i&&"string"==typeof i.text&&i.text.trim()&&(t.text=i.text),K=!1,clearInterval(Y),Y=null,it(!1);const r=Math.max(1,Math.round((Date.now()-H)/1e3)),o=!(!W||!W.signal.aborted);t.text=xe(t.text,{aborted:o,error:i&&i.error,reasoned:n}),ft({role:"done",text:`${le>0?P[1]:P[0]} for ${r}s`},{follow:!1}),pe=Q+1,Q++,W=null;try{const e=ae(),t=de({stream:process.stdout,mode:e.ping,minSeconds:e.pingMinSeconds,elapsedMs:Date.now()-H,isTTY:!!process.stdout.isTTY,aborted:o});t&&ft({role:"note",text:t},{follow:!1})}catch{}s.recordTurn(i);let a=null;try{const e=await s.refreshSpend();a=e?e.lastCost:null}catch{}s.persistTurn&&s.persistTurn(e,i,o?"stopped":i&&i.error?"error":"done",a);const l=i&&i.usage,u=s.tokensFor?s.tokensFor(l):null,c=l?ue(l):null;ft({role:"meta",meta:{model:i&&i.model,tokens:u,input:c?c.input:null,output:c?c.output:null,eur:a,ms:i&&i.ms,calls:i&&i.calls||1}},{follow:!1});const d=Te(fe);d.tools>0&&ft({role:"summary",counts:d},{follow:0===ve}),ut()}},vt=e=>{let t=null;if(e.name===v.PAGE_UP)t=5;else if(e.name===v.PAGE_DOWN)t=-5;else if("wheel"===e.name)t="up"===e.dir?3:-3;else{if("click"===e.name||"drag"===e.name||"release"===e.name)return!(e=>{const t={col:e.col-1,row:e.row-1};if("click"===e.name)return _e=t,!1;if("drag"===e.name)return Me?Me.head=t:Me={anchor:_e||t,head:t},_e=null,!0;const n=_e;_e=null;const r=Me?g(Me.anchor,Me.head):null,o=!(!r||r.startRow===r.endRow&&r.startCol===r.endCol);if(Me=null,!o)return(e=>{const t=Se.get(e);return!(!t||!t.diff||(t.diffOpen=!t.diffOpen,0))})((n||t).row);const s=y(Ge,r);if(!s)return!0;const i=Z(s,{stdout:process.stdout,env:process.env}),a=s.split("\n").length;return Ye=ee(i,`Marked ${a} line${1===a?"":"s"}`),ze=Date.now()+2500,setTimeout((()=>{Date.now()>=ze&&ut()}),2600),!0})(e)||(ct(),!0);"char"!==e.name||!M.vim||Ue||R.buf||("j"===e.ch?t=1:"k"===e.ch&&(t=-1))}return null!==t&&(ve=Math.max(0,ve+t),$e=null,ct(),!0)},bt=()=>A?"palette"===A.type?G.fuzzyRankWithAliases(Pe(A.query),s.visibleCommands(),(e=>e.name),(e=>e.aliases||[])).length:"model"===A.type||"resume"===A.type||"class"===A.type||"provider"===A.type?(A.items||[]).length:"effort"===A.type?D.EFFORT_VALUES.length:0:0,$t=async e=>{if(e){{const t=q.modelKeyPlan(e,{hasStored:!!s.hasProviderKey&&!!s.hasProviderKey("anthropic")}),{row:n,message:r}=Le(e,{needsKey:!(!t||!t.needed),proLoggedIn:q.claudeProLoggedIn(),proEnabled:(()=>{try{return!0===ae().proEnabled}catch{return!1}})(),proModels:B.PRO_MODELS});e=n,r&&ht(r)}e.cls&&"aegis"!==e.cls&&M.modelClass!==e.cls&&await Tt(`/class ${e.cls}`),M.model=e.id,s.updateConfig({model:e.id,currentModelId:e.id,modelClass:M.modelClass}),ht(`model: ${e.id}${"byok"===e.cls?" (byok)":"pro"===e.cls?" (Claude Code Pro)":""}`),await(async e=>{const t=q.modelKeyQueue(e,{accountConfigured:!!s.accountConfigured&&!!s.accountConfigured(),hasStoredFor:e=>!!s.hasProviderKey&&!!s.hasProviderKey(e)});if(!t.length)return;let n=null;try{n=s.makeCommandContext()}catch{n=null}if(n&&"function"==typeof n.readSecret)for(const r of t){const t="account"===r.role?"AEGIS account key":"claude-pro"===r.role?"Claude Code OAuth token (`claude setup-token` mints one)":`${r.provider} key`,o=String(await n.readSecret(`${t} → ${r.env} (kept off screen, Enter to skip): `)||"").trim();if(!o){ht(`no key given — ${r.env} is still unset, so ${e.id} will fail until it is.`);continue}const s="account"===r.role?"AEGIS":"claude-pro"===r.role?"Claude Code OAuth":r.provider||"that provider",i=F(o,{label:s});if(!i.ok){ht(`not saved — ${i.message}. ${r.env} is still unset.`);continue}const a=q.storeModelKey(e,i.key,{env:r.env});a.ok?ht(a.changed?a.foreign?`${r.env} saved to ${a.file} (0600) — read only by the Claude Code Pro transport, never exported.`:`${r.env} saved to ${a.file} (0600) — both hosts read that file; nothing to export.`:`${r.env} was already set in ${a.file}.`):ht(`could not save the key: ${a.error||"unknown error"}`)}else{const n=t.map((e=>`${e.env}: ${e.why}`)).join(" · ");ht(`${e.id} has no key: ${n}. Set the ones above and pick it again.`)}})(e)}},kt=async e=>{e&&e.class&&await Tt(`/class ${e.class}`)},Ct=e=>{const t=D.EFFORT_VALUES[e||0];A=null,M.effort=t||"high",s.updateConfig({effort:M.effort}),ht(`effort: ${M.effort}`),ut()},St=async e=>{if(e)if(A)await(async e=>{const t=A.type;if(e.name===v.ESC||e.name===v.CTRL_C)return A=null,void ut();if("shortcuts"===t||"panel"===t)return A=null,void ut();if(e.name!==v.TAB||"palette"!==t)if(e.name!==v.TAB||"model"!==t&&"effort"!==t&&"class"!==t&&"provider"!==t){if(e.name===v.ENTER){if("palette"===t){const e=j()[A.sel||0],t=String(A.query||"").trim().split(/\s+/).slice(1).join(" ");return A=null,ut(),void(e&&await Tt(t?`/${e.name} ${t}`:`/${e.name}`))}if("model"===t){const e=(A.items||[])[A.sel||0];return A=null,ut(),await $t(e),void ut()}if("effort"===t)return void Ct(A.sel||0);if("class"===t){const e=(A.items||[])[A.sel||0];return A=null,ut(),await kt(e),void ut()}if("provider"===t){const e=(A.items||[])[A.sel||0],t=A.command||"byok-key";return A=null,ut(),void(e&&e.id&&await Tt(`/${t} ${e.id}`))}if("resume"===t){const e=(A.items||[])[A.sel||0];return A=null,ut(),void(e&&s.resumeSession&&await s.resumeSession(e))}return A=null,void ut()}if(e.name===v.SHIFT_UP||e.name===v.SHIFT_DOWN){const n=e.name===v.SHIFT_UP?-1:1,r=Math.max(0,bt()-1);if(A.sel=Math.min(r,Math.max(0,(A.sel||0)+n)),"model"===t){const e=(A.items||[])[A.sel||0];return A=null,ut(),await $t(e),void ut()}if("class"===t){const e=(A.items||[])[A.sel||0];return A=null,ut(),await kt(e),void ut()}if("provider"===t){const e=(A.items||[])[A.sel||0],t=A.command||"byok-key";return A=null,ut(),void(e&&e.id&&await Tt(`/${t} ${e.id}`))}return"effort"===t?void Ct(A.sel||0):void ut()}if(e.name===v.SHIFT_ENTER){if("palette"===t){const e=j()[A.sel||0];return A=null,ut(),void(e&&await Tt(`/${e.name}`))}if("model"===t){const e=(A.items||[])[A.sel||0];return A=null,ut(),await $t(e),void ut()}if("class"===t){const e=(A.items||[])[A.sel||0];return A=null,ut(),await kt(e),void ut()}if("provider"===t){const e=(A.items||[])[A.sel||0],t=A.command||"byok-key";return A=null,ut(),void(e&&e.id&&await Tt(`/${t} ${e.id}`))}return"effort"===t?void Ct(A.sel||0):void 0}if(e.name===v.UP||e.name===v.DOWN){const t=(A.items||[]).length||bt(),n=e.name===v.UP?-1:1;return A.sel=Math.min(Math.max(0,t-1),Math.max(0,(A.sel||0)+n)),void ut()}if("char"===e.name){if("palette"===t)return A.query=(A.query||"")+e.ch,A.sel=0,void ut();if("model"===t){const t=parseInt(e.ch,10),n=A.items||[];return void(Number.isFinite(t)&&t>=1&&t<=n.length&&(A.sel=t-1,ut()))}if("effort"===t||"resume"===t||"class"===t||"provider"===t){const t=parseInt(e.ch,10),n=bt();return void(Number.isFinite(t)&&t>=1&&t<=n&&(A.sel=t-1,ut()))}}e.name===v.BACKSPACE&&"palette"===t&&(A.query=String(A.query||"").slice(0,-1),ut())}else{const e="model"===t||"class"===t||"provider"===t?(A.items||[]).length:D.EFFORT_VALUES.length;e&&(A.sel=((A.sel||0)+1)%e,ut())}else{const e=j()[A.sel||0];e&&(A.query=e.name,A.sel=0,ut())}})(e);else{if("char"===e.name&&!R.buf){if("/"===e.ch)return A={type:"palette",query:"",sel:0},void ut();if("?"===e.ch)return A={type:"shortcuts"},void ut()}if(!M.vim||Ue||R.buf||"char"!==e.name){if(M.vim&&Ue&&e.name===v.ESC)return Ue=!1,R.cursor>0&&R.cursor--,void ut()}else{const t=e.ch;if("i"===t||"a"===t||"o"===t||"s"===t||"S"===t)return"s"===t&&R.substChar(),"S"===t&&R.substLine(),"a"===t&&R.right(),Ue=!0,void ut();if("h"===t)return R.left(),void ut();if("l"===t)return R.right(),void ut();if("0"===t)return R.home(),void ut();if("$"===t)return R.end(),void ut();if("x"===t)return R.delete(),void ut();if("D"===t)return R.killToEnd(),void ut();if("A"===t)return R.end(),Ue=!0,void ut();if(vt(e))return}if(e.name===v.ENTER){const e=R.submit();return Xe=null,Ue=!1,e?void await Tt(e):void ut()}if(e.name!==v.CTRL_V)if(e.name!==v.CTRL_B){if("paste"===e.name)return M.vim&&(Ue=!0),R.insert(String(e.text)),void ut();if("char"===e.name)return M.vim&&!Ue||R.insert(e.ch),void ut();if(e.name===v.BACKSPACE)return R.backspace(),void ut();if(e.name===v.DELETE)return R.delete(),void ut();if(e.name===v.LEFT||e.name===v.CTRL_LEFT)return e.name===v.CTRL_LEFT?R.wordBack():R.left(),void ut();if(e.name!==v.RIGHT||R.buf){if(e.name===v.RIGHT||e.name===v.CTRL_RIGHT)return R.right(),void ut();if(e.name===v.HOME||e.name===v.CTRL_A)return R.home(),void ut();if(e.name===v.END||e.name===v.CTRL_E)return R.end(),void ut();if(e.name===v.UP)return R.historyUp(),void ut();if(e.name===v.DOWN)return R.historyDown(),void ut();if(e.name===v.TAB)return(()=>{const e=R.buf;if(!e.startsWith("/")||e.includes(" "))return!1;const t=e.slice(1),n=s.visibleCommands().flatMap((e=>[e.name,...e.aliases||[]])).filter((e=>e.startsWith(t))).sort();return!!n.length&&(Xe&&Xe.q===t||(Xe={q:t,i:-1}),Xe.i=(Xe.i+1)%n.length,R.buf="/"+n[Xe.i],R.end(),!0)})()||(Ye=R.buf?"Tab completes commands":"Use alt+t to toggle thinking",ze=Date.now()+2500,setTimeout((()=>{Date.now()>=ze&&ut()}),2600)),void ut();if(e.name===v.CTRL_U)return R.buf="",R.cursor=0,void ut();if(e.name===v.CTRL_K)return R.killToEnd(),void ut();if(e.name===v.CTRL_W)return R.wordBack(),void ut();if(e.name===v.CTRL_L)return u(),void ut();if(e.name===v.CTRL_T)return ht(s.tokenSummary?s.tokenSummary():"no token usage yet this session"),void ut();if(e.name!==v.CTRL_R)if(e.name!==v.CTRL_O)if("click"!==e.name&&"drag"!==e.name&&"release"!==e.name)if(e.name!==v.PAGE_UP&&e.name!==v.PAGE_DOWN&&"wheel"!==e.name)if("alt"!==e.name||"p"!==e.ch){if("alt"===e.name&&"t"===e.ch){const e=!(!0===M.thinking);return M.thinking=e,s.updateConfig({thinking:e}),ht("Thinking blocks: "+(e?"expanded":"collapsed")),void ut()}if(e.name!==v.ESC)return e.name===v.CTRL_C?R.buf?(R.buf="",R.cursor=0,void ut()):void await Mt():void(e.name!==v.CTRL_D||R.buf||await Mt());R.buf&&(R.buf="",R.cursor=0,ut())}else await Tt("/model");else vt(e);else vt(e);else await Tt("/permissions");else await Tt("/resume")}else await Tt(s.isYolo&&s.isYolo()?"/automode off":"/automode on")}else(()=>{if(!I.length)return void lt("Nothing to copy yet");const e=Z(re(I),{stdout:process.stdout,env:process.env});lt(ee(e,"Copied the conversation"))})();else(()=>{const e=ne({env:process.env});if(e.ok)try{const t=se.join(ie(),"clipboard");oe.mkdirSync(t,{recursive:!0});const n="image/jpeg"===e.mime?"jpg":"png",r=se.join(t,`pasted-${(new Date).toISOString().replace(/[:.]/g,"-")}.${n}`);oe.writeFileSync(r,e.data,{mode:384});const o=R.buf&&!/\s$/.test(R.buf)?" ":"";return R.insert(o+r),void lt(`Pasted image → ${r}`)}catch(e){return void lt(`Could not save the pasted image: ${e&&e.message||e}`)}const t=te({env:process.env});if(t.ok&&t.text)return R.insert(t.text),void lt(`Pasted ${t.text.length} character${1===t.text.length?"":"s"} from the clipboard`);lt(t.ok?"Clipboard is empty — nothing to paste":`Cannot read the clipboard here (${t.error}) — use your terminal's own paste shortcut instead`)})()}},Tt=async e=>{const t=String(e||"").trim();if("?"===t)return A={type:"shortcuts"},void ut();(!1===await(async(e,t)=>{try{return await((e,t)=>{const n=[];let r,o,s=!1;return e.then((e=>{s=!0,r=e}),(e=>{s=!0,o=e})),(async()=>{for(;!s;){if(!K||A&&"confirm"===A.type){await new Promise((e=>setTimeout(e,60)));continue}const e=await C(120);if(null!==e)if(e.name===v.ESC||e.name===v.CTRL_C){const e=t&&t();e&&e.abort()}else vt(e)||n.push(e)}if(S(n),o)throw o;return r})()})(e(),t)}catch(e){return ft({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),void ut()}})((async()=>{if(t.startsWith("/")){const e=(()=>{const e=s.makeCommandContext();return Object.assign(e,{push:(e,t)=>{ft(e,t),ut()},note:e=>{ft({role:"note",text:e}),ut()},panel:e=>{ft({role:"panel",lines:e||[]}),ut()},render:()=>ut(),openOverlay:e=>{A=e,ut()},closeOverlay:()=>{A=null,a(),ut()},askInput:e=>(e=>new Promise((t=>{He={title:e,buf:""},ut(),(async()=>{for(;;){const e=await k();if(!He)return void t(null);if(e.name===v.ESC||e.name===v.CTRL_C||e.name===v.CTRL_D)return He=null,ut(),void t(null);if(e.name===v.ENTER){const e=He.buf;return He=null,ut(),void t(e)}e.name===v.BACKSPACE?He.buf=[...He.buf].slice(0,-1).join(""):"char"===e.name?He.buf+=e.ch:"paste"===e.name&&(He.buf+=String(e.text).replace(/\n/g," ")),ut()}})()})))(e),withWorking:e=>(async e=>{const t=W;K=!0,z=0,H=Date.now(),V=L[Q%L.length],W=new AbortController,Y=setInterval((()=>{z++,it(!0),z%3==0&&ut()}),100),Y.unref&&Y.unref(),it(!0);try{return await e(W.signal)}finally{K=!1,clearInterval(Y),Y=null,W=t,it(!1),ut()}})(e),runPrompt:async e=>{await wt(e)},state:()=>s.buildState(),setInput:e=>{R.buf=String(null==e?"":e),R.end(),ut()},exit:()=>s.requestExit(),openStream:e=>{Ve=e||null,Qe=Date.now(),ut()},closeStream:e=>{e&&Ve!==e||(Ve=null),ut()},showThemePicker:()=>{s.showThemePicker&&s.showThemePicker(),ut()}}),e})();return s.dispatchLine(t,e)}return await wt(t),!0}),(()=>W))||s.wantsExit())&&await Mt()};let xt=!1,Et=null;const Mt=()=>{xt||(xt=!0,Et&&Et(0))},Lt=()=>{i(),r([]);try{process.stdout.write("[0m")}catch{}try{rt&&we("",process.stdout)}catch{}try{process.stdin.setRawMode(!1)}catch{}m(),p(),d()};let Pt=!1;const Rt=()=>{if(!Pt){Pt=!0;try{Lt()}catch{}}};process.once("exit",Rt);const It=s.stdin||process.stdin;x(),$(It),f(),h(),c(),u(),i(),it(!1);const Nt=()=>ut();"win32"!==process.platform?process.on("SIGWINCH",Nt):process.stdout.on("resize",Nt);const _t=()=>{K&&W?W.abort():Mt()};process.on("SIGINT",_t);const Ot=e=>{Lt();try{process.stderr.write(`\nAEGIS Code hit an unexpected error. Your transcript is saved; rerun to continue.\n${e&&e.stack||e}\n`)}catch{}process.exit(1)};process.on("uncaughtException",Ot),process.on("unhandledRejection",Ot),ut();try{return await new Promise((e=>{Et=e,(async()=>{for(;!xt;){const e=await k();if(xt)break;if(e===b||!e){Mt();break}try{await St(e)}catch(e){ft({role:"note",text:`Error: ${e&&e.message||String(e)}`},{follow:!1}),ut()}}})()}))}finally{xt=!0,process.off("SIGINT",_t),"win32"!==process.platform?process.off("SIGWINCH",Nt):process.stdout.off("resize",Nt),process.off("uncaughtException",Ot),process.off("unhandledRejection",Ot),process.off("exit",Rt),Rt(),T()}}};
|