aegiscode 6.7.5 → 6.7.7

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.
@@ -0,0 +1,198 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The named custom-model catalog behind the `custom` class.
5
+ *
6
+ * This is the aegiscodex-dev `/model add` concept ported into the CLI: a user
7
+ * registers an endpoint they bring themselves — their own base URL, their own
8
+ * model string, their own API key — and the turn is called DIRECTLY through the
9
+ * desktop transport (desktop/lib/local/providers.js openaiCompatible /
10
+ * anthropicMessages), the full agent loop and all, never through the pooled
11
+ * route and never through the BYOK relay. There is no AEGIS margin or handling
12
+ * fee on this lane at all: the request never touches aegiscloud.org.
13
+ *
14
+ * Split storage, on purpose:
15
+ * · metadata (id, name, model, baseURL, wire) → config.json `customModels`.
16
+ * None of it is secret, and config.json is where /model pins already live.
17
+ * · the API key → the settings store under `custom:<id>` (file mode 0600,
18
+ * the same store byok keys use). config.json is NOT 0600 and participates in
19
+ * cloud sync, so a provider key must never land there.
20
+ *
21
+ * `wire` selects the transport: 'anthropic' → anthropicMessages (x-api-key,
22
+ * the Messages API), 'openai' → openaiCompatible (Bearer, /chat/completions).
23
+ * It is auto-detected from the base URL host on add, and overridable.
24
+ */
25
+
26
+ const { loadConfig, updateConfig } = require('./config.js');
27
+
28
+ /** The settings-store row a custom model's key lives in. */
29
+ function customNamespace(id) {
30
+ return `custom:${id}`;
31
+ }
32
+
33
+ /** Host of a URL, lower-cased, or '' if it does not parse. */
34
+ function hostOf(url) {
35
+ try {
36
+ return new URL(String(url)).host.toLowerCase();
37
+ } catch {
38
+ return '';
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Which transport a base URL implies. Anthropic's Messages API is a different
44
+ * wire format (x-api-key, `/v1/messages`, a `system` top-level field) from the
45
+ * OpenAI-compatible majority, so it must be recognised rather than guessed at
46
+ * call time. Everything else — OpenAI, Groq, DeepSeek, together, openrouter,
47
+ * a local llama.cpp — speaks the OpenAI shape.
48
+ */
49
+ function inferWire(baseURL) {
50
+ const host = hostOf(baseURL);
51
+ return host && /(^|\.)anthropic\.com$/.test(host) ? 'anthropic' : 'openai';
52
+ }
53
+
54
+ const VALID_WIRES = Object.freeze(['openai', 'anthropic']);
55
+
56
+ /**
57
+ * Validate and normalise a would-be catalog entry. Returns `{ entry }` on
58
+ * success or `{ error }` with a one-line reason — never throws, so the command
59
+ * layer can show the reason and keep the session alive.
60
+ *
61
+ * The id rules are load-bearing, not cosmetic: a `:` would collide with the
62
+ * `provider:model` shape byok parses, and a whitespace id cannot be typed back
63
+ * to `/model <id>`. A base URL is required and must be http(s) — the transport
64
+ * POSTs to `${baseURL}/…`, so a bare host or a typo becomes an unroutable call
65
+ * later instead of a clear refusal now.
66
+ */
67
+ function normalizeEntry({ id, name, model, baseURL, wire } = {}) {
68
+ const cleanId = String(id == null ? '' : id).trim();
69
+ if (!cleanId) return { error: 'an id is required — /model add <id> <name> <model> <baseURL>' };
70
+ if (/[\s:]/.test(cleanId)) return { error: `invalid id "${cleanId}" — no spaces or ":" (":" is the byok separator)` };
71
+
72
+ const cleanModel = String(model == null ? '' : model).trim();
73
+ if (!cleanModel) return { error: 'a model string is required — the id the provider expects on the wire' };
74
+
75
+ const cleanBase = String(baseURL == null ? '' : baseURL).trim();
76
+ if (!/^https?:\/\//i.test(cleanBase)) return { error: `base URL must start with http(s):// — got ${JSON.stringify(cleanBase)}` };
77
+ if (!hostOf(cleanBase)) return { error: `base URL does not parse — got ${JSON.stringify(cleanBase)}` };
78
+
79
+ let cleanWire = String(wire == null ? '' : wire).trim().toLowerCase();
80
+ if (cleanWire && !VALID_WIRES.includes(cleanWire)) {
81
+ return { error: `wire must be one of ${VALID_WIRES.join(', ')} — got ${JSON.stringify(cleanWire)}` };
82
+ }
83
+ if (!cleanWire) cleanWire = inferWire(cleanBase);
84
+
85
+ const cleanName = String(name == null ? '' : name).trim() || cleanId;
86
+ return { entry: { id: cleanId, name: cleanName, model: cleanModel, baseURL: cleanBase, wire: cleanWire } };
87
+ }
88
+
89
+ /** The stored catalog (metadata only), always an array. */
90
+ function rawCatalog() {
91
+ const list = loadConfig().customModels;
92
+ return Array.isArray(list) ? list.filter((e) => e && typeof e.id === 'string') : [];
93
+ }
94
+
95
+ /** One entry's metadata by id, or null. */
96
+ function getCustom(id) {
97
+ const want = String(id == null ? '' : id).trim();
98
+ return rawCatalog().find((e) => e.id === want) || null;
99
+ }
100
+
101
+ /**
102
+ * The catalog as pickable model rows ({ id, label, note, configured }) — the
103
+ * shape /models and the alt+p picker consume. `configured` reflects whether a
104
+ * key is saved for the row, so the list can say which entries can actually run.
105
+ */
106
+ function listCustomModels(settings) {
107
+ return rawCatalog().map((e) => ({
108
+ id: e.id,
109
+ label: e.name || e.id,
110
+ note: `${e.model} · ${hostOf(e.baseURL) || e.baseURL} · ${e.wire}`,
111
+ configured: hasKey(settings, e.id),
112
+ wire: e.wire,
113
+ }));
114
+ }
115
+
116
+ /** Whether a key is stored for this custom id. */
117
+ function hasKey(settings, id) {
118
+ if (!settings || typeof settings.rawKey !== 'function') return false;
119
+ return Boolean(settings.rawKey(customNamespace(id)));
120
+ }
121
+
122
+ /**
123
+ * Add or replace a catalog entry, and store its key (when supplied) in the
124
+ * 0600 settings row. Returns `{ entry }` or `{ error }`. Adding an id that
125
+ * already exists REPLACES its metadata (and its key when a new one is given),
126
+ * so `/model add` doubles as an edit — re-running it to fix a typo'd base URL
127
+ * does not leave a second, dead row.
128
+ */
129
+ function addCustom(fields, settings) {
130
+ const res = normalizeEntry(fields);
131
+ if (res.error) return res;
132
+ const { entry } = res;
133
+ const next = rawCatalog().filter((e) => e.id !== entry.id);
134
+ next.push(entry);
135
+ updateConfig({ customModels: next });
136
+ if (settings && typeof settings.set === 'function' && fields && fields.key != null && String(fields.key).trim()) {
137
+ settings.set(customNamespace(entry.id), { key: String(fields.key).trim() });
138
+ }
139
+ return { entry };
140
+ }
141
+
142
+ /** Store (or clear) just the key for an existing custom id. */
143
+ function setCustomKey(id, key, settings) {
144
+ if (!settings || typeof settings.set !== 'function') return { error: 'no key store available' };
145
+ settings.set(customNamespace(id), { key: key ? String(key).trim() : null });
146
+ return { ok: true };
147
+ }
148
+
149
+ /**
150
+ * Remove a catalog entry and forget its key. Returns whether anything was
151
+ * removed, so the command can say "removed" vs "there was no such entry".
152
+ */
153
+ function removeCustom(id, settings) {
154
+ const want = String(id == null ? '' : id).trim();
155
+ const before = rawCatalog();
156
+ const after = before.filter((e) => e.id !== want);
157
+ const removed = after.length !== before.length;
158
+ if (removed) updateConfig({ customModels: after });
159
+ if (settings && typeof settings.remove === 'function') {
160
+ try { settings.remove(customNamespace(want)); } catch { /* nothing stored */ }
161
+ }
162
+ return { removed };
163
+ }
164
+
165
+ /**
166
+ * Resolve a pinned custom id to everything the dispatch needs: the transport
167
+ * class it maps to ('anthropic' | 'openai-compat'), its base URL, its wire
168
+ * model string, and its key. Null when the id is not in the catalog. The key
169
+ * is read live from the settings store, never cached, so a key saved after the
170
+ * engine was constructed is picked up on the very next turn.
171
+ */
172
+ function resolveCustom(id, settings) {
173
+ const entry = getCustom(id);
174
+ if (!entry) return null;
175
+ const key = settings && typeof settings.rawKey === 'function' ? settings.rawKey(customNamespace(entry.id)) : null;
176
+ return {
177
+ wireClass: entry.wire === 'anthropic' ? 'anthropic' : 'openai-compat',
178
+ baseURL: entry.baseURL,
179
+ model: entry.model,
180
+ key: key || null,
181
+ wire: entry.wire,
182
+ id: entry.id,
183
+ };
184
+ }
185
+
186
+ module.exports = {
187
+ customNamespace,
188
+ inferWire,
189
+ normalizeEntry,
190
+ getCustom,
191
+ listCustomModels,
192
+ hasKey,
193
+ addCustom,
194
+ setCustomKey,
195
+ removeCustom,
196
+ resolveCustom,
197
+ VALID_WIRES,
198
+ };
package/src/deps.js CHANGED
@@ -56,6 +56,12 @@ const usagePath = resolveShared(path.join('desktop', 'renderer', 'usage.js'));
56
56
  // class) so the CLI's chat loop is the same tool loop as the GUI's, not a
57
57
  // second implementation that can drift out of step with it.
58
58
  const enginePath = resolveShared(path.join('desktop', 'lib', 'local', 'engine.js'));
59
+ // The provider-config store the desktop's settings pane writes (one row per
60
+ // provider: base URL + key, 0600 on disk). The CLI reads the same file for the
61
+ // 'byok' class' per-provider keys, so a key saved in either host is the same
62
+ // key — and so there is one implementation of "where a provider key lives"
63
+ // rather than a second one that drifts.
64
+ const settingsPath = resolveShared(path.join('desktop', 'lib', 'settings.js'));
59
65
  // Subagent role presets (/agents lists these; the model's task tool delegates
60
66
  // to them by name) — lives beside engine.js, staged into the same vendor dir.
61
67
  const agentsPath = resolveShared(path.join('desktop', 'lib', 'local', 'agents.js'));
@@ -75,11 +81,18 @@ const updatePath = resolveShared(path.join('client', 'update.js'));
75
81
  // must work the SAME queue with the SAME rules (scoped commits included).
76
82
  const queuePath = resolveShared(path.join('desktop', 'lib', 'local', 'queue.js'));
77
83
  const autonomousPath = resolveShared(path.join('desktop', 'lib', 'local', 'autonomous.js'));
84
+ // The direct-provider transport (openaiCompatible + anthropicMessages). The
85
+ // desktop injects it into createLocalEngine for its custom-endpoint classes;
86
+ // the CLI injects the same real module for its `custom` class (the /model add
87
+ // catalog) rather than the throwing stub it shipped before.
88
+ const providersPath = resolveShared(path.join('desktop', 'lib', 'local', 'providers.js'));
78
89
 
79
90
  const { createClient } = require(clientPath);
80
91
  const { createTools } = require(toolsPath);
81
92
  const { usageTokens } = require(usagePath);
82
93
  const { createLocalEngine } = require(enginePath);
94
+ const providers = require(providersPath);
95
+ const { createSettingsStore, isReservedNamespace } = require(settingsPath);
83
96
  const { agentRoles, agentRoleLabel } = require(agentsPath);
84
97
  const { buildSystemPrompt } = require(promptPath);
85
98
  const updater = require(updatePath);
@@ -92,12 +105,15 @@ module.exports = {
92
105
  createTools,
93
106
  usageTokens,
94
107
  createLocalEngine,
108
+ providers,
109
+ createSettingsStore,
110
+ isReservedNamespace,
95
111
  agentRoles,
96
112
  agentRoleLabel,
97
113
  buildSystemPrompt,
98
114
  updater,
99
115
  queue,
100
116
  autonomous,
101
- paths: { client: clientPath, tools: toolsPath, usage: usagePath, engine: enginePath, agents: agentsPath, prompt: promptPath, update: updatePath, queue: queuePath, autonomous: autonomousPath },
117
+ paths: { client: clientPath, tools: toolsPath, usage: usagePath, engine: enginePath, providers: providersPath, settings: settingsPath, agents: agentsPath, prompt: promptPath, update: updatePath, queue: queuePath, autonomous: autonomousPath },
102
118
  roots,
103
119
  };
package/src/engine.js CHANGED
@@ -1,24 +1,70 @@
1
1
  'use strict';
2
2
 
3
3
  /**
4
- * Wires the CLI into the same agent-loop engine the desktop app already
5
- * ships (desktop/lib/local/engine.js, commit e4b0a9a): persistent-shell exec,
6
- * readFile/writeFile/editFile/listDir/glob/grep, and Task subagents. This
7
- * host only ever selects the 'aegis' class (it authenticates with an AEGIS
8
- * key, not a local Ollama/BYOK endpoint), so the other three classes'
9
- * dependencies (settings store, Ollama probe, custom-endpoint providers) are
10
- * unreachable and stay stubs that throw if the engine ever calls them —
11
- * proof that a code path meant only for those classes never silently runs
12
- * here instead.
4
+ * Wires the CLI into the same agent-loop engine the desktop app already ships
5
+ * (desktop/lib/local/engine.js): persistent-shell exec, readFile/writeFile/
6
+ * editFile/listDir/glob/grep, and Task subagents.
7
+ *
8
+ * ── the two classes this host runs ──────────────────────────────────────────
9
+ *
10
+ * aegis the pooled route. The account's AEGIS key authenticates the call and
11
+ * pays for it; the pool picks the provider.
12
+ * byok "bring your own key". The user's *provider* key authenticates the
13
+ * upstream call, the account's AEGIS key rides along as X-AEGIS-Key,
14
+ * and the request goes through the stateless relay
15
+ * (POST /api/v1/byok/chat/completions, client/aegis.js
16
+ * byokChatCompletion). The relay charges AEGIS's handling fee on the
17
+ * turn, which is exactly what makes BYOK billable traffic instead of a
18
+ * free ride — and why the key must never be handed to a direct provider
19
+ * call from here.
20
+ *
21
+ * Only those two: `cls` is the engine's own class selector, and the two local
22
+ * classes (ollama, custom endpoints) stay stubs that throw if the engine ever
23
+ * calls them. They need a settings/endpoint surface this host does not offer,
24
+ * and a stub is proof that a code path meant for another host never silently
25
+ * runs here.
26
+ *
27
+ * ── the key store ───────────────────────────────────────────────────────────
28
+ *
29
+ * The 'byok' class reads one row per provider (`byok:<provider>` —
30
+ * desktop/lib/settings.js, the same rows the desktop's Provider settings write)
31
+ * for the provider key. The CLI creates that store itself, without Electron's
32
+ * safeStorage: base64 at rest, file mode 0600, in the CLI's data dir
33
+ * ($AEGISCODE_HOME or ~/.aegiscode). No server-side BYOK mechanism is involved
34
+ * here — that one (/byok-set, services/byok_service.py) stores the key on the
35
+ * AEGIS account and is folded into the pooled route, an unbilled path by
36
+ * design; the two must not be confused.
13
37
  */
14
38
 
15
39
  const os = require('node:os');
16
- const { createLocalEngine } = require('./deps.js');
40
+ const { createLocalEngine, createSettingsStore, providers } = require('./deps.js');
41
+ const { credentials } = require('./shared.js');
42
+ const custom = require('./custommodels.js');
17
43
  const VERSION = require('../package.json').version;
18
44
 
45
+ /**
46
+ * The classes this host can actually run (see the docstring above).
47
+ * aegis — the pooled route (account key pays, pool picks the provider).
48
+ * byok — the BYOK relay (your provider key, AEGIS bills a handling fee).
49
+ * custom — the /model add catalog: your own base URL + key, called DIRECTLY
50
+ * through the desktop transport with the full tool loop, never
51
+ * touching aegiscloud.org (no margin, no fee).
52
+ */
53
+ const HOST_CLASSES = Object.freeze(['aegis', 'byok', 'custom']);
54
+
55
+ /** The class a turn runs on when nothing else is said. */
56
+ const DEFAULT_CLASS = 'aegis';
57
+
58
+ /** One-line labels for /class, the status line and the model picker. */
59
+ const CLASS_LABELS = Object.freeze({
60
+ aegis: 'AEGIS Cloud (pooled)',
61
+ byok: 'Bring your own key (relayed, billed)',
62
+ custom: 'Custom endpoint (your key, direct)',
63
+ });
64
+
19
65
  function unsupported(label) {
20
66
  return async () => {
21
- throw new Error(`aegiscode: ${label} is not available — this client only runs the aegis class`);
67
+ throw new Error(`aegiscode: ${label} is not available — this client only runs the aegis and byok classes`);
22
68
  };
23
69
  }
24
70
 
@@ -27,19 +73,35 @@ function unsupported(label) {
27
73
  * @param {() => boolean} getConfirmMode Whether mutating tools (exec,
28
74
  * writeFile, editFile) require approval before running. Read per call, so
29
75
  * toggling it (/permissions, /yolo) takes effect on the next tool round.
76
+ * @param {() => string} getClass Which class the next turn runs on — read per
77
+ * call for the same reason getConfirmMode is: /class must take effect on the
78
+ * very next turn, not on the next launch.
79
+ * @param {object} [settings] The provider-config store. Injected by tests
80
+ * (and by app.js, so one store serves both the engine and the commands);
81
+ * otherwise created against the CLI's data dir.
82
+ * @returns {{chat: Function, cancel: Function, respondApproval: Function,
83
+ * clearSessionApprovals: Function, listClasses: Function, listModels: Function,
84
+ * classLabel: Function, getClass: Function, setClass: Function, settings: object}}
30
85
  */
31
- function createEngine({ client, getConfirmMode }) {
86
+ function createEngine({ client, getConfirmMode, getClass, settings: injectedSettings } = {}) {
87
+ const settings = injectedSettings || createSettingsStore({ dir: credentials.aegisHome() });
88
+
32
89
  const local = createLocalEngine({
33
90
  aegis: client,
34
- settings: { get: () => ({}), rawKey: unsupported('BYOK/custom endpoints') },
91
+ settings,
35
92
  ollama: {
36
93
  probe: async () => ({ running: false }),
37
94
  listTags: async () => [],
38
95
  chat: unsupported('Ollama'),
39
96
  },
97
+ // The real direct-provider transport — no longer a throwing stub. The
98
+ // `custom` class (the /model add catalog) rewrites a turn to the
99
+ // 'openai-compat' / 'anthropic' class the desktop engine already drives
100
+ // through exactly these two functions, so a user's own endpoint gets the
101
+ // same tool loop the pooled class does.
40
102
  providers: {
41
- anthropicMessages: unsupported('a custom Anthropic-compatible endpoint'),
42
- openaiCompatible: unsupported('a custom OpenAI-compatible endpoint'),
103
+ anthropicMessages: providers.anthropicMessages,
104
+ openaiCompatible: providers.openaiCompatible,
43
105
  },
44
106
  env: {
45
107
  platform: process.platform,
@@ -51,12 +113,95 @@ function createEngine({ client, getConfirmMode }) {
51
113
  getConfirmMode,
52
114
  });
53
115
 
116
+ /** The live class, clamped to what this host can run. */
117
+ function currentClass() {
118
+ const asked = typeof getClass === 'function' ? getClass() : null;
119
+ return HOST_CLASSES.includes(asked) ? asked : DEFAULT_CLASS;
120
+ }
121
+
122
+ /**
123
+ * Rewrite a `custom`-class turn to the concrete transport class the desktop
124
+ * engine already drives. The catalog entry is the source of truth for the
125
+ * endpoint; its base URL + key are written just-in-time into the wire-class
126
+ * settings row (settings.get(cls).baseURL / rawKey(cls) is what the engine's
127
+ * dispatch reads), and the payload's class + model are set to that wire class
128
+ * and the entry's real model string. Throws a clear, in-process error rather
129
+ * than shipping `model: undefined` or an empty base URL upstream.
130
+ */
131
+ function prepareCustom(payload) {
132
+ const modelId = payload && payload.model;
133
+ const resolved = modelId ? custom.resolveCustom(modelId, settings) : null;
134
+ if (!resolved) {
135
+ const err = new Error(
136
+ modelId
137
+ ? `custom: no model "${modelId}" in the catalog — /model add <id> <name> <model> <baseURL>, or /models to list.`
138
+ : 'custom: no model pinned — pin one with /model <id> (/models lists your custom endpoints).'
139
+ );
140
+ err.status = 400;
141
+ throw err;
142
+ }
143
+ if (resolved.wire === 'anthropic' && !resolved.key) {
144
+ const err = new Error(
145
+ `custom: "${resolved.id}" is an Anthropic-style endpoint and needs a key — /model key ${resolved.id}.`
146
+ );
147
+ err.status = 400;
148
+ throw err;
149
+ }
150
+ // Just-in-time scratch write: the wire-class row is only ever this session's
151
+ // active custom endpoint, re-set on every custom turn, so two custom models
152
+ // sharing a wire never collide.
153
+ settings.set(resolved.wireClass, { baseURL: resolved.baseURL, key: resolved.key || null });
154
+ return { ...payload, class: resolved.wireClass, model: resolved.model };
155
+ }
156
+
157
+ function chat(payload, onDelta) {
158
+ const cls = currentClass();
159
+ if (cls === 'custom') return local.chat(prepareCustom(payload), onDelta);
160
+ // `class` is stamped here rather than sent by every caller, so the class a
161
+ // turn runs on has exactly one source of truth (the live session state) and
162
+ // a caller cannot accidentally pin a stale one.
163
+ return local.chat({ ...payload, class: cls }, onDelta);
164
+ }
165
+
54
166
  return {
55
- chat: (payload, onDelta) => local.chat({ ...payload, class: 'aegis' }, onDelta),
167
+ chat,
56
168
  cancel: local.cancel,
57
169
  respondApproval: local.respondApproval,
58
170
  clearSessionApprovals: local.clearSessionApprovals,
171
+ // The engine's own class table, narrowed to the ones this host runs — so a
172
+ // UI built from listClasses() can never offer a class that would throw.
173
+ // `custom` is not in the desktop engine's own CLASSES (it is a CLI concept
174
+ // that rewrites to openai-compat/anthropic), so it is appended here.
175
+ // Async, like the local engine's: listClasses() probes Ollama (a live
176
+ // HTTP round-trip) before it can answer, so returning the raw promise made
177
+ // `/class` throw "filter is not a function". The caller awaits it.
178
+ listClasses: async () => {
179
+ const base = (await local.listClasses()).filter((c) => HOST_CLASSES.includes(c.class));
180
+ const configured = custom.listCustomModels(settings).length > 0;
181
+ return [...base, { class: 'custom', label: CLASS_LABELS.custom, kind: 'custom', configured }];
182
+ },
183
+ // The `custom` class enumerates the catalog (the desktop engine has no such
184
+ // class, so delegating would throw); every other class delegates.
185
+ listModels: (cls) => {
186
+ const want = cls || currentClass();
187
+ if (want === 'custom') return { class: 'custom', models: custom.listCustomModels(settings) };
188
+ return local.listModels(want);
189
+ },
190
+ classLabel: (cls) => CLASS_LABELS[cls] || CLASS_LABELS[DEFAULT_CLASS],
191
+ getClass: currentClass,
192
+ settings,
59
193
  };
60
194
  }
61
195
 
62
- module.exports = { createEngine };
196
+ /**
197
+ * The settings row one BYOK provider's key lives in. Exported (rather than
198
+ * spelled out again in commands.js) because it is the SAME key the shared
199
+ * engine reads when it resolves the relay's provider credential — and the same
200
+ * row the desktop's Provider settings write. Two spellings would mean a key
201
+ * saved by `/byok-key openai` never reaching the call that needs it.
202
+ */
203
+ function byokNamespace(provider) {
204
+ return `byok:${provider}`;
205
+ }
206
+
207
+ module.exports = { createEngine, HOST_CLASSES, DEFAULT_CLASS, CLASS_LABELS, byokNamespace };
package/src/overlays.js CHANGED
@@ -140,13 +140,32 @@ function renderPalette(commands, state = {}, width = 80, height = 24) {
140
140
  * @param {number} width
141
141
  * @param {number} height
142
142
  * @param {string|null} current the currently-pinned model id
143
+ * @param {string} [cls] which class the next turn runs on ('aegis' | 'byok').
144
+ * The rows are already class-scoped by the caller (app.js listModelsFor), but
145
+ * the copy must be too: "manage the list with /model add|remove" is true of
146
+ * the pooled catalog and meaningless on BYOK, where the list is not a stored
147
+ * list at all but a function of which provider keys this machine holds — so
148
+ * the subtitle names the command that actually changes it.
149
+ * @param {(cls: string) => string} [classLabel] the caller's label table
150
+ * (engine.js CLASS_LABELS, via app.js) so the class is named one way in every
151
+ * surface rather than re-spelled here.
143
152
  */
144
- function renderModelPicker(models, sel = 0, width = 80, height = 24, current = null) {
153
+ function renderModelPicker(models, sel = 0, width = 80, height = 24, current = null, cls = null, classLabel = null) {
145
154
  const lines = [];
155
+ const byok = cls === 'byok';
156
+ const label = typeof classLabel === 'function' && cls ? classLabel(cls) : null;
146
157
  lines.push(blank(width));
147
- lines.push([span('', ' '), span(C.white + BOLD, 'Select model'), span(BOLD_OFF, '')]);
158
+ lines.push([
159
+ span('', ' '), span(C.white + BOLD, 'Select model'), span(BOLD_OFF, ''),
160
+ ...(label ? [span(C.gray, ` — ${label}`)] : []),
161
+ ]);
148
162
  lines.push([span('', ' '), span(C.gray, 'Switch between models. Your pick becomes the default for new sessions.')]);
149
- lines.push([span('', ' '), span(C.gray, 'Manage the list with /model add|remove — /model <id> switches directly.')]);
163
+ lines.push([
164
+ span('', ' '),
165
+ span(C.gray, byok
166
+ ? 'Add one with /byok-key <provider> — /models lists what this machine can relay.'
167
+ : 'Manage the list with /model add|remove — /model <id> switches directly.'),
168
+ ]);
150
169
  lines.push(blank(width));
151
170
  for (let i = 0; i < models.length; i++) {
152
171
  const m = models[i] || {};
package/src/panels.js CHANGED
@@ -414,6 +414,14 @@ function buildModelList(currentId, models, ctx = {}) {
414
414
  const t = themeOf(ctx);
415
415
  const list = Array.isArray(models) ? models : [];
416
416
  const cur0 = str(currentId);
417
+ // Which class these rows belong to. On byok a row is `provider:model` (the
418
+ // engine's listModels('byok') shape) and `model` is unset, so the third
419
+ // column would otherwise print "(default)" down the whole panel; the row's
420
+ // `note` is what actually tells the user whether this machine holds the key.
421
+ // The usage line follows the class too: /model add|remove is refused by this
422
+ // build, and on byok the list is not a stored list at all — it is a function
423
+ // of which provider keys exist, so the command that changes it is /byok-key.
424
+ const byok = ctx.modelClass === 'byok';
417
425
  const lines = [];
418
426
  lines.push([span(t.gold + BOLD, 'Models'), span(BOLD_OFF, '')]);
419
427
  lines.push([span(t.gray, '─'.repeat(30))]);
@@ -423,7 +431,7 @@ function buildModelList(currentId, models, ctx = {}) {
423
431
  const cur = idv !== '' && idv === cur0;
424
432
  const id = (cur ? '▶ ' : ' ') + idv;
425
433
  const name = str(m.name || m.label || m.model);
426
- const model = str(m.model) || '(default)';
434
+ const model = byok ? str(m.note) || str(m.model) : str(m.model) || '(default)';
427
435
  lines.push([
428
436
  span(t.white, id), span('', ' '.repeat(Math.max(1, 26 - [...id].length))),
429
437
  span(t.gray, name), span('', ' '.repeat(Math.max(1, 22 - [...name].length))),
@@ -432,7 +440,11 @@ function buildModelList(currentId, models, ctx = {}) {
432
440
  }
433
441
  if (!list.length) lines.push([span('', ' '), span(t.gray, '(no models configured)')]);
434
442
  lines.push([span('', '')]);
435
- lines.push([span(t.gray, 'Switch: /model <id> · Add: /model add <id> <name> <model> <baseURL> [apiKey] · Remove: /model remove <id>')]);
443
+ lines.push([
444
+ span(t.gray, byok
445
+ ? 'Switch: /model <id> · Add a provider key: /byok-key <provider> · Run on it: /class byok'
446
+ : 'Switch: /model <id> · Add: /model add <id> <name> <model> <baseURL> [apiKey] · Remove: /model remove <id>'),
447
+ ]);
436
448
  return lines;
437
449
  }
438
450
 
package/src/tokens.js CHANGED
@@ -41,25 +41,53 @@ const RATES = {
41
41
  deepseek: { input: 0.14, output: 0.28, cacheRead: 0.014, cacheWrite: 0.14 },
42
42
  };
43
43
 
44
+ /**
45
+ * Rate rows a model id may name as a whole word rather than as a prefix.
46
+ * Anthropic spells its family *inside* the id — "claude-opus-4" matches no
47
+ * prefix — so prefix matching alone cannot see it.
48
+ */
49
+ const RATE_FAMILIES = Object.keys(RATES).filter((k) => k !== 'default');
50
+
44
51
  /**
45
52
  * The rate row for a model id, provider, or alias. Exact id wins, then the
46
- * longest matching prefix, then the Sonnet-class default — the same resolution
47
- * order contextWindowFor uses, so the cost meter and the context meter cannot
48
- * disagree about which family a model belongs to.
53
+ * longest matching prefix, then a family named inside the id, then the
54
+ * Sonnet-class default — the same resolution order contextWindowFor uses, so
55
+ * the cost meter and the context meter cannot disagree about which family a
56
+ * model belongs to.
49
57
  */
50
58
  function ratesFor(model) {
51
- const id = String(model || '').toLowerCase();
52
- if (!id) return RATES.default;
53
- if (RATES[id]) return RATES[id];
54
- let best = null;
55
- let bestLen = 0;
56
- for (const [prefix, rates] of Object.entries(RATES)) {
57
- if (id.startsWith(prefix) && prefix.length > bestLen) {
58
- best = rates;
59
- bestLen = prefix.length;
59
+ const raw = String(model || '').toLowerCase();
60
+ if (!raw) return RATES.default;
61
+ // `/class byok` selects a "provider:model" id, and the provider half is a
62
+ // routing label, not a rate: rating it as written fell through every prefix
63
+ // to RATES.default, so an Opus BYOK turn was priced at Sonnet's $3/$15
64
+ // against the vendor's real $5/$25.
65
+ const ids = [raw];
66
+ const tail = raw.slice(raw.lastIndexOf(':') + 1);
67
+ if (tail && tail !== raw) ids.push(tail);
68
+ for (const id of ids) {
69
+ if (RATES[id]) return RATES[id];
70
+ let best = null;
71
+ let bestLen = 0;
72
+ for (const [prefix, rates] of Object.entries(RATES)) {
73
+ if (id.startsWith(prefix) && prefix.length > bestLen) {
74
+ best = rates;
75
+ bestLen = prefix.length;
76
+ }
60
77
  }
78
+ if (best) return best;
61
79
  }
62
- return best || RATES.default;
80
+ // Longest family-key hit wins, so an overlapping pair resolves the same way
81
+ // twice running rather than by object key order.
82
+ let family = null;
83
+ let familyLen = 0;
84
+ for (const key of RATE_FAMILIES) {
85
+ if (raw.includes(key) && key.length > familyLen) {
86
+ family = RATES[key];
87
+ familyLen = key.length;
88
+ }
89
+ }
90
+ return family || RATES.default;
63
91
  }
64
92
 
65
93
  // System prompt + tool definitions overhead, roughly, in tokens.
@@ -97,11 +125,21 @@ const CONTEXT_WINDOWS = {
97
125
 
98
126
  /** The context budget to show/guard against for a model id, provider, or raw model string. */
99
127
  function contextWindowFor(model) {
100
- const id = String(model || '').toLowerCase();
101
- if (!id) return CONTEXT_WINDOW;
102
- if (CONTEXT_WINDOWS[id]) return CONTEXT_WINDOWS[id];
103
- for (const [prefix, win] of Object.entries(CONTEXT_WINDOWS)) {
104
- if (id.startsWith(prefix)) return win;
128
+ const raw = String(model || '').toLowerCase();
129
+ if (!raw) return CONTEXT_WINDOW;
130
+ // Same two-candidate lookup as ratesFor above, for the same reason: a byok
131
+ // id ("deepseek:deepseek-v4-flash") carries a routing label in front of the
132
+ // model, and matching it as written left the 1M-token DeepSeek window reading
133
+ // as the 200k default — a meter that would have told a user they were at 20%
134
+ // of a context that was 4% full.
135
+ const ids = [raw];
136
+ const tail = raw.slice(raw.lastIndexOf(':') + 1);
137
+ if (tail && tail !== raw) ids.push(tail);
138
+ for (const id of ids) {
139
+ if (CONTEXT_WINDOWS[id]) return CONTEXT_WINDOWS[id];
140
+ for (const [prefix, win] of Object.entries(CONTEXT_WINDOWS)) {
141
+ if (id.startsWith(prefix)) return win;
142
+ }
105
143
  }
106
144
  return CONTEXT_WINDOW;
107
145
  }