aegiscode 7.0.13 → 7.0.15
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 +3 -2
- 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 -3008
- package/src/checkpoint.js +1 -90
- package/src/clipboard.js +1 -424
- package/src/cloudsync.js +1 -528
- package/src/commands.js +1 -3987
- 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 -2054
- 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 -85
- 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 -125
- package/vendor/client/hooks.js +1 -430
- package/vendor/client/model-discovery.js +1 -330
- 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 -3228
- package/vendor/desktop/lib/local/entitlement.js +1 -654
- 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/app.js
CHANGED
|
@@ -1,2934 +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 CLI application: session state, the ask/stream path, and the command
|
|
10
|
-
* dispatcher.
|
|
11
|
-
*
|
|
12
|
-
* Split from `bin/aegiscode.js` so the whole app is constructible with injected
|
|
13
|
-
* IO (`out`, `err`, `readline`) and a stub client — the tests drive real turns,
|
|
14
|
-
* real streaming and real command dispatch without a TTY and without a child
|
|
15
|
-
* process. Bin entry = argument parsing and process lifecycle; everything else
|
|
16
|
-
* lives here.
|
|
17
|
-
*
|
|
18
|
-
* Commands come from `./commands.js`. Each entry is either handler-backed
|
|
19
|
-
* (`cmd.handler(c, args)`, the upstream engine contract), tool-backed
|
|
20
|
-
* (`cmd.tool` + `cmd.build`), a generic escape hatch (`cmd.generic`, `/tool`),
|
|
21
|
-
* or `unavailable` (a Claude Code auth-loop command this client cannot honour).
|
|
22
|
-
* Handlers run against the FROZEN command context built below; the tool path
|
|
23
|
-
* and the `/tool` escape hatch are unchanged from the previous revision.
|
|
24
|
-
*/
|
|
25
|
-
|
|
26
|
-
const readline = require('node:readline');
|
|
27
|
-
const os = require('node:os');
|
|
28
|
-
const { randomUUID } = require('node:crypto');
|
|
29
|
-
const { createTools, createClient, usageTokens, usageBuckets, buildSystemPrompt, autoProvisionApiKey, provisionFailureText, trialNote, hostEnv, autonomous, claudePro } = require('./deps.js');
|
|
30
|
-
const { createEngine, HOST_CLASSES, DEFAULT_CLASS, byokNamespace, effortRung, offeredClasses, proEnabled } = require('./engine.js');
|
|
31
|
-
const { GLYPH, VERBS, themeOf, RESET, THEME_TABLE, AUTO_THEME_INDEX, themeIsLight, reconcileThemeIndex } = require('./theme.js');
|
|
32
|
-
const { probeTerminalBackground } = require('./caps.js');
|
|
33
|
-
const { LiveRegion, termWidth, w } = require('./screen.js');
|
|
34
|
-
// The live spinner tail is a token count, so the cell→token rule comes from the
|
|
35
|
-
// one module that owns it rather than a `/4` written inline at the call site
|
|
36
|
-
// (tokens.js explains why the count form has to sit beside the text form).
|
|
37
|
-
const { estimateTokensFromCells } = require('./tokens.js');
|
|
38
|
-
const { editPreview } = require('./diff.js');
|
|
39
|
-
const { defaultOpen } = require('./diffview.js');
|
|
40
|
-
const { parseLine, COMMANDS, visibleCommands } = require('./commands.js');
|
|
41
|
-
const {
|
|
42
|
-
updateConfig,
|
|
43
|
-
loadPermissions,
|
|
44
|
-
loadConfig,
|
|
45
|
-
configExists,
|
|
46
|
-
memoryPersistState,
|
|
47
|
-
memoryPersistEnabled,
|
|
48
|
-
setMemoryPersist,
|
|
49
|
-
confirmPosture,
|
|
50
|
-
} = require('./config.js');
|
|
51
|
-
const credentials = require('./credentials.js');
|
|
52
|
-
// The key pump, so the startup background query can hand back a keystroke that
|
|
53
|
-
// raced its answer (see the `probeTerminalBackground` call in `runInteractive`).
|
|
54
|
-
const events = require('./events.js');
|
|
55
|
-
const cloudsync = require('./cloudsync.js');
|
|
56
|
-
const { readSecret } = require('./secret.js');
|
|
57
|
-
const { normalizeModelCatalog, pickerEntries, catalogIds } = require('./models.js');
|
|
58
|
-
const { appendHistory, readSessionTranscript, readOwnSessions, setSessionTitle } = require('./history.js');
|
|
59
|
-
const naming = require('./naming.js');
|
|
60
|
-
const { snapshotCheckpoint } = require('./checkpoint.js');
|
|
61
|
-
const screens = require('./screens.js');
|
|
62
|
-
const chatflow = require('./chatflow.js');
|
|
63
|
-
const overlays = require('./overlays.js');
|
|
64
|
-
const render = require('./render.js');
|
|
65
|
-
const { fmtTokens, fmtEur, maskKey, feeBillable } = require('./format.js');
|
|
66
|
-
// The rule-5 skip resolver the gate below calls. It was CALLED and never
|
|
67
|
-
// imported: `const skip = resolveSkip({…})` at the top of the `getConfirmMode`
|
|
68
|
-
// callback threw a ReferenceError on every invocation, the surrounding `catch`
|
|
69
|
-
// swallowed it as "the store could not be read", and the whole skip arm was
|
|
70
|
-
// therefore dead in shipped code — `AEGISONE_SKIP_PERMISSIONS` (what the
|
|
71
|
-
// `aegis` bin forwards once it has resolved `--dangerously-skip-permissions`)
|
|
72
|
-
// and the CI/queue spelling both fell through to the store and were ignored,
|
|
73
|
-
// with nothing on screen to say a decision had been discarded. Imported here,
|
|
74
|
-
// beside the other module-level requires, so the two faces resolve a skip
|
|
75
|
-
// through the one function (D8 rule 1) instead of one of them not at all.
|
|
76
|
-
const { resolveSkip } = require('./permissions.js');
|
|
77
|
-
|
|
78
|
-
const VERSION = require('../package.json').version;
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* The persona for a turn this host did not get an explicit system prompt for.
|
|
82
|
-
*
|
|
83
|
-
* Built once and cached: it is the stable head of every request, and a prompt
|
|
84
|
-
* that changed between turns would defeat the provider's prompt cache for the
|
|
85
|
-
* whole conversation behind it.
|
|
86
|
-
*/
|
|
87
|
-
let _defaultSystem = null;
|
|
88
|
-
function defaultSystemPrompt() {
|
|
89
|
-
if (_defaultSystem === null) {
|
|
90
|
-
try {
|
|
91
|
-
// The SAME environment block the desktop engine builds (engine.js
|
|
92
|
-
// hostEnv): platform, the real home and Desktop directories, the working
|
|
93
|
-
// directory, and — the field this host was missing — the shell `exec`
|
|
94
|
-
// really runs in. Building a three-field subset here is what let a
|
|
95
|
-
// Windows CLI session be told it was on linux and reach for `ls`, `cat`
|
|
96
|
-
// and `mkdir -p`: nothing in the prompt said otherwise.
|
|
97
|
-
_defaultSystem = buildSystemPrompt(hostEnv({}, {}, null));
|
|
98
|
-
} catch {
|
|
99
|
-
_defaultSystem = ''; // never let persona construction break a turn
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
return _defaultSystem || undefined;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// The engine accepts exactly 'once' | 'session' and coerces anything else to
|
|
106
|
-
// 'deny' (vendor/desktop/lib/local/engine.js → respondApproval). Bridging the
|
|
107
|
-
// vocabularies here, rather than trusting every prompter to speak the engine's
|
|
108
|
-
// dialect, is what stops an approval from silently becoming a denial. The
|
|
109
|
-
// failure mode is invisible from the outside: the tool is refused, the model
|
|
110
|
-
// is told the user declined, and it retries against a gate that can only ever
|
|
111
|
-
// say no — the turn burns its whole budget.
|
|
112
|
-
//
|
|
113
|
-
// Module scope on purpose: this must exist before createApp() runs, because it
|
|
114
|
-
// is re-exported for the conformance tests. A nested copy here previously left
|
|
115
|
-
// the export binding undefined and threw on require.
|
|
116
|
-
function normalizeDecision(decision) {
|
|
117
|
-
const v = typeof decision === 'string' ? decision.trim().toLowerCase() : '';
|
|
118
|
-
if (v === 'session') return 'session';
|
|
119
|
-
if (v === 'once' || v === 'allow' || v === 'yes' || v === 'approve' || v === 'approved') {
|
|
120
|
-
return 'once';
|
|
121
|
-
}
|
|
122
|
-
return 'deny';
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// ── "that was not an answer" ────────────────────────────────────────────────
|
|
126
|
-
//
|
|
127
|
-
// A provider-side refusal can arrive shaped exactly like a completion: HTTP
|
|
128
|
-
// 200, an assistant message, `usage` absent or zero. Measured 2026-10-21 on
|
|
129
|
-
// this CLI, twice, from live runs:
|
|
130
|
-
//
|
|
131
|
-
// {"text":"Invalid API key · Fix external API key","tokens":0,"balance_eur":1.54}
|
|
132
|
-
// {"text":"You've hit your session limit · resets 9:50pm (Europe/Stockholm)"}
|
|
133
|
-
//
|
|
134
|
-
// Both exited 0. Nothing about the process told a caller that the turn had
|
|
135
|
-
// failed: a shell script, a CI job, or the harness adapter reading `--json`
|
|
136
|
-
// sees a non-empty `text` and calls it success. The harness did exactly that
|
|
137
|
-
// and scored a *broken* run as a scored zero rather than an error.
|
|
138
|
-
//
|
|
139
|
-
// The engine already treats this class as a diagnosed failure mode — see
|
|
140
|
-
// `phantomPin()` and the `session limit` notes in aegiscodex-dev's
|
|
141
|
-
// src/backend.js, where a spent OAuth session "reads like a provider outage
|
|
142
|
-
// rather than a bad pin". This host ships the transport and the CLI, not that
|
|
143
|
-
// brain, so it cannot prevent the misroute; what it *can* do is refuse to pass
|
|
144
|
-
// the resulting sentence off as an answer.
|
|
145
|
-
//
|
|
146
|
-
// Deliberately narrow, because calling a real answer an error is its own bug:
|
|
147
|
-
// - Only when the turn produced NO tokens. A billed turn did work; whatever
|
|
148
|
-
// it says is the model's output, even if it reads oddly.
|
|
149
|
-
// - Only when the whole reply is one short line. A long answer that happens
|
|
150
|
-
// to discuss API keys must not be caught by a substring match.
|
|
151
|
-
// - Only known provider-refusal shapes. Not "any sentence with 'error'".
|
|
152
|
-
const PROVIDER_REFUSAL_PATTERNS = Object.freeze([
|
|
153
|
-
/^invalid api key\b/i,
|
|
154
|
-
/^fix external api key\b/i,
|
|
155
|
-
/^you've hit your session limit\b/i,
|
|
156
|
-
/^you have hit your session limit\b/i,
|
|
157
|
-
/^provider request timed out\b/i,
|
|
158
|
-
/^insufficient (?:credit|balance|quota)\b/i,
|
|
159
|
-
/^rate limit(?:ed)?\b/i,
|
|
160
|
-
/^unauthorized\b/i,
|
|
161
|
-
]);
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* Whether `text` is a provider refusal that arrived dressed as a completion.
|
|
165
|
-
*
|
|
166
|
-
* @param {unknown} text the assistant content `ask()` returned
|
|
167
|
-
* @param {unknown} usage the turn's usage record, if any
|
|
168
|
-
* @returns {string|null} the matched refusal, or null when it is a real answer
|
|
169
|
-
*/
|
|
170
|
-
function providerRefusal(text, usage) {
|
|
171
|
-
if (typeof text !== 'string') return null;
|
|
172
|
-
// A billed turn is not a refusal, whatever it says.
|
|
173
|
-
const total = usage && (usage.total_tokens || 0);
|
|
174
|
-
const out = usage && (usage.output_tokens || usage.completion_tokens || 0);
|
|
175
|
-
if (total > 0 || out > 0) return null;
|
|
176
|
-
const line = text.trim();
|
|
177
|
-
if (!line || line.length > 160 || line.includes('\n')) return null;
|
|
178
|
-
for (const re of PROVIDER_REFUSAL_PATTERNS) {
|
|
179
|
-
if (re.test(line)) return line;
|
|
180
|
-
}
|
|
181
|
-
return null;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
/**
|
|
185
|
-
* One tool call, readable — the arg summary published in `--json`'s `tool_log`.
|
|
186
|
-
*
|
|
187
|
-
* Truncated on a character boundary so a row stays a record a person can read
|
|
188
|
-
* while still showing WHAT each call was. A list of tool names cannot tell
|
|
189
|
-
* "read four files" apart from "ran the same test twelve times", and the
|
|
190
|
-
* archived AEGIS rows carried only names.
|
|
191
|
-
*
|
|
192
|
-
* @param {unknown} a the call's arguments
|
|
193
|
-
* @returns {string} a single line, at most 140 characters
|
|
194
|
-
*/
|
|
195
|
-
function briefArgs(a) {
|
|
196
|
-
let s;
|
|
197
|
-
try { s = typeof a === 'string' ? a : JSON.stringify(a ?? ''); } catch { s = String(a); }
|
|
198
|
-
s = String(s).replace(/\s+/g, ' ').trim();
|
|
199
|
-
return s.length > 140 ? `${s.slice(0, 137)}...` : s;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
function createApp(options = {}) {
|
|
203
|
-
const opts = {
|
|
204
|
-
model: null,
|
|
205
|
-
stream: true,
|
|
206
|
-
light: false,
|
|
207
|
-
maxTokens: undefined,
|
|
208
|
-
system: undefined,
|
|
209
|
-
interactive: true,
|
|
210
|
-
...options,
|
|
211
|
-
};
|
|
212
|
-
const out = options.out || process.stdout;
|
|
213
|
-
const err = options.err || process.stderr;
|
|
214
|
-
// The key comes from the credential store (env → credentials.json →
|
|
215
|
-
// config.json) rather than from the environment alone: an export does not
|
|
216
|
-
// survive a new shell, and until it is *stored* every one of those launches
|
|
217
|
-
// is "no key" with no in-band way to set one. An injected client keeps
|
|
218
|
-
// whatever key it was built with.
|
|
219
|
-
const client = options.client || createClient(credentials.clientOptions({ channel: 'cli' }));
|
|
220
|
-
const { TOOLS, toolList } = options.tools || createTools(client);
|
|
221
|
-
|
|
222
|
-
// With no key configured anywhere, ask aegis1 for a free device key before
|
|
223
|
-
// ever showing "no key" — same shared helper (client/auto-provision.js) the
|
|
224
|
-
// MCP plugin and the desktop app use, so all three ask for the same account
|
|
225
|
-
// on the same machine. One provisioning per `createApp()` instance, not one
|
|
226
|
-
// per call: register-device is rate-limited server-side, and a session that
|
|
227
|
-
// fires several turns before noticing a failure must not retry the same
|
|
228
|
-
// failing call each time. A transient failure gets a few bounded retries
|
|
229
|
-
// inside that one provisioning. A brand-new fingerprint comes back with aegis1's
|
|
230
|
-
// one-time 30-day welcome-trial `unlimited` entitlement (token-bank credit
|
|
231
|
-
// plus a `subscriptions` row) granted in the same request — aegis1 commit
|
|
232
|
-
// 4372830 — so the account is usable pooled right away rather than starting
|
|
233
|
-
// at zero. The credit is finite: once it is spent or the trial lapses, the
|
|
234
|
-
// usual plan/balance gate applies.
|
|
235
|
-
let provisionAttempted = false;
|
|
236
|
-
let keyFailure = '';
|
|
237
|
-
async function provisionDeviceKey() {
|
|
238
|
-
const result = await autoProvisionApiKey(client, credentials, { app: 'cli' });
|
|
239
|
-
keyFailure = result.key ? '' : provisionFailureText(result);
|
|
240
|
-
return result;
|
|
241
|
-
}
|
|
242
|
-
async function ensureApiKey() {
|
|
243
|
-
if (client.apiKey || provisionAttempted) return;
|
|
244
|
-
provisionAttempted = true;
|
|
245
|
-
const result = await provisionDeviceKey();
|
|
246
|
-
if (result.key) {
|
|
247
|
-
emit(
|
|
248
|
-
render.renderNotice(
|
|
249
|
-
ctx(),
|
|
250
|
-
'info',
|
|
251
|
-
`auto-provisioned a free account` +
|
|
252
|
-
(result.ok ? ` (saved to ${credentials.credentialsPath()})` : ' (could not save it — reconfigure with /key)') +
|
|
253
|
-
// Shared clause: covers the withheld case AND the reused one (a
|
|
254
|
-
// returning fingerprint gets its old account, never a second
|
|
255
|
-
// trial). Inline here it only knew `trialGranted`, so a
|
|
256
|
-
// re-registered machine read as a clean first install.
|
|
257
|
-
trialNote(result) +
|
|
258
|
-
`. Fund it at ${client.promptUrl('topup', 'device_autoprovision')} or run /byok to use your own key.`
|
|
259
|
-
)
|
|
260
|
-
);
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
// Tool-approval gate (exec/writeFile/editFile confirm before running).
|
|
265
|
-
// Read per call, so /permissions and /automode take effect on the very next tool
|
|
266
|
-
// round rather than needing a restart. The mode is read LIVE from the
|
|
267
|
-
// permission store rather than from a boolean captured at construction:
|
|
268
|
-
// `/automode` and `/confirm` write the store, so a captured flag made both
|
|
269
|
-
// commands cosmetic — the panel changed while the engine kept asking.
|
|
270
|
-
let confirmMode = options.confirmMode !== false;
|
|
271
|
-
// ── Auto mode's session start state ────────────────────────────────────────
|
|
272
|
-
// The upstream engine (aegiscodex-dev src/autonomous.js) starts an attended
|
|
273
|
-
// session in auto mode unless AEGIS_AUTO_ROUNDS=0 (false/off/no), and the
|
|
274
|
-
// `←`/`→` chord toggles it freely from there: the env var is a STARTING
|
|
275
|
-
// POINT, not a veto. Same contract here, held in a local rather than
|
|
276
|
-
// re-derived per call, because the two are not the same statement:
|
|
277
|
-
//
|
|
278
|
-
// · re-deriving the env var on every read (a `!autoRoundsDefault(env)`
|
|
279
|
-
// guard inside isYolo) makes the opt-out absolute — `/automode on`,
|
|
280
|
-
// the `→` chord and the window's switch all become no-ops that still
|
|
281
|
-
// write the shared posture OFF, so the CLI chip reads "manual mode on"
|
|
282
|
-
// while the desktop's approvals are off. That is the three-surfaces
|
|
283
|
-
// drift (command, store, engine) this file exists to prevent,
|
|
284
|
-
// reintroduced by an environment variable.
|
|
285
|
-
// · a session flag honours the operator's "start me in manual" without
|
|
286
|
-
// disarming the toggle.
|
|
287
|
-
//
|
|
288
|
-
// `/automode on|off` moves it (commands.js writes `setAutoRounds`), so the
|
|
289
|
-
// chord stays live in both directions and the posture keeps exactly one home.
|
|
290
|
-
let autoRoundsSession = (() => {
|
|
291
|
-
try {
|
|
292
|
-
return autonomous.autoRoundsDefault(process.env);
|
|
293
|
-
} catch {
|
|
294
|
-
return true;
|
|
295
|
-
}
|
|
296
|
-
})();
|
|
297
|
-
const engine =
|
|
298
|
-
options.engine ||
|
|
299
|
-
createEngine({
|
|
300
|
-
client,
|
|
301
|
-
// The live class — read per turn rather than captured, for the same
|
|
302
|
-
// reason confirmMode is a callback: a captured value made `/class`
|
|
303
|
-
// cosmetic, changing the panel and not what the next turn ran on.
|
|
304
|
-
getClass: () => commandCtx.modelClass,
|
|
305
|
-
// Whether the `pro` class is enabled (config.js `proEnabled`, off by
|
|
306
|
-
// default). Read per call for the same reason getClass is: `/class pro
|
|
307
|
-
// off` must remove it from the picker and stop the very next turn, not
|
|
308
|
-
// the next launch. A read failure answers "off" — fail closed, because
|
|
309
|
-
// the alternative spends a subscription nobody opted into.
|
|
310
|
-
getProEnabled: () => {
|
|
311
|
-
try {
|
|
312
|
-
return proEnabled(loadConfig());
|
|
313
|
-
} catch {
|
|
314
|
-
return false;
|
|
315
|
-
}
|
|
316
|
-
},
|
|
317
|
-
getConfirmMode: () => {
|
|
318
|
-
if (options.confirmMode !== undefined) return confirmMode;
|
|
319
|
-
// AEGISONE D8 rule 5 — the skip posture, resolved by the SAME function
|
|
320
|
-
// the product uses (cli/src/permissions.js resolveSkip), so the two
|
|
321
|
-
// faces cannot disagree about what a flag or an environment variable
|
|
322
|
-
// means. Two sources only:
|
|
323
|
-
//
|
|
324
|
-
// AEGISONE_SKIP_PERMISSIONS the `aegis` bin's forwarded decision,
|
|
325
|
-
// already checked against rule 5 upstream;
|
|
326
|
-
// AEGIS_SKIP_PERMISSIONS the CI/queue spelling, honored only when
|
|
327
|
-
// this process is NON-interactive. A stray
|
|
328
|
-
// `export` in a shell profile warns and is
|
|
329
|
-
// ignored here, which is the whole point:
|
|
330
|
-
// it must not be able to disarm a human's
|
|
331
|
-
// own gate.
|
|
332
|
-
//
|
|
333
|
-
// A rule-5 refusal is reported once per session, not per tool call —
|
|
334
|
-
// the gate is read on every round and a warning per round would be
|
|
335
|
-
// noise the user learns to scroll past.
|
|
336
|
-
try {
|
|
337
|
-
const skip = resolveSkip({
|
|
338
|
-
env: process.env,
|
|
339
|
-
interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
340
|
-
});
|
|
341
|
-
if (skip.warned && !skipEnvWarned) {
|
|
342
|
-
skipEnvWarned = true;
|
|
343
|
-
process.stderr.write(`aegiscode: ${skip.warning}\n`);
|
|
344
|
-
}
|
|
345
|
-
if (skip.skip) return false;
|
|
346
|
-
} catch {
|
|
347
|
-
/* fall through to the store: a broken skip resolver must not skip */
|
|
348
|
-
}
|
|
349
|
-
try {
|
|
350
|
-
// ON8 / D8 rule 1: the posture is read from the SHARED store first
|
|
351
|
-
// (config.js confirmPosture), which is the same store the desktop's
|
|
352
|
-
// "confirm before running tools" switch writes. Before this, the shell
|
|
353
|
-
// read only its own rule file, so the switch and `/automode` were two
|
|
354
|
-
// postures for one question — the drift D8 names. The rule file is
|
|
355
|
-
// still the answer for an install that never touched the switch, so
|
|
356
|
-
// nothing changes for it.
|
|
357
|
-
return confirmPosture().enabled;
|
|
358
|
-
} catch {
|
|
359
|
-
return confirmMode;
|
|
360
|
-
}
|
|
361
|
-
},
|
|
362
|
-
});
|
|
363
|
-
// How a class is named in every surface that shows one (the status line, the
|
|
364
|
-
// class panel, the model picker's title). One definition, because the engine
|
|
365
|
-
// owns the label table (CLASS_LABELS) and re-spelling it here would let the
|
|
366
|
-
// picker and /class disagree about what the user is about to run on. Guarded
|
|
367
|
-
// because an injected engine (tests, embedding) may predate the class surface.
|
|
368
|
-
const classLabelOf = (cls) =>
|
|
369
|
-
typeof engine.classLabel === 'function' ? engine.classLabel(cls) : String(cls || '');
|
|
370
|
-
|
|
371
|
-
// Set by runInteractive: a question/answer channel for the engine's
|
|
372
|
-
// tool-approval requests. Left null in one-shot (-p) runs, where there is
|
|
373
|
-
// no one to ask — see the approval branch in ask() below.
|
|
374
|
-
let approvalPrompter = null;
|
|
375
|
-
|
|
376
|
-
const width = () => (options.width ? options.width() : termWidth());
|
|
377
|
-
|
|
378
|
-
// ── live session/command state ─────────────────────────────────────────────
|
|
379
|
-
// `commandCtx` is the FROZEN `c.ctx` a handler receives: the mutable slice of
|
|
380
|
-
// session state a command may set (model, effort, thinking, theme, vim, stream,
|
|
381
|
-
// cwd, lastRecap). The renderers read their colours from it via ctx().
|
|
382
|
-
const commandCtx = {
|
|
383
|
-
light: opts.light,
|
|
384
|
-
model: opts.model,
|
|
385
|
-
// Which class the next turn runs on. 'aegis' is the default because it is
|
|
386
|
-
// the one class an account key alone can run — BYOK additionally needs a
|
|
387
|
-
// provider key, so defaulting to it would break a fresh install.
|
|
388
|
-
modelClass: DEFAULT_CLASS,
|
|
389
|
-
// The budget rung the next turn travels with. `null` here means "nothing
|
|
390
|
-
// restored yet", not "auto": the rung actually sent is resolved by
|
|
391
|
-
// effortRung() at the request, which floors to 'high' — the same default
|
|
392
|
-
// the config file seeds and the desktop select offers. Retiring "auto" is
|
|
393
|
-
// the point: it was the default, so the default turn sent no effort at all
|
|
394
|
-
// and low/medium/high only moved the status line.
|
|
395
|
-
effort: null,
|
|
396
|
-
thinking: false,
|
|
397
|
-
// Deep recall (`aegis_recall_deep`) — the metered tier of the read: brain
|
|
398
|
-
// corrections plus the semantic answer cache, and the answer cache costs
|
|
399
|
-
// one provider embedding per turn (aegis1 app.py:8367 →
|
|
400
|
-
// services/brain_memory.py find_cached_answer). This host recalls on every
|
|
401
|
-
// turn already and pays per turn, so the deep tier is NEVER inferred: it is
|
|
402
|
-
// false here, `/memory-deep on` is the only thing that flips it, and that
|
|
403
|
-
// choice is deliberately NOT persisted — a flag that meters every turn must
|
|
404
|
-
// not survive into a session where nobody asked for it.
|
|
405
|
-
recallDeep: false,
|
|
406
|
-
// "Auto (match terminal)" is the default row, not "Dark mode": the row's
|
|
407
|
-
// whole purpose is that it resolves against the terminal's reported
|
|
408
|
-
// background, and leaving the default on explicit Dark drew the dark
|
|
409
|
-
// palette's white body text over a light terminal — an invisible UI — for
|
|
410
|
-
// every user who never opened the picker.
|
|
411
|
-
themeIndex: opts.light ? 2 : AUTO_THEME_INDEX,
|
|
412
|
-
vim: false,
|
|
413
|
-
stream: opts.stream,
|
|
414
|
-
cwd: process.cwd(),
|
|
415
|
-
lastRecap: null,
|
|
416
|
-
sessionId: randomUUID(),
|
|
417
|
-
};
|
|
418
|
-
// The light flag must start consistent with the default row above, or the
|
|
419
|
-
// ctx and the palette disagree until the first `/theme`: with `AUTO_THEME_INDEX`
|
|
420
|
-
// as the default, a light-background terminal gets the light palette *and*
|
|
421
|
-
// the "light" label, a dark one is byte-identical to before.
|
|
422
|
-
if (commandCtx.themeIndex === AUTO_THEME_INDEX) commandCtx.light = themeIsLight(AUTO_THEME_INDEX);
|
|
423
|
-
// The transcript rows a handler reads/pushes (user/assistant/note/panel/…).
|
|
424
|
-
// It is also the source of the engine's conversation history, so /clear and
|
|
425
|
-
// /new genuinely reset context.
|
|
426
|
-
const transcript = [];
|
|
427
|
-
let wantExit = false;
|
|
428
|
-
// When non-null, `emit` appends here instead of writing to `out`. Used by the
|
|
429
|
-
// one-shot path to run a command and report its output as one JSON document
|
|
430
|
-
// (`--json`) rather than as loose human text on stdout. Every command's output
|
|
431
|
-
// funnels through `emit` (pushRow's panel/note/turn branches all call it), so
|
|
432
|
-
// one switch here covers the whole command surface.
|
|
433
|
-
let capture = null;
|
|
434
|
-
|
|
435
|
-
const ctx = () => ({ light: commandCtx.light });
|
|
436
|
-
|
|
437
|
-
const session = {
|
|
438
|
-
turns: 0,
|
|
439
|
-
calls: 0,
|
|
440
|
-
tokens: 0,
|
|
441
|
-
inputTokens: 0,
|
|
442
|
-
outputTokens: 0,
|
|
443
|
-
cacheReadTokens: 0,
|
|
444
|
-
cacheWriteTokens: 0,
|
|
445
|
-
cost: 0, // € spent, from the ledger rows that landed AFTER the baseline
|
|
446
|
-
balance: null,
|
|
447
|
-
// How many times each ledger-row identity is already accounted for.
|
|
448
|
-
// A COUNT, not a Set — see ledgerRowKey for why identity is content-based
|
|
449
|
-
// and refreshSpend for why the multiplicity matters.
|
|
450
|
-
seenLedgerRows: new Map(),
|
|
451
|
-
// Whether the account's existing ledger has been snapshotted as history.
|
|
452
|
-
// The balance endpoint returns the ACCOUNT's ledger, so the rows visible on
|
|
453
|
-
// the first refresh are everything the customer ever spent. Until this is
|
|
454
|
-
// true, no row may be folded into `cost`: session.cost is rendered as
|
|
455
|
-
// "This session" and would otherwise print the account's lifetime spend
|
|
456
|
-
// under it. See refreshSpend.
|
|
457
|
-
ledgerBaselined: false,
|
|
458
|
-
startedAt: Date.now(),
|
|
459
|
-
};
|
|
460
|
-
|
|
461
|
-
let activeSessionId = null;
|
|
462
|
-
let closed = false;
|
|
463
|
-
|
|
464
|
-
// --- helpers --------------------------------------------------------------
|
|
465
|
-
|
|
466
|
-
/**
|
|
467
|
-
* How much one ledger row is worth to the customer, in EUR (always >= 0).
|
|
468
|
-
*
|
|
469
|
-
* `amount_eur` is signed from the user's side (negative = spent) and is what
|
|
470
|
-
* /api/token-bank/balance actually returns. `charged_micros` is the raw
|
|
471
|
-
* column with the OPPOSITE sign, kept only as a fallback for a server build
|
|
472
|
-
* that drops amount_eur — which is why it is negated here.
|
|
473
|
-
*
|
|
474
|
-
* Returns null for a row that is not a charge at all, or that carries no
|
|
475
|
-
* usable number. Anything non-finite is null rather than NaN: a NaN that
|
|
476
|
-
* reaches a tally poisons it for the rest of the session, and a NaN written
|
|
477
|
-
* into history.jsonl is invisible until /cost renders it.
|
|
478
|
-
*/
|
|
479
|
-
function ledgerRowEur(row) {
|
|
480
|
-
if (!row || typeof row !== 'object') return null;
|
|
481
|
-
// A top-up is money IN, not a charge. Folding one into the spend tally
|
|
482
|
-
// would report a customer who just added €20 as having spent €20.
|
|
483
|
-
if (row.kind !== 'usage') return null;
|
|
484
|
-
const raw = row.amount_eur != null ? Number(row.amount_eur) : -Number(row.charged_micros || 0) / 1e6;
|
|
485
|
-
if (!Number.isFinite(raw)) return null;
|
|
486
|
-
// The magnitude is the charge either way; the server's sign convention for
|
|
487
|
-
// a spend row is not something this client should depend on.
|
|
488
|
-
return Math.abs(raw);
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
/**
|
|
492
|
-
* The identity of a ledger row, used to decide "is this new?".
|
|
493
|
-
*
|
|
494
|
-
* Deliberately NOT `created_at`. That column is stamped to the second, so two
|
|
495
|
-
* turns inside the same second collide: the second row compared equal to the
|
|
496
|
-
* first, was skipped as "already counted", and — because chatflow persists the
|
|
497
|
-
* turn with whatever this returned — the exchange was written to history.jsonl
|
|
498
|
-
* with NO charge attached. /cost then fell back to the local rate table for
|
|
499
|
-
* that turn and reported a figure that was not the bill. Every column the
|
|
500
|
-
* endpoint returns that can distinguish two rows is folded in here.
|
|
501
|
-
*
|
|
502
|
-
* The endpoint returns no unique row id (see mcp/tools.js, which reads the
|
|
503
|
-
* same columns), so this is content-based and two genuinely identical charges
|
|
504
|
-
* — same model, same token counts, same second — hash the same. That is why
|
|
505
|
-
* callers count occurrences rather than merely testing membership: a Set
|
|
506
|
-
* would treat the second identical charge as already-counted and silently
|
|
507
|
-
* under-bill it, which is the original defect wearing a different hat.
|
|
508
|
-
*/
|
|
509
|
-
function ledgerRowKey(row) {
|
|
510
|
-
return [
|
|
511
|
-
row.created_at || '',
|
|
512
|
-
row.kind || '',
|
|
513
|
-
row.amount_eur != null ? row.amount_eur : '',
|
|
514
|
-
row.charged_micros != null ? row.charged_micros : '',
|
|
515
|
-
row.id != null ? row.id : '',
|
|
516
|
-
row.note != null ? row.note : '',
|
|
517
|
-
].join('|');
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
/** Refresh the balance and fold any *new* usage row into the session tally.
|
|
521
|
-
*
|
|
522
|
-
* The first successful refresh of a session is a BASELINE: it observes the
|
|
523
|
-
* account's whole ledger and folds nothing. Each entry point therefore calls
|
|
524
|
-
* this once at session start, so the baseline can never swallow a real
|
|
525
|
-
* turn's charge. Best-effort: an accounting refresh must never break a turn.
|
|
526
|
-
*
|
|
527
|
-
* @returns {Promise<{balance:number, lastCost:number|null}|null>} */
|
|
528
|
-
async function refreshSpend() {
|
|
529
|
-
try {
|
|
530
|
-
const data = await client.tokenBankBalance();
|
|
531
|
-
const balance = Number(data.balance_eur);
|
|
532
|
-
if (Number.isFinite(balance)) session.balance = balance;
|
|
533
|
-
let lastCost = null;
|
|
534
|
-
const ledger = Array.isArray(data.ledger) ? data.ledger : [];
|
|
535
|
-
|
|
536
|
-
// Fold every row that is new since the last refresh, not just the head of
|
|
537
|
-
// the list. A single refresh can legitimately see more than one unseen
|
|
538
|
-
// charge — a refresh skipped while the balance endpoint was down, a long
|
|
539
|
-
// tool turn that dispatched two billed provider calls, or the first
|
|
540
|
-
// refresh after /billing already consumed the head — and taking only
|
|
541
|
-
// ledger[0] silently dropped the rest from the session tally.
|
|
542
|
-
//
|
|
543
|
-
// Count occurrences within the pass BEFORE folding, so two identical rows
|
|
544
|
-
// are billed twice. Testing membership one row at a time cannot tell the
|
|
545
|
-
// first occurrence from the second and under-charges by one.
|
|
546
|
-
const seenHere = new Map(); // key -> { n, row }
|
|
547
|
-
for (const row of ledger) {
|
|
548
|
-
const key = ledgerRowKey(row);
|
|
549
|
-
const hit = seenHere.get(key);
|
|
550
|
-
if (hit) hit.n += 1;
|
|
551
|
-
else seenHere.set(key, { n: 1, row });
|
|
552
|
-
}
|
|
553
|
-
|
|
554
|
-
for (const [key, { n, row }] of seenHere) {
|
|
555
|
-
const already = session.seenLedgerRows.get(key) || 0;
|
|
556
|
-
session.seenLedgerRows.set(key, n);
|
|
557
|
-
|
|
558
|
-
// This endpoint returns the ACCOUNT's ledger, so on the opening refresh
|
|
559
|
-
// it holds everything the customer has ever spent. Those rows are
|
|
560
|
-
// history — mark them seen and fold nothing, so `cost` starts at zero.
|
|
561
|
-
//
|
|
562
|
-
// Reaching this loop at all means the endpoint answered, so this pass
|
|
563
|
-
// really did observe the full ledger and it is safe to call it the
|
|
564
|
-
// baseline. That is deliberately self-healing: if the session-start
|
|
565
|
-
// call failed (offline, no balance rights) the NEXT successful refresh
|
|
566
|
-
// becomes the baseline, and the worst case is one turn under-reported.
|
|
567
|
-
// The reverse — folding an unobserved ledger — would report the
|
|
568
|
-
// customer's lifetime spend as "This session", a number they already
|
|
569
|
-
// paid and are not being charged again.
|
|
570
|
-
if (!session.ledgerBaselined) continue;
|
|
571
|
-
|
|
572
|
-
// Only the occurrences beyond those already accounted for are new.
|
|
573
|
-
const fresh = n - already;
|
|
574
|
-
if (fresh <= 0) continue;
|
|
575
|
-
|
|
576
|
-
const eur = ledgerRowEur(row);
|
|
577
|
-
if (eur != null && eur > 0) {
|
|
578
|
-
session.cost += eur * fresh;
|
|
579
|
-
// The charge to attribute to this turn. The endpoint returns the
|
|
580
|
-
// ledger NEWEST-FIRST (mcp/tools.js takes `.slice(0, 5)` as "Recent
|
|
581
|
-
// activity" and renders those as the latest rows), and the folds above
|
|
582
|
-
// run in that order, so the first charge seen here is the newest —
|
|
583
|
-
// i.e. the row this turn just produced. Taking the first rather than
|
|
584
|
-
// the largest matters when one pass sees several: the max would
|
|
585
|
-
// report an older, pricier call as this turn's cost.
|
|
586
|
-
if (lastCost == null) lastCost = eur;
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
session.ledgerBaselined = true;
|
|
590
|
-
|
|
591
|
-
return { balance: session.balance, lastCost };
|
|
592
|
-
} catch {
|
|
593
|
-
return null; // no balance rights / offline: keep showing tokens
|
|
594
|
-
}
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
// ── the AEGIS account key ─────────────────────────────────────────────────
|
|
598
|
-
//
|
|
599
|
-
// Set/forget at runtime, for `/key` and `aegiscode login`. Both paths are the
|
|
600
|
-
// same three steps — persist, apply to the live client, invalidate the model
|
|
601
|
-
// catalog — because a key that is stored but not applied leaves the current
|
|
602
|
-
// session failing, and one that is applied but not stored is gone next launch.
|
|
603
|
-
|
|
604
|
-
/**
|
|
605
|
-
* Persist an account key and start using it immediately.
|
|
606
|
-
*
|
|
607
|
-
* `verify` spends one `/api/verify-api-key` round trip to catch a bad key at
|
|
608
|
-
* the moment it is entered rather than at the first prompt, and is also how
|
|
609
|
-
* the memory token (cloud sync's credential) is obtained — so a successful
|
|
610
|
-
* login leaves both credentials in the store.
|
|
611
|
-
*/
|
|
612
|
-
async function setApiKey(raw, { verify = true } = {}) {
|
|
613
|
-
const saved = credentials.saveApiKey(raw);
|
|
614
|
-
if (!saved.ok) return saved;
|
|
615
|
-
client.setApiKey(saved.key);
|
|
616
|
-
modelCache.models = [];
|
|
617
|
-
modelCache.at = 0;
|
|
618
|
-
let account = null;
|
|
619
|
-
let error = null;
|
|
620
|
-
if (verify) {
|
|
621
|
-
try {
|
|
622
|
-
const info = (await client.verifyApiKey()) || {};
|
|
623
|
-
account = info;
|
|
624
|
-
const patch = { verifiedAt: new Date().toISOString() };
|
|
625
|
-
if (info.memory_token) patch.memoryToken = info.memory_token;
|
|
626
|
-
if (info.plan) patch.plan = info.plan;
|
|
627
|
-
patch.account = { plan: info.plan || null, email: info.email || null, valid: info.valid !== false };
|
|
628
|
-
credentials.writeCredentials(patch);
|
|
629
|
-
if (info.plan) session.plan = info.plan;
|
|
630
|
-
if (info.email) session.account = { ...(session.account || {}), email: info.email };
|
|
631
|
-
} catch (e) {
|
|
632
|
-
error = e;
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
return { ...saved, account, error };
|
|
636
|
-
}
|
|
637
|
-
|
|
638
|
-
/** Drop the stored key and stop authenticating this session. */
|
|
639
|
-
function forgetApiKey() {
|
|
640
|
-
const res = credentials.clearApiKey();
|
|
641
|
-
client.setApiKey('');
|
|
642
|
-
modelCache.models = [];
|
|
643
|
-
modelCache.at = 0;
|
|
644
|
-
return res;
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
/** Explicit `/key register`: unlike the automatic path, this runs again after a failure. */
|
|
648
|
-
async function registerAccount() {
|
|
649
|
-
if (client.apiKey) return { alreadyKeyed: true };
|
|
650
|
-
return provisionDeviceKey();
|
|
651
|
-
}
|
|
652
|
-
|
|
653
|
-
/**
|
|
654
|
-
* The persisting-memory gate — the WRITE half of aegis_memory, and now ON by
|
|
655
|
-
* default for every account (see config.js `memoryPersistState` for the
|
|
656
|
-
* migration and the reasoning). The name is historical: `/sync`, `/cloud sync`
|
|
657
|
-
* and `cloudSyncEnabled()` predate the flip, and they all mean this one gate,
|
|
658
|
-
* so there is exactly one boolean behind every switch and status line.
|
|
659
|
-
*/
|
|
660
|
-
function cloudSyncEnabled() {
|
|
661
|
-
try {
|
|
662
|
-
return memoryPersistEnabled();
|
|
663
|
-
} catch {
|
|
664
|
-
return true; // default on: a corrupt config must not silently stop storage
|
|
665
|
-
}
|
|
666
|
-
}
|
|
667
|
-
|
|
668
|
-
/** Where that answer came from — 'config' | 'legacy' | 'default'. */
|
|
669
|
-
function cloudSyncState() {
|
|
670
|
-
try {
|
|
671
|
-
return memoryPersistState();
|
|
672
|
-
} catch {
|
|
673
|
-
return { enabled: true, source: 'default', explicit: false };
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
|
|
677
|
-
function setCloudSync(on) {
|
|
678
|
-
return setMemoryPersist(on);
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
/**
|
|
682
|
-
* Copy a key found in config.json into the 0600 store, once, so the next run
|
|
683
|
-
* reads the tight copy. Never deletes the original — that file belongs to
|
|
684
|
-
* another product and holds the user's key.
|
|
685
|
-
*/
|
|
686
|
-
function adoptLegacyKeyOnce() {
|
|
687
|
-
try {
|
|
688
|
-
const resolved = credentials.resolveApiKey();
|
|
689
|
-
if (resolved.source !== 'config') return [];
|
|
690
|
-
return credentials.adoptLegacy().adopted;
|
|
691
|
-
} catch {
|
|
692
|
-
return [];
|
|
693
|
-
}
|
|
694
|
-
}
|
|
695
|
-
|
|
696
|
-
// ── the AEGIS Cloud model catalog ──────────────────────────────────────────
|
|
697
|
-
//
|
|
698
|
-
// `/model` (and the alt+p chord that dispatches it) reads the pinnable ids
|
|
699
|
-
// from the server, and `state().models` is where it looks. That path had no
|
|
700
|
-
// source at all: `commands.js` calls `c.loadModels()` inside a `try {} catch
|
|
701
|
-
// {}`, `c.loadModels` was never defined on either command context, and
|
|
702
|
-
// `buildState()` hardcoded `models: []` — so the TypeError was swallowed and
|
|
703
|
-
// both `/model` and the picker reported "no models advertised" on a perfectly
|
|
704
|
-
// healthy account, forever. The ids themselves are the server's (see
|
|
705
|
-
// models.js), fetched here and cached, because the pool adds and retires
|
|
706
|
-
// providers without a client release.
|
|
707
|
-
const MODEL_CACHE_MS = 5 * 60_000;
|
|
708
|
-
const modelCache = { at: 0, models: [] };
|
|
709
|
-
// The BYOK half of the same question. A BYOK model id is `provider:model`
|
|
710
|
-
// (the engine's splitByokModel), built from the server's provider catalog
|
|
711
|
-
// plus the provider rows this machine actually holds a key for — so this list
|
|
712
|
-
// is per-machine, not per-account, and cannot be served by the pooled catalog.
|
|
713
|
-
const byokCache = { at: 0, models: [], declared: '' };
|
|
714
|
-
|
|
715
|
-
/**
|
|
716
|
-
* The user-model declarations (`$AEGISCODE_HOME/models.json`) as one
|
|
717
|
-
* comparable string, or '' when they cannot be read.
|
|
718
|
-
*
|
|
719
|
-
* The byok list is not only the server's: `engine.listModels('byok')` folds
|
|
720
|
-
* the USER's own declarations into each provider row (`client/user-models.js`
|
|
721
|
-
* `withUserModels`), so the id set can change with no network call and no
|
|
722
|
-
* provider catalog change. A custom provider in particular has NO catalog
|
|
723
|
-
* model at all — its rows exist solely because someone declared them — so a
|
|
724
|
-
* cache keyed only on time shows an empty provider for up to five minutes
|
|
725
|
-
* after the declaration was written.
|
|
726
|
-
*
|
|
727
|
-
* That is the cross-host case this exists for: the desktop's Custom provider
|
|
728
|
-
* card, `/model-add` in another terminal, and a hand-edited file all write
|
|
729
|
-
* the SAME file, and none of them can reach this process's `byokCache`. So
|
|
730
|
-
* the file's content is part of the cache key: a declaration made elsewhere
|
|
731
|
-
* is visible the next time the picker is opened, not five minutes later.
|
|
732
|
-
*
|
|
733
|
-
* Read through `engine.userModels()` rather than the path, so this stays one
|
|
734
|
-
* store and one implementation (the CLI's engine is the same module the
|
|
735
|
-
* desktop uses). A store that throws is treated as unchanged — the time
|
|
736
|
-
* window still expires the cache, so a broken read cannot pin stale rows
|
|
737
|
-
* forever.
|
|
738
|
-
*/
|
|
739
|
-
function declaredModelsKey() {
|
|
740
|
-
try {
|
|
741
|
-
if (typeof engine.userModels !== 'function') return '';
|
|
742
|
-
const map = (engine.userModels() || {}).map || {};
|
|
743
|
-
return JSON.stringify(Object.keys(map).sort().map((p) => [p, map[p]]));
|
|
744
|
-
} catch {
|
|
745
|
-
return '';
|
|
746
|
-
}
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
async function loadByokModels({ force = false } = {}) {
|
|
750
|
-
const declared = declaredModelsKey();
|
|
751
|
-
const fresh =
|
|
752
|
-
byokCache.models.length &&
|
|
753
|
-
Date.now() - byokCache.at < MODEL_CACHE_MS &&
|
|
754
|
-
// The declarations are part of the key: see declaredModelsKey().
|
|
755
|
-
declared === byokCache.declared;
|
|
756
|
-
if (!force && fresh) return byokCache.models;
|
|
757
|
-
// An injected engine (tests, embedding) may predate the class surface; an
|
|
758
|
-
// empty list is the honest answer then, not a fabricated one.
|
|
759
|
-
if (typeof engine.listModels !== 'function') return [];
|
|
760
|
-
const res = await engine.listModels('byok');
|
|
761
|
-
// The engine's row is `{id: "provider:model", label, provider, configured}`.
|
|
762
|
-
// `note` is added here because it is the field both renderers actually paint
|
|
763
|
-
// (the picker draws `m.note || m.model`, /models draws `m.note || m.label`)
|
|
764
|
-
// and because "openai:gpt-4o" alone does not say whether this machine holds
|
|
765
|
-
// the key the relay would ask for — a row without one is a turn that 400s,
|
|
766
|
-
// so it names the command that fixes it.
|
|
767
|
-
byokCache.models = ((res && res.models) || []).map((m) => ({
|
|
768
|
-
...m,
|
|
769
|
-
note: m.configured ? 'key on this machine' : `no key — /byok-key ${m.provider}`,
|
|
770
|
-
}));
|
|
771
|
-
byokCache.at = Date.now();
|
|
772
|
-
byokCache.declared = declared;
|
|
773
|
-
return byokCache.models;
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
/**
|
|
777
|
-
* The ids pinnable on one class — the ONE function `/model`, alt+p and
|
|
778
|
-
* `/models` all read, so the picker cannot offer something the class the turn
|
|
779
|
-
* runs on would reject. Both branches swallow their failure into "nothing to
|
|
780
|
-
* offer": a catalog is a convenience, and an offline client must still be
|
|
781
|
-
* able to chat on the server's own default.
|
|
782
|
-
*/
|
|
783
|
-
async function listModelsFor(cls) {
|
|
784
|
-
// The OFFERED set, not HOST_CLASSES: a class that is not selectable (a
|
|
785
|
-
// disabled `pro`) yields NOTHING rather than the live class's rows. The
|
|
786
|
-
// merged picker tags whatever comes back as belonging to the class it
|
|
787
|
-
// asked about, so substituting pooled rows here would paint pooled ids as
|
|
788
|
-
// Pro rows — and pinning one would move the session onto the subscription.
|
|
789
|
-
const allowed = selectableClasses();
|
|
790
|
-
if (cls && !allowed.includes(cls) && HOST_CLASSES.includes(cls)) return [];
|
|
791
|
-
const want = allowed.includes(cls) ? cls : commandCtx.modelClass;
|
|
792
|
-
try {
|
|
793
|
-
if (want === 'byok') {
|
|
794
|
-
const byok = await loadByokModels();
|
|
795
|
-
// The pooled catalog may never have been fetched on a byok-only session
|
|
796
|
-
// (`/model` alone on a fresh install), and the Nexus row below can only
|
|
797
|
-
// come from it — so read it here, best-effort. A failed read (offline,
|
|
798
|
-
// or no account key) leaves the byok rows, which is the honest list: no
|
|
799
|
-
// pooled row, rather than one this process cannot name.
|
|
800
|
-
if (!modelCache.models.length) {
|
|
801
|
-
try {
|
|
802
|
-
await loadModels();
|
|
803
|
-
} catch {
|
|
804
|
-
/* no pooled catalog to read — byok rows stand alone */
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
// `want`, not the live class: this call is answering for the class it
|
|
808
|
-
// was ASKED about. See classScopedModels.
|
|
809
|
-
return classScopedModels(byok, want);
|
|
810
|
-
}
|
|
811
|
-
if (want === 'pro') {
|
|
812
|
-
// The Claude Code Pro class' rows come from the engine itself (the
|
|
813
|
-
// CLI's own aliases, claude-pro.js PRO_MODELS) rather than from a
|
|
814
|
-
// fetched catalog, so they are read straight off listModels('pro') —
|
|
815
|
-
// one source, the same one the desktop's picker reads.
|
|
816
|
-
//
|
|
817
|
-
// NOT gated on the subscription already being present — that gate used
|
|
818
|
-
// to hide every pro row until `~/.claude/.credentials.json` (or
|
|
819
|
-
// CLAUDE_CODE_OAUTH_TOKEN) already existed, which made the row
|
|
820
|
-
// impossible to ever reach from THIS picker: there was no way to pick
|
|
821
|
-
// "Claude Code Pro" to set the credential up in the first place, only
|
|
822
|
-
// to confirm one that was already there. A byok row offers exactly the
|
|
823
|
-
// same way with no key either, and picking it is what collects one
|
|
824
|
-
// (`collectKeyFor`, chatflow.js) — a pro row now does the same,
|
|
825
|
-
// through the very token `modelKeyQueue` asks for (client/env-file.js
|
|
826
|
-
// keyForModelId's `foreign: true` branch). `configured` on each row
|
|
827
|
-
// still states whether a turn would succeed RIGHT NOW; listing is a
|
|
828
|
-
// separate question from being ready.
|
|
829
|
-
const info = await engine.listModels('pro');
|
|
830
|
-
return (info && info.models) || [];
|
|
831
|
-
}
|
|
832
|
-
// Anything else is asked of the engine by name — 'local' especially,
|
|
833
|
-
// which used to fall through to the pooled catalog below and so answered
|
|
834
|
-
// "here are the AEGIS Cloud models" to a question about the free local
|
|
835
|
-
// class. Only 'aegis' (the pool) is read from the cached client fetch.
|
|
836
|
-
if (want !== 'aegis') {
|
|
837
|
-
const info = await engine.listModels(want);
|
|
838
|
-
return (info && info.models) || [];
|
|
839
|
-
}
|
|
840
|
-
return await loadModels();
|
|
841
|
-
} catch {
|
|
842
|
-
return [];
|
|
843
|
-
}
|
|
844
|
-
}
|
|
845
|
-
|
|
846
|
-
/** The pooled class's pickable rows, each tagged with the class it runs on. */
|
|
847
|
-
function pooledRows() {
|
|
848
|
-
return pickerEntries(modelCache.models).map((m) => ({ ...m, cls: 'aegis' }));
|
|
849
|
-
}
|
|
850
|
-
|
|
851
|
-
/** The byok class's own `provider:model` rows, tagged the same way. */
|
|
852
|
-
function byokRows() {
|
|
853
|
-
return pickerEntries(byokCache.models).map((m) => ({ ...m, cls: 'byok' }));
|
|
854
|
-
}
|
|
855
|
-
|
|
856
|
-
/**
|
|
857
|
-
* The Claude Code Pro class' rows, tagged the same way as the two above. The
|
|
858
|
-
* list is the CLI's own aliases (PRO_MODELS), which is why there is no cache
|
|
859
|
-
* here: nothing is fetched, so nothing can go stale or be missing offline.
|
|
860
|
-
*/
|
|
861
|
-
function proRows() {
|
|
862
|
-
return pickerEntries(claudePro.PRO_MODELS.map((m) => ({
|
|
863
|
-
id: m.id,
|
|
864
|
-
label: m.label,
|
|
865
|
-
note: m.note,
|
|
866
|
-
}))).map((m) => ({ ...m, cls: 'pro' }));
|
|
867
|
-
}
|
|
868
|
-
|
|
869
|
-
/**
|
|
870
|
-
* The class-scoped model list — `state().models`, `/models`, the alt+p chord
|
|
871
|
-
* and the `/class` auto-pick all read it, so it is one list and not four.
|
|
872
|
-
*
|
|
873
|
-
* On the POOLED class it is just the catalog's pickable rows. On the BYOK
|
|
874
|
-
* class it is those rows PLUS the pooled Nexus row, which the server's
|
|
875
|
-
* `provider:model` listing can never contain: the two id spaces are disjoint
|
|
876
|
-
* (`models.js` documents it, and `pinBelongsToClass` enforces it), so a
|
|
877
|
-
* session sitting on byok used to see a list with no way back to the pooled
|
|
878
|
-
* lane in it — the same "correct list, undiscoverable half" defect
|
|
879
|
-
* `mergedPickerModels` in commands.js fixes for the `/model` picker, fixed
|
|
880
|
-
* here for the list the other surfaces read, so the panel, the chord and the
|
|
881
|
-
* picker cannot disagree about whether Nexus is an option.
|
|
882
|
-
*
|
|
883
|
-
* Each row carries its own `cls`, which is what the picker's ENTER handler
|
|
884
|
-
* switches on and what `/models` paints its "pooled lane" marker from:
|
|
885
|
-
* picking Nexus from the byok list moves the session to the pooled class
|
|
886
|
-
* BEFORE the pin applies, because a pooled id pinned under byok is parsed as
|
|
887
|
-
* a provider name and 400s at the relay. Tagging is not decoration — it is
|
|
888
|
-
* why this row is safe to offer from a class that cannot run it.
|
|
889
|
-
*
|
|
890
|
-
* The pooled row comes from the same `pickerEntries` shaping the pooled class
|
|
891
|
-
* uses (`filterAegisCatalog`'s single-row collapse), never a hand-built
|
|
892
|
-
* literal: a second spelling of "the brain's id and label" is exactly the
|
|
893
|
-
* drift `client/brain-catalog.js` exists to end. Its absence is not an error
|
|
894
|
-
* — no account key means no pooled catalog to read, and a byok-only session
|
|
895
|
-
* must still list its own models.
|
|
896
|
-
*
|
|
897
|
-
* @param {Array<object>} [byokOverride] rows already fetched by an async
|
|
898
|
-
* caller, so an awaiting caller does not re-read a cache it just filled.
|
|
899
|
-
* @param {string} [cls] the class to answer FOR. Defaults to the live class,
|
|
900
|
-
* which is what `state().models` wants — but not what `/model` wants.
|
|
901
|
-
*
|
|
902
|
-
* THE CLASS ASKED IS NOT THE CLASS LIVE, and conflating them is what emptied
|
|
903
|
-
* the picker. `mergedPickerModels` (commands.js) asks this module for all
|
|
904
|
-
* three classes in one turn — it opens ONE list containing pooled, byok and
|
|
905
|
-
* Pro rows so a model in another class is reachable without knowing to run
|
|
906
|
-
* `/class` first. Answering every one of those asks from the LIVE class made
|
|
907
|
-
* that merge a lie: on the default `aegis` class the byok ask came back with
|
|
908
|
-
* the pooled rows again (tagged `byok`, so the picker painted Nexus and
|
|
909
|
-
* deepseek twice and the provider ids never at all), and on the `pro` class
|
|
910
|
-
* the pooled ask came back with Pro's aliases — the list a user reads as
|
|
911
|
-
* "only pool and sonnet, where are the rest of my models?". The requested
|
|
912
|
-
* class is the parameter precisely so a caller may ask about a class it is
|
|
913
|
-
* not on; only an absent/unknown `cls` may fall back to the live one.
|
|
914
|
-
*/
|
|
915
|
-
function classScopedModels(byokOverride, cls) {
|
|
916
|
-
const allowed = selectableClasses();
|
|
917
|
-
const want = allowed.includes(cls) ? cls : commandCtx.modelClass;
|
|
918
|
-
// A disabled `pro` yields no rows at all — not the pooled ones either,
|
|
919
|
-
// because the caller asked for pro's id space and answering with pooled ids
|
|
920
|
-
// is the cross-class mix-up this branch exists to prevent (the merged
|
|
921
|
-
// picker would tag them `pro`).
|
|
922
|
-
if (cls === 'pro' && !allowed.includes('pro')) return [];
|
|
923
|
-
// The Pro class' list is its own alias set, never the pooled catalog: a
|
|
924
|
-
// pooled id pinned under pro would be sent to `claude --model`, which
|
|
925
|
-
// resolves aliases and real model names, not AEGIS ids — the same
|
|
926
|
-
// cross-class mismatch the byok branch below is shaped to prevent. It is
|
|
927
|
-
// checked before the pooled default for exactly that reason.
|
|
928
|
-
if (want === 'pro') return proRows();
|
|
929
|
-
if (want !== 'byok') return pooledRows();
|
|
930
|
-
const byok = Array.isArray(byokOverride)
|
|
931
|
-
? byokOverride.map((m) => ({ ...m, cls: 'byok' }))
|
|
932
|
-
: byokRows();
|
|
933
|
-
return [...pooledRows(), ...byok];
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
/**
|
|
937
|
-
* The ids the Pro class can address: claude-pro.js's PRO_MODELS, lowercased
|
|
938
|
-
* once. Read from the module rather than re-listed, because the transport
|
|
939
|
-
* spawns `claude --model <id>` with these exact strings — a second list here
|
|
940
|
-
* could offer a row the child rejects, which is the cross-class defect the
|
|
941
|
-
* byok rule below is shaped to prevent.
|
|
942
|
-
*/
|
|
943
|
-
function proModelIds() {
|
|
944
|
-
return new Set(claudePro.PRO_MODELS.map((m) => String(m.id).toLowerCase()));
|
|
945
|
-
}
|
|
946
|
-
|
|
947
|
-
/**
|
|
948
|
-
* Whether a pinned id can run on `cls`, decided synchronously (switchClass is
|
|
949
|
-
* not async). byok ids are `provider:model`; aegis and local take anything
|
|
950
|
-
* that is not — the pooled catalog is validated separately, at launch, by
|
|
951
|
-
* validatePinnedModel. pro takes ONLY its own aliases.
|
|
952
|
-
*/
|
|
953
|
-
function pinBelongsToClass(cls, id) {
|
|
954
|
-
const s = String(id == null ? '' : id);
|
|
955
|
-
if (cls === 'byok') return s.includes(':');
|
|
956
|
-
// pro: `claude --model` resolves these aliases and full model names, and
|
|
957
|
-
// AEGIS ids are neither. Without this rule a pooled id ("deepseek") pinned
|
|
958
|
-
// under pro is handed to the child, which fails the turn with a message
|
|
959
|
-
// about a model rather than about the class the user is on.
|
|
960
|
-
if (cls === 'pro') return proModelIds().has(s.toLowerCase());
|
|
961
|
-
// aegis/local: not a byok id.
|
|
962
|
-
return !s.includes(':');
|
|
963
|
-
}
|
|
964
|
-
|
|
965
|
-
/**
|
|
966
|
-
* The classes selectable right now. `pro` is behind the `proEnabled` gate
|
|
967
|
-
* (config.js, default off): HOST_CLASSES says this host CAN run it, this says
|
|
968
|
-
* whether it has been opted into. Every surface that lists or validates a
|
|
969
|
-
* class reads this, so the gate cannot be honoured in one place and ignored
|
|
970
|
-
* in another. A config read failure answers "pro is off" (fail closed).
|
|
971
|
-
*/
|
|
972
|
-
function selectableClasses() {
|
|
973
|
-
try {
|
|
974
|
-
return offeredClasses(proEnabled(loadConfig()));
|
|
975
|
-
} catch {
|
|
976
|
-
return offeredClasses(false);
|
|
977
|
-
}
|
|
978
|
-
}
|
|
979
|
-
|
|
980
|
-
/**
|
|
981
|
-
* Switch the live class. Refuses anything this host cannot run (engine.js's
|
|
982
|
-
* HOST_CLASSES is the authority) and anything it does not offer — `pro` needs
|
|
983
|
-
* a one-time `/class pro on` first.
|
|
984
|
-
*
|
|
985
|
-
* A pin is cleared when it does not belong to the class being entered: a
|
|
986
|
-
* pooled id pinned under byok would be parsed as provider `<pooled id>` and
|
|
987
|
-
* fail at the relay with a confusing "no key saved for …" instead of here,
|
|
988
|
-
* with a reason. Symmetrically, `anthropic:claude-…` under aegis is an id the
|
|
989
|
-
* pooled catalog does not advertise, which is the silent-fallback case
|
|
990
|
-
* validatePinnedModel exists to prevent.
|
|
991
|
-
*/
|
|
992
|
-
function switchClass(next) {
|
|
993
|
-
const want = String(next == null ? '' : next).trim().toLowerCase();
|
|
994
|
-
const allowed = selectableClasses();
|
|
995
|
-
if (!allowed.includes(want)) {
|
|
996
|
-
if (want === 'pro') {
|
|
997
|
-
return {
|
|
998
|
-
ok: false,
|
|
999
|
-
error:
|
|
1000
|
-
'the pro class (your Claude Code subscription) is off by default — ' +
|
|
1001
|
-
'enable it once with `/class pro on`',
|
|
1002
|
-
};
|
|
1003
|
-
}
|
|
1004
|
-
return { ok: false, error: `unknown class "${next}" — classes: ${allowed.join(', ')}` };
|
|
1005
|
-
}
|
|
1006
|
-
const prev = commandCtx.modelClass;
|
|
1007
|
-
commandCtx.modelClass = want;
|
|
1008
|
-
let cleared = null;
|
|
1009
|
-
if (prev !== want && commandCtx.model) {
|
|
1010
|
-
if (!pinBelongsToClass(want, commandCtx.model)) {
|
|
1011
|
-
cleared = commandCtx.model;
|
|
1012
|
-
commandCtx.model = null;
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
updateConfig({
|
|
1016
|
-
modelClass: want,
|
|
1017
|
-
model: commandCtx.model,
|
|
1018
|
-
currentModelId: commandCtx.model,
|
|
1019
|
-
});
|
|
1020
|
-
return { ok: true, class: want, prev, cleared };
|
|
1021
|
-
}
|
|
1022
|
-
|
|
1023
|
-
/**
|
|
1024
|
-
* Fetch (or return the cached) model catalog. Rejects when the account cannot
|
|
1025
|
-
* read it at all — no key, offline, or a server error — which callers treat as
|
|
1026
|
-
* "nothing to offer" rather than retrying per keystroke.
|
|
1027
|
-
* @returns {Promise<Array<{id:string,label:string,note:string}>>}
|
|
1028
|
-
*/
|
|
1029
|
-
async function loadModels({ force = false } = {}) {
|
|
1030
|
-
const fresh = modelCache.models.length && Date.now() - modelCache.at < MODEL_CACHE_MS;
|
|
1031
|
-
if (!force && fresh) return modelCache.models;
|
|
1032
|
-
const data = await client.listModels();
|
|
1033
|
-
modelCache.models = normalizeModelCatalog(data && data.models);
|
|
1034
|
-
modelCache.at = Date.now();
|
|
1035
|
-
return modelCache.models;
|
|
1036
|
-
}
|
|
1037
|
-
|
|
1038
|
-
/**
|
|
1039
|
-
* A pinned model id the server does not advertise is a *silent* fallback: the
|
|
1040
|
-
* pool answers from its own default with no error, so the pin looks honoured
|
|
1041
|
-
* while the reply came from another model — and the cost is attributed to the
|
|
1042
|
-
* model that was pinned. Two shipped defaults did exactly that: `sonnet`
|
|
1043
|
-
* (written into config.json by onboarding, merged in from DEFAULT_CONFIG, and
|
|
1044
|
-
* never advertised by AEGIS Cloud) and any `provider/model` spelling a user
|
|
1045
|
-
* typed by hand. Clears such a pin once, says so, and leaves the server's own
|
|
1046
|
-
* default in its place.
|
|
1047
|
-
*
|
|
1048
|
-
* Best-effort and offline-safe: a catalog that cannot be read clears nothing.
|
|
1049
|
-
*/
|
|
1050
|
-
async function validatePinnedModel() {
|
|
1051
|
-
const pinned = commandCtx.model;
|
|
1052
|
-
if (!pinned) return null;
|
|
1053
|
-
// A BYOK pin is validated by shape, not by the pooled catalog: the catalog
|
|
1054
|
-
// can never contain a `provider:model` id, so checking it here would clear
|
|
1055
|
-
// every legitimate BYOK pin on every launch.
|
|
1056
|
-
if (commandCtx.modelClass === 'byok') {
|
|
1057
|
-
if (String(pinned).includes(':')) return null;
|
|
1058
|
-
commandCtx.model = null;
|
|
1059
|
-
updateConfig({ model: null, currentModelId: null });
|
|
1060
|
-
emit(
|
|
1061
|
-
render.renderNotice(
|
|
1062
|
-
ctx(),
|
|
1063
|
-
'warn',
|
|
1064
|
-
`pinned model "${pinned}" belongs to the pooled class — on BYOK an id is ` +
|
|
1065
|
-
'"<provider>:<model>"; pin cleared, /models lists what this machine can relay.'
|
|
1066
|
-
)
|
|
1067
|
-
);
|
|
1068
|
-
return pinned;
|
|
1069
|
-
}
|
|
1070
|
-
// A Pro pin is validated against the child's OWN alias list, locally, and
|
|
1071
|
-
// never against the pooled catalog: that catalogue cannot contain these
|
|
1072
|
-
// aliases, so checking it here would clear every legitimate Pro pin on every
|
|
1073
|
-
// launch. There is no fetch on this path either — the list is a constant, so
|
|
1074
|
-
// this is the one class whose validation cannot be defeated by being offline.
|
|
1075
|
-
if (commandCtx.modelClass === 'pro') {
|
|
1076
|
-
if (!proModelIds().has(String(pinned).toLowerCase())) {
|
|
1077
|
-
commandCtx.model = null;
|
|
1078
|
-
updateConfig({ model: null, currentModelId: null });
|
|
1079
|
-
emit(
|
|
1080
|
-
render.renderNotice(
|
|
1081
|
-
ctx(),
|
|
1082
|
-
'warn',
|
|
1083
|
-
`pinned model "${pinned}" is not one the Claude Code CLI resolves — pin cleared, ` +
|
|
1084
|
-
`the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map((m) => m.id).join(', ')}).`
|
|
1085
|
-
)
|
|
1086
|
-
);
|
|
1087
|
-
return pinned;
|
|
1088
|
-
}
|
|
1089
|
-
// The alias resolves — but resolving an alias is not the same as having
|
|
1090
|
-
// anything to spend on it. This is the phantom-pin case aegiscodex-dev
|
|
1091
|
-
// learned first (phantomPin() in its src/backend.js): when the host has
|
|
1092
|
-
// no subscription and no console key, the `claude` child has no usable
|
|
1093
|
-
// credential, and the turn does not fail loudly here — it fails after a
|
|
1094
|
-
// round-trip with "Invalid API key" or "You've hit your session limit",
|
|
1095
|
-
// which reads like a provider outage rather than a missing credential.
|
|
1096
|
-
// Checked before the turn, so the user is told why and the pin stops
|
|
1097
|
-
// re-creating the problem on the next launch.
|
|
1098
|
-
let proCallable = true;
|
|
1099
|
-
try {
|
|
1100
|
-
const st = claudePro.claudeProStatus({ env: process.env });
|
|
1101
|
-
// `credentialPresent` — not `subscriptionPresent`, and not a fresh read
|
|
1102
|
-
// of `process.env` here. Three different questions live in this area and
|
|
1103
|
-
// conflating them is how the pin went unchecked in the first place:
|
|
1104
|
-
// - "is there a subscription to shadow?" → subscriptionPresent
|
|
1105
|
-
// (excludes a bare console key on disk, by design)
|
|
1106
|
-
// - "can this host serve a pro turn?" → credentialPresent (this one)
|
|
1107
|
-
// - "is this env value a credential?" → childEnvPlan's verdict
|
|
1108
|
-
// The third is why this reads a field instead of testing
|
|
1109
|
-
// `process.env.ANTHROPIC_API_KEY` directly: the planner REFUSES a value
|
|
1110
|
-
// that would be dropped from the child, so an env var alone is not
|
|
1111
|
-
// evidence of a route. See childEnvPlan / isAnthropicConsoleKey.
|
|
1112
|
-
proCallable = !!st.credentialPresent;
|
|
1113
|
-
} catch {
|
|
1114
|
-
// An unprovable credential is not a proven absence: leave the pin alone.
|
|
1115
|
-
proCallable = true;
|
|
1116
|
-
}
|
|
1117
|
-
if (!proCallable) {
|
|
1118
|
-
commandCtx.model = null;
|
|
1119
|
-
updateConfig({ model: null, currentModelId: null });
|
|
1120
|
-
emit(
|
|
1121
|
-
render.renderNotice(
|
|
1122
|
-
ctx(),
|
|
1123
|
-
'warn',
|
|
1124
|
-
`pinned model "${pinned}" needs a Claude Pro subscription or an ` +
|
|
1125
|
-
`ANTHROPIC_API_KEY, and this host has neither — pin cleared. ` +
|
|
1126
|
-
`Run \`claude /login\`, export a console key, or \`/class pro off\`.`
|
|
1127
|
-
)
|
|
1128
|
-
);
|
|
1129
|
-
return pinned;
|
|
1130
|
-
}
|
|
1131
|
-
return null;
|
|
1132
|
-
}
|
|
1133
|
-
let models;
|
|
1134
|
-
try {
|
|
1135
|
-
models = await loadModels();
|
|
1136
|
-
} catch {
|
|
1137
|
-
return null;
|
|
1138
|
-
}
|
|
1139
|
-
if (!models.length) return null;
|
|
1140
|
-
if (catalogIds(models).has(String(pinned).toLowerCase())) return null;
|
|
1141
|
-
commandCtx.model = null;
|
|
1142
|
-
updateConfig({ model: null, currentModelId: null });
|
|
1143
|
-
emit(
|
|
1144
|
-
render.renderNotice(
|
|
1145
|
-
ctx(),
|
|
1146
|
-
'warn',
|
|
1147
|
-
`pinned model "${pinned}" is not advertised by AEGIS Cloud — pin cleared, ` +
|
|
1148
|
-
'the pool will choose; /models lists what you can pin.'
|
|
1149
|
-
)
|
|
1150
|
-
);
|
|
1151
|
-
return pinned;
|
|
1152
|
-
}
|
|
1153
|
-
|
|
1154
|
-
function bannerLines() {
|
|
1155
|
-
return render.renderBanner(ctx(), {
|
|
1156
|
-
width: width(),
|
|
1157
|
-
version: VERSION,
|
|
1158
|
-
model: commandCtx.model || 'server default',
|
|
1159
|
-
base: client.apiBase,
|
|
1160
|
-
key: maskKey(client.apiKey),
|
|
1161
|
-
stream: commandCtx.stream,
|
|
1162
|
-
});
|
|
1163
|
-
}
|
|
1164
|
-
|
|
1165
|
-
/**
|
|
1166
|
-
* Write lines out. Accepts a single line as well as a block — a bare string
|
|
1167
|
-
* would otherwise be iterated as characters, which renders a notice one
|
|
1168
|
-
* character per line.
|
|
1169
|
-
*/
|
|
1170
|
-
function emit(lines) {
|
|
1171
|
-
const block = typeof lines === 'string' ? [lines] : lines;
|
|
1172
|
-
for (const l of block) out.write(l + '\n');
|
|
1173
|
-
}
|
|
1174
|
-
|
|
1175
|
-
// --- the ask path ---------------------------------------------------------
|
|
1176
|
-
|
|
1177
|
-
/**
|
|
1178
|
-
* One turn through the agent-loop engine (persistent-shell exec,
|
|
1179
|
-
* readFile/writeFile/editFile/listDir/glob/grep, Task subagents), streamed
|
|
1180
|
-
* into the live region. `history` is every prior turn's user/assistant pair
|
|
1181
|
-
* — never that turn's own tool-call scratchpad, which the engine keeps
|
|
1182
|
-
* internally and never returns (see engine.js's `chat()`).
|
|
1183
|
-
* @returns {Promise<{text:string, usage:object|null, model:string|null, ms:number, interrupted:boolean}>}
|
|
1184
|
-
*/
|
|
1185
|
-
async function ask(prompt, { history = [], presenter = null, signal = null } = {}) {
|
|
1186
|
-
const started = Date.now();
|
|
1187
|
-
// A presenter takes over ALL presentation (the chatflow's frame paints the
|
|
1188
|
-
// streaming answer into a transcript row), so the linear/inline live region
|
|
1189
|
-
// is only built when there is none.
|
|
1190
|
-
const live =
|
|
1191
|
-
!presenter && opts.interactive && opts.stream && out.isTTY ? new LiveRegion(out) : null;
|
|
1192
|
-
let tick = 0;
|
|
1193
|
-
let chars = 0;
|
|
1194
|
-
let partial = '';
|
|
1195
|
-
let reasoning = 0;
|
|
1196
|
-
// Thinking tokens the PROVIDER measured, added verbatim. A subscription
|
|
1197
|
-
// turn withholds its deliberation text (`thinking_delta.thinking` is the
|
|
1198
|
-
// empty string), so the `reasoning` char count above stays 0 for the whole
|
|
1199
|
-
// thinking phase and the spinner read `↓0 tokens` while thousands of
|
|
1200
|
-
// thinking tokens were billed. Not routed through `w()`/4: this is already
|
|
1201
|
-
// a token count, and dividing it would print a quarter of the truth.
|
|
1202
|
-
let thinkingTokens = 0;
|
|
1203
|
-
let verb = VERBS[Math.floor(Math.random() * VERBS.length)];
|
|
1204
|
-
let sawReasoning = false;
|
|
1205
|
-
let usedTools = false;
|
|
1206
|
-
|
|
1207
|
-
const paint = () => {
|
|
1208
|
-
if (!live) return;
|
|
1209
|
-
live.update([
|
|
1210
|
-
render.renderWorking(ctx(), {
|
|
1211
|
-
tick: tick++,
|
|
1212
|
-
verb,
|
|
1213
|
-
elapsedMs: Date.now() - started,
|
|
1214
|
-
// `chars` accumulates `w(chunk.delta)` — a display width, not a token
|
|
1215
|
-
// count — and render.js prints this field as `↓N tokens`. Converted at
|
|
1216
|
-
// the producer so both spinner renderers receive the same unit.
|
|
1217
|
-
//
|
|
1218
|
-
// `+ reasoning` because the live figure is the turn's BILLED output:
|
|
1219
|
-
// the answer plus the thinking trace it is charged for, which is what
|
|
1220
|
-
// the desktop's bubble sums (`desktop/renderer/app.js`: reply +
|
|
1221
|
-
// reasoning cells at this same ratio). Reasoning is accumulated in its
|
|
1222
|
-
// own variable above so the "reasoned but wrote nothing" case stays
|
|
1223
|
-
// distinguishable — but leaving it out of the figure here stalled the
|
|
1224
|
-
// spinner on `↓0 tokens` for the whole thinking phase of every turn,
|
|
1225
|
-
// which is the row that exists to show the turn is moving.
|
|
1226
|
-
streamed: estimateTokensFromCells(chars + reasoning) + thinkingTokens,
|
|
1227
|
-
// See render.js: any contribution from `thinkingTokens` is Anthropic's
|
|
1228
|
-
// own under-counting running estimate, not the real billed figure.
|
|
1229
|
-
streamedFloor: thinkingTokens > 0,
|
|
1230
|
-
}),
|
|
1231
|
-
]);
|
|
1232
|
-
};
|
|
1233
|
-
|
|
1234
|
-
const timer = live ? setInterval(paint, 90) : null;
|
|
1235
|
-
if (timer && timer.unref) timer.unref();
|
|
1236
|
-
paint();
|
|
1237
|
-
|
|
1238
|
-
// Presentation hooks. With no presenter these reproduce the linear
|
|
1239
|
-
// behaviour exactly (live-region spinner, tool rows written to scrollback).
|
|
1240
|
-
const p = presenter || {};
|
|
1241
|
-
// The engine opens a tool with a `phase: 'run'` frame BEFORE the executor
|
|
1242
|
-
// runs, so a writeFile preview built here still reads the pre-edit file.
|
|
1243
|
-
// Cached per tool id so the later `done` frame reuses the same preview
|
|
1244
|
-
// instead of re-reading a file the tool has already overwritten (which
|
|
1245
|
-
// would diff clean and show nothing).
|
|
1246
|
-
const diffCache = new Map();
|
|
1247
|
-
const previewFor = (tool) => {
|
|
1248
|
-
const key =
|
|
1249
|
-
tool && tool.id !== undefined
|
|
1250
|
-
? `id:${tool.id}`
|
|
1251
|
-
: `${tool && tool.name}:${JSON.stringify(tool && tool.args)}`;
|
|
1252
|
-
if (!diffCache.has(key)) {
|
|
1253
|
-
diffCache.set(key, editPreview(tool && tool.name, tool && tool.args, { cwd: process.cwd() }));
|
|
1254
|
-
}
|
|
1255
|
-
return diffCache.get(key);
|
|
1256
|
-
};
|
|
1257
|
-
const present = {
|
|
1258
|
-
text: (d) => {
|
|
1259
|
-
if (p.text) return p.text(d);
|
|
1260
|
-
if (live && tick % 2 === 0) paint();
|
|
1261
|
-
return undefined;
|
|
1262
|
-
},
|
|
1263
|
-
reasoning: (r) => {
|
|
1264
|
-
if (p.reasoning) return p.reasoning(r);
|
|
1265
|
-
return undefined;
|
|
1266
|
-
},
|
|
1267
|
-
// Token-count channel, distinct from `reasoning` above (which is text).
|
|
1268
|
-
// A presenter drives its own spinner, so it must receive this or the live
|
|
1269
|
-
// figure stays at 0 for the whole thinking phase of a subscription turn.
|
|
1270
|
-
thinkingTokens: (n) => {
|
|
1271
|
-
if (p.thinkingTokens) return p.thinkingTokens(n);
|
|
1272
|
-
return undefined;
|
|
1273
|
-
},
|
|
1274
|
-
tool: (tool) => {
|
|
1275
|
-
if (p.tool) return p.tool(tool);
|
|
1276
|
-
if (live) live.clear();
|
|
1277
|
-
const diff = previewFor(tool);
|
|
1278
|
-
emit(
|
|
1279
|
-
render.renderTurn(
|
|
1280
|
-
ctx(),
|
|
1281
|
-
{ role: 'tool', label: tool.name, args: tool.args, ok: tool.ok, diff, diffOpen: defaultOpen(diff) },
|
|
1282
|
-
width()
|
|
1283
|
-
)
|
|
1284
|
-
);
|
|
1285
|
-
paint();
|
|
1286
|
-
return undefined;
|
|
1287
|
-
},
|
|
1288
|
-
};
|
|
1289
|
-
|
|
1290
|
-
const sessionId = randomUUID();
|
|
1291
|
-
activeSessionId = sessionId;
|
|
1292
|
-
let interrupted = false;
|
|
1293
|
-
// One cancel path for both callers: a SIGINT from the process, and the
|
|
1294
|
-
// chatflow's Esc, which aborts the controller it handed in. Without this
|
|
1295
|
-
// second source the full-screen loop's Esc had nothing listening to it —
|
|
1296
|
-
// the turn kept running and billing while the UI said "stopped".
|
|
1297
|
-
const cancel = () => {
|
|
1298
|
-
interrupted = true;
|
|
1299
|
-
engine.cancel(sessionId);
|
|
1300
|
-
};
|
|
1301
|
-
const onSigint = () => cancel();
|
|
1302
|
-
process.once('SIGINT', onSigint);
|
|
1303
|
-
if (signal) {
|
|
1304
|
-
if (signal.aborted) cancel();
|
|
1305
|
-
else signal.addEventListener('abort', cancel, { once: true });
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
|
-
// A denial with no one to ask it of: -p and any other run with no
|
|
1309
|
-
// approvalPrompter set. Fails safe (deny) rather than hanging the tool
|
|
1310
|
-
// round forever waiting for an answer nobody can give.
|
|
1311
|
-
const denyNoPrompter = (info) => {
|
|
1312
|
-
err.write(
|
|
1313
|
-
`aegiscode: ${info.tool} needs confirmation but this run has no prompt for it — denied ` +
|
|
1314
|
-
'(pass --automode (alias --yolo) to auto-approve mutating tools).\n'
|
|
1315
|
-
);
|
|
1316
|
-
return Promise.resolve('deny');
|
|
1317
|
-
};
|
|
1318
|
-
|
|
1319
|
-
// The round-horizon ask's own no-one-to-answer fallback. Unreachable in
|
|
1320
|
-
// practice — `roundsAsk` below is only sent `true` when `p.rounds` exists,
|
|
1321
|
-
// so the engine never raises the ask without a prompter — but kept so a
|
|
1322
|
-
// future caller that forgets the guard fails safe (stop) instead of
|
|
1323
|
-
// hanging the tool loop on an unanswerable promise.
|
|
1324
|
-
const denyRoundsNoPrompter = () => Promise.resolve(false);
|
|
1325
|
-
|
|
1326
|
-
// Vocabulary bridging lives at module scope (see normalizeDecision) so the
|
|
1327
|
-
// same function the tests import is the one the live path calls.
|
|
1328
|
-
const onDelta = (chunk) => {
|
|
1329
|
-
if (!chunk) return;
|
|
1330
|
-
// Provider-measured thinking progress — the ONLY live signal on a
|
|
1331
|
-
// subscription turn, whose deliberation text is withheld. Counted and
|
|
1332
|
-
// repainted, but never handed to `present.reasoning`: that channel is
|
|
1333
|
-
// text and its consumers accumulate display width from it.
|
|
1334
|
-
if (chunk.thinkingTokens) {
|
|
1335
|
-
thinkingTokens += chunk.thinkingTokens;
|
|
1336
|
-
if (!sawReasoning) {
|
|
1337
|
-
sawReasoning = true;
|
|
1338
|
-
verb = 'Reasoning';
|
|
1339
|
-
}
|
|
1340
|
-
present.thinkingTokens(chunk.thinkingTokens);
|
|
1341
|
-
paint();
|
|
1342
|
-
}
|
|
1343
|
-
if (chunk.reasoning) {
|
|
1344
|
-
reasoning += w(chunk.reasoning);
|
|
1345
|
-
// The pool's worker findings arrive on the reasoning channel before
|
|
1346
|
-
// the answer; say so rather than looking stalled.
|
|
1347
|
-
if (!sawReasoning) {
|
|
1348
|
-
sawReasoning = true;
|
|
1349
|
-
verb = 'Reasoning';
|
|
1350
|
-
paint();
|
|
1351
|
-
}
|
|
1352
|
-
present.reasoning(chunk.reasoning);
|
|
1353
|
-
}
|
|
1354
|
-
if (chunk.delta) { chars += w(chunk.delta);
|
|
1355
|
-
partial += chunk.delta;
|
|
1356
|
-
present.text(chunk.delta);
|
|
1357
|
-
}
|
|
1358
|
-
if (chunk.tool) {
|
|
1359
|
-
usedTools = true;
|
|
1360
|
-
present.tool(chunk.tool);
|
|
1361
|
-
}
|
|
1362
|
-
if (chunk.approval) {
|
|
1363
|
-
const info = chunk.approval;
|
|
1364
|
-
if (live) live.clear();
|
|
1365
|
-
const decide = p.approval || approvalPrompter || denyNoPrompter;
|
|
1366
|
-
Promise.resolve(decide(info))
|
|
1367
|
-
.catch(() => 'deny')
|
|
1368
|
-
.then((decision) => engine.respondApproval(info.id, normalizeDecision(decision)));
|
|
1369
|
-
}
|
|
1370
|
-
if (chunk.rounds) {
|
|
1371
|
-
const info = chunk.rounds;
|
|
1372
|
-
if (live) live.clear();
|
|
1373
|
-
const decide = p.rounds || denyRoundsNoPrompter;
|
|
1374
|
-
Promise.resolve(decide(info))
|
|
1375
|
-
.catch(() => false)
|
|
1376
|
-
.then((decision) => engine.respondRoundsAsk(info.id, decision === true));
|
|
1377
|
-
}
|
|
1378
|
-
};
|
|
1379
|
-
|
|
1380
|
-
try {
|
|
1381
|
-
const res = await engine.chat(
|
|
1382
|
-
{
|
|
1383
|
-
prompt,
|
|
1384
|
-
messages: history,
|
|
1385
|
-
model: commandCtx.model || undefined,
|
|
1386
|
-
// A caller-supplied system wins; otherwise the shared persona. Sent
|
|
1387
|
-
// explicitly rather than left to the server, because the pooled
|
|
1388
|
-
// route takes the system prompt from the request and the CLI was
|
|
1389
|
-
// sending none — the model got tool schemas and no rule about when
|
|
1390
|
-
// to use them.
|
|
1391
|
-
system: opts.system || defaultSystemPrompt(),
|
|
1392
|
-
maxTokens: opts.maxTokens,
|
|
1393
|
-
// `effort` is the budget rung, and it travels on EVERY turn for every
|
|
1394
|
-
// model — this host only ever runs the 'aegis' class, whose calls are
|
|
1395
|
-
// sized server-side from it (aegis1 services/pool_brain.py), and BYOK
|
|
1396
|
-
// turns translate it per vendor in cli/src/engine.js. A stored `null`
|
|
1397
|
-
// or a value this build no longer offers resolves to `high` — the
|
|
1398
|
-
// same rung the desktop and the engine apply — instead of being
|
|
1399
|
-
// omitted, because omitting it was the defect: `auto` was the
|
|
1400
|
-
// default, so nothing reached the wire and the levels changed the
|
|
1401
|
-
// status line and nothing else.
|
|
1402
|
-
effort: effortRung(commandCtx.effort),
|
|
1403
|
-
// The deep-recall opt-in travels only when this session turned it on
|
|
1404
|
-
// (`/memory-deep on`). Sent as a literal `true` or not at all: the
|
|
1405
|
-
// engine treats anything but `true` as off, and an omitted field is
|
|
1406
|
-
// what keeps a stray value from ever buying a per-turn embedding.
|
|
1407
|
-
recallDeep: commandCtx.recallDeep === true ? true : undefined,
|
|
1408
|
-
// false asks the engine for the buffered (non-stream) wire form, so
|
|
1409
|
-
// `--no-stream` and piped runs get a single body rather than SSE.
|
|
1410
|
-
stream: commandCtx.stream !== false,
|
|
1411
|
-
sessionId,
|
|
1412
|
-
// The CONVERSATION id, which `sessionId` above is not — that one is
|
|
1413
|
-
// minted fresh for THIS turn so a cancel can target it. Memory that
|
|
1414
|
-
// has to outlive a turn (the Pro class's `claude` child session) is
|
|
1415
|
-
// keyed by this one instead, so a thread keeps its context and
|
|
1416
|
-
// `/new` or `/resume` genuinely starts/continues a different one.
|
|
1417
|
-
sessionKey: commandCtx.sessionId,
|
|
1418
|
-
// Opt-in to the round-horizon dialog (see engine.js requestRoundsAsk)
|
|
1419
|
-
// only when there is actually a `rounds` prompter to answer it — a
|
|
1420
|
-
// one-shot `-p` run or any other caller with no presenter keeps the
|
|
1421
|
-
// engine's old stop-and-record-session behaviour untouched.
|
|
1422
|
-
roundsAsk: Boolean(p.rounds),
|
|
1423
|
-
},
|
|
1424
|
-
onDelta
|
|
1425
|
-
);
|
|
1426
|
-
|
|
1427
|
-
const choice = (res.choices && res.choices[0]) || {};
|
|
1428
|
-
const text = (choice.message && choice.message.content) || partial;
|
|
1429
|
-
return {
|
|
1430
|
-
text,
|
|
1431
|
-
usage: res.usage || null,
|
|
1432
|
-
model: res.model || commandCtx.model || null,
|
|
1433
|
-
ms: Date.now() - started,
|
|
1434
|
-
interrupted,
|
|
1435
|
-
reasoningChars: reasoning,
|
|
1436
|
-
usedTools,
|
|
1437
|
-
};
|
|
1438
|
-
} catch (e) {
|
|
1439
|
-
// A user interrupt is not a failure: keep what already streamed.
|
|
1440
|
-
if (interrupted && partial) {
|
|
1441
|
-
return {
|
|
1442
|
-
text: partial,
|
|
1443
|
-
usage: null,
|
|
1444
|
-
model: commandCtx.model || null,
|
|
1445
|
-
ms: Date.now() - started,
|
|
1446
|
-
interrupted: true,
|
|
1447
|
-
reasoningChars: reasoning,
|
|
1448
|
-
usedTools,
|
|
1449
|
-
};
|
|
1450
|
-
}
|
|
1451
|
-
throw e;
|
|
1452
|
-
} finally {
|
|
1453
|
-
if (timer) clearInterval(timer);
|
|
1454
|
-
process.removeListener('SIGINT', onSigint);
|
|
1455
|
-
if (signal) signal.removeEventListener('abort', cancel);
|
|
1456
|
-
if (live) live.clear();
|
|
1457
|
-
activeSessionId = null;
|
|
1458
|
-
}
|
|
1459
|
-
}
|
|
1460
|
-
|
|
1461
|
-
/** Print a completed turn: role block, then the accounting line. */
|
|
1462
|
-
function printTurn(turn) {
|
|
1463
|
-
emit(render.renderTurn(ctx(), turn, width()));
|
|
1464
|
-
}
|
|
1465
|
-
|
|
1466
|
-
/** Prior user/assistant pairs from the live transcript, for the engine. */
|
|
1467
|
-
function historyPairs() {
|
|
1468
|
-
return transcript
|
|
1469
|
-
.filter((m) => m.role === 'user' || m.role === 'assistant')
|
|
1470
|
-
.map((m) => ({ role: m.role, content: m.text }));
|
|
1471
|
-
}
|
|
1472
|
-
|
|
1473
|
-
/** Ask, then account for it. Shared by plain prompts and `/ask`. */
|
|
1474
|
-
async function runPrompt(prompt, { label = 'you' } = {}) {
|
|
1475
|
-
if (!prompt) {
|
|
1476
|
-
emit(render.renderNotice(ctx(), 'warn', 'nothing to ask — give /ask a prompt'));
|
|
1477
|
-
return;
|
|
1478
|
-
}
|
|
1479
|
-
if (!client.apiKey) await ensureApiKey();
|
|
1480
|
-
if (!client.apiKey) {
|
|
1481
|
-
emit(
|
|
1482
|
-
render.renderNotice(
|
|
1483
|
-
ctx(),
|
|
1484
|
-
'error',
|
|
1485
|
-
`no AEGIS account key — ${credentials.HOW_TO_SET} (or set $${credentials.KEY_ENV})`
|
|
1486
|
-
)
|
|
1487
|
-
);
|
|
1488
|
-
return;
|
|
1489
|
-
}
|
|
1490
|
-
|
|
1491
|
-
const history = historyPairs();
|
|
1492
|
-
printTurn({ role: 'user', text: prompt, label });
|
|
1493
|
-
transcript.push({ role: 'user', text: prompt });
|
|
1494
|
-
|
|
1495
|
-
let res;
|
|
1496
|
-
try {
|
|
1497
|
-
res = await ask(prompt, { history });
|
|
1498
|
-
} catch (e) {
|
|
1499
|
-
persistTurn(prompt, { text: '', error: e.message }, 'error');
|
|
1500
|
-
emit(render.renderTurn(ctx(), { role: 'error', text: e.message }, width()));
|
|
1501
|
-
return;
|
|
1502
|
-
}
|
|
1503
|
-
|
|
1504
|
-
if (res.text) transcript.push({ role: 'assistant', text: res.text });
|
|
1505
|
-
|
|
1506
|
-
const tokens = recordTurn(res);
|
|
1507
|
-
|
|
1508
|
-
// Ask the ledger what this call settled at BEFORE persisting it. The order
|
|
1509
|
-
// is the whole point: the charge is the server's number (pool margin and
|
|
1510
|
-
// prompt-cache discount included) and only the ledger knows it. Persisting
|
|
1511
|
-
// first wrote the exchange with no charge attached, so /cost recomputed it
|
|
1512
|
-
// from a local rate table that knows about neither — and the figure the
|
|
1513
|
-
// customer read did not match the bill they paid. Same ordering as the
|
|
1514
|
-
// chatflow session loop.
|
|
1515
|
-
let settledCost = null;
|
|
1516
|
-
try {
|
|
1517
|
-
const spend = await refreshSpend();
|
|
1518
|
-
settledCost = spend ? spend.lastCost : null;
|
|
1519
|
-
} catch {
|
|
1520
|
-
/* accounting must never break a turn */
|
|
1521
|
-
}
|
|
1522
|
-
persistTurn(prompt, res, res.interrupted ? 'stopped' : res.error ? 'error' : 'done', settledCost);
|
|
1523
|
-
|
|
1524
|
-
printTurn({
|
|
1525
|
-
role: 'assistant',
|
|
1526
|
-
text: res.text || '(the pool returned no text — see /balance for what it charged)',
|
|
1527
|
-
meta: {
|
|
1528
|
-
model: res.model,
|
|
1529
|
-
tokens,
|
|
1530
|
-
// Folded through the SHARED normaliser, for the same reason recordTurn
|
|
1531
|
-
// is (see its comment): the providers do not merely spell these fields
|
|
1532
|
-
// differently, they MEASURE them differently. Anthropic's `input_tokens`
|
|
1533
|
-
// EXCLUDES `cache_read_input_tokens`; OpenAI's and DeepSeek's
|
|
1534
|
-
// `prompt_tokens` INCLUDES `prompt_cache_hit_tokens`. Reading the raw
|
|
1535
|
-
// field here therefore printed the WHOLE prompt as fresh input on a
|
|
1536
|
-
// cached turn — the cache-hit half restated at miss price, in the one
|
|
1537
|
-
// row a user reads immediately after every turn. That is precisely the
|
|
1538
|
-
// "the CLI's live tally disagrees with its own ledger about the same
|
|
1539
|
-
// turn" defect recordTurn's comment names; this call site was the one
|
|
1540
|
-
// it did not cover, and it is why the CLI's per-turn token readout ran
|
|
1541
|
-
// far above the engine's for the same turn on the same model.
|
|
1542
|
-
usage: res.usage == null ? null : usageBuckets(res.usage),
|
|
1543
|
-
// What this call settled at, from the ledger row it produced — the
|
|
1544
|
-
// number that has to agree with the token count beside it.
|
|
1545
|
-
eur: settledCost,
|
|
1546
|
-
ms: res.ms,
|
|
1547
|
-
calls: 1,
|
|
1548
|
-
},
|
|
1549
|
-
});
|
|
1550
|
-
|
|
1551
|
-
if (res.interrupted) {
|
|
1552
|
-
emit(render.renderNotice(ctx(), 'warn', 'interrupted — the pool may still be running and billing this call'));
|
|
1553
|
-
}
|
|
1554
|
-
}
|
|
1555
|
-
|
|
1556
|
-
// --- command dispatch -----------------------------------------------------
|
|
1557
|
-
|
|
1558
|
-
async function runTool(name, args) {
|
|
1559
|
-
const tool = TOOLS[name];
|
|
1560
|
-
if (!tool) throw new Error(`unknown tool: ${name}`);
|
|
1561
|
-
if (!client.apiKey) await ensureApiKey();
|
|
1562
|
-
if (!client.apiKey) {
|
|
1563
|
-
throw new Error(`no AEGIS account key — ${credentials.HOW_TO_SET}`);
|
|
1564
|
-
}
|
|
1565
|
-
const text = await tool.run(args || {});
|
|
1566
|
-
emit(render.renderToolResult(ctx(), name, text, width()));
|
|
1567
|
-
}
|
|
1568
|
-
|
|
1569
|
-
/**
|
|
1570
|
-
* The nearest routable name to a mistyped one: a prefix of it, or a name it
|
|
1571
|
-
* is a prefix of. Deliberately simple — `cli/src/fuzzy.js` is a separate
|
|
1572
|
-
* workstream and may not exist, so this must not depend on it.
|
|
1573
|
-
*/
|
|
1574
|
-
function nearest(name) {
|
|
1575
|
-
const n = String(name || '').toLowerCase();
|
|
1576
|
-
if (!n) return null;
|
|
1577
|
-
let best = null;
|
|
1578
|
-
for (const c of COMMANDS) {
|
|
1579
|
-
for (const cand of [c.name, ...(c.aliases || [])]) {
|
|
1580
|
-
if (cand === n) continue;
|
|
1581
|
-
if (cand.startsWith(n) || n.startsWith(cand)) {
|
|
1582
|
-
if (best == null || Math.abs(cand.length - n.length) < Math.abs(best.length - n.length)) {
|
|
1583
|
-
best = cand;
|
|
1584
|
-
}
|
|
1585
|
-
}
|
|
1586
|
-
}
|
|
1587
|
-
}
|
|
1588
|
-
return best;
|
|
1589
|
-
}
|
|
1590
|
-
|
|
1591
|
-
/** Tokenize one argument string, honouring single/double quotes. */
|
|
1592
|
-
function tokenize(s) {
|
|
1593
|
-
const out = [];
|
|
1594
|
-
let cur = '';
|
|
1595
|
-
let quote = null;
|
|
1596
|
-
let has = false;
|
|
1597
|
-
for (const ch of String(s || '')) {
|
|
1598
|
-
if (quote) {
|
|
1599
|
-
if (ch === quote) quote = null;
|
|
1600
|
-
else cur += ch;
|
|
1601
|
-
continue;
|
|
1602
|
-
}
|
|
1603
|
-
if (ch === '"' || ch === "'") { quote = ch; has = true; continue; }
|
|
1604
|
-
if (/\s/.test(ch)) {
|
|
1605
|
-
if (cur || has) { out.push(cur); cur = ''; has = false; }
|
|
1606
|
-
continue;
|
|
1607
|
-
}
|
|
1608
|
-
cur += ch;
|
|
1609
|
-
has = true;
|
|
1610
|
-
}
|
|
1611
|
-
if (cur || has) out.push(cur);
|
|
1612
|
-
return out;
|
|
1613
|
-
}
|
|
1614
|
-
|
|
1615
|
-
/** Positional args keyed by the entry's `args` names, plus `_rest`. */
|
|
1616
|
-
function parseArgs(cmd, arg) {
|
|
1617
|
-
const raw = String(arg == null ? '' : arg);
|
|
1618
|
-
const names = Array.isArray(cmd.args) ? cmd.args : [];
|
|
1619
|
-
const tokens = tokenize(raw);
|
|
1620
|
-
const out = { _rest: raw.trim() };
|
|
1621
|
-
names.forEach((n, i) => { if (tokens[i] !== undefined) out[n] = tokens[i]; });
|
|
1622
|
-
return out;
|
|
1623
|
-
}
|
|
1624
|
-
|
|
1625
|
-
/** A fresh snapshot for panels.js (the frozen `c.state()` shape). */
|
|
1626
|
-
function buildState() {
|
|
1627
|
-
const rules = loadPermissions();
|
|
1628
|
-
// ON8: `/status` reports the POSTURE, so a gate turned off in the window
|
|
1629
|
-
// shows here as `allow` rather than as a rule file that no longer decides.
|
|
1630
|
-
const posture = confirmPosture();
|
|
1631
|
-
return {
|
|
1632
|
-
version: VERSION,
|
|
1633
|
-
model: commandCtx.model || 'server default',
|
|
1634
|
-
class: commandCtx.modelClass,
|
|
1635
|
-
effort: commandCtx.effort,
|
|
1636
|
-
thinking: commandCtx.thinking,
|
|
1637
|
-
theme: commandCtx.light ? 'light' : 'dark',
|
|
1638
|
-
themeIndex: commandCtx.themeIndex,
|
|
1639
|
-
vim: commandCtx.vim,
|
|
1640
|
-
stream: commandCtx.stream,
|
|
1641
|
-
cwd: commandCtx.cwd,
|
|
1642
|
-
home: os.homedir(),
|
|
1643
|
-
sessionId: commandCtx.sessionId,
|
|
1644
|
-
base: client.apiBase,
|
|
1645
|
-
keyMask: maskKey(client.apiKey),
|
|
1646
|
-
online: !!client.apiKey,
|
|
1647
|
-
turns: session.turns,
|
|
1648
|
-
calls: session.calls,
|
|
1649
|
-
startedAt: session.startedAt,
|
|
1650
|
-
// The shared bucket shape `{input, output, cacheRead, cacheWrite}` — the
|
|
1651
|
-
// same object /cost's accounting and the ledger carry, so the panels
|
|
1652
|
-
// cannot render a different turn than the one that was billed. `input` is
|
|
1653
|
-
// the miss half; see recordTurn.
|
|
1654
|
-
tokens: {
|
|
1655
|
-
input: session.inputTokens,
|
|
1656
|
-
output: session.outputTokens,
|
|
1657
|
-
cacheRead: session.cacheReadTokens,
|
|
1658
|
-
cacheWrite: session.cacheWriteTokens,
|
|
1659
|
-
total: session.tokens,
|
|
1660
|
-
},
|
|
1661
|
-
costEur: session.cost,
|
|
1662
|
-
balance: session.balance,
|
|
1663
|
-
plan: session.plan || null,
|
|
1664
|
-
account: session.account || null,
|
|
1665
|
-
permissions: { mode: posture.enabled ? rules.defaultMode : 'allow', confirm: posture.enabled, source: posture.source, rules },
|
|
1666
|
-
// The selectable (pickable) catalog, not the raw payload: alias tiers are
|
|
1667
|
-
// dropped, live ids only (see models.js pickerEntries).
|
|
1668
|
-
// Whichever class is live decides what is pinnable — the pooled ids the
|
|
1669
|
-
// server advertises, or the `provider:model` ids this machine can relay.
|
|
1670
|
-
models: classScopedModels(),
|
|
1671
|
-
commands: visibleCommands(),
|
|
1672
|
-
transcript: transcript.slice(),
|
|
1673
|
-
sessions: [],
|
|
1674
|
-
memory: {},
|
|
1675
|
-
lastRecap: commandCtx.lastRecap,
|
|
1676
|
-
backend: commandCtx.modelClass,
|
|
1677
|
-
url: client.apiBase,
|
|
1678
|
-
};
|
|
1679
|
-
}
|
|
1680
|
-
|
|
1681
|
-
/** Flatten a span line (panels.js/overlays.js output) back to an ANSI row. */
|
|
1682
|
-
function flattenSpans(line) {
|
|
1683
|
-
if (!Array.isArray(line)) return String(line == null ? '' : line);
|
|
1684
|
-
return line.map((sp) => (sp && (sp.s || '') + (sp.t == null ? '' : sp.t)) || '').join('');
|
|
1685
|
-
}
|
|
1686
|
-
|
|
1687
|
-
/**
|
|
1688
|
-
* Push one transcript row. `c.push(row)`/`c.note`/`c.panel` land here; the
|
|
1689
|
-
* linear CLI prints each row once to scrollback (there is no alt-screen).
|
|
1690
|
-
*/
|
|
1691
|
-
function pushRow(row) {
|
|
1692
|
-
if (!row || typeof row !== 'object') return;
|
|
1693
|
-
const W = width();
|
|
1694
|
-
switch (row.role) {
|
|
1695
|
-
case 'panel': {
|
|
1696
|
-
const lines = Array.isArray(row.lines) ? row.lines : [];
|
|
1697
|
-
for (const line of lines) emit(flattenSpans(line));
|
|
1698
|
-
return;
|
|
1699
|
-
}
|
|
1700
|
-
case 'note': emit(render.renderNotice(ctx(), 'info', row.text)); return;
|
|
1701
|
-
case 'tip': emit(render.renderNotice(ctx(), 'info', row.text)); return;
|
|
1702
|
-
case 'done': emit(render.renderNotice(ctx(), 'ok', row.text)); return;
|
|
1703
|
-
case 'error': emit(render.renderNotice(ctx(), 'error', row.text)); return;
|
|
1704
|
-
case 'user': emit(render.renderTurn(ctx(), { role: 'user', text: row.text, label: row.label }, W)); return;
|
|
1705
|
-
case 'assistant': emit(render.renderTurn(ctx(), { role: 'assistant', text: row.text }, W)); return;
|
|
1706
|
-
case 'tool': {
|
|
1707
|
-
// A chatflow row carries the preview it built from the run frame
|
|
1708
|
-
// (chatflow.js); a row pushed straight from a command handler has none,
|
|
1709
|
-
// so build one here rather than re-showing the gray `$ {args}` row.
|
|
1710
|
-
if (row.diff === undefined) {
|
|
1711
|
-
row.diff = editPreview(row.name || row.label, row.args, { cwd: process.cwd() });
|
|
1712
|
-
row.diffOpen = defaultOpen(row.diff);
|
|
1713
|
-
}
|
|
1714
|
-
emit(render.renderTurn(ctx(), { role: 'tool', label: row.label || row.name, args: row.args, ok: row.ok, diff: row.diff, diffOpen: !!row.diffOpen }, W));
|
|
1715
|
-
return;
|
|
1716
|
-
}
|
|
1717
|
-
default: emit(render.renderNotice(ctx(), 'info', row.text == null ? '' : String(row.text))); return;
|
|
1718
|
-
}
|
|
1719
|
-
}
|
|
1720
|
-
|
|
1721
|
-
/** A static (non-interactive) print of an overlay's contents. */
|
|
1722
|
-
function openOverlay(o) {
|
|
1723
|
-
if (!o || typeof o !== 'object') return;
|
|
1724
|
-
const W = width();
|
|
1725
|
-
const rows = Math.max(5, (process.stdout && process.stdout.rows) || 24);
|
|
1726
|
-
let lines = null;
|
|
1727
|
-
if (o.type === 'panel') lines = o.lines;
|
|
1728
|
-
else if (o.type === 'palette') lines = overlays.renderPalette(visibleCommands(), { query: o.query || '', sel: o.sel || 0 }, W, rows);
|
|
1729
|
-
else if (o.type === 'model') lines = overlays.renderModelPicker(o.items || [], o.sel || 0, W, rows, o.current != null ? o.current : commandCtx.model, o.cls || commandCtx.modelClass, classLabelOf);
|
|
1730
|
-
else if (o.type === 'effort') lines = overlays.renderEffortPicker(o.sel || 0, W, commandCtx.effort);
|
|
1731
|
-
else if (o.type === 'class') lines = overlays.renderClassPicker(o.items || [], o.sel || 0, W, o.current || commandCtx.modelClass, classLabelOf);
|
|
1732
|
-
else if (o.type === 'provider') lines = overlays.renderProviderPicker(o.items || [], o.sel || 0, W, o.current, o.hint);
|
|
1733
|
-
else if (o.type === 'resume') lines = overlays.renderResumeList(o.items || [], o.sel || 0, W, rows);
|
|
1734
|
-
else if (o.type === 'confirm') lines = render.renderApproval(ctx(), o.info || {}, W).map((s) => [spanRow(s)]);
|
|
1735
|
-
if (!lines) return;
|
|
1736
|
-
for (const line of lines) emit(flattenSpans(line));
|
|
1737
|
-
}
|
|
1738
|
-
|
|
1739
|
-
/** A single-span row for a pre-styled string (renderApproval output). */
|
|
1740
|
-
function spanRow(s) {
|
|
1741
|
-
return { t: s, s: '', w: w(s) };
|
|
1742
|
-
}
|
|
1743
|
-
|
|
1744
|
-
/** Run `fn(signal)` with the spinner up (interactive TTY only). */
|
|
1745
|
-
async function withWorking(fn) {
|
|
1746
|
-
const controller = new AbortController();
|
|
1747
|
-
const live = opts.interactive && out.isTTY ? new LiveRegion(out) : null;
|
|
1748
|
-
let timer = null;
|
|
1749
|
-
if (live) {
|
|
1750
|
-
let tick = 0;
|
|
1751
|
-
const started = Date.now();
|
|
1752
|
-
const paint = () => live.update([render.renderWorking(ctx(), { tick: tick++, verb: VERBS[0], elapsedMs: Date.now() - started })]);
|
|
1753
|
-
paint();
|
|
1754
|
-
timer = setInterval(paint, 90);
|
|
1755
|
-
if (timer.unref) timer.unref();
|
|
1756
|
-
}
|
|
1757
|
-
try {
|
|
1758
|
-
return await fn(controller.signal);
|
|
1759
|
-
} finally {
|
|
1760
|
-
if (timer) clearInterval(timer);
|
|
1761
|
-
if (live) live.clear();
|
|
1762
|
-
}
|
|
1763
|
-
}
|
|
1764
|
-
|
|
1765
|
-
/**
|
|
1766
|
-
* The theme picker. On a real terminal this is the onboarding screen; anywhere
|
|
1767
|
-
* else (`/theme` in a pipe, a test with no TTY) it stays the light/dark toggle
|
|
1768
|
-
* it has always been, so a non-interactive caller never blocks on a key.
|
|
1769
|
-
*/
|
|
1770
|
-
async function showThemePicker() {
|
|
1771
|
-
if (options.readline || !process.stdin.isTTY || !process.stdout.isTTY || options.chatflow === false) {
|
|
1772
|
-
commandCtx.light = !commandCtx.light;
|
|
1773
|
-
commandCtx.themeIndex = commandCtx.light ? 2 : 1;
|
|
1774
|
-
emit(render.renderNotice(ctx(), 'ok', `theme: ${commandCtx.light ? 'light' : 'dark'}`));
|
|
1775
|
-
return commandCtx.themeIndex;
|
|
1776
|
-
}
|
|
1777
|
-
return screens.showThemePicker(commandCtx);
|
|
1778
|
-
}
|
|
1779
|
-
|
|
1780
|
-
/** Build the FROZEN command context `c` a handler runs against. */
|
|
1781
|
-
function makeCommandContext() {
|
|
1782
|
-
const c = {
|
|
1783
|
-
ctx: commandCtx,
|
|
1784
|
-
transcript,
|
|
1785
|
-
push: (row) => pushRow(row),
|
|
1786
|
-
note: (text) => pushRow({ role: 'note', text }),
|
|
1787
|
-
panel: (lines) => pushRow({ role: 'panel', lines }),
|
|
1788
|
-
render: () => {},
|
|
1789
|
-
openOverlay: (o) => openOverlay(o),
|
|
1790
|
-
closeOverlay: () => {},
|
|
1791
|
-
// Auto mode's session switch, written by `/automode on|off` (commands.js)
|
|
1792
|
-
// and read by makeHost's isYolo. It lives on the context for the same
|
|
1793
|
-
// reason `switchClass` does: the command must move the fact the status
|
|
1794
|
-
// line, the round-budget allowance and the approval gate all read, or the
|
|
1795
|
-
// command is cosmetic. See the session flag's comment near createApp's
|
|
1796
|
-
// gate wiring for why AEGIS_AUTO_ROUNDS=0 is a starting point and not a
|
|
1797
|
-
// veto.
|
|
1798
|
-
setAutoRounds: (v) => {
|
|
1799
|
-
autoRoundsSession = Boolean(v);
|
|
1800
|
-
},
|
|
1801
|
-
askInput: () => Promise.resolve(null),
|
|
1802
|
-
withWorking: (fn) => withWorking(fn),
|
|
1803
|
-
runPrompt: (text) => runPrompt(text),
|
|
1804
|
-
ask: (text) => ask(text),
|
|
1805
|
-
runTool: (name, args) => runTool(name, args),
|
|
1806
|
-
// The catalog `/model` and alt+p expect. Routed through listModelsFor so
|
|
1807
|
-
// it follows the LIVE class: on the pooled class that is the server's
|
|
1808
|
-
// catalog (loadModels), on byok the `provider:model` ids this machine can
|
|
1809
|
-
// relay. Wired on the app's context so the chatflow's `Object.assign`
|
|
1810
|
-
// based context inherits it too — one definition, both hosts, and the
|
|
1811
|
-
// picker can never offer something the class would reject.
|
|
1812
|
-
loadModels: () => listModelsFor(commandCtx.modelClass),
|
|
1813
|
-
// The provider-key store (`byok:<provider>` rows) /byok-key writes. Read
|
|
1814
|
-
// through a function, not captured, because an injected engine may not
|
|
1815
|
-
// carry one.
|
|
1816
|
-
settings: () => engine.settings || null,
|
|
1817
|
-
// The one spelling of a provider's settings row, shared with the engine
|
|
1818
|
-
// that reads it (`byok:<provider>`) — see engine.js byokNamespace.
|
|
1819
|
-
byokNamespace: (p) => byokNamespace(p),
|
|
1820
|
-
// The class surface: /class switches, /models lists for whichever class
|
|
1821
|
-
// is live (the frozen state carries the current one as c.ctx.modelClass).
|
|
1822
|
-
listModelsFor: (cls) => listModelsFor(cls),
|
|
1823
|
-
// Re-read the byok rows NOW, past the 5-minute cache. `/model-add` writes
|
|
1824
|
-
// the user-model file and then asks for this, because a picker that
|
|
1825
|
-
// answers from a cache older than the file it just wrote would report the
|
|
1826
|
-
// model it was told to add as missing — for five minutes.
|
|
1827
|
-
refreshByokModels: () => loadByokModels({ force: true }),
|
|
1828
|
-
switchClass: (cls) => switchClass(cls),
|
|
1829
|
-
classLabel: (cls) => classLabelOf(cls),
|
|
1830
|
-
classes: () => (typeof engine.listClasses === 'function' ? engine.listClasses() : []),
|
|
1831
|
-
refreshSpend: () => refreshSpend(),
|
|
1832
|
-
state: () => buildState(),
|
|
1833
|
-
setInput: () => {},
|
|
1834
|
-
exit: () => { wantExit = true; },
|
|
1835
|
-
client,
|
|
1836
|
-
TOOLS,
|
|
1837
|
-
saveConfig: (patch) => updateConfig(patch),
|
|
1838
|
-
showThemePicker: () => showThemePicker(),
|
|
1839
|
-
// Credential + cloud-sync surface for the /key, /cloud and /sync commands.
|
|
1840
|
-
// Defined here on the app's context so the chatflow's Object.assign-based
|
|
1841
|
-
// context inherits them too — one definition, both hosts.
|
|
1842
|
-
keyStatus: () => credentials.keyStatus(),
|
|
1843
|
-
setApiKey: (raw, o) => setApiKey(raw, o),
|
|
1844
|
-
forgetApiKey: () => forgetApiKey(),
|
|
1845
|
-
registerAccount: () => registerAccount(),
|
|
1846
|
-
readSecret: (text) => readSecret(text, { stdin: process.stdin, stdout: out }),
|
|
1847
|
-
cloudsync,
|
|
1848
|
-
cloudSyncEnabled: () => cloudSyncEnabled(),
|
|
1849
|
-
cloudSyncState: () => cloudSyncState(),
|
|
1850
|
-
setCloudSync: (on) => setCloudSync(on),
|
|
1851
|
-
adoptLegacyKey: () => adoptLegacyKeyOnce(),
|
|
1852
|
-
};
|
|
1853
|
-
Object.defineProperty(c, 'sessionId', {
|
|
1854
|
-
enumerable: true,
|
|
1855
|
-
get: () => commandCtx.sessionId,
|
|
1856
|
-
set: (v) => { commandCtx.sessionId = v; },
|
|
1857
|
-
});
|
|
1858
|
-
// Drop whatever a transport remembered ABOUT this conversation, as opposed
|
|
1859
|
-
// to what this host keeps in `transcript`. `/clear` empties the transcript,
|
|
1860
|
-
// but the Pro class's memory lives in the `claude` child's own session —
|
|
1861
|
-
// reattaching to it afterwards would answer from turns the user just
|
|
1862
|
-
// erased, which reads as the clear having failed. Keyed by session id, the
|
|
1863
|
-
// same id `sessionKey` travels as, so the two cannot drift.
|
|
1864
|
-
c.clearConversationMemory = () => {
|
|
1865
|
-
if (engine && typeof engine.clearSessionApprovals === 'function') {
|
|
1866
|
-
engine.clearSessionApprovals(commandCtx.sessionId);
|
|
1867
|
-
}
|
|
1868
|
-
};
|
|
1869
|
-
return c;
|
|
1870
|
-
}
|
|
1871
|
-
|
|
1872
|
-
/**
|
|
1873
|
-
* Handle one line of input. Returns false when the session should end.
|
|
1874
|
-
*
|
|
1875
|
-
* `cOverride` lets the chatflow supply the context it owns (its own `push`,
|
|
1876
|
-
* `render`, `openOverlay`, `askInput`, `runPrompt`) instead of the linear
|
|
1877
|
-
* defaults — the handlers are identical either way, which is the point.
|
|
1878
|
-
*/
|
|
1879
|
-
async function handleLine(line, cOverride = null) {
|
|
1880
|
-
const parsed = parseLine(line);
|
|
1881
|
-
|
|
1882
|
-
if (parsed.kind === 'empty') return true;
|
|
1883
|
-
if (parsed.kind === 'prompt') {
|
|
1884
|
-
await runPrompt(parsed.text);
|
|
1885
|
-
return true;
|
|
1886
|
-
}
|
|
1887
|
-
if (parsed.kind === 'unknown') {
|
|
1888
|
-
const alt = nearest(parsed.name);
|
|
1889
|
-
emit(
|
|
1890
|
-
render.renderNotice(
|
|
1891
|
-
ctx(),
|
|
1892
|
-
'error',
|
|
1893
|
-
`unknown command: /${parsed.name}${alt ? ` — did you mean /${alt}?` : ` — try /help`}`
|
|
1894
|
-
)
|
|
1895
|
-
);
|
|
1896
|
-
return true;
|
|
1897
|
-
}
|
|
1898
|
-
if (parsed.kind === 'unavailable') {
|
|
1899
|
-
const c = parsed.command;
|
|
1900
|
-
emit(render.renderNotice(ctx(), 'warn', `/${c.name} is not available in aegiscode — ${c.unavailable}`));
|
|
1901
|
-
if (c.alt) emit(render.renderNotice(ctx(), 'info', `try ${c.alt} instead`));
|
|
1902
|
-
else {
|
|
1903
|
-
const alt = nearest(c.name);
|
|
1904
|
-
if (alt) emit(render.renderNotice(ctx(), 'info', `try /${alt} instead`));
|
|
1905
|
-
}
|
|
1906
|
-
return true;
|
|
1907
|
-
}
|
|
1908
|
-
|
|
1909
|
-
const cmd = parsed.command;
|
|
1910
|
-
const arg = parsed.arg;
|
|
1911
|
-
|
|
1912
|
-
// The generic escape hatch (/tool <name> [json]).
|
|
1913
|
-
if (cmd.generic) {
|
|
1914
|
-
let built;
|
|
1915
|
-
try {
|
|
1916
|
-
built = cmd.build(arg);
|
|
1917
|
-
} catch (e) {
|
|
1918
|
-
emit(render.renderNotice(ctx(), 'error', e.message));
|
|
1919
|
-
return true;
|
|
1920
|
-
}
|
|
1921
|
-
const { tool, args } = built;
|
|
1922
|
-
if (!tool) {
|
|
1923
|
-
emit(render.renderNotice(ctx(), 'error', '/tool needs a tool name — see /help'));
|
|
1924
|
-
return true;
|
|
1925
|
-
}
|
|
1926
|
-
try {
|
|
1927
|
-
await runTool(tool, args);
|
|
1928
|
-
} catch (e) {
|
|
1929
|
-
emit(render.renderNotice(ctx(), 'error', e.message));
|
|
1930
|
-
}
|
|
1931
|
-
return true;
|
|
1932
|
-
}
|
|
1933
|
-
|
|
1934
|
-
// Handler-backed (the reference aegiscode-dev contract).
|
|
1935
|
-
if (typeof cmd.handler === 'function') {
|
|
1936
|
-
const args = parseArgs(cmd, arg);
|
|
1937
|
-
const c = cOverride || makeCommandContext();
|
|
1938
|
-
try {
|
|
1939
|
-
const keep = await cmd.handler(c, args);
|
|
1940
|
-
return keep === false ? false : true;
|
|
1941
|
-
} catch (e) {
|
|
1942
|
-
emit(render.renderNotice(ctx(), 'error', e && e.message ? e.message : String(e)));
|
|
1943
|
-
return true;
|
|
1944
|
-
}
|
|
1945
|
-
}
|
|
1946
|
-
|
|
1947
|
-
// Tool-backed command.
|
|
1948
|
-
try {
|
|
1949
|
-
let args = cmd.build(arg);
|
|
1950
|
-
if (cmd.secret) {
|
|
1951
|
-
// A bare "provider key for openai:" tells the user nothing about which
|
|
1952
|
-
// key to paste or where to get it, which is exactly the step people get
|
|
1953
|
-
// wrong. When a command can describe its own secret it does, and the
|
|
1954
|
-
// description is best-effort: a catalog fetch that fails must still
|
|
1955
|
-
// leave a working prompt rather than aborting the command.
|
|
1956
|
-
const spec = await describeSecret(cmd, args);
|
|
1957
|
-
if (spec && spec.note) emit(render.renderNotice(ctx(), 'info', spec.note));
|
|
1958
|
-
// An explicit `prompt: null` is a refusal, not a missing description.
|
|
1959
|
-
// Reading it as "no description" and falling through to the generic
|
|
1960
|
-
// prompt is how `/byok-set <typo>` printed "unknown provider … Nothing
|
|
1961
|
-
// was sent" and then asked for the key anyway and sent it: the command
|
|
1962
|
-
// had decided this must not be stored, and the dispatcher overrode it.
|
|
1963
|
-
if (spec && spec.prompt === null) return true;
|
|
1964
|
-
// The command may have resolved the typed word to a canonical id
|
|
1965
|
-
// (`together-ai` → `together`). Send that. Otherwise the prompt names
|
|
1966
|
-
// the real provider while the request carries the alias the server does
|
|
1967
|
-
// not know, and the save fails after the user has already pasted a key.
|
|
1968
|
-
if (spec && spec.provider) args = { ...args, provider: spec.provider };
|
|
1969
|
-
const key = await askSecret((spec && spec.prompt) || `provider key for ${args.provider}: `);
|
|
1970
|
-
if (!key) {
|
|
1971
|
-
emit(render.renderNotice(ctx(), 'warn', 'empty key — nothing sent'));
|
|
1972
|
-
return true;
|
|
1973
|
-
}
|
|
1974
|
-
args = { ...args, api_key: key };
|
|
1975
|
-
}
|
|
1976
|
-
if (cmd.tool === 'aegis_ask') return await runPrompt(args.prompt);
|
|
1977
|
-
await runTool(cmd.tool, args);
|
|
1978
|
-
// `/memory` is where a user actually looks at what is stored, so the
|
|
1979
|
-
// quota state belongs here as well as in /cloud: the ceiling is the one
|
|
1980
|
-
// fact about this feature that changes what the account can do, and it is
|
|
1981
|
-
// invisible from the entries themselves.
|
|
1982
|
-
if (cmd.tool === 'aegis_memory_list' || cmd.tool === 'aegis_memory_search') memoryQuotaNote();
|
|
1983
|
-
} catch (e) {
|
|
1984
|
-
emit(render.renderNotice(ctx(), 'error', e.message));
|
|
1985
|
-
}
|
|
1986
|
-
return true;
|
|
1987
|
-
}
|
|
1988
|
-
|
|
1989
|
-
/**
|
|
1990
|
-
* One line of quota state for the memory read commands. Quiet when the server
|
|
1991
|
-
* has not reported a ceiling yet (nothing useful to say), a statement when it
|
|
1992
|
-
* has, and — when the account is at it — the two halves spelled out: reads
|
|
1993
|
-
* keep working, new writes do not.
|
|
1994
|
-
*/
|
|
1995
|
-
function memoryQuotaNote() {
|
|
1996
|
-
let st;
|
|
1997
|
-
try {
|
|
1998
|
-
st = cloudsync.status();
|
|
1999
|
-
} catch {
|
|
2000
|
-
return;
|
|
2001
|
-
}
|
|
2002
|
-
const q = st.quota;
|
|
2003
|
-
if (!q) return;
|
|
2004
|
-
const used = fmtTokens(q.used || 0);
|
|
2005
|
-
const limit = fmtTokens(q.limit || 0);
|
|
2006
|
-
if (st.overQuota) {
|
|
2007
|
-
emit(
|
|
2008
|
-
render.renderNotice(
|
|
2009
|
-
ctx(),
|
|
2010
|
-
'warn',
|
|
2011
|
-
`cloud memory: ${used} of ${limit} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`
|
|
2012
|
-
)
|
|
2013
|
-
);
|
|
2014
|
-
return;
|
|
2015
|
-
}
|
|
2016
|
-
emit(render.renderNotice(ctx(), 'info', `cloud memory: ${used} of ${limit} synced tokens — /cloud memory for the full state`));
|
|
2017
|
-
}
|
|
2018
|
-
|
|
2019
|
-
/**
|
|
2020
|
-
* Ask the command how to describe the secret it is about to collect.
|
|
2021
|
-
*
|
|
2022
|
-
* Returns `{ note, prompt }` or null. The command opts in by defining
|
|
2023
|
-
* `secretDescribe(args, client)`, which is awaited and therefore free to
|
|
2024
|
-
* consult the server. A throw here is swallowed on purpose: guidance is an
|
|
2025
|
-
* improvement to a prompt, and a user who typed `/byok-set openai` on a
|
|
2026
|
-
* flaky connection should still get the prompt.
|
|
2027
|
-
*/
|
|
2028
|
-
async function describeSecret(cmd, args) {
|
|
2029
|
-
if (typeof cmd.secretDescribe !== 'function') return null;
|
|
2030
|
-
try {
|
|
2031
|
-
const spec = await cmd.secretDescribe(args, client);
|
|
2032
|
-
return spec && typeof spec === 'object' ? spec : null;
|
|
2033
|
-
} catch {
|
|
2034
|
-
return null;
|
|
2035
|
-
}
|
|
2036
|
-
}
|
|
2037
|
-
|
|
2038
|
-
/**
|
|
2039
|
-
* Ask for a secret on this session's streams.
|
|
2040
|
-
*
|
|
2041
|
-
* The prompt loop itself lives in secret.js, shared with `aegiscode login` in
|
|
2042
|
-
* the bin — one implementation, so the terminal host and the non-interactive
|
|
2043
|
-
* entry point cannot differ in whether a key is echoed or masked. Only the
|
|
2044
|
-
* prompt's colouring is the session's business.
|
|
2045
|
-
*/
|
|
2046
|
-
function askSecret(promptText) {
|
|
2047
|
-
const t = themeOf(ctx());
|
|
2048
|
-
return readSecret(t.gray + promptText + RESET, { stdin: process.stdin, stdout: out });
|
|
2049
|
-
}
|
|
2050
|
-
|
|
2051
|
-
// --- entry points ---------------------------------------------------------
|
|
2052
|
-
|
|
2053
|
-
/**
|
|
2054
|
-
* Give the local lane back its hardware, on the way out.
|
|
2055
|
-
*
|
|
2056
|
-
* The desktop has done this from its quit path since the class shipped
|
|
2057
|
-
* (`main.js` before-quit -> `engine.unloadLocalModels` -> local.js
|
|
2058
|
-
* `unloadAll`): "closing the app closes the model". The CLI had no equivalent
|
|
2059
|
-
* at all, so exiting a session after a `local` turn left the weights resident
|
|
2060
|
-
* for the remainder of the pin the turn itself set — `DEFAULT_WARM_SECS` is
|
|
2061
|
-
* 1800 (local.js), i.e. up to thirty minutes of a loaded model on hardware
|
|
2062
|
-
* nobody was using anymore, which is the one cost this lane exists to not
|
|
2063
|
-
* have.
|
|
2064
|
-
*
|
|
2065
|
-
* Best-effort by construction: `unloadAll` never throws and each request is
|
|
2066
|
-
* bounded by `UNLOAD_TIMEOUT_MS` (4s) inside the transport, so a daemon that
|
|
2067
|
-
* is slow, wedged or already gone cannot turn a clean exit into a hang or a
|
|
2068
|
-
* crash. Called from every exit path of every entry point below — INCLUDING
|
|
2069
|
-
* `-p`, whose whole life may be one local turn.
|
|
2070
|
-
*
|
|
2071
|
-
* Deliberately not a `process.on('exit')` handler: that callback cannot
|
|
2072
|
-
* await, so the request would be issued into a process that is already
|
|
2073
|
-
* tearing the socket down. Awaiting at the end of the session is what makes
|
|
2074
|
-
* the eviction actually reach the daemon.
|
|
2075
|
-
*/
|
|
2076
|
-
async function releaseLocalModel() {
|
|
2077
|
-
if (!engine || typeof engine.unloadLocalModels !== 'function') return;
|
|
2078
|
-
try {
|
|
2079
|
-
await engine.unloadLocalModels();
|
|
2080
|
-
} catch {
|
|
2081
|
-
/* the model's own keep-alive lapses; never fail an exit over cleanup */
|
|
2082
|
-
}
|
|
2083
|
-
}
|
|
2084
|
-
|
|
2085
|
-
/**
|
|
2086
|
-
* One-shot run: the turn itself (`runOnceTurn`), then the local lane handed
|
|
2087
|
-
* back even if that turn threw. A `-p` run can BE a whole local session, so
|
|
2088
|
-
* it needs the same closing the interactive loop gets — see
|
|
2089
|
-
* `releaseLocalModel`.
|
|
2090
|
-
*/
|
|
2091
|
-
async function runOnce(prompt, opts = {}) {
|
|
2092
|
-
try {
|
|
2093
|
-
return await runOnceTurn(prompt, opts);
|
|
2094
|
-
} finally {
|
|
2095
|
-
await releaseLocalModel();
|
|
2096
|
-
}
|
|
2097
|
-
}
|
|
2098
|
-
|
|
2099
|
-
/** Non-interactive: one prompt, plain output, exit code. */
|
|
2100
|
-
async function runOnceTurn(prompt, { json = false } = {}) {
|
|
2101
|
-
// The one-shot path used to skip this entirely, so `-p` always ran
|
|
2102
|
-
// DEFAULT_CLASS ('aegis', the pooled route) no matter what the user had
|
|
2103
|
-
// pinned: `/class byok` (or a saved byok/byok-model pin) applied to the
|
|
2104
|
-
// interactive loop only. That made the documented headless entry point
|
|
2105
|
-
// unable to use BYOK at all — it billed the pool instead, or, on a box
|
|
2106
|
-
// whose pooled backend was down, failed with a provider timeout while the
|
|
2107
|
-
// user's own key sat unused. Same restore the REPL does, before the first
|
|
2108
|
-
// turn and therefore before `ask()` resolves a route.
|
|
2109
|
-
restorePrefs();
|
|
2110
|
-
adoptLegacyKeyOnce();
|
|
2111
|
-
// Same self-service a fresh `aegiscode -p ...` deserves as a fresh
|
|
2112
|
-
// interactive session (runInteractive) or a fresh `/ask` (runPrompt):
|
|
2113
|
-
// this path used to skip straight to the "no key" refusal below, so
|
|
2114
|
-
// every headless/scripted first run (CI, docker, a README one-liner)
|
|
2115
|
-
// left an installed-but-never-registered machine with no account row
|
|
2116
|
-
// and no welcome trial, instead of the free device key auto-provision
|
|
2117
|
-
// was built to hand it.
|
|
2118
|
-
//
|
|
2119
|
-
// Not the shared `ensureApiKey()` helper: it reports through `emit()`,
|
|
2120
|
-
// which writes to `out` — the same stream `--json` puts its one machine-
|
|
2121
|
-
// readable line on. A notice ahead of that line would break every script
|
|
2122
|
-
// piping `-p ... --json` into a JSON parser, so this path's own notice
|
|
2123
|
-
// always goes to `err` regardless of `json`.
|
|
2124
|
-
if (!client.apiKey && !provisionAttempted) {
|
|
2125
|
-
provisionAttempted = true;
|
|
2126
|
-
const result = await autoProvisionApiKey(client, credentials, { app: 'cli' });
|
|
2127
|
-
if (result.key) {
|
|
2128
|
-
err.write(
|
|
2129
|
-
`aegiscode: auto-provisioned a free account` +
|
|
2130
|
-
(result.ok ? ` (saved to ${credentials.credentialsPath()})` : ' (could not save it — reconfigure with /key)') +
|
|
2131
|
-
trialNote(result) +
|
|
2132
|
-
`. Fund it at ${client.promptUrl('topup', 'device_autoprovision')} or run /byok to use your own key.\n`
|
|
2133
|
-
);
|
|
2134
|
-
}
|
|
2135
|
-
}
|
|
2136
|
-
if (!client.apiKey) {
|
|
2137
|
-
err.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`);
|
|
2138
|
-
return 2;
|
|
2139
|
-
}
|
|
2140
|
-
// Snapshot the account's existing ledger BEFORE the billed call. Without
|
|
2141
|
-
// this the refresh after the turn would treat every historical row as new,
|
|
2142
|
-
// and the reported charge would be whatever the account spent last rather
|
|
2143
|
-
// than what this call cost.
|
|
2144
|
-
await refreshSpend();
|
|
2145
|
-
// Under `--json`, stdout carries ONE document and nothing else. A turn that
|
|
2146
|
-
// uses tools renders a row per call (`ask()`'s `tool` presenter below), and
|
|
2147
|
-
// those rows went to `out` — so the document was preceded by ANSI-coloured
|
|
2148
|
-
// progress text and no parser could read it. Measured: a tool-using turn
|
|
2149
|
-
// emitted 1238 bytes of `Bash ⎿ ✔` rows before the JSON, which is why the
|
|
2150
|
-
// harness sweep recorded `tokens_in: 0` for tasks the CLI had in fact
|
|
2151
|
-
// SOLVED. The rows are still shown, just on stderr, where a human sees them
|
|
2152
|
-
// and a parser does not.
|
|
2153
|
-
// Every tool call this turn really made, by name. `--json` is the only
|
|
2154
|
-
// machine-readable surface the CLI has, and the harness measures "how much
|
|
2155
|
-
// work did the loop do" from it. A tool-using turn that reports no tools is
|
|
2156
|
-
// indistinguishable from a turn that answered from memory — the benchmark
|
|
2157
|
-
// scored three tasks SOLVED with `tool_calls: 0` while the workspace showed
|
|
2158
|
-
// genuine edits, because nothing published the count.
|
|
2159
|
-
const toolsUsed = [];
|
|
2160
|
-
const toolLog = [];
|
|
2161
|
-
const jsonPresenter = json
|
|
2162
|
-
? {
|
|
2163
|
-
tool: (tool) => {
|
|
2164
|
-
// One entry per CALL, not per frame. The engine reports every tool
|
|
2165
|
-
// twice — `phase: 'run'` before it executes and `phase: 'done'`
|
|
2166
|
-
// with the outcome — and both arrive here. Pushing on both doubled
|
|
2167
|
-
// `tools` (a 6-call turn published 12-14 names), and the benchmark
|
|
2168
|
-
// adapters count array elements as calls, so AEGIS's tool count was
|
|
2169
|
-
// inflated by exactly 2x while its `tokens_per_solved` was flattered
|
|
2170
|
-
// by the same factor. The done frame now only settles the entry it
|
|
2171
|
-
// belongs to.
|
|
2172
|
-
const phase = tool && tool.phase;
|
|
2173
|
-
if (phase === 'done') {
|
|
2174
|
-
const match = (tool.id && toolLog.find((c) => c.id === tool.id && c.settled !== true))
|
|
2175
|
-
|| (tool.id ? null : toolLog[toolLog.length - 1]);
|
|
2176
|
-
if (match) {
|
|
2177
|
-
match.settled = true;
|
|
2178
|
-
match.ok = tool.ok !== false;
|
|
2179
|
-
} else {
|
|
2180
|
-
// A `done` frame with no unsettled entry to settle is a call we
|
|
2181
|
-
// are learning about for the first time — the engine batched or
|
|
2182
|
-
// outlived the matching `run` frame (seen on the sweep: one
|
|
2183
|
-
// `run` then every later call arriving already `done`). Falling
|
|
2184
|
-
// back to "settle the last entry" silently discarded those
|
|
2185
|
-
// calls: a task that ran 7 tools published `tool_calls: 1`
|
|
2186
|
-
// while its own stderr rendered all 7. Record it, already
|
|
2187
|
-
// settled, so counting stays at one per call.
|
|
2188
|
-
if (tool && tool.name) toolsUsed.push(tool.name);
|
|
2189
|
-
toolLog.push({
|
|
2190
|
-
name: (tool && tool.name) || null,
|
|
2191
|
-
id: (tool && tool.id) || null,
|
|
2192
|
-
args: briefArgs(tool && tool.args),
|
|
2193
|
-
settled: true,
|
|
2194
|
-
ok: tool.ok !== false,
|
|
2195
|
-
});
|
|
2196
|
-
}
|
|
2197
|
-
} else {
|
|
2198
|
-
if (tool && tool.name) toolsUsed.push(tool.name);
|
|
2199
|
-
toolLog.push({
|
|
2200
|
-
name: (tool && tool.name) || null,
|
|
2201
|
-
id: (tool && tool.id) || null,
|
|
2202
|
-
// The same brief rendering a reader gets on stderr, so an
|
|
2203
|
-
// archived run can say WHAT the calls were rather than only how
|
|
2204
|
-
// many. `--json` used to publish the count and no evidence:
|
|
2205
|
-
// a 14-entry `tools` array was all a benchmark row could see.
|
|
2206
|
-
args: briefArgs(tool && tool.args),
|
|
2207
|
-
settled: false,
|
|
2208
|
-
ok: null,
|
|
2209
|
-
});
|
|
2210
|
-
}
|
|
2211
|
-
const diff = tool && tool.preview !== undefined ? tool.preview : null;
|
|
2212
|
-
const lines = render.renderTurn(
|
|
2213
|
-
ctx(),
|
|
2214
|
-
{ role: 'tool', label: tool.name, args: tool.args, ok: tool.ok, diff, diffOpen: false },
|
|
2215
|
-
width()
|
|
2216
|
-
);
|
|
2217
|
-
for (const l of Array.isArray(lines) ? lines : [lines]) err.write(l + '\n');
|
|
2218
|
-
return undefined;
|
|
2219
|
-
},
|
|
2220
|
-
}
|
|
2221
|
-
: null;
|
|
2222
|
-
const res = await ask(prompt, jsonPresenter ? { presenter: jsonPresenter } : {});
|
|
2223
|
-
await refreshSpend();
|
|
2224
|
-
const tokens = usageTokens(res.usage);
|
|
2225
|
-
// A refusal that arrived as content: report it as a failure, not an answer.
|
|
2226
|
-
const refusal = providerRefusal(res.text, res.usage);
|
|
2227
|
-
if (json) {
|
|
2228
|
-
out.write(
|
|
2229
|
-
JSON.stringify(
|
|
2230
|
-
{
|
|
2231
|
-
text: res.text,
|
|
2232
|
-
model: res.model,
|
|
2233
|
-
// The route this turn actually took, so a run can PROVE its class
|
|
2234
|
-
// instead of asserting it in prose. The benchmark spent two sweeps
|
|
2235
|
-
// comparing a pooled-relay CLI turn against a BYOK-direct desktop
|
|
2236
|
-
// turn while both rows claimed `deepseek-flash`; the 3.5× cost gap
|
|
2237
|
-
// was the transport, and nothing in the document said so. `--json`
|
|
2238
|
-
// is the only machine-readable surface this CLI has.
|
|
2239
|
-
class: commandCtx.modelClass,
|
|
2240
|
-
// The engine stamps `calls` onto this accumulator (one per provider
|
|
2241
|
-
// dispatch), so it is the turn's real round-trip count. Republished
|
|
2242
|
-
// under the name every benchmark adapter already looks for:
|
|
2243
|
-
// `harness-bench.mjs` read `e.rounds` and, finding nothing, fell
|
|
2244
|
-
// back to `1`, so every archived AEGIS row claimed a single round
|
|
2245
|
-
// for turns that made dozens.
|
|
2246
|
-
rounds: (res.usage && Number(res.usage.calls)) || null,
|
|
2247
|
-
usage: res.usage,
|
|
2248
|
-
tokens,
|
|
2249
|
-
ms: res.ms,
|
|
2250
|
-
interrupted: res.interrupted,
|
|
2251
|
-
// Present only when the turn actually called tools, so a reader can
|
|
2252
|
-
// tell "answered from memory" from "did work" without inferring it
|
|
2253
|
-
// from a token count.
|
|
2254
|
-
...(toolsUsed.length ? { tools: toolsUsed } : {}),
|
|
2255
|
-
// The evidence beside the count: name + a one-line arg summary per
|
|
2256
|
-
// call, with the outcome written back from the matching done frame.
|
|
2257
|
-
// `tools` above is kept unchanged because five archived runs and a
|
|
2258
|
-
// test read it, and it is the field that says HOW MANY rounds
|
|
2259
|
-
// touched a tool; this one says which.
|
|
2260
|
-
...(toolLog.length ? { tool_log: toolLog } : {}),
|
|
2261
|
-
// Present only when the reply was a provider refusal. A caller that
|
|
2262
|
-
// gates on `error` can now tell a dead turn from a working one;
|
|
2263
|
-
// before this field existed both were `{text, tokens: 0}` with
|
|
2264
|
-
// exit 0, and the harness scored a broken run as a scored zero.
|
|
2265
|
-
...(refusal ? { error: refusal } : {}),
|
|
2266
|
-
balance_eur: session.balance,
|
|
2267
|
-
},
|
|
2268
|
-
null,
|
|
2269
|
-
2
|
|
2270
|
-
) + '\n'
|
|
2271
|
-
);
|
|
2272
|
-
} else {
|
|
2273
|
-
out.write(res.text + '\n');
|
|
2274
|
-
if (refusal) err.write(`aegiscode: the provider refused this turn — ${refusal}\n`);
|
|
2275
|
-
if (tokens != null) {
|
|
2276
|
-
const t = themeOf(ctx());
|
|
2277
|
-
out.write(
|
|
2278
|
-
t.dim + GLYPH.hook + ' ' + t.blue + (res.model || 'aegis') + RESET +
|
|
2279
|
-
t.dim + ' ' + GLYPH.bullet + ' ' + RESET +
|
|
2280
|
-
t.white + `${fmtTokens(tokens)} tokens` + RESET + '\n'
|
|
2281
|
-
);
|
|
2282
|
-
}
|
|
2283
|
-
}
|
|
2284
|
-
return res.interrupted ? 130 : (refusal ? 1 : 0);
|
|
2285
|
-
}
|
|
2286
|
-
|
|
2287
|
-
/** Fold one completed turn's usage into the session tallies.
|
|
2288
|
-
* @returns {number|null} the total token count for the turn, when known. */
|
|
2289
|
-
/**
|
|
2290
|
-
* Name the conversation, on this host's own turn path (naming.js).
|
|
2291
|
-
*
|
|
2292
|
-
* The model round goes through `ask()`, so it uses the same client, the same
|
|
2293
|
-
* key and the same model the session is already talking to — a naming round
|
|
2294
|
-
* cannot become a second, differently-authenticated caller, and it costs one
|
|
2295
|
-
* short completion. `naming.js` owns every rule about what a name is: a
|
|
2296
|
-
* greeting is answered locally without a call at all, an echo of the prompt
|
|
2297
|
-
* is not a name, and the local derivation is the floor when nothing answers.
|
|
2298
|
-
*
|
|
2299
|
-
* The name is also written onto the session's history records, so `/resume`
|
|
2300
|
-
* lists the conversation by what it is about instead of by its raw first
|
|
2301
|
-
* message. Best-effort throughout: a failure here costs a label.
|
|
2302
|
-
*/
|
|
2303
|
-
async function nameConversation(prompt, { signal = null } = {}) {
|
|
2304
|
-
const title = await naming.nameConversation(prompt, {
|
|
2305
|
-
signal,
|
|
2306
|
-
callModel: (text, o) =>
|
|
2307
|
-
ask(text, {
|
|
2308
|
-
system: (o && o.system) || naming.TITLE_SYSTEM,
|
|
2309
|
-
maxTokens: 64,
|
|
2310
|
-
signal: (o && o.signal) || signal,
|
|
2311
|
-
}).then((r) => (r && r.text) || null),
|
|
2312
|
-
});
|
|
2313
|
-
const clean = String(title || '').trim();
|
|
2314
|
-
if (clean) setSessionTitle(commandCtx.sessionId, clean);
|
|
2315
|
-
return clean;
|
|
2316
|
-
}
|
|
2317
|
-
|
|
2318
|
-
function recordTurn(res) {
|
|
2319
|
-
session.turns++;
|
|
2320
|
-
session.calls += Number((res && res.calls) || 1) || 1;
|
|
2321
|
-
const usage = res && res.usage;
|
|
2322
|
-
const tokens = usageTokens(usage);
|
|
2323
|
-
if (tokens != null) {
|
|
2324
|
-
session.tokens += tokens;
|
|
2325
|
-
// The session tally is folded through the SHARED normaliser, not the raw
|
|
2326
|
-
// wire spellings. Reading `input_tokens ?? prompt_tokens` here is what
|
|
2327
|
-
// made the CLI's live tally disagree with its own ledger about the same
|
|
2328
|
-
// turn: the providers do not merely spell these fields differently, they
|
|
2329
|
-
// MEASURE them differently. Anthropic's `input_tokens` EXCLUDES
|
|
2330
|
-
// `cache_read_input_tokens`; OpenAI/DeepSeek's `prompt_tokens` INCLUDES
|
|
2331
|
-
// the hit. So `input + cacheRead` is right for the first and a
|
|
2332
|
-
// double-count of the prompt for the second. `usageBuckets` resolves
|
|
2333
|
-
// `input` to the MISS half in both cases (the same normalisation the
|
|
2334
|
-
// ledger row, the desktop roll and costBreakdown already use), which is
|
|
2335
|
-
// the only reading under which the /context prompt row means one thing on
|
|
2336
|
-
// every provider. Without this the CLI accumulated no cache buckets at
|
|
2337
|
-
// all, so /tokens drew two bars it could never fill.
|
|
2338
|
-
const b = usageBuckets(usage);
|
|
2339
|
-
session.inputTokens += b.input;
|
|
2340
|
-
session.outputTokens += b.output;
|
|
2341
|
-
session.cacheReadTokens += b.cacheRead;
|
|
2342
|
-
session.cacheWriteTokens += b.cacheWrite;
|
|
2343
|
-
}
|
|
2344
|
-
return tokens;
|
|
2345
|
-
}
|
|
2346
|
-
|
|
2347
|
-
/**
|
|
2348
|
-
* Persist one finished exchange: the history row and a transcript checkpoint.
|
|
2349
|
-
*
|
|
2350
|
-
* `appendHistory` and `snapshotCheckpoint` were both dead code — nothing ever
|
|
2351
|
-
* called them, so `history.jsonl` was never created. Every consumer of it
|
|
2352
|
-
* degraded silently rather than loudly: `/resume` could never find a stored
|
|
2353
|
-
* session, `/cost` summed zero rows, `/clear`'s prune was a no-op, and
|
|
2354
|
-
* `/rewind` always answered "No checkpoints yet". The session loop is the only
|
|
2355
|
-
* place that sees the prompt *and* its reply, so it is the place that writes.
|
|
2356
|
-
*
|
|
2357
|
-
* Best-effort by construction: the two writers swallow their own failures, and
|
|
2358
|
-
* accounting must never be able to break a turn.
|
|
2359
|
-
*/
|
|
2360
|
-
function persistTurn(prompt, res, status = 'done', costEur = null) {
|
|
2361
|
-
try {
|
|
2362
|
-
const usage = res && res.usage;
|
|
2363
|
-
// What the POOL charged, straight from the ledger — margin and
|
|
2364
|
-
// prompt-cache discount already applied. Stored so /cost can report the
|
|
2365
|
-
// real bill instead of recomputing from provider rates it cannot see.
|
|
2366
|
-
// (The history field is historically named `costUsd`; the value here is
|
|
2367
|
-
// EUR, which is what every surface in this client displays.)
|
|
2368
|
-
const settled = typeof costEur === 'number' && Number.isFinite(costEur) ? costEur : null;
|
|
2369
|
-
appendHistory({
|
|
2370
|
-
sessionId: commandCtx.sessionId,
|
|
2371
|
-
prompt,
|
|
2372
|
-
reply: (res && res.text) || '',
|
|
2373
|
-
status,
|
|
2374
|
-
usage: usage
|
|
2375
|
-
? {
|
|
2376
|
-
// Not re-derived here. `usageBuckets` is the one module both
|
|
2377
|
-
// hosts resolve (deps.js), so the terminal and the GUI cannot
|
|
2378
|
-
// disagree about what a turn consumed — including whether a
|
|
2379
|
-
// provider's cached count sits INSIDE its prompt count
|
|
2380
|
-
// (OpenAI, DeepSeek) or BESIDE it (Anthropic). Reading only the
|
|
2381
|
-
// Anthropic spelling recorded cacheRead: 0 for every DeepSeek
|
|
2382
|
-
// turn, which priced the whole prompt at the miss rate.
|
|
2383
|
-
...usageBuckets(usage),
|
|
2384
|
-
...(settled != null ? { costUsd: settled } : {}),
|
|
2385
|
-
}
|
|
2386
|
-
: settled != null
|
|
2387
|
-
? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, costUsd: settled }
|
|
2388
|
-
: null,
|
|
2389
|
-
});
|
|
2390
|
-
snapshotCheckpoint(commandCtx.sessionId, transcript);
|
|
2391
|
-
} catch {
|
|
2392
|
-
/* persistence is best-effort */
|
|
2393
|
-
}
|
|
2394
|
-
// Auto-sync hook: one place, reached by both the linear REPL and the
|
|
2395
|
-
// chatflow's session loop. On by default — a push is billed against the
|
|
2396
|
-
// plan's synced-token ceiling (aegis1 charges the *growth* of a session),
|
|
2397
|
-
// so it is a real gate rather than an unconditional write, but the default
|
|
2398
|
-
// is on because a session that dies at its tool-round horizon is only
|
|
2399
|
-
// recoverable if the transcript exists somewhere the next session can read
|
|
2400
|
-
// it. `/cloud memory off` is the opt-out.
|
|
2401
|
-
if (cloudSyncEnabled()) autoSync();
|
|
2402
|
-
}
|
|
2403
|
-
|
|
2404
|
-
/**
|
|
2405
|
-
* Push after a turn, in the background.
|
|
2406
|
-
*
|
|
2407
|
-
* Deliberately not awaited and deliberately quiet on success: this runs after
|
|
2408
|
-
* every turn, and a line per turn would be noise. Failures are reported once
|
|
2409
|
-
* per session per session-cycle — a quota refusal that repeats forever is a
|
|
2410
|
-
* wall of text, not information — and never thrown, because the user's turn
|
|
2411
|
-
* already succeeded by the time this runs.
|
|
2412
|
-
*
|
|
2413
|
-
* The quota refusal gets its own sentence, and it is the whole point of the
|
|
2414
|
-
* default flip being safe: past the plan's ceiling the account does NOT lose
|
|
2415
|
-
* anything it already stored (reads keep working — aegis1 meters writes
|
|
2416
|
-
* only), and the failure is not "sync failed", it is "there is no room left
|
|
2417
|
-
* for new writes". Saying which half stopped is what keeps a silent stop from
|
|
2418
|
-
* looking like a broken feature.
|
|
2419
|
-
*/
|
|
2420
|
-
let autoSyncNotes = new Set();
|
|
2421
|
-
function autoSync() {
|
|
2422
|
-
if (!client.apiKey) return;
|
|
2423
|
-
Promise.resolve()
|
|
2424
|
-
.then(() => cloudsync.push(client))
|
|
2425
|
-
.then((res) => {
|
|
2426
|
-
if (res && res.failed && res.failed.length) {
|
|
2427
|
-
const f = res.failed[0];
|
|
2428
|
-
if (autoSyncNotes.has(f.kind)) return;
|
|
2429
|
-
autoSyncNotes.add(f.kind);
|
|
2430
|
-
if (f.kind === 'quota') {
|
|
2431
|
-
emit(
|
|
2432
|
-
render.renderNotice(
|
|
2433
|
-
ctx(),
|
|
2434
|
-
'warn',
|
|
2435
|
-
`cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying.`
|
|
2436
|
-
)
|
|
2437
|
-
);
|
|
2438
|
-
return;
|
|
2439
|
-
}
|
|
2440
|
-
const hint = f.hint ? ` — ${f.hint}` : '';
|
|
2441
|
-
emit(render.renderNotice(ctx(), 'error', `cloud sync: ${f.message}${hint}`));
|
|
2442
|
-
}
|
|
2443
|
-
})
|
|
2444
|
-
.catch(() => {
|
|
2445
|
-
/* offline is not worth interrupting a session over */
|
|
2446
|
-
});
|
|
2447
|
-
}
|
|
2448
|
-
|
|
2449
|
-
/**
|
|
2450
|
-
* First-run notice for the write half, printed once, right after onboarding.
|
|
2451
|
-
*
|
|
2452
|
-
* The default flip is invisible otherwise: the read half was already on for
|
|
2453
|
-
* everyone, so nothing about the first session looks different — the thing
|
|
2454
|
-
* that changed is that the transcript is now being *stored*, and that costs
|
|
2455
|
-
* quota on a free plan. One line at the moment the account is set up is the
|
|
2456
|
-
* difference between a default and a surprise.
|
|
2457
|
-
*/
|
|
2458
|
-
function memoryFirstRunNotice() {
|
|
2459
|
-
const st = cloudSyncState();
|
|
2460
|
-
if (!st.enabled) {
|
|
2461
|
-
emit(
|
|
2462
|
-
render.renderNotice(
|
|
2463
|
-
ctx(),
|
|
2464
|
-
'info',
|
|
2465
|
-
'cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later'
|
|
2466
|
-
)
|
|
2467
|
-
);
|
|
2468
|
-
return;
|
|
2469
|
-
}
|
|
2470
|
-
const quota = cloudsync.status().quota;
|
|
2471
|
-
const usage = quota && quota.limit ? ` (used ${fmtTokens(quota.used || 0)} of ${fmtTokens(quota.limit)} tokens)` : '';
|
|
2472
|
-
emit(
|
|
2473
|
-
render.renderNotice(
|
|
2474
|
-
ctx(),
|
|
2475
|
-
'info',
|
|
2476
|
-
`cross-session memory: on${usage} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`
|
|
2477
|
-
)
|
|
2478
|
-
);
|
|
2479
|
-
}
|
|
2480
|
-
|
|
2481
|
-
/** One line of session accounting, for ctrl+t and the meta row. */ function tokenSummary() {
|
|
2482
|
-
// Output only, the same rule as the meta row this lands in (see format.js's
|
|
2483
|
-
// `fmtUsageSplit`): the input half is the prompt restated and the one figure
|
|
2484
|
-
// a reader cannot act on. A session that recorded no output figure at all
|
|
2485
|
-
// falls back to its total, because stating what was measured beats stating
|
|
2486
|
-
// nothing — and `0 tokens` is refused for the reason `fmtRoll` refuses
|
|
2487
|
-
// `0 tokens`: it states a figure the provider never reported. The label is
|
|
2488
|
-
// `tokens`, the word `fmtUsageSplit` puts on the same figure in the meta row
|
|
2489
|
-
// this shares a slot with: `in`/`out` is a status-line shorthand of this
|
|
2490
|
-
// CLI's own invention, and a reader who has to be told it reads `out` as
|
|
2491
|
-
// something dropped.
|
|
2492
|
-
const produced = session.outputTokens > 0
|
|
2493
|
-
? `${fmtTokens(session.outputTokens)} tokens`
|
|
2494
|
-
: `${fmtTokens(session.tokens)} tokens`;
|
|
2495
|
-
// Tokens and calls always; money only on a tier AEGIS PROVES a fee is owed
|
|
2496
|
-
// to. Same rule as the meta row and the desktop's topbar roll
|
|
2497
|
-
// (`feeBillable`) — on Unlimited or a welcome trial there is no per-turn
|
|
2498
|
-
// charge and no bank draw, so a `€0.0031` and a `balance` figure here would
|
|
2499
|
-
// be two prices for a session that has none.
|
|
2500
|
-
const parts = [produced, `${session.calls} call${session.calls === 1 ? '' : 's'}`];
|
|
2501
|
-
if (feeBillable()) {
|
|
2502
|
-
parts.push(fmtEur(session.cost));
|
|
2503
|
-
if (session.balance != null) parts.push(`balance ${fmtEur(session.balance)}`);
|
|
2504
|
-
}
|
|
2505
|
-
return parts.join(' · ');
|
|
2506
|
-
}
|
|
2507
|
-
|
|
2508
|
-
/** Load a stored session back into the live transcript. */
|
|
2509
|
-
async function resumeSession(item) {
|
|
2510
|
-
if (!item || !item.id) return;
|
|
2511
|
-
const rows = readSessionTranscript(item.id);
|
|
2512
|
-
if (!rows.length) {
|
|
2513
|
-
emit(render.renderNotice(ctx(), 'warn', `no stored turns for ${item.id}`));
|
|
2514
|
-
return;
|
|
2515
|
-
}
|
|
2516
|
-
// Replace, rather than append: "resume" means continue THIS conversation,
|
|
2517
|
-
// and appending would put two sessions' turns in one context window.
|
|
2518
|
-
transcript.length = 0;
|
|
2519
|
-
for (const r of rows) transcript.push(r);
|
|
2520
|
-
commandCtx.sessionId = item.id;
|
|
2521
|
-
emit(render.renderNotice(ctx(), 'ok', `resumed ${item.id} — ${rows.length} turn(s)`));
|
|
2522
|
-
}
|
|
2523
|
-
|
|
2524
|
-
/**
|
|
2525
|
-
* The host the chatflow drives. Everything the loop needs from the app, with
|
|
2526
|
-
* no layering of its own — the loop owns the frame and the keys, this owns
|
|
2527
|
-
* the transport, the tools, the command table and the tallies.
|
|
2528
|
-
*/
|
|
2529
|
-
function makeHost() {
|
|
2530
|
-
return {
|
|
2531
|
-
ctx: commandCtx,
|
|
2532
|
-
version: VERSION,
|
|
2533
|
-
transcript,
|
|
2534
|
-
session,
|
|
2535
|
-
client,
|
|
2536
|
-
TOOLS,
|
|
2537
|
-
ask: (prompt, o) => ask(prompt, o),
|
|
2538
|
-
makeCommandContext: () => makeCommandContext(),
|
|
2539
|
-
// The two stores that are NOT `~/.aegiscode/.env`, which the picker's key
|
|
2540
|
-
// queue has to consult before it may ask for a key that is already saved
|
|
2541
|
-
// somewhere both hosts read:
|
|
2542
|
-
// - `accountConfigured` — the AEGIS account key in credentials.json,
|
|
2543
|
-
// written by /key and by `aegiscode login`.
|
|
2544
|
-
// - `hasProviderKey(p)` — a `byok:<provider>` row, the store /byok-key
|
|
2545
|
-
// and the desktop's Provider settings share (engine.js byokNamespace).
|
|
2546
|
-
// Without these two the picker would re-prompt for a key the machine
|
|
2547
|
-
// demonstrably holds, which is how the same key got saved twice.
|
|
2548
|
-
accountConfigured: () => !!(credentials.keyStatus() || {}).configured,
|
|
2549
|
-
// `get()` is the MASKED read — it returns {provider, baseURL, configured,
|
|
2550
|
-
// keyMask} and never carries a `.key` field. Reading `row.key` here made
|
|
2551
|
-
// this predicate permanently false, so the picker re-prompted for a key
|
|
2552
|
-
// the machine demonstrably held: the exact bug the comment above says it
|
|
2553
|
-
// exists to prevent. `rawKey()` is the reader that returns the plaintext;
|
|
2554
|
-
// `configured` is the fallback for a store that offers only `get()`.
|
|
2555
|
-
hasProviderKey: (provider) => {
|
|
2556
|
-
const store = engine.settings;
|
|
2557
|
-
if (!store || !provider) return false;
|
|
2558
|
-
const row = byokNamespace(provider);
|
|
2559
|
-
if (typeof store.rawKey === 'function') {
|
|
2560
|
-
return !!String(store.rawKey(row) || '').trim();
|
|
2561
|
-
}
|
|
2562
|
-
if (typeof store.get !== 'function') return false;
|
|
2563
|
-
return !!((store.get(row) || {}).configured);
|
|
2564
|
-
},
|
|
2565
|
-
loadModels: (o) => loadModels(o),
|
|
2566
|
-
buildState: () => buildState(),
|
|
2567
|
-
dispatchLine: (line, c) => handleLine(line, c),
|
|
2568
|
-
refreshSpend: () => refreshSpend(),
|
|
2569
|
-
updateConfig: (patch) => updateConfig(patch),
|
|
2570
|
-
showThemePicker: () => showThemePicker(),
|
|
2571
|
-
// `costEur` MUST be forwarded. chatflow's session loop passes the settled
|
|
2572
|
-
// charge as its fourth argument, and this binding used to accept only
|
|
2573
|
-
// three — so the argument was dropped, persistTurn fell back to
|
|
2574
|
-
// costEur = null, and every interactive turn was written to
|
|
2575
|
-
// history.jsonl with no charge attached. /cost then recomputed each of
|
|
2576
|
-
// them from the local rate table (no pool margin, no prompt-cache
|
|
2577
|
-
// discount) and reported a number the customer never paid. The parameter
|
|
2578
|
-
// is the whole reason the ledger is consulted before persisting.
|
|
2579
|
-
persistTurn: (prompt, res, status, costEur) => persistTurn(prompt, res, status, costEur),
|
|
2580
|
-
nameConversation: (prompt, o) => nameConversation(prompt, o),
|
|
2581
|
-
visibleCommands: () => visibleCommands(),
|
|
2582
|
-
tokensFor: (usage) => usageTokens(usage),
|
|
2583
|
-
recordTurn: (res) => recordTurn(res),
|
|
2584
|
-
tokenSummary: () => tokenSummary(),
|
|
2585
|
-
resumeSession: (item) => resumeSession(item),
|
|
2586
|
-
requestExit: () => {
|
|
2587
|
-
wantExit = true;
|
|
2588
|
-
},
|
|
2589
|
-
wantsExit: () => wantExit,
|
|
2590
|
-
keyNotice: () => (client.apiKey ? '' : keyFailure),
|
|
2591
|
-
isYolo: () => {
|
|
2592
|
-
// Both halves, in the order the desktop host reads them
|
|
2593
|
-
// (main.js autoRoundsOn): "this session runs auto mode" AND "the
|
|
2594
|
-
// stored posture says don't ask". The first is the session flag above
|
|
2595
|
-
// — `AEGIS_AUTO_ROUNDS=0` starts manual, and `/automode on` (or the
|
|
2596
|
-
// `→` chord, which dispatches exactly that) turns it back on.
|
|
2597
|
-
if (!autoRoundsSession) return false;
|
|
2598
|
-
try {
|
|
2599
|
-
// The posture, not the rule file: since ON8 the window's switch is the
|
|
2600
|
-
// same fact, so a switch turned off there lights this chip too.
|
|
2601
|
-
return confirmPosture().enabled === false;
|
|
2602
|
-
} catch {
|
|
2603
|
-
return false;
|
|
2604
|
-
}
|
|
2605
|
-
},
|
|
2606
|
-
// `/automode on|off` moves the session flag the predicate above reads, so
|
|
2607
|
-
// the command and the chip can never disagree — and an env opt-out is
|
|
2608
|
-
// escapable at the prompt instead of for the life of the process.
|
|
2609
|
-
setAutoRounds: (v) => {
|
|
2610
|
-
autoRoundsSession = Boolean(v);
|
|
2611
|
-
},
|
|
2612
|
-
};
|
|
2613
|
-
}
|
|
2614
|
-
|
|
2615
|
-
/** The plain (non-alt-screen) REPL: readline, one turn written to scrollback. */
|
|
2616
|
-
async function runLinearRepl() {
|
|
2617
|
-
emit(bannerLines());
|
|
2618
|
-
await refreshSpend();
|
|
2619
|
-
out.write('\n');
|
|
2620
|
-
|
|
2621
|
-
const rl = options.readline || readline.createInterface({ input: process.stdin, output: out, terminal: true });
|
|
2622
|
-
const promptStr = themeOf(ctx()).gold + GLYPH.cursor + ' ' + RESET;
|
|
2623
|
-
rl.setPrompt(promptStr);
|
|
2624
|
-
rl.prompt();
|
|
2625
|
-
|
|
2626
|
-
return new Promise((resolve) => {
|
|
2627
|
-
rl.on('line', async (line) => {
|
|
2628
|
-
rl.pause();
|
|
2629
|
-
let keep = true;
|
|
2630
|
-
try {
|
|
2631
|
-
keep = await handleLine(line);
|
|
2632
|
-
} catch (e) {
|
|
2633
|
-
emit(render.renderNotice(ctx(), 'error', e.message));
|
|
2634
|
-
}
|
|
2635
|
-
if (!keep || wantExit) {
|
|
2636
|
-
closed = true;
|
|
2637
|
-
rl.close();
|
|
2638
|
-
return;
|
|
2639
|
-
}
|
|
2640
|
-
rl.resume();
|
|
2641
|
-
rl.prompt();
|
|
2642
|
-
});
|
|
2643
|
-
rl.on('close', () => {
|
|
2644
|
-
if (!closed) out.write('\n');
|
|
2645
|
-
resolve(0);
|
|
2646
|
-
});
|
|
2647
|
-
});
|
|
2648
|
-
}
|
|
2649
|
-
|
|
2650
|
-
/**
|
|
2651
|
-
* Restore persisted preferences into the live context. The reference does this
|
|
2652
|
-
* at startup (`main.js:290-296`); this client never called `loadConfig()` on
|
|
2653
|
-
* launch at all, so a model or effort chosen in a previous session was written
|
|
2654
|
-
* to disk and then ignored on the next run.
|
|
2655
|
-
*
|
|
2656
|
-
* An explicit CLI flag always wins over the stored value — `aegiscode -m x`
|
|
2657
|
-
* must mean `x`, not "x unless the config disagrees".
|
|
2658
|
-
*/
|
|
2659
|
-
function restorePrefs() {
|
|
2660
|
-
// An embedded/injected readline is a programmatic caller: it gets a
|
|
2661
|
-
// deterministic context rather than whatever happens to be on disk.
|
|
2662
|
-
if (options.readline) return;
|
|
2663
|
-
// A fresh install has no expressed preference to restore. Applying
|
|
2664
|
-
// DEFAULT_CONFIG here would silently pin the user to a model they never
|
|
2665
|
-
// chose, which is the opposite of "remember what I picked".
|
|
2666
|
-
if (!configExists()) return;
|
|
2667
|
-
let cfg;
|
|
2668
|
-
try {
|
|
2669
|
-
cfg = loadConfig();
|
|
2670
|
-
} catch {
|
|
2671
|
-
return;
|
|
2672
|
-
}
|
|
2673
|
-
// The class first: a stored BYOK pin is only meaningful under byok, and the
|
|
2674
|
-
// pin check right after this reads whichever class won.
|
|
2675
|
-
//
|
|
2676
|
-
// Gated on the OFFERED set, not HOST_CLASSES: a config written while `pro`
|
|
2677
|
-
// was enabled must not restore a subscription session onto a machine where
|
|
2678
|
-
// it has been turned off, or where this install never opted in. Such a
|
|
2679
|
-
// stored value falls back to the live default rather than being trusted.
|
|
2680
|
-
if (selectableClasses().includes(cfg.modelClass)) commandCtx.modelClass = cfg.modelClass;
|
|
2681
|
-
// A `--class` flag outranks the stored pin, the same way `--model` outranks
|
|
2682
|
-
// `cfg.model` on the next line. Clamped to the OFFERED set for the reason
|
|
2683
|
-
// the restore above is: a class this host cannot run (or `pro` on an install
|
|
2684
|
-
// that never opted in) must not be honoured just because it was typed.
|
|
2685
|
-
// An unknown or unoffered value is refused rather than silently downgraded
|
|
2686
|
-
// to the pooled route — a headless turn that asked for byok and got billed
|
|
2687
|
-
// to the pool is the exact defect this flag exists to fix.
|
|
2688
|
-
if (opts.class) {
|
|
2689
|
-
const want = String(opts.class).trim().toLowerCase();
|
|
2690
|
-
if (!selectableClasses().includes(want)) {
|
|
2691
|
-
throw new Error(
|
|
2692
|
-
`--class ${opts.class}: not available on this host (offered: ${selectableClasses().join(', ')})`
|
|
2693
|
-
);
|
|
2694
|
-
}
|
|
2695
|
-
commandCtx.modelClass = want;
|
|
2696
|
-
}
|
|
2697
|
-
if (!opts.model && cfg.model) commandCtx.model = cfg.model;
|
|
2698
|
-
// Restored through effortRung(), so a config written by an older build is
|
|
2699
|
-
// never a value this one does not send: `null`, `''` and the retired
|
|
2700
|
-
// `'auto'` all come back as 'high' — the same rung the request would have
|
|
2701
|
-
// carried had the key been missing from the file entirely.
|
|
2702
|
-
commandCtx.effort = effortRung(cfg.effort);
|
|
2703
|
-
if (typeof cfg.vim === 'boolean') commandCtx.vim = cfg.vim;
|
|
2704
|
-
if (cfg.lastRecap) commandCtx.lastRecap = cfg.lastRecap;
|
|
2705
|
-
// THEME_TABLE lives in theme.js, not screens.js: reading it off the screens
|
|
2706
|
-
// module yielded undefined, and only on a *second* launch (the first has no
|
|
2707
|
-
// config to restore, so this branch never ran) — so the very first run
|
|
2708
|
-
// appeared to work and every run after it died on startup.
|
|
2709
|
-
if (!opts.light && typeof cfg.themeIndex === 'number' && THEME_TABLE[cfg.themeIndex]) {
|
|
2710
|
-
commandCtx.themeIndex = cfg.themeIndex;
|
|
2711
|
-
// `themeIsLight` and not `row.light`: row 0's own flag is the dark
|
|
2712
|
-
// fallback, and reading it directly is what pinned a light-terminal user
|
|
2713
|
-
// back to the dark palette on every launch after they chose "Auto".
|
|
2714
|
-
commandCtx.light = themeIsLight(cfg.themeIndex);
|
|
2715
|
-
// A stored row is a preference about a *terminal*, and the terminal it
|
|
2716
|
-
// was chosen on need not be the one it is being restored on. Row 2 is
|
|
2717
|
-
// "Light mode" — primary text `RGB(40,40,40)` — and restoring it onto a
|
|
2718
|
-
// dark terminal drew that text over `#1e1e2e`: contrast 1.11:1, a body of
|
|
2719
|
-
// text present and unreadable. Reading the row as a bare brightness (what
|
|
2720
|
-
// this line did before) is why nothing ever checked. The stored value is
|
|
2721
|
-
// left untouched: the correction belongs to this terminal, and moving
|
|
2722
|
-
// back to a light one restores the choice by itself.
|
|
2723
|
-
const fixed = reconcileThemeIndex(commandCtx.themeIndex);
|
|
2724
|
-
if (fixed.changed) {
|
|
2725
|
-
commandCtx.themeIndex = fixed.index;
|
|
2726
|
-
commandCtx.light = themeIsLight(fixed.index);
|
|
2727
|
-
commandCtx.themeNotice = fixed.reason;
|
|
2728
|
-
// And it is written back. The stored row is a choice that THIS terminal
|
|
2729
|
-
// cannot satisfy, so leaving it on disk would mean the correction is
|
|
2730
|
-
// re-applied — and re-announced — on every launch forever, with the
|
|
2731
|
-
// config asserting a preference the session never honours. `/theme`
|
|
2732
|
-
// still sets it, and the announcement says which value was saved, so
|
|
2733
|
-
// the file and the screen never disagree silently.
|
|
2734
|
-
try {
|
|
2735
|
-
updateConfig({ themeIndex: fixed.index, light: themeIsLight(fixed.index) });
|
|
2736
|
-
} catch {
|
|
2737
|
-
// An unwritable config is not a reason to draw unreadable text: the
|
|
2738
|
-
// in-memory correction above already applies, and the notice says so.
|
|
2739
|
-
commandCtx.themeNotice += ' (could not save it)';
|
|
2740
|
-
}
|
|
2741
|
-
}
|
|
2742
|
-
}
|
|
2743
|
-
}
|
|
2744
|
-
|
|
2745
|
-
/**
|
|
2746
|
-
* Say the stored theme was corrected for this terminal, once, on a real
|
|
2747
|
-
* screen. Emitted before the session takes the alternate screen so it lands
|
|
2748
|
-
* in scrollback rather than being wiped by the session's first frame, and
|
|
2749
|
-
* only when the correction actually happened — an unasked-for notice about an
|
|
2750
|
-
* unchanged setting is noise.
|
|
2751
|
-
*/
|
|
2752
|
-
function themeNoticeFirstRun() {
|
|
2753
|
-
if (!commandCtx.themeNotice) return;
|
|
2754
|
-
const reason = commandCtx.themeNotice;
|
|
2755
|
-
commandCtx.themeNotice = '';
|
|
2756
|
-
emit(render.renderNotice(ctx(), 'warn', `theme: ${reason} (saved)`));
|
|
2757
|
-
}
|
|
2758
|
-
|
|
2759
|
-
/**
|
|
2760
|
-
* Interactive entry point. On a real terminal this is the full chatflow
|
|
2761
|
-
* (alternate screen, header, transcript viewport, spinner, effort line,
|
|
2762
|
-
* input line, status line, overlays). Anywhere else — a pipe, a test with an
|
|
2763
|
-
* injected readline, `--print` — it stays the linear loop, so output remains
|
|
2764
|
-
* pipeable and scriptable.
|
|
2765
|
-
*/
|
|
2766
|
-
/**
|
|
2767
|
-
* Interactive session: the loop itself (`runInteractiveSession`), then the
|
|
2768
|
-
* local lane handed back. Wrapped for the same reason `runOnce` is: the loop
|
|
2769
|
-
* has several exits (a declined onboarding, `/quit`, a reset key stream, the
|
|
2770
|
-
* linear REPL), and "closing the session closes the model" must hold on all
|
|
2771
|
-
* of them rather than on the one path a `return` happens to reach.
|
|
2772
|
-
*/
|
|
2773
|
-
async function runInteractive() {
|
|
2774
|
-
try {
|
|
2775
|
-
return await runInteractiveSession();
|
|
2776
|
-
} finally {
|
|
2777
|
-
await releaseLocalModel();
|
|
2778
|
-
}
|
|
2779
|
-
}
|
|
2780
|
-
|
|
2781
|
-
async function runInteractiveSession() {
|
|
2782
|
-
const tty =
|
|
2783
|
-
!options.readline &&
|
|
2784
|
-
options.chatflow !== false &&
|
|
2785
|
-
process.stdin.isTTY &&
|
|
2786
|
-
process.stdout.isTTY;
|
|
2787
|
-
if (tty) {
|
|
2788
|
-
// Ask the terminal what its background is BEFORE the stored theme is
|
|
2789
|
-
// restored, because the restore is a decision *about that background*.
|
|
2790
|
-
// Nothing in the environment answers this on the terminals people run —
|
|
2791
|
-
// Alacritty sets neither `COLORFGBG` nor `TERM_BACKGROUND` — so without
|
|
2792
|
-
// the query the palette was chosen from silence. Bounded (120ms) and
|
|
2793
|
-
// skipped entirely when an env var already decided, so a session that
|
|
2794
|
-
// reports nothing is as fast as it was.
|
|
2795
|
-
//
|
|
2796
|
-
// A keypress can race the terminal's answer into the same read, so any
|
|
2797
|
-
// byte that was not the answer is handed back to the key pump's own queue
|
|
2798
|
-
// rather than to the stream: `events.feedKeys` delivers it exactly as a
|
|
2799
|
-
// `data` event would have, including after stdin has ended.
|
|
2800
|
-
// `keystrokes: true` matters. The probe hands back a whole burst, and a
|
|
2801
|
-
// command issued at launch (`/exit\r`) arrives as one string containing a
|
|
2802
|
-
// newline — which the paste heuristic would otherwise collapse into a
|
|
2803
|
-
// single paste key, losing the Enter and parking the session loop forever
|
|
2804
|
-
// at the welcome screen. See `events.feedKeys`.
|
|
2805
|
-
await probeTerminalBackground({
|
|
2806
|
-
onLeftover: (text) => events.feedKeys(text, { keystrokes: true }),
|
|
2807
|
-
});
|
|
2808
|
-
restorePrefs();
|
|
2809
|
-
themeNoticeFirstRun();
|
|
2810
|
-
adoptLegacyKeyOnce();
|
|
2811
|
-
// Give aegis1 a chance to auto-provision a free device key BEFORE
|
|
2812
|
-
// deciding whether onboarding needs to ask for one — a fresh install
|
|
2813
|
-
// should never be prompted for a key it can get on its own.
|
|
2814
|
-
if (!client.apiKey) await ensureApiKey();
|
|
2815
|
-
// Onboarding runs in the normal buffer, before the session takes the
|
|
2816
|
-
// alternate screen — the reference's order. A declined trust check must
|
|
2817
|
-
// abort: the reference returns without ever reaching `session(ctx)`.
|
|
2818
|
-
const onboard = await screens.runOnboarding(commandCtx, {
|
|
2819
|
-
continue: !!options.continue,
|
|
2820
|
-
seen: options.seen || configExists,
|
|
2821
|
-
save: (patch) => updateConfig(patch),
|
|
2822
|
-
// With no key the session can do nothing, so ask for it here where the
|
|
2823
|
-
// user is already answering questions — verified on submit, and saved
|
|
2824
|
-
// 0600 so the next launch (and every script) has it.
|
|
2825
|
-
needsKey: () => !client.apiKey,
|
|
2826
|
-
submitKey: (key) => setApiKey(key),
|
|
2827
|
-
});
|
|
2828
|
-
if (!onboard.ok) return 0;
|
|
2829
|
-
if (onboard.key && onboard.key.set) {
|
|
2830
|
-
emit(
|
|
2831
|
-
render.renderNotice(
|
|
2832
|
-
ctx(),
|
|
2833
|
-
'info',
|
|
2834
|
-
`key saved to ${credentials.credentialsPath()} — no export needed from now on`
|
|
2835
|
-
)
|
|
2836
|
-
);
|
|
2837
|
-
}
|
|
2838
|
-
if (onboard.key && onboard.key.skipped && !client.apiKey) {
|
|
2839
|
-
emit(
|
|
2840
|
-
render.renderNotice(
|
|
2841
|
-
ctx(),
|
|
2842
|
-
'warn',
|
|
2843
|
-
`no key saved — /key <api_key> or \`aegiscode login\` whenever you are ready`
|
|
2844
|
-
)
|
|
2845
|
-
);
|
|
2846
|
-
}
|
|
2847
|
-
// The write half of cross-session memory is on by default (see
|
|
2848
|
-
// config.js). Say so once, on the run that sets the account up, together
|
|
2849
|
-
// with the ceiling and the opt-out — a default nobody is told about is a
|
|
2850
|
-
// setting they cannot make a decision about.
|
|
2851
|
-
if (onboard.firstRun) memoryFirstRunNotice();
|
|
2852
|
-
// A stored pin the platform does not advertise routes elsewhere in
|
|
2853
|
-
// silence (see validatePinnedModel) — checked once, here, where the user
|
|
2854
|
-
// can act on it. Not on `-p`: a network round-trip ahead of the first
|
|
2855
|
-
// token would be a startup cost bought for a warning no script watches.
|
|
2856
|
-
await validatePinnedModel();
|
|
2857
|
-
// `--continue` must load the last session *before* the loop starts, and
|
|
2858
|
-
// it has to be read here rather than captured at construction: the
|
|
2859
|
-
// history file is written by the loop itself.
|
|
2860
|
-
if (options.continue) {
|
|
2861
|
-
const last = readOwnSessions(1)[0];
|
|
2862
|
-
if (last) {
|
|
2863
|
-
commandCtx.continueSession = last.id;
|
|
2864
|
-
await resumeSession({ id: last.id });
|
|
2865
|
-
}
|
|
2866
|
-
}
|
|
2867
|
-
// Snapshot the account's ledger before the loop's first billed turn, so
|
|
2868
|
-
// the session tally cannot absorb the customer's existing spend and the
|
|
2869
|
-
// first turn's charge is not mistaken for pre-existing history.
|
|
2870
|
-
await refreshSpend();
|
|
2871
|
-
await chatflow.runSession(makeHost());
|
|
2872
|
-
return 0;
|
|
2873
|
-
}
|
|
2874
|
-
restorePrefs();
|
|
2875
|
-
adoptLegacyKeyOnce();
|
|
2876
|
-
return runLinearRepl();
|
|
2877
|
-
}
|
|
2878
|
-
|
|
2879
|
-
return {
|
|
2880
|
-
opts,
|
|
2881
|
-
session,
|
|
2882
|
-
client,
|
|
2883
|
-
TOOLS,
|
|
2884
|
-
toolList,
|
|
2885
|
-
ctx: commandCtx,
|
|
2886
|
-
transcript,
|
|
2887
|
-
ask,
|
|
2888
|
-
runPrompt,
|
|
2889
|
-
handleLine,
|
|
2890
|
-
runOnce,
|
|
2891
|
-
runInteractive,
|
|
2892
|
-
runLinearRepl,
|
|
2893
|
-
refreshSpend,
|
|
2894
|
-
bannerLines,
|
|
2895
|
-
makeHost,
|
|
2896
|
-
loadModels,
|
|
2897
|
-
validatePinnedModel,
|
|
2898
|
-
recordTurn,
|
|
2899
|
-
persistTurn,
|
|
2900
|
-
restorePrefs,
|
|
2901
|
-
setApiKey,
|
|
2902
|
-
forgetApiKey,
|
|
2903
|
-
adoptLegacyKeyOnce,
|
|
2904
|
-
cloudSyncEnabled,
|
|
2905
|
-
cloudSyncState,
|
|
2906
|
-
setCloudSync,
|
|
2907
|
-
cloudsync,
|
|
2908
|
-
keyStatus: () => credentials.keyStatus(),
|
|
2909
|
-
accountConfigured: () => !!(credentials.keyStatus() || {}).configured,
|
|
2910
|
-
// Same masked-read defect as the host binding above — see the comment
|
|
2911
|
-
// there. Kept identical so the two hosts cannot disagree about whether a
|
|
2912
|
-
// key is stored.
|
|
2913
|
-
hasProviderKey: (provider) => {
|
|
2914
|
-
const store = engine.settings;
|
|
2915
|
-
if (!store || !provider) return false;
|
|
2916
|
-
const row = byokNamespace(provider);
|
|
2917
|
-
if (typeof store.rawKey === 'function') {
|
|
2918
|
-
return !!String(store.rawKey(row) || '').trim();
|
|
2919
|
-
}
|
|
2920
|
-
if (typeof store.get !== 'function') return false;
|
|
2921
|
-
return !!((store.get(row) || {}).configured);
|
|
2922
|
-
},
|
|
2923
|
-
sessionId: () => commandCtx.sessionId,
|
|
2924
|
-
tokenSummary,
|
|
2925
|
-
resumeSession,
|
|
2926
|
-
makeCommandContext,
|
|
2927
|
-
buildState,
|
|
2928
|
-
get aborted() {
|
|
2929
|
-
return false;
|
|
2930
|
-
},
|
|
2931
|
-
};
|
|
2932
|
-
}
|
|
2933
|
-
|
|
2934
|
-
module.exports = { createApp, VERSION, normalizeDecision };
|
|
3
|
+
const e=require("node:readline"),t=require("node:os"),{randomUUID:n}=require("node:crypto"),{createTools:r,createClient:o,usageTokens:s,usageBuckets:i,buildSystemPrompt:a,autoProvisionApiKey:l,provisionFailureText:c,trialNote:u,hostEnv:d,autonomous:m,claudePro:f}=require("./deps.js"),{createEngine:p,HOST_CLASSES:y,DEFAULT_CLASS:h,byokNamespace:g,effortRung:k,offeredClasses:w,proEnabled:v}=require("./engine.js"),{GLYPH:b,VERBS:S,themeOf:T,RESET:C,THEME_TABLE:x,AUTO_THEME_INDEX:N,themeIsLight:I,reconcileThemeIndex:$}=require("./theme.js"),{probeTerminalBackground:E}=require("./caps.js"),{LiveRegion:A,termWidth:M,w:L}=require("./screen.js"),{estimateTokensFromCells:O}=require("./tokens.js"),{editPreview:P}=require("./diff.js"),{defaultOpen:K}=require("./diffview.js"),{parseLine:_,COMMANDS:j,visibleCommands:q}=require("./commands.js"),{updateConfig:R,loadPermissions:D,loadConfig:B,configExists:W,memoryPersistState:Y,memoryPersistEnabled:F,setMemoryPersist:H,confirmPosture:U}=require("./config.js"),G=require("./credentials.js"),z=require("./events.js"),J=require("./cloudsync.js"),{readSecret:V}=require("./secret.js"),{normalizeModelCatalog:Q,pickerEntries:X,catalogIds:Z}=require("./models.js"),{appendHistory:ee,readSessionTranscript:te,readOwnSessions:ne,setSessionTitle:re}=require("./history.js"),oe=require("./naming.js"),{snapshotCheckpoint:se}=require("./checkpoint.js"),ie=require("./screens.js"),ae=require("./chatflow.js"),le=require("./overlays.js"),ce=require("./render.js"),{fmtTokens:ue,fmtEur:de,maskKey:me,feeBillable:fe}=require("./format.js"),{resolveSkip:pe}=require("./permissions.js"),ye=require("../package.json").version;let he=null;function ge(){if(null===he)try{he=a(d({},{},null))}catch{he=""}return he||void 0}function ke(e){const t="string"==typeof e?e.trim().toLowerCase():"";return"session"===t?"session":"once"===t||"allow"===t||"yes"===t||"approve"===t||"approved"===t?"once":"deny"}const we=Object.freeze([/^invalid api key\b/i,/^fix external api key\b/i,/^you've hit your session limit\b/i,/^you have hit your session limit\b/i,/^provider request timed out\b/i,/^insufficient (?:credit|balance|quota)\b/i,/^rate limit(?:ed)?\b/i,/^unauthorized\b/i]);function ve(e){let t;try{t="string"==typeof e?e:JSON.stringify(e??"")}catch{t=String(e)}return t=String(t).replace(/\s+/g," ").trim(),t.length>140?`${t.slice(0,137)}...`:t}module.exports={createApp:function(a={}){const d={model:null,stream:!0,light:!1,maxTokens:void 0,system:void 0,interactive:!0,...a},he=a.out||process.stdout,be=a.err||process.stderr,Se=a.client||o(G.clientOptions({channel:"cli"})),{TOOLS:Te,toolList:Ce}=a.tools||r(Se);let xe=!1,Ne="";async function Ie(){const e=await l(Se,G,{app:"cli"});return Ne=e.key?"":c(e),e}async function $e(){if(Se.apiKey||xe)return;xe=!0;const e=await Ie();e.key&&ct(ce.renderNotice(qe(),"info","auto-provisioned a free account"+(e.ok?` (saved to ${G.credentialsPath()})`:" (could not save it — reconfigure with /key)")+u(e)+`. Fund it at ${Se.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.`))}let Ee=!1!==a.confirmMode,Ae=(()=>{try{return m.autoRoundsDefault(process.env)}catch{return!0}})();const Me=a.engine||p({client:Se,getClass:()=>Ke.modelClass,getProEnabled:()=>{try{return v(B())}catch{return!1}},getConfirmMode:()=>{if(void 0!==a.confirmMode)return Ee;try{const e=pe({env:process.env,interactive:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});if(e.warned&&!skipEnvWarned&&(skipEnvWarned=!0,process.stderr.write(`aegiscode: ${e.warning}\n`)),e.skip)return!1}catch{}try{return U().enabled}catch{return Ee}}}),Le=e=>"function"==typeof Me.classLabel?Me.classLabel(e):String(e||"");let Oe=null;const Pe=()=>a.width?a.width():M(),Ke={light:d.light,model:d.model,modelClass:h,effort:null,thinking:!1,recallDeep:!1,themeIndex:d.light?2:N,vim:!1,stream:d.stream,cwd:process.cwd(),lastRecap:null,sessionId:n()};Ke.themeIndex===N&&(Ke.light=I(N));const _e=[];let je=!1;const qe=()=>({light:Ke.light}),Re={turns:0,calls:0,tokens:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,cost:0,balance:null,seenLedgerRows:new Map,ledgerBaselined:!1,startedAt:Date.now()};let De=null,Be=!1;function We(e){if(!e||"object"!=typeof e)return null;if("usage"!==e.kind)return null;const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6;return Number.isFinite(t)?Math.abs(t):null}function Ye(e){return[e.created_at||"",e.kind||"",null!=e.amount_eur?e.amount_eur:"",null!=e.charged_micros?e.charged_micros:"",null!=e.id?e.id:"",null!=e.note?e.note:""].join("|")}async function Fe(){try{const e=await Se.tokenBankBalance(),t=Number(e.balance_eur);Number.isFinite(t)&&(Re.balance=t);let n=null;const r=Array.isArray(e.ledger)?e.ledger:[],o=new Map;for(const e of r){const t=Ye(e),n=o.get(t);n?n.n+=1:o.set(t,{n:1,row:e})}for(const[e,{n:t,row:r}]of o){const o=Re.seenLedgerRows.get(e)||0;if(Re.seenLedgerRows.set(e,t),!Re.ledgerBaselined)continue;const s=t-o;if(s<=0)continue;const i=We(r);null!=i&&i>0&&(Re.cost+=i*s,null==n&&(n=i))}return Re.ledgerBaselined=!0,{balance:Re.balance,lastCost:n}}catch{return null}}async function He(e,{verify:t=!0}={}){const n=G.saveApiKey(e);if(!n.ok)return n;Se.setApiKey(n.key),Xe.models=[],Xe.at=0;let r=null,o=null;if(t)try{const e=await Se.verifyApiKey()||{};r=e;const t={verifiedAt:(new Date).toISOString()};e.memory_token&&(t.memoryToken=e.memory_token),e.plan&&(t.plan=e.plan),t.account={plan:e.plan||null,email:e.email||null,valid:!1!==e.valid},G.writeCredentials(t),e.plan&&(Re.plan=e.plan),e.email&&(Re.account={...Re.account||{},email:e.email})}catch(e){o=e}return{...n,account:r,error:o}}function Ue(){const e=G.clearApiKey();return Se.setApiKey(""),Xe.models=[],Xe.at=0,e}function Ge(){try{return F()}catch{return!0}}function ze(){try{return Y()}catch{return{enabled:!0,source:"default",explicit:!1}}}function Je(e){return H(e)}function Ve(){try{return"config"!==G.resolveApiKey().source?[]:G.adoptLegacy().adopted}catch{return[]}}const Qe=3e5,Xe={at:0,models:[]},Ze={at:0,models:[],declared:""};async function et({force:e=!1}={}){const t=function(){try{if("function"!=typeof Me.userModels)return"";const e=(Me.userModels()||{}).map||{};return JSON.stringify(Object.keys(e).sort().map((t=>[t,e[t]])))}catch{return""}}(),n=Ze.models.length&&Date.now()-Ze.at<Qe&&t===Ze.declared;if(!e&&n)return Ze.models;if("function"!=typeof Me.listModels)return[];const r=await Me.listModels("byok");return Ze.models=(r&&r.models||[]).map((e=>({...e,note:e.configured?"key on this machine":`no key — /byok-key ${e.provider}`}))),Ze.at=Date.now(),Ze.declared=t,Ze.models}async function tt(e){const t=st();if(e&&!t.includes(e)&&y.includes(e))return[];const n=t.includes(e)?e:Ke.modelClass;try{if("byok"===n){const e=await et();if(!Xe.models.length)try{await it()}catch{}return rt(e,n)}if("pro"===n){const e=await Me.listModels("pro");return e&&e.models||[]}if("aegis"!==n){const e=await Me.listModels(n);return e&&e.models||[]}return await it()}catch{return[]}}function nt(){return X(Xe.models).map((e=>({...e,cls:"aegis"})))}function rt(e,t){const n=st(),r=n.includes(t)?t:Ke.modelClass;if("pro"===t&&!n.includes("pro"))return[];if("pro"===r)return X(f.PRO_MODELS.map((e=>({id:e.id,label:e.label,note:e.note})))).map((e=>({...e,cls:"pro"})));if("byok"!==r)return nt();const o=Array.isArray(e)?e.map((e=>({...e,cls:"byok"}))):X(Ze.models).map((e=>({...e,cls:"byok"})));return[...nt(),...o]}function ot(){return new Set(f.PRO_MODELS.map((e=>String(e.id).toLowerCase())))}function st(){try{return w(v(B()))}catch{return w(!1)}}async function it({force:e=!1}={}){const t=Xe.models.length&&Date.now()-Xe.at<Qe;if(!e&&t)return Xe.models;const n=await Se.listModels();return Xe.models=Q(n&&n.models),Xe.at=Date.now(),Xe.models}async function at(){const e=Ke.model;if(!e)return null;if("byok"===Ke.modelClass)return String(e).includes(":")?null:(Ke.model=null,R({model:null,currentModelId:null}),ct(ce.renderNotice(qe(),"warn",`pinned model "${e}" belongs to the pooled class — on BYOK an id is "<provider>:<model>"; pin cleared, /models lists what this machine can relay.`)),e);if("pro"===Ke.modelClass){if(!ot().has(String(e).toLowerCase()))return Ke.model=null,R({model:null,currentModelId:null}),ct(ce.renderNotice(qe(),"warn",`pinned model "${e}" is not one the Claude Code CLI resolves — pin cleared, the CLI will choose; /models lists the aliases (${f.PRO_MODELS.map((e=>e.id)).join(", ")}).`)),e;let t=!0;try{t=!!f.claudeProStatus({env:process.env}).credentialPresent}catch{t=!0}return t?null:(Ke.model=null,R({model:null,currentModelId:null}),ct(ce.renderNotice(qe(),"warn",`pinned model "${e}" needs a Claude Pro subscription or an ANTHROPIC_API_KEY, and this host has neither — pin cleared. Run \`claude /login\`, export a console key, or \`/class pro off\`.`)),e)}let t;try{t=await it()}catch{return null}return t.length?Z(t).has(String(e).toLowerCase())?null:(Ke.model=null,R({model:null,currentModelId:null}),ct(ce.renderNotice(qe(),"warn",`pinned model "${e}" is not advertised by AEGIS Cloud — pin cleared, the pool will choose; /models lists what you can pin.`)),e):null}function lt(){return ce.renderBanner(qe(),{width:Pe(),version:ye,model:Ke.model||"server default",base:Se.apiBase,key:me(Se.apiKey),stream:Ke.stream})}function ct(e){const t="string"==typeof e?[e]:e;for(const e of t)he.write(e+"\n")}async function ut(e,{history:t=[],presenter:r=null,signal:o=null}={}){const s=Date.now(),i=!r&&d.interactive&&d.stream&&he.isTTY?new A(he):null;let a=0,l=0,c="",u=0,m=0,f=S[Math.floor(Math.random()*S.length)],p=!1,y=!1;const h=()=>{i&&i.update([ce.renderWorking(qe(),{tick:a++,verb:f,elapsedMs:Date.now()-s,streamed:O(l+u)+m,streamedFloor:m>0})])},g=i?setInterval(h,90):null;g&&g.unref&&g.unref(),h();const w=r||{},v=new Map,b=n();De=b;let T=!1;const C=()=>{T=!0,Me.cancel(b)},x=()=>C();process.once("SIGINT",x),o&&(o.aborted?C():o.addEventListener("abort",C,{once:!0}));const N=e=>(be.write(`aegiscode: ${e.tool} needs confirmation but this run has no prompt for it — denied (pass --automode (alias --yolo) to auto-approve mutating tools).\n`),Promise.resolve("deny")),I=()=>Promise.resolve(!1),$=e=>{if(e){if(e.thinkingTokens&&(m+=e.thinkingTokens,p||(p=!0,f="Reasoning"),(e=>{if(w.thinkingTokens)w.thinkingTokens(e)})(e.thinkingTokens),h()),e.reasoning&&(u+=L(e.reasoning),p||(p=!0,f="Reasoning",h()),(e=>{if(w.reasoning)w.reasoning(e)})(e.reasoning)),e.delta&&(l+=L(e.delta),c+=e.delta,(e=>{if(w.text)return w.text(e);i&&a%2==0&&h()})(e.delta)),e.tool&&(y=!0,(e=>{if(w.tool)return w.tool(e);i&&i.clear();const t=(e=>{const t=e&&void 0!==e.id?`id:${e.id}`:`${e&&e.name}:${JSON.stringify(e&&e.args)}`;return v.has(t)||v.set(t,P(e&&e.name,e&&e.args,{cwd:process.cwd()})),v.get(t)})(e);ct(ce.renderTurn(qe(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:K(t)},Pe())),h()})(e.tool)),e.approval){const t=e.approval;i&&i.clear();const n=w.approval||Oe||N;Promise.resolve(n(t)).catch((()=>"deny")).then((e=>Me.respondApproval(t.id,ke(e))))}if(e.rounds){const t=e.rounds;i&&i.clear();const n=w.rounds||I;Promise.resolve(n(t)).catch((()=>!1)).then((e=>Me.respondRoundsAsk(t.id,!0===e)))}}};try{const n=await Me.chat({prompt:e,messages:t,model:Ke.model||void 0,system:d.system||ge(),maxTokens:d.maxTokens,effort:k(Ke.effort),recallDeep:!0===Ke.recallDeep||void 0,stream:!1!==Ke.stream,sessionId:b,sessionKey:Ke.sessionId,roundsAsk:Boolean(w.rounds)},$),r=n.choices&&n.choices[0]||{};return{text:r.message&&r.message.content||c,usage:n.usage||null,model:n.model||Ke.model||null,ms:Date.now()-s,interrupted:T,reasoningChars:u,usedTools:y}}catch(e){if(T&&c)return{text:c,usage:null,model:Ke.model||null,ms:Date.now()-s,interrupted:!0,reasoningChars:u,usedTools:y};throw e}finally{g&&clearInterval(g),process.removeListener("SIGINT",x),o&&o.removeEventListener("abort",C),i&&i.clear(),De=null}}function dt(e){ct(ce.renderTurn(qe(),e,Pe()))}async function mt(e,{label:t="you"}={}){if(!e)return void ct(ce.renderNotice(qe(),"warn","nothing to ask — give /ask a prompt"));if(Se.apiKey||await $e(),!Se.apiKey)return void ct(ce.renderNotice(qe(),"error",`no AEGIS account key — ${G.HOW_TO_SET} (or set $${G.KEY_ENV})`));const n=_e.filter((e=>"user"===e.role||"assistant"===e.role)).map((e=>({role:e.role,content:e.text})));let r;dt({role:"user",text:e,label:t}),_e.push({role:"user",text:e});try{r=await ut(e,{history:n})}catch(t){return Ct(e,{text:"",error:t.message},"error"),void ct(ce.renderTurn(qe(),{role:"error",text:t.message},Pe()))}r.text&&_e.push({role:"assistant",text:r.text});const o=Tt(r);let s=null;try{const e=await Fe();s=e?e.lastCost:null}catch{}Ct(e,r,r.interrupted?"stopped":r.error?"error":"done",s),dt({role:"assistant",text:r.text||"(the pool returned no text — see /balance for what it charged)",meta:{model:r.model,tokens:o,usage:null==r.usage?null:i(r.usage),eur:s,ms:r.ms,calls:1}}),r.interrupted&&ct(ce.renderNotice(qe(),"warn","interrupted — the pool may still be running and billing this call"))}async function ft(e,t){const n=Te[e];if(!n)throw new Error(`unknown tool: ${e}`);if(Se.apiKey||await $e(),!Se.apiKey)throw new Error(`no AEGIS account key — ${G.HOW_TO_SET}`);const r=await n.run(t||{});ct(ce.renderToolResult(qe(),e,r,Pe()))}function pt(e){const t=String(e||"").toLowerCase();if(!t)return null;let n=null;for(const e of j)for(const r of[e.name,...e.aliases||[]])r!==t&&(r.startsWith(t)||t.startsWith(r))&&(null==n||Math.abs(r.length-t.length)<Math.abs(n.length-t.length))&&(n=r);return n}function yt(){const e=D(),n=U();return{version:ye,model:Ke.model||"server default",class:Ke.modelClass,effort:Ke.effort,thinking:Ke.thinking,theme:Ke.light?"light":"dark",themeIndex:Ke.themeIndex,vim:Ke.vim,stream:Ke.stream,cwd:Ke.cwd,home:t.homedir(),sessionId:Ke.sessionId,base:Se.apiBase,keyMask:me(Se.apiKey),online:!!Se.apiKey,turns:Re.turns,calls:Re.calls,startedAt:Re.startedAt,tokens:{input:Re.inputTokens,output:Re.outputTokens,cacheRead:Re.cacheReadTokens,cacheWrite:Re.cacheWriteTokens,total:Re.tokens},costEur:Re.cost,balance:Re.balance,plan:Re.plan||null,account:Re.account||null,permissions:{mode:n.enabled?e.defaultMode:"allow",confirm:n.enabled,source:n.source,rules:e},models:rt(),commands:q(),transcript:_e.slice(),sessions:[],memory:{},lastRecap:Ke.lastRecap,backend:Ke.modelClass,url:Se.apiBase}}function ht(e){return Array.isArray(e)?e.map((e=>e&&(e.s||"")+(null==e.t?"":e.t)||"")).join(""):String(null==e?"":e)}function gt(e){if(!e||"object"!=typeof e)return;const t=Pe();switch(e.role){case"panel":{const t=Array.isArray(e.lines)?e.lines:[];for(const e of t)ct(ht(e));return}case"note":case"tip":return void ct(ce.renderNotice(qe(),"info",e.text));case"done":return void ct(ce.renderNotice(qe(),"ok",e.text));case"error":return void ct(ce.renderNotice(qe(),"error",e.text));case"user":return void ct(ce.renderTurn(qe(),{role:"user",text:e.text,label:e.label},t));case"assistant":return void ct(ce.renderTurn(qe(),{role:"assistant",text:e.text},t));case"tool":return void 0===e.diff&&(e.diff=P(e.name||e.label,e.args,{cwd:process.cwd()}),e.diffOpen=K(e.diff)),void ct(ce.renderTurn(qe(),{role:"tool",label:e.label||e.name,args:e.args,ok:e.ok,diff:e.diff,diffOpen:!!e.diffOpen},t));default:return void ct(ce.renderNotice(qe(),"info",null==e.text?"":String(e.text)))}}function kt(e){return{t:e,s:"",w:L(e)}}async function wt(){return!a.readline&&process.stdin.isTTY&&process.stdout.isTTY&&!1!==a.chatflow?ie.showThemePicker(Ke):(Ke.light=!Ke.light,Ke.themeIndex=Ke.light?2:1,ct(ce.renderNotice(qe(),"ok","theme: "+(Ke.light?"light":"dark"))),Ke.themeIndex)}function vt(){const e={ctx:Ke,transcript:_e,push:e=>gt(e),note:e=>gt({role:"note",text:e}),panel:e=>gt({role:"panel",lines:e}),render:()=>{},openOverlay:e=>function(e){if(!e||"object"!=typeof e)return;const t=Pe(),n=Math.max(5,process.stdout&&process.stdout.rows||24);let r=null;if("panel"===e.type?r=e.lines:"palette"===e.type?r=le.renderPalette(q(),{query:e.query||"",sel:e.sel||0},t,n):"model"===e.type?r=le.renderModelPicker(e.items||[],e.sel||0,t,n,null!=e.current?e.current:Ke.model,e.cls||Ke.modelClass,Le):"effort"===e.type?r=le.renderEffortPicker(e.sel||0,t,Ke.effort):"class"===e.type?r=le.renderClassPicker(e.items||[],e.sel||0,t,e.current||Ke.modelClass,Le):"provider"===e.type?r=le.renderProviderPicker(e.items||[],e.sel||0,t,e.current,e.hint):"resume"===e.type?r=le.renderResumeList(e.items||[],e.sel||0,t,n):"confirm"===e.type&&(r=ce.renderApproval(qe(),e.info||{},t).map((e=>[kt(e)]))),r)for(const e of r)ct(ht(e))}(e),closeOverlay:()=>{},setAutoRounds:e=>{Ae=Boolean(e)},askInput:()=>Promise.resolve(null),withWorking:e=>async function(e){const t=new AbortController,n=d.interactive&&he.isTTY?new A(he):null;let r=null;if(n){let e=0;const t=Date.now(),o=()=>n.update([ce.renderWorking(qe(),{tick:e++,verb:S[0],elapsedMs:Date.now()-t})]);o(),r=setInterval(o,90),r.unref&&r.unref()}try{return await e(t.signal)}finally{r&&clearInterval(r),n&&n.clear()}}(e),runPrompt:e=>mt(e),ask:e=>ut(e),runTool:(e,t)=>ft(e,t),loadModels:()=>tt(Ke.modelClass),settings:()=>Me.settings||null,byokNamespace:e=>g(e),listModelsFor:e=>tt(e),refreshByokModels:()=>et({force:!0}),switchClass:e=>function(e){const t=String(null==e?"":e).trim().toLowerCase(),n=st();if(!n.includes(t))return"pro"===t?{ok:!1,error:"the pro class (your Claude Code subscription) is off by default — enable it once with `/class pro on`"}:{ok:!1,error:`unknown class "${e}" — classes: ${n.join(", ")}`};const r=Ke.modelClass;Ke.modelClass=t;let o=null;return r!==t&&Ke.model&&(function(e,t){const n=String(null==t?"":t);return"byok"===e?n.includes(":"):"pro"===e?ot().has(n.toLowerCase()):!n.includes(":")}(t,Ke.model)||(o=Ke.model,Ke.model=null)),R({modelClass:t,model:Ke.model,currentModelId:Ke.model}),{ok:!0,class:t,prev:r,cleared:o}}(e),classLabel:e=>Le(e),classes:()=>"function"==typeof Me.listClasses?Me.listClasses():[],refreshSpend:()=>Fe(),state:()=>yt(),setInput:()=>{},exit:()=>{je=!0},client:Se,TOOLS:Te,saveConfig:e=>R(e),showThemePicker:()=>wt(),keyStatus:()=>G.keyStatus(),setApiKey:(e,t)=>He(e,t),forgetApiKey:()=>Ue(),registerAccount:()=>async function(){return Se.apiKey?{alreadyKeyed:!0}:Ie()}(),readSecret:e=>V(e,{stdin:process.stdin,stdout:he}),cloudsync:J,cloudSyncEnabled:()=>Ge(),cloudSyncState:()=>ze(),setCloudSync:e=>Je(e),adoptLegacyKey:()=>Ve()};return Object.defineProperty(e,"sessionId",{enumerable:!0,get:()=>Ke.sessionId,set:e=>{Ke.sessionId=e}}),e.clearConversationMemory=()=>{Me&&"function"==typeof Me.clearSessionApprovals&&Me.clearSessionApprovals(Ke.sessionId)},e}async function bt(e,t=null){const n=_(e);if("empty"===n.kind)return!0;if("prompt"===n.kind)return await mt(n.text),!0;if("unknown"===n.kind){const e=pt(n.name);return ct(ce.renderNotice(qe(),"error",`unknown command: /${n.name}${e?` — did you mean /${e}?`:" — try /help"}`)),!0}if("unavailable"===n.kind){const e=n.command;if(ct(ce.renderNotice(qe(),"warn",`/${e.name} is not available in aegiscode — ${e.unavailable}`)),e.alt)ct(ce.renderNotice(qe(),"info",`try ${e.alt} instead`));else{const t=pt(e.name);t&&ct(ce.renderNotice(qe(),"info",`try /${t} instead`))}return!0}const r=n.command,o=n.arg;if(r.generic){let e;try{e=r.build(o)}catch(e){return ct(ce.renderNotice(qe(),"error",e.message)),!0}const{tool:t,args:n}=e;if(!t)return ct(ce.renderNotice(qe(),"error","/tool needs a tool name — see /help")),!0;try{await ft(t,n)}catch(e){ct(ce.renderNotice(qe(),"error",e.message))}return!0}if("function"==typeof r.handler){const e=function(e,t){const n=String(null==t?"":t),r=Array.isArray(e.args)?e.args:[],o=function(e){const t=[];let n="",r=null,o=!1;for(const s of String(e||""))r?s===r?r=null:n+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(n||o)&&(t.push(n),n="",o=!1):(n+=s,o=!0):(r=s,o=!0);return(n||o)&&t.push(n),t}(n),s={_rest:n.trim()};return r.forEach(((e,t)=>{void 0!==o[t]&&(s[e]=o[t])})),s}(r,o),n=t||vt();try{return!1!==await r.handler(n,e)}catch(e){return ct(ce.renderNotice(qe(),"error",e&&e.message?e.message:String(e))),!0}}try{let e=r.build(o);if(r.secret){const t=await async function(e,t){if("function"!=typeof e.secretDescribe)return null;try{const n=await e.secretDescribe(t,Se);return n&&"object"==typeof n?n:null}catch{return null}}(r,e);if(t&&t.note&&ct(ce.renderNotice(qe(),"info",t.note)),t&&null===t.prompt)return!0;t&&t.provider&&(e={...e,provider:t.provider});const n=await function(e){const t=T(qe());return V(t.gray+e+C,{stdin:process.stdin,stdout:he})}(t&&t.prompt||`provider key for ${e.provider}: `);if(!n)return ct(ce.renderNotice(qe(),"warn","empty key — nothing sent")),!0;e={...e,api_key:n}}if("aegis_ask"===r.tool)return await mt(e.prompt);await ft(r.tool,e),"aegis_memory_list"!==r.tool&&"aegis_memory_search"!==r.tool||function(){let e;try{e=J.status()}catch{return}const t=e.quota;if(!t)return;const n=ue(t.used||0),r=ue(t.limit||0);e.overQuota?ct(ce.renderNotice(qe(),"warn",`cloud memory: ${n} of ${r} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`)):ct(ce.renderNotice(qe(),"info",`cloud memory: ${n} of ${r} synced tokens — /cloud memory for the full state`))}()}catch(e){ct(ce.renderNotice(qe(),"error",e.message))}return!0}async function St(){if(Me&&"function"==typeof Me.unloadLocalModels)try{await Me.unloadLocalModels()}catch{}}function Tt(e){Re.turns++,Re.calls+=Number(e&&e.calls||1)||1;const t=e&&e.usage,n=s(t);if(null!=n){Re.tokens+=n;const e=i(t);Re.inputTokens+=e.input,Re.outputTokens+=e.output,Re.cacheReadTokens+=e.cacheRead,Re.cacheWriteTokens+=e.cacheWrite}return n}function Ct(e,t,n="done",r=null){try{const o=t&&t.usage,s="number"==typeof r&&Number.isFinite(r)?r:null;ee({sessionId:Ke.sessionId,prompt:e,reply:t&&t.text||"",status:n,usage:o?{...i(o),...null!=s?{costUsd:s}:{}}:null!=s?{input:0,output:0,cacheRead:0,cacheWrite:0,costUsd:s}:null}),se(Ke.sessionId,_e)}catch{}Ge()&&Se.apiKey&&Promise.resolve().then((()=>J.push(Se))).then((e=>{if(e&&e.failed&&e.failed.length){const t=e.failed[0];if(xt.has(t.kind))return;if(xt.add(t.kind),"quota"===t.kind)return void ct(ce.renderNotice(qe(),"warn","cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying."));const n=t.hint?` — ${t.hint}`:"";ct(ce.renderNotice(qe(),"error",`cloud sync: ${t.message}${n}`))}})).catch((()=>{}))}let xt=new Set;function Nt(){const e=[Re.outputTokens>0?`${ue(Re.outputTokens)} tokens`:`${ue(Re.tokens)} tokens`,`${Re.calls} call${1===Re.calls?"":"s"}`];return fe()&&(e.push(de(Re.cost)),null!=Re.balance&&e.push(`balance ${de(Re.balance)}`)),e.join(" · ")}async function It(e){if(!e||!e.id)return;const t=te(e.id);if(t.length){_e.length=0;for(const e of t)_e.push(e);Ke.sessionId=e.id,ct(ce.renderNotice(qe(),"ok",`resumed ${e.id} — ${t.length} turn(s)`))}else ct(ce.renderNotice(qe(),"warn",`no stored turns for ${e.id}`))}function $t(){return{ctx:Ke,version:ye,transcript:_e,session:Re,client:Se,TOOLS:Te,ask:(e,t)=>ut(e,t),makeCommandContext:()=>vt(),accountConfigured:()=>!!(G.keyStatus()||{}).configured,hasProviderKey:e=>{const t=Me.settings;if(!t||!e)return!1;const n=g(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},loadModels:e=>it(e),buildState:()=>yt(),dispatchLine:(e,t)=>bt(e,t),refreshSpend:()=>Fe(),updateConfig:e=>R(e),showThemePicker:()=>wt(),persistTurn:(e,t,n,r)=>Ct(e,t,n,r),nameConversation:(e,t)=>async function(e,{signal:t=null}={}){const n=await oe.nameConversation(e,{signal:t,callModel:(e,n)=>ut(e,{system:n&&n.system||oe.TITLE_SYSTEM,maxTokens:64,signal:n&&n.signal||t}).then((e=>e&&e.text||null))}),r=String(n||"").trim();return r&&re(Ke.sessionId,r),r}(e,t),visibleCommands:()=>q(),tokensFor:e=>s(e),recordTurn:e=>Tt(e),tokenSummary:()=>Nt(),resumeSession:e=>It(e),requestExit:()=>{je=!0},wantsExit:()=>je,keyNotice:()=>Se.apiKey?"":Ne,isYolo:()=>{if(!Ae)return!1;try{return!1===U().enabled}catch{return!1}},setAutoRounds:e=>{Ae=Boolean(e)}}}async function Et(){ct(lt()),await Fe(),he.write("\n");const t=a.readline||e.createInterface({input:process.stdin,output:he,terminal:!0}),n=T(qe()).gold+b.cursor+" "+C;return t.setPrompt(n),t.prompt(),new Promise((e=>{t.on("line",(async e=>{t.pause();let n=!0;try{n=await bt(e)}catch(e){ct(ce.renderNotice(qe(),"error",e.message))}if(!n||je)return Be=!0,void t.close();t.resume(),t.prompt()})),t.on("close",(()=>{Be||he.write("\n"),e(0)}))}))}function At(){if(a.readline)return;if(!W())return;let e;try{e=B()}catch{return}if(st().includes(e.modelClass)&&(Ke.modelClass=e.modelClass),d.class){const e=String(d.class).trim().toLowerCase();if(!st().includes(e))throw new Error(`--class ${d.class}: not available on this host (offered: ${st().join(", ")})`);Ke.modelClass=e}if(!d.model&&e.model&&(Ke.model=e.model),Ke.effort=k(e.effort),"boolean"==typeof e.vim&&(Ke.vim=e.vim),e.lastRecap&&(Ke.lastRecap=e.lastRecap),!d.light&&"number"==typeof e.themeIndex&&x[e.themeIndex]){Ke.themeIndex=e.themeIndex,Ke.light=I(e.themeIndex);const t=$(Ke.themeIndex);if(t.changed){Ke.themeIndex=t.index,Ke.light=I(t.index),Ke.themeNotice=t.reason;try{R({themeIndex:t.index,light:I(t.index)})}catch{Ke.themeNotice+=" (could not save it)"}}}}return{opts:d,session:Re,client:Se,TOOLS:Te,toolList:Ce,ctx:Ke,transcript:_e,ask:ut,runPrompt:mt,handleLine:bt,runOnce:async function(e,t={}){try{return await async function(e,{json:t=!1}={}){if(At(),Ve(),!Se.apiKey&&!xe){xe=!0;const e=await l(Se,G,{app:"cli"});e.key&&be.write("aegiscode: auto-provisioned a free account"+(e.ok?` (saved to ${G.credentialsPath()})`:" (could not save it — reconfigure with /key)")+u(e)+`. Fund it at ${Se.promptUrl("topup","device_autoprovision")} or run /byok to use your own key.\n`)}if(!Se.apiKey)return be.write(`aegiscode: no AEGIS account key. ${G.HOW_TO_SET}, or set $${G.KEY_ENV}.\n`),2;await Fe();const n=[],r=[],o=t?{tool:e=>{if("done"===(e&&e.phase)){const t=e.id&&r.find((t=>t.id===e.id&&!0!==t.settled))||(e.id?null:r[r.length-1]);t?(t.settled=!0,t.ok=!1!==e.ok):(e&&e.name&&n.push(e.name),r.push({name:e&&e.name||null,id:e&&e.id||null,args:ve(e&&e.args),settled:!0,ok:!1!==e.ok}))}else e&&e.name&&n.push(e.name),r.push({name:e&&e.name||null,id:e&&e.id||null,args:ve(e&&e.args),settled:!1,ok:null});const t=e&&void 0!==e.preview?e.preview:null,o=ce.renderTurn(qe(),{role:"tool",label:e.name,args:e.args,ok:e.ok,diff:t,diffOpen:!1},Pe());for(const e of Array.isArray(o)?o:[o])be.write(e+"\n")}}:null,i=await ut(e,o?{presenter:o}:{});await Fe();const a=s(i.usage),c=function(e,t){if("string"!=typeof e)return null;const n=t&&(t.total_tokens||0),r=t&&(t.output_tokens||t.completion_tokens||0);if(n>0||r>0)return null;const o=e.trim();if(!o||o.length>160||o.includes("\n"))return null;for(const e of we)if(e.test(o))return o;return null}(i.text,i.usage);if(t)he.write(JSON.stringify({text:i.text,model:i.model,class:Ke.modelClass,rounds:i.usage&&Number(i.usage.calls)||null,usage:i.usage,tokens:a,ms:i.ms,interrupted:i.interrupted,...n.length?{tools:n}:{},...r.length?{tool_log:r}:{},...c?{error:c}:{},balance_eur:Re.balance},null,2)+"\n");else if(he.write(i.text+"\n"),c&&be.write(`aegiscode: the provider refused this turn — ${c}\n`),null!=a){const e=T(qe());he.write(e.dim+b.hook+" "+e.blue+(i.model||"aegis")+C+e.dim+" "+b.bullet+" "+C+e.white+`${ue(a)} tokens`+C+"\n")}return i.interrupted?130:c?1:0}(e,t)}finally{await St()}},runInteractive:async function(){try{return await async function(){if(!a.readline&&!1!==a.chatflow&&process.stdin.isTTY&&process.stdout.isTTY){await E({onLeftover:e=>z.feedKeys(e,{keystrokes:!0})}),At(),function(){if(!Ke.themeNotice)return;const e=Ke.themeNotice;Ke.themeNotice="",ct(ce.renderNotice(qe(),"warn",`theme: ${e} (saved)`))}(),Ve(),Se.apiKey||await $e();const e=await ie.runOnboarding(Ke,{continue:!!a.continue,seen:a.seen||W,save:e=>R(e),needsKey:()=>!Se.apiKey,submitKey:e=>He(e)});if(!e.ok)return 0;if(e.key&&e.key.set&&ct(ce.renderNotice(qe(),"info",`key saved to ${G.credentialsPath()} — no export needed from now on`)),e.key&&e.key.skipped&&!Se.apiKey&&ct(ce.renderNotice(qe(),"warn","no key saved — /key <api_key> or `aegiscode login` whenever you are ready")),e.firstRun&&function(){if(!ze().enabled)return void ct(ce.renderNotice(qe(),"info","cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later"));const e=J.status().quota,t=e&&e.limit?` (used ${ue(e.used||0)} of ${ue(e.limit)} tokens)`:"";ct(ce.renderNotice(qe(),"info",`cross-session memory: on${t} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`))}(),await at(),a.continue){const e=ne(1)[0];e&&(Ke.continueSession=e.id,await It({id:e.id}))}return await Fe(),await ae.runSession($t()),0}return At(),Ve(),Et()}()}finally{await St()}},runLinearRepl:Et,refreshSpend:Fe,bannerLines:lt,makeHost:$t,loadModels:it,validatePinnedModel:at,recordTurn:Tt,persistTurn:Ct,restorePrefs:At,setApiKey:He,forgetApiKey:Ue,adoptLegacyKeyOnce:Ve,cloudSyncEnabled:Ge,cloudSyncState:ze,setCloudSync:Je,cloudsync:J,keyStatus:()=>G.keyStatus(),accountConfigured:()=>!!(G.keyStatus()||{}).configured,hasProviderKey:e=>{const t=Me.settings;if(!t||!e)return!1;const n=g(e);return"function"==typeof t.rawKey?!!String(t.rawKey(n)||"").trim():"function"==typeof t.get&&!!(t.get(n)||{}).configured},sessionId:()=>Ke.sessionId,tokenSummary:Nt,resumeSession:It,makeCommandContext:vt,buildState:yt,get aborted(){return!1}}},VERSION:ye,normalizeDecision:ke};
|