aegisone 1.0.16 → 1.0.17

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.
@@ -97,6 +97,119 @@ function mirrorProviderKeyToEnvFile(envFile, provider, key, opts = {}) {
97
97
  }
98
98
  }
99
99
 
100
+ /**
101
+ * Copy every provider key the store already holds into the shared env file.
102
+ *
103
+ * `wrapProviderKeyMirror` above is a WRITE-TIME hook: it mirrors a key at the
104
+ * moment it is saved. That leaves a real gap the hook cannot close, because a
105
+ * key saved before the hook existed never fires it — an install whose provider
106
+ * row predates this module (or any row written while the wrapper was not
107
+ * installed, e.g. a direct settings write from a test or a repair script) keeps
108
+ * its key in the encrypted store alone, and the CLI never sees it. A stored key
109
+ * is not a mirrored key; only a fresh Save used to make them the same thing.
110
+ *
111
+ * The same gap swallows a "blank = keep" save: `renderer/app.js` saves a
112
+ * provider row with `key` undefined when the key field is left empty (that
113
+ * means "keep the stored one" — see the wrapper's comment), so the wrapper
114
+ * correctly mirrors nothing and the row's real key stays host-local for ever.
115
+ *
116
+ * So this runs ONCE at start-up and reconciles the two stores by reading, not
117
+ * by writing: for every non-reserved row that HAS a stored key whose variable
118
+ * the shared file does not already carry, write it. It is:
119
+ *
120
+ * - idempotent — a second call on an already-synced machine mirrors nothing
121
+ * (the `keyStatus(...).inFile` check is the guard), and it never rewrites a
122
+ * variable that is already present, so a hand-edited `.env` keeps its own
123
+ * spelling, comments and line order;
124
+ * - one-directional — store -> file only. The file is never read back into
125
+ * the encrypted store, so this cannot become a merge loop or overwrite a
126
+ * newer key the CLI wrote (which the desktop would then be second-guessing);
127
+ * - non-fatal — a row that cannot be decrypted or written is REPORTED and
128
+ * skipped. A start-up reconcile must never keep the window from opening.
129
+ *
130
+ * Must run after app 'ready': `safeStorage` (which decrypts the stored key) is
131
+ * not usable before then.
132
+ *
133
+ * @param {object} store a settings store (needs `list`, and `rawKey` for the
134
+ * decrypted value — the exact pair settings.js exposes)
135
+ * @param {object} envFile client/env-file.js
136
+ * @param {object} [opts] `onWarn`, `envOpts` (see above)
137
+ * @returns {{mirrored:string[], skipped:string[], failed:string[]}} what
138
+ * happened per provider, so a caller/test can assert rather than guess
139
+ */
140
+ function backfillProviderKeys(store, envFile, opts = {}) {
141
+ const warn = typeof opts.onWarn === 'function' ? opts.onWarn : () => {};
142
+ const envOpts = opts.envOpts || {};
143
+ const out = { mirrored: [], skipped: [], failed: [] };
144
+ if (!store || typeof store.list !== 'function') return out;
145
+ if (!envFile || typeof envFile.envVarFor !== 'function') return out;
146
+
147
+ let rows = [];
148
+ try {
149
+ rows = store.list() || [];
150
+ } catch (e) {
151
+ warn(`could not read the provider store to backfill the shared env file: ${e && e.message}`);
152
+ return out;
153
+ }
154
+
155
+ for (const row of rows) {
156
+ const provider = row && row.provider;
157
+ // Same filters as the write-time mirror: a reserved row is the store's own
158
+ // bookkeeping, and an unmappable name is a name we do not invent.
159
+ if (typeof provider !== 'string' || !provider) continue;
160
+ if (provider.startsWith(RESERVED_PREFIX)) continue;
161
+
162
+ const name = envFile.envVarFor(provider);
163
+ if (!name || !KEY_VAR_SUFFIX.test(name)) {
164
+ out.skipped.push(provider);
165
+ continue;
166
+ }
167
+ // A name the env file itself refuses (a production secret, not a host key)
168
+ // is not a failure to report — `setEnvValue` would reject it by design.
169
+ if (typeof envFile.isForeignSecret === 'function' && envFile.isForeignSecret(name)) {
170
+ out.skipped.push(provider);
171
+ continue;
172
+ }
173
+
174
+ // Already shared? Then there is nothing to do, and — importantly — nothing
175
+ // to overwrite. This is the idempotence guard.
176
+ let status = null;
177
+ try {
178
+ status = typeof envFile.keyStatus === 'function' ? envFile.keyStatus(name, envOpts) : null;
179
+ } catch { /* unreadable file is "not in the file"; the write below reports it */ }
180
+ if (status && status.inFile) {
181
+ out.skipped.push(provider);
182
+ continue;
183
+ }
184
+
185
+ // `row.configured` is the store's own "a key is stored" flag (settings.js
186
+ // get() derives it from the decrypted value), so a base-URL-only row is
187
+ // skipped here rather than being asked for a key it never had.
188
+ if (row.configured === false) {
189
+ out.skipped.push(provider);
190
+ continue;
191
+ }
192
+
193
+ let key = '';
194
+ try {
195
+ key = typeof store.rawKey === 'function' ? store.rawKey(provider) : '';
196
+ } catch (e) {
197
+ warn(`could not decrypt ${provider}'s stored key for the shared env file: ${e && e.message}`);
198
+ out.failed.push(provider);
199
+ continue;
200
+ }
201
+ if (!key) {
202
+ out.skipped.push(provider);
203
+ continue;
204
+ }
205
+
206
+ const res = mirrorProviderKeyToEnvFile(envFile, provider, key, opts);
207
+ if (res && res.ok) out.mirrored.push(provider);
208
+ else out.failed.push(provider);
209
+ }
210
+ return out;
211
+ }
212
+
100
213
  /**
101
214
  * Wrap a provider-settings store so every key saved or removed through it is
102
215
  * also written to the shared env file.
@@ -138,4 +251,4 @@ function wrapProviderKeyMirror(store, envFile, opts = {}) {
138
251
  return store;
139
252
  }
140
253
 
141
- module.exports = { mirrorProviderKeyToEnvFile, wrapProviderKeyMirror };
254
+ module.exports = { mirrorProviderKeyToEnvFile, wrapProviderKeyMirror, backfillProviderKeys };
@@ -220,6 +220,29 @@ const QUICK_PREFIX = 'quick:';
220
220
  const QUEUE_PREFIX = 'queue:';
221
221
  const AUTO_PREFIX = 'auto:';
222
222
 
223
+ /**
224
+ * The model classes THIS face offers in its pickers, in registry order.
225
+ *
226
+ * Narrower than the engine's `CLASSES` registry on purpose. The engine is
227
+ * shared with the CLI (`cli/src/deps.js` requires this same file), so a class
228
+ * is added or removed once, in `engine.js`, for both hosts — and the CLI does
229
+ * ship `pro` (the user's own Claude Code subscription, spawned through the
230
+ * `claude` binary). This face does not: the Pro transport hands the turn to a
231
+ * headless child that runs its own agent loop and its own permission prompts,
232
+ * and this window has no channel to answer those prompts, so selecting it here
233
+ * is a class a user can pick and then watch do nothing. Omitted rather than
234
+ * listed-and-broken.
235
+ *
236
+ * Filtering HERE rather than in the registry is the same move the CLI makes in
237
+ * `cli/src/engine.js` (`listClasses().filter((c) => HOST_CLASSES.includes(…))`):
238
+ * the registry stays the single source of truth for every class that EXISTS,
239
+ * and each host names the subset it offers. Removing this filter, or adding a
240
+ * class here that `engine.listClasses()` does not return, is a one-line change
241
+ * on this line — and the picker is built from this function's output, so a class
242
+ * absent here is one no user can select, which is the whole point.
243
+ */
244
+ const DESKTOP_CLASSES = Object.freeze(['aegis', 'byok', 'local']);
245
+
223
246
  /**
224
247
  * Main -> renderer push channel for chat SSE deltas (D2.1 streaming render).
225
248
  * The invoke of aegis:chatCompletion still resolves once with the normalised
@@ -1579,7 +1602,10 @@ function createModelDispatch(engine, { env = process.env, settings } = {}) {
1579
1602
  };
1580
1603
 
1581
1604
  const dispatch = {
1582
- listClasses: () => engine.listClasses(),
1605
+ // The picker's source. Filtered through DESKTOP_CLASSES so this face never
1606
+ // offers a class it cannot serve; see that constant for why `pro` is
1607
+ // omitted here while the engine still ships it for the CLI.
1608
+ listClasses: async () => (await engine.listClasses()).filter((c) => DESKTOP_CLASSES.includes(c.class)),
1583
1609
  listModels: (payload) => engine.listModels(payload && payload.class),
1584
1610
  chat: chatWithAutoRounds,
1585
1611
  // The AEGIS key lives in a reserved namespace the store refuses to expose
@@ -3984,6 +4010,36 @@ function bootstrap() {
3984
4010
  } catch (err) {
3985
4011
  console.warn('presence: beacon not started', err && err.message);
3986
4012
  }
4013
+ // One-way backfill of the cross-host key mirror. wrapProviderKeyMirror
4014
+ // (above) is a WRITE-TIME hook: it only fires when a key is saved through
4015
+ // this store, so every row that predates the hook — or was saved with the
4016
+ // key field left blank ("keep the stored one", which mirrors nothing by
4017
+ // design) — still lives only in this app's encrypted store and is invisible
4018
+ // to the CLI and the MCP plugin. Running the reconcile here closes that gap
4019
+ // once per launch, in the store -> file direction only, and skips any
4020
+ // variable the shared file already carries. After app 'ready', because
4021
+ // safeStorage (which decrypts the stored key) is unusable before then, and
4022
+ // deliberately before createWindow() so the CLI's next run — not the next
4023
+ // Save — is when the key becomes visible.
4024
+ //
4025
+ // Never fatal: the keys are already saved, and a failed copy to the shared
4026
+ // file is a smaller problem than a window that does not open.
4027
+ try {
4028
+ const { backfillProviderKeys } = require('./lib/provider-key-mirror.js');
4029
+ const onWarn = (m) => console.warn(`aegis: ${m}`);
4030
+ const result = backfillProviderKeys(settings, envFile, { onWarn });
4031
+ if (result.mirrored.length) {
4032
+ console.warn(
4033
+ `aegis: shared ${result.mirrored.join(', ')} key(s) with the other hosts `
4034
+ + `(${envFile.envFileFor()})`
4035
+ );
4036
+ }
4037
+ if (engine && engine.settings && engine.settings !== settings) {
4038
+ backfillProviderKeys(engine.settings, envFile, { onWarn });
4039
+ }
4040
+ } catch (e) {
4041
+ console.warn(`aegis: could not backfill the shared env-file key mirror: ${e && e.message}`);
4042
+ }
3987
4043
  // Apply whatever was last saved (or the default): ship the shortcut only
3988
4044
  // when app.isPackaged || the settings flag is on — see
3989
4045
  // shouldEnableGlobalShortcut — so a plain `electron .` dev run never
@@ -4054,6 +4110,7 @@ module.exports = {
4054
4110
  taggedChunk,
4055
4111
  maskKey,
4056
4112
  createModelDispatch,
4113
+ DESKTOP_CLASSES,
4057
4114
  readTextFileForPreview,
4058
4115
  PREVIEW_READ_MAX_BYTES,
4059
4116
  createSyncDispatch,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegis-desktop",
3
3
  "productName": "AEGIS Desktop",
4
- "version": "1.0.8",
4
+ "version": "1.0.9",
5
5
  "description": "Thin Electron host for AEGIS — a local chat UI over the shared client/aegis.js transport. Ships transport + UI only; engine logic stays server-side.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -572,6 +572,11 @@ function renderRollMeter(sessionId, live) {
572
572
  // model the meter sat on one number for the whole (longest, priciest)
573
573
  // phase of the turn and looked dead while the AI was demonstrably working.
574
574
  reasoning: live.reasoning,
575
+ // …and the provider-measured thinking tokens, which on a subscription
576
+ // turn are the whole of the deliberation (its text is withheld). The
577
+ // preview must carry the same quantity the bubble's own figure shows, or
578
+ // the two live meters disagree — which this file forbids.
579
+ measuredReasoningTokens: live.measuredReasoningTokens,
575
580
  });
576
581
  }
577
582
  const line = roll ? fmtRoll(roll) : '';
@@ -611,6 +616,15 @@ function renderRollMeter(sessionId, live) {
611
616
  function liveTokenFig(live) {
612
617
  const reply = typeof live.reply === 'string' ? live.reply : '';
613
618
  const reasoning = typeof live.reasoning === 'string' ? live.reasoning : '';
619
+ // Thinking tokens the PROVIDER measured — the only live signal on a
620
+ // subscription turn, which withholds the deliberation text entirely (every
621
+ // real `thinking_delta` carries `thinking: ""` while `estimated_tokens`
622
+ // advances). Part of the billed output, so it belongs in this figure exactly
623
+ // as the `reasoning` text does, and it is already a token count.
624
+ const measured =
625
+ typeof live.measuredReasoningTokens === 'number' && live.measuredReasoningTokens > 0
626
+ ? live.measuredReasoningTokens
627
+ : 0;
614
628
  // A turn in flight that has produced nothing YET. Its figure is zero, and
615
629
  // zero is what the other measured surface shows at this moment: the CLI's
616
630
  // spinner tail counts the answer's deltas and the thinking trace's, so it too
@@ -632,7 +646,12 @@ function liveTokenFig(live) {
632
646
  // a threshold. Safe because the caller only passes `live` for a turn still
633
647
  // running: this is a statement about that turn, not a fabricated measurement
634
648
  // of a finished one.
635
- if (!reply && !reasoning) return '↓0 tokens';
649
+ // The measured thinking count alone is enough to have a figure. Without this
650
+ // term a subscription turn — empty `reply`, empty `reasoning` text, but
651
+ // thousands of billed thinking tokens — took the `↓0 tokens` branch below for
652
+ // its whole thinking phase, which is the bug this function's `measured`
653
+ // addend exists to close.
654
+ if (!reply && !reasoning && !measured) return '↓0 tokens';
636
655
  let output = 0;
637
656
  try {
638
657
  const est = estimatedBuckets(live.prompt, reply, reasoning);
@@ -660,8 +679,19 @@ function liveTokenFig(live) {
660
679
  }
661
680
  output = Math.ceil(cells / 4);
662
681
  }
682
+ // Summed, not substituted: `measured` is the provider's count of deliberation
683
+ // that never entered `reply`/`reasoning` as text, so the two are disjoint and
684
+ // both are billed output. Adding it here is also what keeps the figure moving
685
+ // through the thinking phase and then continuing to climb as the answer
686
+ // streams, rather than dropping back to the answer-only estimate.
687
+ output += measured;
663
688
  if (!output) return '';
664
- return `↓${Math.round(output)} tokens`;
689
+ // `measured` is Anthropic's own `estimated_tokens` running count, which the
690
+ // stream parser's own measurements show landing under the real billed
691
+ // thinking-token figure (1900 vs 1943, 1800 vs 1832, 250 vs 339) — so once
692
+ // it has contributed, the figure is a floor, not the true count, until the
693
+ // turn's real `usage` lands.
694
+ return `↓${measured > 0 ? '≥' : ''}${Math.round(output)} tokens`;
665
695
  }
666
696
 
667
697
  /**
@@ -4984,6 +5014,10 @@ async function send() {
4984
5014
 
4985
5015
  let streamedText = '';
4986
5016
  let reasoningText = '';
5017
+ // Thinking tokens the provider MEASURED (subscription turns report progress
5018
+ // in these while withholding the text). Added verbatim to the live figure,
5019
+ // never divided by 4 the way the text channels are.
5020
+ let measuredReasoningTokens = 0;
4987
5021
  const toolLog = [];
4988
5022
  // How much of the stream the live meter last measured. Per-turn by
4989
5023
  // construction (declared here, not at module scope), so a new turn starts its
@@ -5019,14 +5053,39 @@ async function send() {
5019
5053
  // stream and this runs inside the painter: ungated it is linear per frame,
5020
5054
  // i.e. quadratic over the turn, on the thread the reader is scrolling.
5021
5055
  const streamChars = streamedText.length + reasoningText.length;
5022
- if (liveMeterDue(meterChars, streamChars)) {
5023
- meterChars = streamChars;
5024
- renderRollMeter(sessionId, { prompt, reply: streamedText, reasoning: reasoningText });
5056
+ // The provider's thinking tokens are progress too, and on a subscription
5057
+ // turn they are the ONLY progress: no text arrives at all during the
5058
+ // thinking phase, so a char-only gate saw `grown <= 0` and refused to
5059
+ // repaint, leaving the bubble frozen on `↓0 tokens` however many tokens were
5060
+ // billed. Counted at the same 4 chars:1 token ratio the other live surfaces
5061
+ // use, purely so this gate sees growth; the figure itself is rendered from
5062
+ // the token count, never this char-equivalent.
5063
+ const progress = streamChars + measuredReasoningTokens * 4;
5064
+ if (liveMeterDue(meterChars, progress)) {
5065
+ meterChars = progress;
5066
+ renderRollMeter(sessionId, {
5067
+ prompt,
5068
+ reply: streamedText,
5069
+ reasoning: reasoningText,
5070
+ measuredReasoningTokens,
5071
+ });
5025
5072
  }
5026
5073
  stickToBottom();
5027
5074
  });
5028
5075
 
5029
5076
  const onDelta = (chunk) => {
5077
+ // Provider-MEASURED thinking progress, in tokens. On a subscription turn
5078
+ // the deliberation text is withheld (`thinking_delta.thinking` is the empty
5079
+ // string), so the `reasoning` text branch below never fires and the live
5080
+ // meter sat on `↓0 tokens` through the whole thinking phase — the longest,
5081
+ // priciest part of the turn — while thousands of thinking tokens were
5082
+ // billed. Already a token count, so it is added rather than divided by 4
5083
+ // like the text channels.
5084
+ if (chunk && typeof chunk.thinkingTokens === 'number' && chunk.thinkingTokens > 0) {
5085
+ measuredReasoningTokens += chunk.thinkingTokens;
5086
+ paintStream();
5087
+ return;
5088
+ }
5030
5089
  // Extended-reasoning trace from a pooled brain turn: the fan-out's worker
5031
5090
  // findings, streamed before the synthesis pass writes the answer. Shown so
5032
5091
  // "work autonomously" doesn't look idle for the whole worker phase.
@@ -565,13 +565,7 @@
565
565
  <button type="button" class="wc-link" id="welcome-byok">
566
566
  Bring your own key →
567
567
  </button>
568
- <span class="wc-note" id="welcome-byok-note">
569
- The free path, and it stays free: exec, write and edit run on
570
- your machine, your repos, sessions and keys live on this disk,
571
- and a local model server needs no account at all. A provider
572
- key relayed through AEGIS is still a cloud turn, so it bills a
573
- small handling fee — nothing that runs on this machine does.
574
- </span>
568
+ <span class="wc-note" id="welcome-byok-note"></span>
575
569
  <button type="button" class="wc-skip" id="welcome-dismiss">
576
570
  Don't show this again
577
571
  </button>
@@ -828,16 +828,35 @@ function rollTurn(roll, usage, opts = {}) {
828
828
  // number, and what stops the total standing still on exactly the turns the
829
829
  // pool declined to report on — the symptom this fallback exists to remove.
830
830
  const est = estimatedBuckets(opts.prompt, opts.reply, opts.reasoning);
831
+ // Thinking tokens the provider MEASURED, not estimated. On a subscription
832
+ // turn the deliberation text is withheld entirely (every real
833
+ // `thinking_delta` carries `thinking: ""`), so `estimatedBuckets` above
834
+ // cannot see the longest, priciest part of the turn and the live preview
835
+ // read 0 for the whole thinking phase. Added verbatim — it is already a
836
+ // token count, and it is billed output exactly as the reply is.
837
+ const measured =
838
+ typeof opts.measuredReasoningTokens === 'number' && opts.measuredReasoningTokens > 0
839
+ ? opts.measuredReasoningTokens
840
+ : 0;
831
841
  if (!est) {
832
- // Nothing reported AND no text to estimate from. The single case that
833
- // stays uncounted: `unknown` names the gap, where a fabricated zero would
834
- // read as a measurement.
835
- next.unknown += 1;
842
+ // A subscription turn with nothing written yet but thinking under way is
843
+ // NOT the `unknown` case: the provider measured it, so a zero would be a
844
+ // fabricated reading rather than an absent one.
845
+ if (!measured) {
846
+ // Nothing reported AND no text to estimate from. The single case that
847
+ // stays uncounted: `unknown` names the gap, where a fabricated zero
848
+ // would read as a measurement.
849
+ next.unknown += 1;
850
+ return next;
851
+ }
852
+ next.tokens += measured;
853
+ next.output += measured;
854
+ next.estimated += 1;
836
855
  return next;
837
856
  }
838
- next.tokens += est.input + est.output;
857
+ next.tokens += est.input + est.output + measured;
839
858
  next.input += est.input;
840
- next.output += est.output;
859
+ next.output += est.output + measured;
841
860
  next.estimated += 1;
842
861
  return next;
843
862
  }
@@ -1133,6 +1133,7 @@ function createClient(opts = {}) {
1133
1133
  onStream,
1134
1134
  signal,
1135
1135
  providerKey,
1136
+ baseURL,
1136
1137
  } = {}) {
1137
1138
  const key = providerKey !== undefined ? providerKey : opts.providerKey;
1138
1139
  // Same rule as the pooled path above: omit `max_tokens` entirely when the
@@ -1169,6 +1170,11 @@ function createClient(opts = {}) {
1169
1170
  // `tools: []` differently from the field's plain absence.
1170
1171
  ...(Array.isArray(tools) && tools.length ? { tools } : {}),
1171
1172
  ...(toolChoice ? { tool_choice: toolChoice } : {}),
1173
+ // Read server-side ONLY for provider "custom" (aegis1 app.py
1174
+ // byok_chat_completions) — every other provider's upstream host is a
1175
+ // constant the server already knows, so sending this for them is a
1176
+ // no-op rather than a behaviour change.
1177
+ ...(baseURL ? { base_url: baseURL } : {}),
1172
1178
  };
1173
1179
  if (model) body.model = model;
1174
1180
  const headers = {
@@ -27,7 +27,7 @@
27
27
  *
28
28
  * ── what a user does now ───────────────────────────────────────────────────
29
29
  *
30
- * CLI `/model-add <provider> <model-id>` (and `/model-rm …`)
30
+ * CLI `/model-add <provider> [api-key] <model-id>` (and `/model-rm …`)
31
31
  * Desktop Settings → "Add a model" → provider + id
32
32
  * Either hand-edit `$AEGISCODE_HOME/models.json` (default `~/.aegiscode`)
33
33
  *