aegiscode 6.7.4 → 6.7.6

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
@@ -188,15 +188,24 @@ function findByokProvider(providers, typed) {
188
188
  return { provider: null, exact: false };
189
189
  }
190
190
 
191
- /** One catalog row: id, whether it is already set, its models, and key guidance. */
191
+ /** One catalog row: id, whether it is already set, its models, and key guidance.
192
+ *
193
+ * Every line is an array of span objects, never a plain string — panel/paint
194
+ * (`screen.js` `padLine`/`paint`) iterate a line as spans and read `.t`/`.w`
195
+ * off each entry. A plain string here gets walked character-by-character
196
+ * instead, each "span" comes out `{t: undefined, w: undefined}`, and paint's
197
+ * `sp.s + sp.t` prints the literal text "NaN" once per character.
198
+ */
192
199
  function byokProviderLines(providers) {
193
200
  const lines = [];
194
201
  for (const p of providers) {
195
202
  const state = p.configured
196
203
  ? span(C.green, `set${p.masked ? ` (${p.masked})` : ''}`)
197
204
  : 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}`);
205
+ const row = [span(C.gold + BOLD, ` ${p.id}`)];
206
+ if (p.label) row.push(span(C.gray, ` — ${p.label}`));
207
+ row.push(span('', ' '), state);
208
+ lines.push(row);
200
209
  // `models` arrives as bare ids. The catalog used to be read here as if each
201
210
  // one were an object with `.id`, which silently rendered nothing — a
202
211
  // provider listed with an empty model line reads as "no models", not as a
@@ -204,9 +213,9 @@ function byokProviderLines(providers) {
204
213
  const models = (p.models || [])
205
214
  .map((m) => (typeof m === 'string' ? m : m && m.id))
206
215
  .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)}`);
216
+ if (models.length) lines.push([span(C.gray, ` models: ${models.join(', ')}`)]);
217
+ if (p.key_prefix) lines.push([span(C.gray, ` key starts with ${p.key_prefix}`)]);
218
+ if (p.key_url) lines.push([span(C.gray, ` ${p.key_url}`)]);
210
219
  }
211
220
  return lines;
212
221
  }
