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.
package/src/commands.js CHANGED
@@ -73,6 +73,9 @@ const {
73
73
  const {
74
74
  aggregateSessionUsage, pruneSessionHistory, readResumeList,
75
75
  } = require('./history.js');
76
+ // The custom-endpoint catalog behind the `custom` class and /model add|key|remove.
77
+ const customModelsCatalog = require('./custommodels.js');
78
+ const { VALID_WIRES } = customModelsCatalog;
76
79
 
77
80
  // Guarded: a concurrent workstream owns ./markdown.js.
78
81
  let markdownModule = null;
@@ -111,8 +114,46 @@ const EFFORT_LEVELS = overlays.EFFORT_VALUES;
111
114
 
112
115
  // ── Small handler helpers ─────────────────────────────────────────────────────
113
116
 
114
- const note = (c, text) => c.push({ role: 'note', text });
115
- const panel = (c, lines) => c.push({ role: 'panel', lines });
117
+ /**
118
+ * Split a command's raw tail into tokens, honouring double quotes so a model
119
+ * name or id with a space stays one token
120
+ * (`/model add local "Llama 3 70B" http://…`). Backslash escapes a quote or a
121
+ * backslash inside a quoted run. Never throws — an unclosed quote simply ends
122
+ * at the end of the line.
123
+ */
124
+ function splitArgs(raw) {
125
+ const text = String(raw == null ? '' : raw);
126
+ const out = [];
127
+ let cur = '';
128
+ let quoted = false;
129
+ let started = false;
130
+ for (let i = 0; i < text.length; i++) {
131
+ const ch = text[i];
132
+ if (ch === '\\' && quoted && i + 1 < text.length && (text[i + 1] === '"' || text[i + 1] === '\\')) {
133
+ cur += text[++i];
134
+ started = true;
135
+ continue;
136
+ }
137
+ if (ch === '"') {
138
+ quoted = !quoted;
139
+ // A quoted empty string ("") is a real, intentional token.
140
+ started = true;
141
+ continue;
142
+ }
143
+ if (!quoted && /\s/.test(ch)) {
144
+ if (started) out.push(cur);
145
+ cur = '';
146
+ started = false;
147
+ continue;
148
+ }
149
+ cur += ch;
150
+ started = true;
151
+ }
152
+ if (started) out.push(cur);
153
+ return out;
154
+ }
155
+
156
+ const note = (c, text) => c.push({ role: 'note', text });const panel = (c, lines) => c.push({ role: 'panel', lines });
116
157
  const tip = (c, text) => c.push({ role: 'tip', text });
117
158
  const done = (c, text) => c.push({ role: 'done', text });
118
159
  const shortCwd = () => process.cwd().split('/').filter(Boolean).pop() || '~';
@@ -188,15 +229,24 @@ function findByokProvider(providers, typed) {
188
229
  return { provider: null, exact: false };
189
230
  }
190
231
 
191
- /** One catalog row: id, whether it is already set, its models, and key guidance. */
232
+ /** One catalog row: id, whether it is already set, its models, and key guidance.
233
+ *
234
+ * Every line is an array of span objects, never a plain string — panel/paint
235
+ * (`screen.js` `padLine`/`paint`) iterate a line as spans and read `.t`/`.w`
236
+ * off each entry. A plain string here gets walked character-by-character
237
+ * instead, each "span" comes out `{t: undefined, w: undefined}`, and paint's
238
+ * `sp.s + sp.t` prints the literal text "NaN" once per character.
239
+ */
192
240
  function byokProviderLines(providers) {
193
241
  const lines = [];
194
242
  for (const p of providers) {
195
243
  const state = p.configured
196
244
  ? span(C.green, `set${p.masked ? ` (${p.masked})` : ''}`)
197
245
  : span(C.gray, 'not set');
198
- const label = p.label ? span(C.gray, ` — ${p.label}`) : '';
199
- lines.push(` ${span(C.gold + BOLD, p.id)}${label} ${state}`);
246
+ const row = [span(C.gold + BOLD, ` ${p.id}`)];
247
+ if (p.label) row.push(span(C.gray, ` — ${p.label}`));
248
+ row.push(span('', ' '), state);
249
+ lines.push(row);
200
250
  // `models` arrives as bare ids. The catalog used to be read here as if each
201
251
  // one were an object with `.id`, which silently rendered nothing — a
202
252
  // provider listed with an empty model line reads as "no models", not as a
@@ -204,9 +254,9 @@ function byokProviderLines(providers) {
204
254
  const models = (p.models || [])
205
255
  .map((m) => (typeof m === 'string' ? m : m && m.id))
206
256
  .filter(Boolean);
207
- if (models.length) lines.push(` ${span(C.gray, `models: ${models.join(', ')}`)}`);
208
- if (p.key_prefix) lines.push(` ${span(C.gray, `key starts with ${p.key_prefix}`)}`);
209
- if (p.key_url) lines.push(` ${span(C.gray, p.key_url)}`);
257
+ if (models.length) lines.push([span(C.gray, ` models: ${models.join(', ')}`)]);
258
+ if (p.key_prefix) lines.push([span(C.gray, ` key starts with ${p.key_prefix}`)]);
259
+ if (p.key_url) lines.push([span(C.gray, ` ${p.key_url}`)]);
210
260
  }
211
261
  return lines;
212
262
  }
@@ -791,6 +841,17 @@ const COMMANDS = [
791
841
  desc: 'Switch AI model — pin an id ("-" clears it)',
792
842
  handler: async (c, args) => {
793
843
  const id = (args.sub || '').trim();
844
+ // Which class the pin applies to — /model is class-scoped, because the
845
+ // id spaces are disjoint: the pooled catalog is server-advertised ids,
846
+ // byok is `provider:model`. Every branch below reads the live class, so
847
+ // the copy and the picker's contents describe the route the next turn
848
+ // will actually take (app.js's buildState().models is class-scoped too).
849
+ const cls = (c.ctx && c.ctx.modelClass) || 'aegis';
850
+ const byok = cls === 'byok';
851
+ // The sub-command token, lower-cased: `add` / `key` / `remove` are the
852
+ // custom-endpoint catalog's verbs. A model id is never one of these in
853
+ // practice, and `list` already shadows a real id the same way.
854
+ const sub = id.toLowerCase();
794
855
  if (!id) {
795
856
  note(c, `model: ${c.ctx.model || 'server default'}`);
796
857
  // Populate the picker from the server first — app.js's state().models
@@ -802,27 +863,39 @@ const COMMANDS = [
802
863
  // Say why, and what unblocks it: an unreachable catalog is almost
803
864
  // always a missing key or no network, and "no models advertised"
804
865
  // read as "the platform has none" rather than "this client could not
805
- // ask".
806
- note(c, c.state().online
807
- ? 'Could not read the model catalog (offline, or the server refused it) — /models retries.'
808
- : // The key travels in the environment only (client/aegis.js reads
809
- // AEGIS_API_KEY); /login is an unavailable command here, so
810
- // pointing at it would send the user to a refusal.
811
- 'No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free at https://aegiscloud.org), then retry /model.');
866
+ // ask". On byok "no models" has a third cause — the relay is fine and
867
+ // the account is fine, this machine simply holds no provider key yet,
868
+ // which is exactly what /byok-key fixes.
869
+ note(c, byok
870
+ ? 'No relayable models — this machine holds no provider key yet. Save one with /byok-key <provider>, then retry /model.'
871
+ : c.state().online
872
+ ? 'Could not read the model catalog (offline, or the server refused it) — /models retries.'
873
+ : // The key travels in the environment only (client/aegis.js reads
874
+ // AEGIS_API_KEY); /login is an unavailable command here, so
875
+ // pointing at it would send the user to a refusal.
876
+ 'No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free at https://aegiscloud.org), then retry /model.');
812
877
  c.render();
813
878
  return true;
814
879
  }
815
880
  // A pin that is not in the catalog is not honoured — the pool answers
816
881
  // from its own default with no error. Say so where the pin is visible
817
- // rather than letting the reply look like the pinned model.
882
+ // rather than letting the reply look like the pinned model. On byok the
883
+ // failure mode is different and louder (the relay 400s on a provider it
884
+ // has no key for), so the sentence names the right one.
818
885
  if (c.ctx.model && !models.some((m) => m.id === c.ctx.model)) {
819
- note(c, `pinned model "${c.ctx.model}" is not in the catalog — the pool will answer with its own default; pick one below.`);
886
+ note(c, byok
887
+ ? `pinned model "${c.ctx.model}" is not one this machine can relay — pick from the list below.`
888
+ : `pinned model "${c.ctx.model}" is not in the catalog — the pool will answer with its own default; pick one below.`);
820
889
  }
821
890
  // The overlay's own copy promises /model add|remove (overlays.js, a
822
891
  // separate workstream); this build refuses both, so say here how a
823
892
  // model is actually selected.
824
- note(c, '/model <id> pins one for this session; /models lists what the server advertises.');
825
- c.openOverlay({ type: 'model', items: models, sel: 0, current: c.ctx.model });
893
+ note(c, byok
894
+ ? '/model <id> pins one for this session; /models lists what this machine can relay.'
895
+ : '/model <id> pins one for this session; /models lists what the server advertises.');
896
+ // `cls` rides on the overlay so the picker's title and subtitle render
897
+ // for the class that opened it, even if /class moves while it is open.
898
+ c.openOverlay({ type: 'model', items: models, sel: 0, current: c.ctx.model, cls });
826
899
  return true;
827
900
  }
828
901
  if (id === 'list') {
@@ -833,15 +906,102 @@ const COMMANDS = [
833
906
  c.render();
834
907
  return true;
835
908
  }
836
- if (id === 'add' || id === 'remove' || id === 'rm') {
837
- note(c, 'Model add/remove isn\'t supported in this build — pin an existing server id with /model <id>.');
909
+ // The /model add catalog — the aegiscodex-dev concept ported in. A user
910
+ // registers their own endpoint (own base URL, own model string, own key)
911
+ // and the CLI calls it DIRECTLY through the desktop transport, the full
912
+ // tool loop and all: no pooled route, no BYOK relay, no fee or margin.
913
+ // The classic entry form is the positional one
914
+ // /model add <id> <name> <model> <baseURL> [wire]
915
+ // with the key prompted for (masked) right after, or supplied inline
916
+ // /model add <id> <name> <model> <baseURL> [wire] <key>
917
+ // (the scriptable spelling, like /byok-key's second token).
918
+ if (sub === 'add') {
919
+ const parts = splitArgs(args._rest);
920
+ // `sub` itself is the first token of _rest, so drop its own copy.
921
+ const rest = parts[0] === 'add' ? parts.slice(1) : parts;
922
+ // The wire name is optional and only recognised when it is one of the
923
+ // two transports — otherwise that token is the key (so
924
+ // `/model add id name model url sk-…` needs no placeholder).
925
+ let at = 4;
926
+ let wire;
927
+ if (VALID_WIRES.includes(String(rest[at] || '').toLowerCase())) {
928
+ wire = String(rest[at]).toLowerCase();
929
+ at += 1;
930
+ }
931
+ const fields = { id: rest[0], name: rest[1], model: rest[2], baseURL: rest[3], wire };
932
+ if (!fields.id || !fields.model || !fields.baseURL) {
933
+ note(c, 'Usage: /model add <id> <name> <model> <baseURL> [openai|anthropic] [key]');
934
+ note(c, ' e.g. /model add local Llama-3 "meta-llama/Llama-3-70b" http://localhost:8080/v1');
935
+ note(c, ' the key is prompted for and stored 0600 on this machine — never in config.json.');
936
+ c.render();
937
+ return true;
938
+ }
939
+ const inlineKey = rest[at] || '';
940
+ const store = c.settings && c.settings();
941
+ const res = customModelsCatalog.addCustom({ ...fields, key: null }, store);
942
+ if (res.error) {
943
+ c.push({ role: 'error', text: `couldn't add "${fields.id}": ${res.error}` });
944
+ return true;
945
+ }
946
+ const entry = res.entry;
947
+ let key = inlineKey || '';
948
+ if (!key) {
949
+ note(c, `storing a key for "${entry.id}" — leave it blank to add it later with /model key ${entry.id}.`);
950
+ c.render();
951
+ key = String((await c.readSecret(`${entry.id} key: `)) || '').trim();
952
+ }
953
+ if (key) {
954
+ customModelsCatalog.setCustomKey(entry.id, key, store);
955
+ }
956
+ note(c, `added "${entry.id}" → ${entry.model} at ${entry.baseURL} (${entry.wire} wire)${key ? '' : ' — no key yet'}.`);
957
+ note(c, key
958
+ ? `run it with /class custom (then /model ${entry.id}), or /model ${entry.id} while on the custom class.`
959
+ : `add its key with /model key ${entry.id}, then /class custom runs it.`);
960
+ c.render();
961
+ return true;
962
+ }
963
+ if (sub === 'key') {
964
+ const target = splitArgs(args._rest)[1];
965
+ if (!target) { note(c, 'Usage: /model key <id> — /models lists your custom endpoints.'); c.render(); return true; }
966
+ const entry = customModelsCatalog.getCustom(target);
967
+ if (!entry) { note(c, `no custom endpoint "${target}" — /model add registers one.`); c.render(); return true; }
968
+ const store = c.settings && c.settings();
969
+ note(c, `storing a key for "${entry.id}" — blank clears it.`);
970
+ c.render();
971
+ const key = String((await c.readSecret(`${entry.id} key: `)) || '').trim();
972
+ if (!key) { note(c, 'nothing saved.'); c.render(); return true; }
973
+ customModelsCatalog.setCustomKey(entry.id, key, store);
974
+ note(c, `saved a key for "${entry.id}" on this machine — /class custom runs it.`);
975
+ c.render();
976
+ return true;
977
+ }
978
+ if (sub === 'remove' || sub === 'rm') {
979
+ const target = splitArgs(args._rest)[1];
980
+ if (!target) { note(c, 'Usage: /model remove <id>'); c.render(); return true; }
981
+ const store = c.settings && c.settings();
982
+ const { removed } = customModelsCatalog.removeCustom(target, store);
983
+ if (!removed) { note(c, `no custom endpoint "${target}" — /models lists your endpoints.`); c.render(); return true; }
984
+ // A pin on the row we just deleted would otherwise outlive its entry and
985
+ // fail at the next send with "no model … in the catalog".
986
+ if (String(c.ctx.model || '') === String(target)) {
987
+ c.ctx.model = null;
988
+ c.saveConfig({ model: null, currentModelId: null });
989
+ note(c, `unpinned "${target}" (its catalog entry is gone).`);
990
+ }
991
+ note(c, `removed "${target}" and forgot its key.`);
838
992
  c.render();
839
993
  return true;
840
994
  }
841
995
  if (id === '-') {
842
996
  c.ctx.model = null;
843
997
  c.saveConfig({ model: null, currentModelId: null });
844
- note(c, 'Model pin cleared — the server will choose.');
998
+ note(c, byok
999
+ // There is no such thing as a byok default: the relay addresses a
1000
+ // provider by the id itself, so "nothing pinned" is not a fallback
1001
+ // here, it is a turn that will 400 with "model must be
1002
+ // <provider>:<model>". Said now rather than at the next send.
1003
+ ? 'Model pin cleared. The byok class has no server default — the next turn needs <provider>:<model>, so pin one from /models before sending.'
1004
+ : 'Model pin cleared — the server will choose.');
845
1005
  c.render();
846
1006
  return true;
847
1007
  }
@@ -852,15 +1012,20 @@ const COMMANDS = [
852
1012
  // dir, so the write stays inside that dir.
853
1013
  c.saveConfig({ model: id, currentModelId: id });
854
1014
  note(c, `Pinned model: ${id}`);
855
- // The server accepts an id it does not advertise and answers from its own
856
- // default — no error, a different model, and the spend attributed to the
857
- // id that was pinned. Warn (never refuse: the catalog is cached, and
858
- // refusing would break a pin made against a server that is briefly
859
- // unreachable) so the mismatch is visible at the moment it is created.
1015
+ // A pin the class cannot honour is the same problem on both classes and
1016
+ // only the consequence differs, so both branches say the consequence.
1017
+ // Pooled: the server accepts an id it does not advertise and answers from
1018
+ // its own default — no error, a different model, and the spend attributed
1019
+ // to the id that was pinned. Byok: the id is parsed as a provider name,
1020
+ // so a pooled id becomes "no key saved for <that id>" at the relay.
1021
+ // Warn, never refuse: the catalog is cached, and refusing would break a
1022
+ // pin made against a server that is briefly unreachable.
860
1023
  await loadModels(c);
861
1024
  const models = c.state().models || [];
862
1025
  if (models.length && !models.some((m) => m.id === id)) {
863
- note(c, `"${id}" is not in the AEGIS Cloud catalog — the pool will answer with its own default. /models lists the real ids.`);
1026
+ note(c, byok
1027
+ ? `"${id}" is not one this machine can relay — a byok id is "<provider>:<model>", and the relay will refuse anything else. /models lists the real ids.`
1028
+ : `"${id}" is not in the AEGIS Cloud catalog — the pool will answer with its own default. /models lists the real ids.`);
864
1029
  }
865
1030
  c.render();
866
1031
  return true;
@@ -1914,7 +2079,7 @@ const COMMANDS = [
1914
2079
  [span(C.gray, '─'.repeat(34))],
1915
2080
  [
1916
2081
  span(set ? C.green : C.gray, ` ${set} of ${providers.length} providers set`),
1917
- span(C.gray, ' — /byok-set <provider>'),
2082
+ span(C.gray, ' — /byok-key <provider>'),
1918
2083
  ],
1919
2084
  '',
1920
2085
  ...byokProviderLines(providers),
@@ -1926,7 +2091,7 @@ const COMMANDS = [
1926
2091
  },
1927
2092
  {
1928
2093
  name: 'byok-set', args: ['provider'], hint: '<provider>', category: 'auth',
1929
- desc: 'Set YOUR provider key (prompted, never echoed, never in history)',
2094
+ desc: 'Store your provider key on your AEGIS ACCOUNT (pooled route) — for the byok class use /byok-key',
1930
2095
  tool: 'aegis_byok_set',
1931
2096
  secret: 'key',
1932
2097
  build: (arg) => ({ provider: String(arg || '').trim() }),
@@ -1985,11 +2150,195 @@ const COMMANDS = [
1985
2150
  tool: 'aegis_byok_set',
1986
2151
  build: (arg) => ({ provider: String(arg || '').trim() }),
1987
2152
  },
2153
+ {
2154
+ name: 'class', args: ['class'], hint: '[aegis|byok]', category: 'model',
2155
+ desc: 'Show or switch which class turns run on: pooled AEGIS Cloud, or your own key',
2156
+ handler: async (c, a) => {
2157
+ const args = a || {};
2158
+ const cur = (c.ctx && c.ctx.modelClass) || 'aegis';
2159
+ const label = (id) => (c.classLabel ? c.classLabel(id) : id);
2160
+ const want = String(args.class || '').trim().toLowerCase();
2161
+ if (!want) {
2162
+ // Awaited: the engine's listClasses() is async (it probes for a local
2163
+ // Ollama before answering), and a context that offers no class surface
2164
+ // at all falls back to the two static rows below.
2165
+ const classes = await Promise.resolve(c.classes ? c.classes() : []).catch(() => []);
2166
+ const rows = classes.length ? classes : [{ class: 'aegis' }, { class: 'byok' }];
2167
+ const lines = [
2168
+ [span(C.gold + BOLD, 'Class'), span(BOLD_OFF, ' — which route the next turn takes')],
2169
+ [span(C.gray, '─'.repeat(52))],
2170
+ ];
2171
+ for (const k of rows) {
2172
+ const id = k.class;
2173
+ const on = id === cur;
2174
+ // The distinction that matters to a user: who pays, and with which
2175
+ // credential. Stated per class rather than in a footnote.
2176
+ const note =
2177
+ id === 'byok'
2178
+ ? k.configured
2179
+ ? 'your key, relayed by AEGIS — billed a handling fee'
2180
+ : 'needs a provider key: /byok-key <provider>'
2181
+ : 'the pool — your AEGIS account key pays for it';
2182
+ lines.push([
2183
+ span(on ? C.green : C.gray, ` ${on ? '●' : '○'} ${String(id).padEnd(6)}`),
2184
+ span(on ? C.green : C.gray, label(id)),
2185
+ span(C.gray, ` ${note}`),
2186
+ ]);
2187
+ }
2188
+ lines.push('', [span(C.gray, ' switch with /class byok or /class aegis')]);
2189
+ panel(c, lines);
2190
+ c.render();
2191
+ return true;
2192
+ }
2193
+ const res = c.switchClass(want);
2194
+ if (!res.ok) {
2195
+ c.push({ role: 'error', text: res.error });
2196
+ return true;
2197
+ }
2198
+ c.push({ role: 'done', text: `class: ${res.class} — ${label(res.class)}` });
2199
+ if (res.cleared) {
2200
+ c.push({
2201
+ role: 'note',
2202
+ text: `cleared the pin "${res.cleared}" — it does not belong to this class. /models lists what fits.`,
2203
+ });
2204
+ }
2205
+ // Entering byok with nothing pinned fails the very next turn: the relay's
2206
+ // model id must be "<provider>:<model>" and there is no server default to
2207
+ // fall back to (engine.js chatCompletion throws a 400 on a bare id). So
2208
+ // land on one this machine can actually run — a provider it holds a key
2209
+ // for wins, since the alternative 400s on the key rather than the id.
2210
+ if (res.class === 'byok' && !(c.ctx && c.ctx.model)) {
2211
+ const models = (await c.listModelsFor('byok')) || [];
2212
+ const pick = models.find((m) => m.configured) || models[0];
2213
+ if (pick) {
2214
+ c.ctx.model = pick.id;
2215
+ c.saveConfig({ model: pick.id, currentModelId: pick.id });
2216
+ c.push({
2217
+ role: 'note',
2218
+ text: pick.configured
2219
+ ? `using ${pick.id} — /models lists the rest.`
2220
+ : `using ${pick.id}, but no ${pick.provider} key is saved yet — /byok-key ${pick.provider}.`,
2221
+ });
2222
+ } else if (models.length === 0) {
2223
+ c.push({
2224
+ role: 'note',
2225
+ text: 'nothing to relay yet — save a provider key with /byok-key <provider>, then /models.',
2226
+ });
2227
+ }
2228
+ }
2229
+ return true;
2230
+ },
2231
+ },
1988
2232
  {
1989
2233
  name: 'models', aliases: ['model-list'], hint: '', category: 'model',
1990
- desc: 'List the model ids you can pin with /model',
1991
- tool: 'aegis_list_models',
1992
- build: () => ({}),
2234
+ desc: 'List the model ids you can pin with /model, for the class you are on',
2235
+ handler: async (c) => {
2236
+ const cls = (c.ctx && c.ctx.modelClass) || 'aegis';
2237
+ const models = (await c.listModelsFor(cls)) || [];
2238
+ const lines = [
2239
+ [span(C.gold + BOLD, 'Models'), span(BOLD_OFF, ` — ${c.classLabel ? c.classLabel(cls) : cls}`)],
2240
+ [span(C.gray, '─'.repeat(52))],
2241
+ ];
2242
+ if (!models.length) {
2243
+ lines.push('', [
2244
+ span(
2245
+ C.gray,
2246
+ cls === 'byok'
2247
+ ? ' nothing to relay yet — save a provider key with /byok-key <provider>'
2248
+ : ' no models advertised — check the account with /status, then retry'
2249
+ ),
2250
+ ]);
2251
+ } else {
2252
+ const pinned = c.ctx && c.ctx.model;
2253
+ for (const m of models) {
2254
+ const on = pinned === m.id;
2255
+ lines.push([
2256
+ span(on ? C.green : C.gray, ` ${on ? '●' : '○'} `),
2257
+ span(on ? C.green : C.gray, String(m.id).padEnd(30)),
2258
+ span(C.gray, m.note || m.label || ''),
2259
+ ]);
2260
+ }
2261
+ lines.push('', [span(C.gray, ' pin one with /model <id> — /model alone opens the picker')]);
2262
+ }
2263
+ panel(c, lines);
2264
+ c.render();
2265
+ return true;
2266
+ },
2267
+ },
2268
+ {
2269
+ name: 'byok-key', args: ['provider'], hint: '<provider> [key]', category: 'auth',
2270
+ desc: 'Save YOUR provider key on THIS MACHINE — the key the byok class sends',
2271
+ handler: async (c, a) => {
2272
+ const args = a || {};
2273
+ const typed = String(args.provider || '').trim().toLowerCase();
2274
+ if (!typed) {
2275
+ c.push({ role: 'error', text: 'Usage: /byok-key <provider> — /byok lists the providers.' });
2276
+ return true;
2277
+ }
2278
+ const store = c.settings && c.settings();
2279
+ if (!store || typeof store.set !== 'function') {
2280
+ c.push({ role: 'error', text: 'this client has no provider-key store.' });
2281
+ return true;
2282
+ }
2283
+ // Resolve the alias against the server's catalog so the row is written
2284
+ // under the id the relay will actually be asked for (`/byok-key OpenAI`
2285
+ // and `/byok-key openai` must be one key, not two).
2286
+ const providers = await byokCatalog(c.client);
2287
+ const match = providers ? findByokProvider(providers, typed) : null;
2288
+ if (match && match.ambiguous) {
2289
+ c.push({ role: 'error', text: `"${typed}" matches ${match.ambiguous.join(', ')} — retype the exact id.` });
2290
+ return true;
2291
+ }
2292
+ const p = match && match.provider;
2293
+ const id = (p && p.id) || typed;
2294
+ // A second token is the scriptable path (`/byok-key openai sk-…`); with
2295
+ // none we prompt — readSecret never echoes and never enters history.
2296
+ const rest = String(args._rest || '').trim();
2297
+ const sp = rest.indexOf(' ');
2298
+ let key = sp === -1 ? '' : rest.slice(sp + 1).trim();
2299
+ if (!key) {
2300
+ if (p && p.key_url) c.push({ role: 'note', text: `create a ${p.label || id} key at ${p.key_url}` });
2301
+ key = String((await c.readSecret(`${id} key: `)) || '').trim();
2302
+ }
2303
+ if (!key) {
2304
+ c.push({ role: 'note', text: 'nothing saved.' });
2305
+ return true;
2306
+ }
2307
+ if (p && p.key_prefix && !key.startsWith(p.key_prefix)) {
2308
+ c.push({ role: 'note', text: `heads up: ${id} keys normally start with "${p.key_prefix}" — saved anyway.` });
2309
+ }
2310
+ store.set(c.byokNamespace(id), { key });
2311
+ c.push({
2312
+ role: 'done',
2313
+ text: `saved a ${id} key on this machine — /models lists its models, /class byok runs on it.`,
2314
+ });
2315
+ return true;
2316
+ },
2317
+ },
2318
+ {
2319
+ name: 'byok-rm-key', args: ['provider'], hint: '<provider>', category: 'auth',
2320
+ desc: 'Forget the provider key saved on this machine',
2321
+ handler: async (c, a) => {
2322
+ const args = a || {};
2323
+ const id = String(args.provider || '').trim().toLowerCase();
2324
+ if (!id) {
2325
+ c.push({ role: 'error', text: 'Usage: /byok-rm-key <provider> — /byok lists the providers.' });
2326
+ return true;
2327
+ }
2328
+ const store = c.settings && c.settings();
2329
+ if (!store || typeof store.remove !== 'function') {
2330
+ c.push({ role: 'error', text: 'this client has no provider-key store.' });
2331
+ return true;
2332
+ }
2333
+ const row = c.byokNamespace(id);
2334
+ const had = typeof store.rawKey === 'function' ? store.rawKey(row) : null;
2335
+ store.remove(row);
2336
+ c.push({
2337
+ role: had ? 'done' : 'note',
2338
+ text: had ? `removed the ${id} key from this machine.` : `no ${id} key was saved on this machine.`,
2339
+ });
2340
+ return true;
2341
+ },
1993
2342
  },
1994
2343
  {
1995
2344
  name: 'tool', args: ['name', 'json'], hint: '<name> [json]', category: 'aegis',
package/src/config.js CHANGED
@@ -60,11 +60,29 @@ const DEFAULT_CONFIG = {
60
60
  // chooses, and app.js's validatePinnedModel() clears a stored id the catalog
61
61
  // does not advertise.
62
62
  model: null,
63
+ // Which class turns run on: 'aegis' (the pool, authenticated and paid for by
64
+ // the account key) or 'byok' (the user's own provider key, relayed and billed
65
+ // a handling fee). Persisted so `/class byok` survives a restart — a class
66
+ // choice that silently reverted would send the next launch's turn somewhere
67
+ // the user did not choose, and on a BYOK setup there is no pooled key to fall
68
+ // back to. Defaulted to the pooled class, which is the only one an account
69
+ // key alone can run.
70
+ modelClass: 'aegis',
63
71
  // Phase 6: the full model table (seeded from src/models.js MODELS on first
64
72
  // read by pickerModels()). 'currentModelId' mirrors `model` under the
65
73
  // aegiscode- name so /model add/remove/switch stay compatible both ways.
66
74
  models: null,
67
75
  currentModelId: null,
76
+ // The named custom-model catalog behind the `custom` class — the
77
+ // aegiscodex-dev `/model add` concept: each entry names an endpoint the user
78
+ // brings themselves (own base URL + own key), called DIRECTLY through the
79
+ // desktop transport (providers.openaiCompatible / anthropicMessages), tools
80
+ // and all, never through the pooled route or the BYOK relay. Only the
81
+ // non-secret metadata lives here; the key is in the 0600 settings store under
82
+ // `custom:<id>` (engine.js), never in this file (config.json is not 0600 and
83
+ // participates in cloud sync). Shape: [{ id, name, model, baseURL, wire }],
84
+ // wire ∈ {'openai','anthropic'}.
85
+ customModels: [],
68
86
  // `null` = no effort pinned, i.e. "auto": each turn is sized by the server
69
87
  // from the ask itself (aegis1 services/pool_brain.py estimate_effort). The
70
88
  // old 'high' was a *pin* on the top rung of the budget ladder — the most the