@@ -791,6 +800,13 @@ const COMMANDS = [
791
800
  desc: 'Switch AI model — pin an id ("-" clears it)',
792
801
  handler: async (c, args) => {
793
802
  const id = (args.sub || '').trim();
803
+ // Which class the pin applies to — /model is class-scoped, because the
804
+ // id spaces are disjoint: the pooled catalog is server-advertised ids,
805
+ // byok is `provider:model`. Every branch below reads the live class, so
806
+ // the copy and the picker's contents describe the route the next turn
807
+ // will actually take (app.js's buildState().models is class-scoped too).
808
+ const cls = (c.ctx && c.ctx.modelClass) || 'aegis';
809
+ const byok = cls === 'byok';
794
810
  if (!id) {
795
811
  note(c, `model: ${c.ctx.model || 'server default'}`);
796
812
  // Populate the picker from the server first — app.js's state().models
@@ -802,27 +818,39 @@ const COMMANDS = [
802
818
  // Say why, and what unblocks it: an unreachable catalog is almost
803
819
  // always a missing key or no network, and "no models advertised"
804
820
  // 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.');
821
+ // ask". On byok "no models" has a third cause — the relay is fine and
822
+ // the account is fine, this machine simply holds no provider key yet,
823
+ // which is exactly what /byok-key fixes.
824
+ note(c, byok
825
+ ? 'No relayable models — this machine holds no provider key yet. Save one with /byok-key <provider>, then retry /model.'
826
+ : c.state().online
827
+ ? 'Could not read the model catalog (offline, or the server refused it) — /models retries.'
828
+ : // The key travels in the environment only (client/aegis.js reads
829
+ // AEGIS_API_KEY); /login is an unavailable command here, so
830
+ // pointing at it would send the user to a refusal.
831
+ 'No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free at https://aegiscloud.org), then retry /model.');
812
832
  c.render();
813
833
  return true;
814
834
  }
815
835
  // A pin that is not in the catalog is not honoured — the pool answers
816
836
  // 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.
837
+ // rather than letting the reply look like the pinned model. On byok the
838
+ // failure mode is different and louder (the relay 400s on a provider it
839
+ // has no key for), so the sentence names the right one.
818
840
  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.`);
841
+ note(c, byok
842
+ ? `pinned model "${c.ctx.model}" is not one this machine can relay — pick from the list below.`
843
+ : `pinned model "${c.ctx.model}" is not in the catalog — the pool will answer with its own default; pick one below.`);
820
844
  }
821
845
  // The overlay's own copy promises /model add|remove (overlays.js, a
822
846
  // separate workstream); this build refuses both, so say here how a
823
847
  // 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 });
848
+ note(c, byok
849
+ ? '/model <id> pins one for this session; /models lists what this machine can relay.'
850
+ : '/model <id> pins one for this session; /models lists what the server advertises.');
851
+ // `cls` rides on the overlay so the picker's title and subtitle render
852
+ // for the class that opened it, even if /class moves while it is open.
853
+ c.openOverlay({ type: 'model', items: models, sel: 0, current: c.ctx.model, cls });
826
854
  return true;
827
855
  }
828
856
  if (id === 'list') {
@@ -834,14 +862,22 @@ const COMMANDS = [
834
862
  return true;
835
863
  }
836
864
  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>.');
865
+ note(c, byok
866
+ ? 'Model add/remove isn\'t supported in this build — on the byok class the list follows the provider keys you hold (/byok-key <provider>), then /model <provider>:<model>.'
867
+ : 'Model add/remove isn\'t supported in this build — pin an existing server id with /model <id>.');
838
868
  c.render();
839
869
  return true;
840
870
  }
841
871
  if (id === '-') {
842
872
  c.ctx.model = null;
843
873
  c.saveConfig({ model: null, currentModelId: null });
844
- note(c, 'Model pin cleared — the server will choose.');
874
+ note(c, byok
875
+ // There is no such thing as a byok default: the relay addresses a
876
+ // provider by the id itself, so "nothing pinned" is not a fallback
877
+ // here, it is a turn that will 400 with "model must be
878
+ // <provider>:<model>". Said now rather than at the next send.
879
+ ? 'Model pin cleared. The byok class has no server default — the next turn needs <provider>:<model>, so pin one from /models before sending.'
880
+ : 'Model pin cleared — the server will choose.');
845
881
  c.render();
846
882
  return true;
847
883
  }
@@ -852,15 +888,20 @@ const COMMANDS = [
852
888
  // dir, so the write stays inside that dir.
853
889
  c.saveConfig({ model: id, currentModelId: id });
854
890
  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.
891
+ // A pin the class cannot honour is the same problem on both classes and
892
+ // only the consequence differs, so both branches say the consequence.
893
+ // Pooled: the server accepts an id it does not advertise and answers from
894
+ // its own default — no error, a different model, and the spend attributed
895
+ // to the id that was pinned. Byok: the id is parsed as a provider name,
896
+ // so a pooled id becomes "no key saved for <that id>" at the relay.
897
+ // Warn, never refuse: the catalog is cached, and refusing would break a
898
+ // pin made against a server that is briefly unreachable.
860
899
  await loadModels(c);
861
900
  const models = c.state().models || [];
862
901
  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.`);
902
+ note(c, byok
903
+ ? `"${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.`
904
+ : `"${id}" is not in the AEGIS Cloud catalog — the pool will answer with its own default. /models lists the real ids.`);
864
905
  }
865
906
  c.render();
866
907
  return true;
@@ -1914,7 +1955,7 @@ const COMMANDS = [
1914
1955
  [span(C.gray, '─'.repeat(34))],
1915
1956
  [
1916
1957
  span(set ? C.green : C.gray, ` ${set} of ${providers.length} providers set`),
1917
- span(C.gray, ' — /byok-set <provider>'),
1958
+ span(C.gray, ' — /byok-key <provider>'),
1918
1959
  ],
1919
1960
  '',
1920
1961
  ...byokProviderLines(providers),
@@ -1926,7 +1967,7 @@ const COMMANDS = [
1926
1967
  },
1927
1968
  {
1928
1969
  name: 'byok-set', args: ['provider'], hint: '<provider>', category: 'auth',
1929
- desc: 'Set YOUR provider key (prompted, never echoed, never in history)',
1970
+ desc: 'Store your provider key on your AEGIS ACCOUNT (pooled route) — for the byok class use /byok-key',
1930
1971
  tool: 'aegis_byok_set',
1931
1972
  secret: 'key',
1932
1973
  build: (arg) => ({ provider: String(arg || '').trim() }),
@@ -1985,11 +2026,195 @@ const COMMANDS = [
1985
2026
  tool: 'aegis_byok_set',
1986
2027
  build: (arg) => ({ provider: String(arg || '').trim() }),
1987
2028
  },
2029
+ {
2030
+ name: 'class', args: ['class'], hint: '[aegis|byok]', category: 'model',
2031
+ desc: 'Show or switch which class turns run on: pooled AEGIS Cloud, or your own key',
2032
+ handler: async (c, a) => {
2033
+ const args = a || {};
2034
+ const cur = (c.ctx && c.ctx.modelClass) || 'aegis';
2035
+ const label = (id) => (c.classLabel ? c.classLabel(id) : id);
2036
+ const want = String(args.class || '').trim().toLowerCase();
2037
+ if (!want) {
2038
+ // Awaited: the engine's listClasses() is async (it probes for a local
2039
+ // Ollama before answering), and a context that offers no class surface
2040
+ // at all falls back to the two static rows below.
2041
+ const classes = await Promise.resolve(c.classes ? c.classes() : []).catch(() => []);
2042
+ const rows = classes.length ? classes : [{ class: 'aegis' }, { class: 'byok' }];
2043
+ const lines = [
2044
+ [span(C.gold + BOLD, 'Class'), span(BOLD_OFF, ' — which route the next turn takes')],
2045
+ [span(C.gray, '─'.repeat(52))],
2046
+ ];
2047
+ for (const k of rows) {
2048
+ const id = k.class;
2049
+ const on = id === cur;
2050
+ // The distinction that matters to a user: who pays, and with which
2051
+ // credential. Stated per class rather than in a footnote.
2052
+ const note =
2053
+ id === 'byok'
2054
+ ? k.configured
2055
+ ? 'your key, relayed by AEGIS — billed a handling fee'
2056
+ : 'needs a provider key: /byok-key <provider>'
2057
+ : 'the pool — your AEGIS account key pays for it';
2058
+ lines.push([
2059
+ span(on ? C.green : C.gray, ` ${on ? '●' : '○'} ${String(id).padEnd(6)}`),
2060
+ span(on ? C.green : C.gray, label(id)),
2061
+ span(C.gray, ` ${note}`),
2062
+ ]);
2063
+ }
2064
+ lines.push('', [span(C.gray, ' switch with /class byok or /class aegis')]);
2065
+ panel(c, lines);
2066
+ c.render();
2067
+ return true;
2068
+ }
2069
+ const res = c.switchClass(want);
2070
+ if (!res.ok) {
2071
+ c.push({ role: 'error', text: res.error });
2072
+ return true;
2073
+ }
2074
+ c.push({ role: 'done', text: `class: ${res.class} — ${label(res.class)}` });
2075
+ if (res.cleared) {
2076
+ c.push({
2077
+ role: 'note',
2078
+ text: `cleared the pin "${res.cleared}" — it does not belong to this class. /models lists what fits.`,
2079
+ });
2080
+ }
2081
+ // Entering byok with nothing pinned fails the very next turn: the relay's
2082
+ // model id must be "<provider>:<model>" and there is no server default to
2083
+ // fall back to (engine.js chatCompletion throws a 400 on a bare id). So
2084
+ // land on one this machine can actually run — a provider it holds a key
2085
+ // for wins, since the alternative 400s on the key rather than the id.
2086
+ if (res.class === 'byok' && !(c.ctx && c.ctx.model)) {
2087
+ const models = (await c.listModelsFor('byok')) || [];
2088
+ const pick = models.find((m) => m.configured) || models[0];
2089
+ if (pick) {
2090
+ c.ctx.model = pick.id;
2091
+ c.saveConfig({ model: pick.id, currentModelId: pick.id });
2092
+ c.push({
2093
+ role: 'note',
2094
+ text: pick.configured
2095
+ ? `using ${pick.id} — /models lists the rest.`
2096
+ : `using ${pick.id}, but no ${pick.provider} key is saved yet — /byok-key ${pick.provider}.`,
2097
+ });
2098
+ } else if (models.length === 0) {
2099
+ c.push({
2100
+ role: 'note',
2101
+ text: 'nothing to relay yet — save a provider key with /byok-key <provider>, then /models.',
2102
+ });
2103
+ }
2104
+ }
2105
+ return true;
2106
+ },
2107
+ },
1988
2108
  {
1989
2109
  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: () => ({}),
2110
+ desc: 'List the model ids you can pin with /model, for the class you are on',
2111
+ handler: async (c) => {
2112
+ const cls = (c.ctx && c.ctx.modelClass) || 'aegis';
2113
+ const models = (await c.listModelsFor(cls)) || [];
2114
+ const lines = [
2115
+ [span(C.gold + BOLD, 'Models'), span(BOLD_OFF, ` — ${c.classLabel ? c.classLabel(cls) : cls}`)],
2116
+ [span(C.gray, '─'.repeat(52))],
2117
+ ];
2118
+ if (!models.length) {
2119
+ lines.push('', [
2120
+ span(
2121
+ C.gray,
2122
+ cls === 'byok'
2123
+ ? ' nothing to relay yet — save a provider key with /byok-key <provider>'
2124
+ : ' no models advertised — check the account with /status, then retry'
2125
+ ),
2126
+ ]);
2127
+ } else {
2128
+ const pinned = c.ctx && c.ctx.model;
2129
+ for (const m of models) {
2130
+ const on = pinned === m.id;
2131
+ lines.push([
2132
+ span(on ? C.green : C.gray, ` ${on ? '●' : '○'} `),
2133
+ span(on ? C.green : C.gray, String(m.id).padEnd(30)),
2134
+ span(C.gray, m.note || m.label || ''),
2135
+ ]);
2136
+ }
2137
+ lines.push('', [span(C.gray, ' pin one with /model <id> — /model alone opens the picker')]);
2138
+ }
2139
+ panel(c, lines);
2140
+ c.render();
2141
+ return true;
2142
+ },
2143
+ },
2144
+ {
2145
+ name: 'byok-key', args: ['provider'], hint: '<provider> [key]', category: 'auth',
2146
+ desc: 'Save YOUR provider key on THIS MACHINE — the key the byok class sends',
2147
+ handler: async (c, a) => {
2148
+ const args = a || {};
2149
+ const typed = String(args.provider || '').trim().toLowerCase();
2150
+ if (!typed) {
2151
+ c.push({ role: 'error', text: 'Usage: /byok-key <provider> — /byok lists the providers.' });
2152
+ return true;
2153
+ }
2154
+ const store = c.settings && c.settings();
2155
+ if (!store || typeof store.set !== 'function') {
2156
+ c.push({ role: 'error', text: 'this client has no provider-key store.' });
2157
+ return true;
2158
+ }
2159
+ // Resolve the alias against the server's catalog so the row is written
2160
+ // under the id the relay will actually be asked for (`/byok-key OpenAI`
2161
+ // and `/byok-key openai` must be one key, not two).
2162
+ const providers = await byokCatalog(c.client);
2163
+ const match = providers ? findByokProvider(providers, typed) : null;
2164
+ if (match && match.ambiguous) {
2165
+ c.push({ role: 'error', text: `"${typed}" matches ${match.ambiguous.join(', ')} — retype the exact id.` });
2166
+ return true;
2167
+ }
2168
+ const p = match && match.provider;
2169
+ const id = (p && p.id) || typed;
2170
+ // A second token is the scriptable path (`/byok-key openai sk-…`); with
2171
+ // none we prompt — readSecret never echoes and never enters history.
2172
+ const rest = String(args._rest || '').trim();
2173
+ const sp = rest.indexOf(' ');
2174
+ let key = sp === -1 ? '' : rest.slice(sp + 1).trim();
2175
+ if (!key) {
2176
+ if (p && p.key_url) c.push({ role: 'note', text: `create a ${p.label || id} key at ${p.key_url}` });
2177
+ key = String((await c.readSecret(`${id} key: `)) || '').trim();
2178
+ }
2179
+ if (!key) {
2180
+ c.push({ role: 'note', text: 'nothing saved.' });
2181
+ return true;
2182
+ }
2183
+ if (p && p.key_prefix && !key.startsWith(p.key_prefix)) {
2184
+ c.push({ role: 'note', text: `heads up: ${id} keys normally start with "${p.key_prefix}" — saved anyway.` });
2185
+ }
2186
+ store.set(c.byokNamespace(id), { key });
2187
+ c.push({
2188
+ role: 'done',
2189
+ text: `saved a ${id} key on this machine — /models lists its models, /class byok runs on it.`,
2190
+ });
2191
+ return true;
2192
+ },
2193
+ },
2194
+ {
2195
+ name: 'byok-rm-key', args: ['provider'], hint: '<provider>', category: 'auth',
2196
+ desc: 'Forget the provider key saved on this machine',
2197
+ handler: async (c, a) => {
2198
+ const args = a || {};
2199
+ const id = String(args.provider || '').trim().toLowerCase();
2200
+ if (!id) {
2201
+ c.push({ role: 'error', text: 'Usage: /byok-rm-key <provider> — /byok lists the providers.' });
2202
+ return true;
2203
+ }
2204
+ const store = c.settings && c.settings();
2205
+ if (!store || typeof store.remove !== 'function') {
2206
+ c.push({ role: 'error', text: 'this client has no provider-key store.' });
2207
+ return true;
2208
+ }
2209
+ const row = c.byokNamespace(id);
2210
+ const had = typeof store.rawKey === 'function' ? store.rawKey(row) : null;
2211
+ store.remove(row);
2212
+ c.push({
2213
+ role: had ? 'done' : 'note',
2214
+ text: had ? `removed the ${id} key from this machine.` : `no ${id} key was saved on this machine.`,
2215
+ });
2216
+ return true;
2217
+ },
1993
2218
  },
1994
2219
  {
1995
2220
  name: 'tool', args: ['name', 'json'], hint: '<name> [json]', category: 'aegis',
package/src/config.js CHANGED
@@ -60,6 +60,14 @@ 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.
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'));
@@ -80,6 +86,7 @@ const { createClient } = require(clientPath);
80
86
  const { createTools } = require(toolsPath);
81
87
  const { usageTokens } = require(usagePath);
82
88
  const { createLocalEngine } = require(enginePath);
89
+ const { createSettingsStore, isReservedNamespace } = require(settingsPath);
83
90
  const { agentRoles, agentRoleLabel } = require(agentsPath);
84
91
  const { buildSystemPrompt } = require(promptPath);
85
92
  const updater = require(updatePath);
@@ -92,12 +99,14 @@ module.exports = {
92
99
  createTools,
93
100
  usageTokens,
94
101
  createLocalEngine,
102
+ createSettingsStore,
103
+ isReservedNamespace,
95
104
  agentRoles,
96
105
  agentRoleLabel,
97
106
  buildSystemPrompt,
98
107
  updater,
99
108
  queue,
100
109
  autonomous,
101
- paths: { client: clientPath, tools: toolsPath, usage: usagePath, engine: enginePath, agents: agentsPath, prompt: promptPath, update: updatePath, queue: queuePath, autonomous: autonomousPath },
110
+ paths: { client: clientPath, tools: toolsPath, usage: usagePath, engine: enginePath, settings: settingsPath, agents: agentsPath, prompt: promptPath, update: updatePath, queue: queuePath, autonomous: autonomousPath },
102
111
  roots,
103
112
  };
package/src/engine.js CHANGED
@@ -1,24 +1,61 @@
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 } = require('./deps.js');
41
+ const { credentials } = require('./shared.js');
17
42
  const VERSION = require('../package.json').version;
18
43
 
44
+ /** The classes this host can actually run (see the docstring above). */
45
+ const HOST_CLASSES = Object.freeze(['aegis', 'byok']);
46
+
47
+ /** The class a turn runs on when nothing else is said. */
48
+ const DEFAULT_CLASS = 'aegis';
49
+
50
+ /** One-line labels for /class, the status line and the model picker. */
51
+ const CLASS_LABELS = Object.freeze({
52
+ aegis: 'AEGIS Cloud (pooled)',
53
+ byok: 'Bring your own key (relayed, billed)',
54
+ });
55
+
19
56
  function unsupported(label) {
20
57
  return async () => {
21
- throw new Error(`aegiscode: ${label} is not available — this client only runs the aegis class`);
58
+ throw new Error(`aegiscode: ${label} is not available — this client only runs the aegis and byok classes`);
22
59
  };
23
60
  }
24
61
 
@@ -27,11 +64,22 @@ function unsupported(label) {
27
64
  * @param {() => boolean} getConfirmMode Whether mutating tools (exec,
28
65
  * writeFile, editFile) require approval before running. Read per call, so
29
66
  * toggling it (/permissions, /yolo) takes effect on the next tool round.
67
+ * @param {() => string} getClass Which class the next turn runs on — read per
68
+ * call for the same reason getConfirmMode is: /class must take effect on the
69
+ * very next turn, not on the next launch.
70
+ * @param {object} [settings] The provider-config store. Injected by tests
71
+ * (and by app.js, so one store serves both the engine and the commands);
72
+ * otherwise created against the CLI's data dir.
73
+ * @returns {{chat: Function, cancel: Function, respondApproval: Function,
74
+ * clearSessionApprovals: Function, listClasses: Function, listModels: Function,
75
+ * classLabel: Function, getClass: Function, setClass: Function, settings: object}}
30
76
  */
31
- function createEngine({ client, getConfirmMode }) {
77
+ function createEngine({ client, getConfirmMode, getClass, settings: injectedSettings } = {}) {
78
+ const settings = injectedSettings || createSettingsStore({ dir: credentials.aegisHome() });
79
+
32
80
  const local = createLocalEngine({
33
81
  aegis: client,
34
- settings: { get: () => ({}), rawKey: unsupported('BYOK/custom endpoints') },
82
+ settings,
35
83
  ollama: {
36
84
  probe: async () => ({ running: false }),
37
85
  listTags: async () => [],
@@ -51,12 +99,42 @@ function createEngine({ client, getConfirmMode }) {
51
99
  getConfirmMode,
52
100
  });
53
101
 
102
+ /** The live class, clamped to what this host can run. */
103
+ function currentClass() {
104
+ const asked = typeof getClass === 'function' ? getClass() : null;
105
+ return HOST_CLASSES.includes(asked) ? asked : DEFAULT_CLASS;
106
+ }
107
+
54
108
  return {
55
- chat: (payload, onDelta) => local.chat({ ...payload, class: 'aegis' }, onDelta),
109
+ // `class` is stamped here rather than sent by every caller, so the class a
110
+ // turn runs on has exactly one source of truth (the live session state) and
111
+ // a caller cannot accidentally pin a stale one.
112
+ chat: (payload, onDelta) => local.chat({ ...payload, class: currentClass() }, onDelta),
56
113
  cancel: local.cancel,
57
114
  respondApproval: local.respondApproval,
58
115
  clearSessionApprovals: local.clearSessionApprovals,
116
+ // The engine's own class table, narrowed to the two this host runs — so a
117
+ // UI built from listClasses() can never offer a class that would throw.
118
+ // Async, like the local engine's: listClasses() probes Ollama (a live
119
+ // HTTP round-trip) before it can answer, so returning the raw promise made
120
+ // `/class` throw "filter is not a function". The caller awaits it.
121
+ listClasses: async () => (await local.listClasses()).filter((c) => HOST_CLASSES.includes(c.class)),
122
+ listModels: (cls) => local.listModels(cls || currentClass()),
123
+ classLabel: (cls) => CLASS_LABELS[cls] || CLASS_LABELS[DEFAULT_CLASS],
124
+ getClass: currentClass,
125
+ settings,
59
126
  };
60
127
  }
61
128
 
62
- module.exports = { createEngine };
129
+ /**
130
+ * The settings row one BYOK provider's key lives in. Exported (rather than
131
+ * spelled out again in commands.js) because it is the SAME key the shared
132
+ * engine reads when it resolves the relay's provider credential — and the same
133
+ * row the desktop's Provider settings write. Two spellings would mean a key
134
+ * saved by `/byok-key openai` never reaching the call that needs it.
135
+ */
136
+ function byokNamespace(provider) {
137
+ return `byok:${provider}`;
138
+ }
139
+
140
+ 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