aegisone 1.0.18 → 1.0.20

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.
Files changed (48) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/scripts/bump.mjs +29 -4
  4. package/scripts/predist.mjs +2 -0
  5. package/src/dispatch.js +1 -0
  6. package/vendor/cli/bin/aegiscode.js +29 -0
  7. package/vendor/cli/package.json +1 -1
  8. package/vendor/cli/src/app.js +335 -24
  9. package/vendor/cli/src/autonomous.js +19 -2
  10. package/vendor/cli/src/chatflow.js +77 -4
  11. package/vendor/cli/src/commands.js +175 -5
  12. package/vendor/cli/src/config.js +21 -0
  13. package/vendor/cli/src/connect.js +351 -0
  14. package/vendor/cli/src/deps.js +97 -1
  15. package/vendor/cli/src/engine.js +98 -8
  16. package/vendor/cli/src/fingerprint.js +46 -16
  17. package/vendor/cli/src/limits.js +1 -1
  18. package/vendor/cli/src/overlays.js +54 -0
  19. package/vendor/cli/src/provenance.lock.json +3 -3
  20. package/vendor/cli/src/screens.js +14 -1
  21. package/vendor/cli/vendor/client/credentials.js +9 -2
  22. package/vendor/cli/vendor/client/google-signin.js +127 -0
  23. package/vendor/cli/vendor/client/record-vault.js +431 -113
  24. package/vendor/cli/vendor/client/update.js +266 -0
  25. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +134 -11
  26. package/vendor/cli/vendor/desktop/lib/local/engine.js +47 -25
  27. package/vendor/cli/vendor/desktop/lib/settings.js +65 -24
  28. package/vendor/desktop/lib/auto.js +11 -7
  29. package/vendor/desktop/lib/fingerprint.js +76 -17
  30. package/vendor/desktop/lib/local/claude-pro.js +134 -11
  31. package/vendor/desktop/lib/local/engine.js +47 -25
  32. package/vendor/desktop/lib/settings.js +65 -24
  33. package/vendor/desktop/main.js +79 -24
  34. package/vendor/desktop/package.json +4 -2
  35. package/vendor/desktop/preload.js +31 -12
  36. package/vendor/desktop/renderer/app.js +676 -17
  37. package/vendor/desktop/renderer/budget.js +18 -9
  38. package/vendor/desktop/renderer/companion.js +225 -0
  39. package/vendor/desktop/renderer/fingerprint.css +16 -0
  40. package/vendor/desktop/renderer/fingerprint.js +62 -2
  41. package/vendor/desktop/renderer/index.html +285 -121
  42. package/vendor/desktop/renderer/provider-toolbar.js +136 -0
  43. package/vendor/desktop/renderer/providers.js +261 -0
  44. package/vendor/desktop/renderer/style.css +547 -171
  45. package/vendor/desktop/vendor/credentials.js +9 -2
  46. package/vendor/desktop/vendor/google-signin.js +127 -0
  47. package/vendor/desktop/vendor/record-vault.js +431 -113
  48. package/vendor/desktop/vendor/update.js +266 -0
@@ -96,6 +96,14 @@ const ELEMENT_IDS = {
96
96
  apiKeyHint: 'api-key-hint',
97
97
  classSelect: 'class-select',
98
98
  modelSelect: 'model-select',
99
+ ptSearch: 'pt-search',
100
+ ptRefresh: 'pt-refresh',
101
+ ptList: 'pt-list',
102
+ ptCount: 'pt-count',
103
+ ptHint: 'pt-hint',
104
+ companionCard: 'companion-card',
105
+ companionText: 'companion-text',
106
+ companionDismiss: 'companion-dismiss',
99
107
  modelFree: 'model-input',
100
108
  budgetHint: 'budget-hint',
101
109
  autonomousToggle: 'autonomous-toggle',
@@ -106,6 +114,15 @@ const ELEMENT_IDS = {
106
114
  modelHint: 'model-hint',
107
115
  settingsList: 'settings-list',
108
116
  settingsHint: 'settings-hint',
117
+ // The custom-provider card (index.html #custom-provider-card): an address, a
118
+ // key and a model id, saved as `byok:custom`. Separate from settingsList
119
+ // because its row carries a base URL the catalog rows do not have.
120
+ customBaseUrl: 'custom-base-url',
121
+ customKey: 'custom-key',
122
+ customModel: 'custom-model',
123
+ customSave: 'custom-save',
124
+ customRemove: 'custom-remove',
125
+ customStatus: 'custom-status',
109
126
  quickLauncherEnabled: 'quick-launcher-enabled',
110
127
  quickLauncherShortcut: 'quick-launcher-shortcut',
111
128
  quickLauncherSave: 'quick-launcher-save',
@@ -239,6 +256,20 @@ const RESERVED_PROVIDERS = new Set(['__aegis', 'aegis']);
239
256
  // (desktop/lib/settings.js) and the engine re-checks before every call, so the
240
257
  // value typed here can only ever address this machine or this LAN.
241
258
  const LOCAL_PROVIDER = 'local';
259
+ // The one catalog provider whose configuration is not a key alone.
260
+ //
261
+ // aegis1 lists `custom` in GET /api/v1/byok/providers (services/byok_service.py
262
+ // `byok_provider_catalog`) even though its descriptor pins no credential env and
263
+ // no base URL, because the address travels per request instead. That makes it
264
+ // the only row where "paste your key" is not enough: aegis1's
265
+ // `_byok_custom_base_url` refuses a custom call that carries no `base_url`, so a
266
+ // key saved with no address is a credential nothing can spend.
267
+ //
268
+ // So the catalog loop below SKIPS this id and the card under #custom-provider-card
269
+ // owns it end to end (address + key + model id, one Save). Kept as one constant
270
+ // because two surfaces must agree on the spelling — the row that is skipped here
271
+ // and the row that is written there.
272
+ const CUSTOM_PROVIDER = 'custom';
242
273
  // Ollama's stock port: the address a freshly installed daemon actually answers
243
274
  // on, so the field's placeholder is also the value a blank save falls back to.
244
275
  const LOCAL_DEFAULT_BASE = 'http://localhost:11434';
@@ -1102,6 +1133,12 @@ function renderStatus(s) {
1102
1133
  // from the CLI) retires the connect block; with no key it stays. No-ops when
1103
1134
  // the panel is not mounted.
1104
1135
  applyWelcomeConnect();
1136
+ // The personalized line reads the same facts (a key that just landed, an
1137
+ // update that just downloaded), and the panel is painted BEFORE this read
1138
+ // returns on a cold start — so without this repaint the line would keep the
1139
+ // tip it chose while the key state was still unknown. No-ops when the panel
1140
+ // is not mounted.
1141
+ applyWelcomePersonal();
1105
1142
  // And the two-key pop-up's gate: a status read is the only thing that knows
1106
1143
  // either fact, so this is where the sheet is opened (a key still missing) or
1107
1144
  // retired (both present). No-ops while the markup is absent.
@@ -1123,6 +1160,10 @@ let updateDismissedFor = null;
1123
1160
  function renderUpdateBanner(state) {
1124
1161
  if (!els.updateBanner) return;
1125
1162
  lastUpdateState = state;
1163
+ // A downloaded update is the single most actionable fact the daily line can
1164
+ // report, and it arrives AFTER boot. Re-rendering here is what keeps the two
1165
+ // from disagreeing — the dismissal rule inside renderCompanion still wins.
1166
+ try { renderCompanion(); } catch { /* the banner must not fail on the card */ }
1126
1167
  const status = state && state.status;
1127
1168
  // 'unavailable' is the npm channel's silent verdict after a background check
1128
1169
  // that failed for a transient reason (no network yet at login, a VPN coming
@@ -2045,7 +2086,7 @@ function handleQuickLauncherPush(payload) {
2045
2086
  //
2046
2087
  // Field set per entry (aegis1/app.py:9349 `_memory_row_to_dict`): id,
2047
2088
  // timestamp, createdAt (epoch ms), source, role, tags[], content, session,
2048
- // importance, summary(bool), topics[], entities[], sentiment, tokenCount,
2089
+ // importance, summary(bool), entities[], sentiment, tokenCount,
2049
2090
  // embedding[]. There is no `tier` — L0–L3 is the local CLI engine's concept
2050
2091
  // (the upstream engine's memory module) and does not exist on the cloud rows, so
2051
2092
  // source/role are the real provenance axes here.
@@ -2125,6 +2166,166 @@ function keysOverlayOpen() {
2125
2166
  * above can ask it whether it is open without reaching into its internals. */
2126
2167
  let fpPanel = null;
2127
2168
 
2169
+ // ------------------------------------------------- providers & models toolbar
2170
+ //
2171
+ // The list is built from the SAME calls the Model card uses (models.listClasses
2172
+ // then models.listModels per class), so a provider that appears in one place
2173
+ // cannot be missing from the other. It is deliberately lazy: the per-class
2174
+ // catalog calls cost a network round trip each, and this card is a reference,
2175
+ // not the control the user is working in — so it loads on first sight (the
2176
+ // Refresh button, or the moment the card is actually opened) rather than
2177
+ // delaying boot behind four catalog fetches.
2178
+ let ptToolbar = null;
2179
+ let ptLoaded = false;
2180
+
2181
+ /** Collect every class's models payload, in class order. Never throws. */
2182
+ async function collectProviderRows() {
2183
+ let classes = [];
2184
+ try {
2185
+ classes = (await models.listClasses()) || [];
2186
+ } catch (err) {
2187
+ els.ptHint.textContent =
2188
+ `listClasses failed: ${err && err.message ? err.message : err}`;
2189
+ return [];
2190
+ }
2191
+ const rows = [];
2192
+ for (const c of classes) {
2193
+ if (!c || !c.class) continue;
2194
+ let list = null;
2195
+ try {
2196
+ list = await models.listModels(c.class);
2197
+ } catch (err) {
2198
+ // A class that failed is reported AS a class that failed, not dropped:
2199
+ // an absent row would read as "this build cannot address it", which is a
2200
+ // different and much worse claim than "its catalog call errored".
2201
+ list = { models: [], error: (err && err.message) || String(err) };
2202
+ }
2203
+ rows.push({ class: c.class, classLabel: c.label, classConfigured: Boolean(c.configured), list });
2204
+ }
2205
+ return rows;
2206
+ }
2207
+
2208
+ async function loadProviderToolbar(force) {
2209
+ if (!ptToolbar) return;
2210
+ if (ptLoaded && !force) return;
2211
+ if (els.ptHint) els.ptHint.textContent = 'listing providers…';
2212
+ const rows = await collectProviderRows();
2213
+ ptLoaded = true;
2214
+ ptToolbar.set(rows);
2215
+ }
2216
+
2217
+ /** Apply a toolbar pick to the Model card's own controls. */
2218
+ function applyProviderPick(sel) {
2219
+ if (!sel || !sel.class) return;
2220
+ if (!Array.from(els.classSelect.options).some((o) => o.value === sel.class)) return;
2221
+ els.classSelect.value = sel.class;
2222
+ localStorage.setItem(CLASS_KEY, sel.class);
2223
+ updateBudgetControls(sel.class);
2224
+ loadModels(sel.class).then(() => {
2225
+ // The model list is async, so the model can only be applied once the
2226
+ // options exist. Setting a value the picker does not offer would leave the
2227
+ // select on its first entry while the toolbar claims a different row.
2228
+ if (sel.model && Array.from(els.modelSelect.options).some((o) => o.value === sel.model)) {
2229
+ els.modelSelect.value = sel.model;
2230
+ els.modelSelect.dispatchEvent(new Event('change'));
2231
+ }
2232
+ });
2233
+ }
2234
+
2235
+ function mountProviderToolbar() {
2236
+ if (!window.aegisProviderToolbar || !els.ptList) return;
2237
+ ptToolbar = window.aegisProviderToolbar.mount({
2238
+ list: els.ptList,
2239
+ count: els.ptCount,
2240
+ search: els.ptSearch,
2241
+ hint: els.ptHint,
2242
+ onSelect: applyProviderPick,
2243
+ });
2244
+ if (els.ptRefresh) {
2245
+ els.ptRefresh.addEventListener('click', () => { loadProviderToolbar(true); });
2246
+ }
2247
+ // Lazy first load: fires once, when the card is first scrolled into view.
2248
+ if (typeof IntersectionObserver === 'function' && els.ptList.closest('section')) {
2249
+ const io = new IntersectionObserver((hits) => {
2250
+ if (hits.some((h) => h.isIntersecting)) {
2251
+ io.disconnect();
2252
+ loadProviderToolbar(false);
2253
+ }
2254
+ });
2255
+ io.observe(els.ptList.closest('section'));
2256
+ } else {
2257
+ loadProviderToolbar(false);
2258
+ }
2259
+ }
2260
+
2261
+ // ------------------------------------------------------- the daily line
2262
+ //
2263
+ // One message per local day, from facts this process already holds (see
2264
+ // companion.js for why every branch is fact-gated). Stored as `{day, id}` so a
2265
+ // dismissal survives a restart and a NEW day re-opens the card.
2266
+ const COMPANION_KEY = 'aegis.companion.dismissed';
2267
+
2268
+ function companionFacts() {
2269
+ const facts = { keyConfigured: keyConfigured === null ? undefined : keyConfigured };
2270
+ // Only counts the renderer can actually see are passed; everything else is
2271
+ // left undefined so companion.js drops that branch instead of guessing.
2272
+ //
2273
+ // The memory count comes from `memoryView.entries` — the inspector's own
2274
+ // fetched page — NOT from `fpPanel.entries()`, which this used to call and
2275
+ // which does not exist: renderer/fingerprint.js's mount() returns open/close/
2276
+ // isOpen/refresh/loadAutoMint/state/actions and nothing else, so that branch
2277
+ // was dead code and `memoryCount` was never populated, which in turn made the
2278
+ // memory branch in companion.js unreachable in the app. `memoryView.entries`
2279
+ // is empty until the inspector has been opened once (loadMemoryOverlay is
2280
+ // what fills it), so this reports a count only when the process has really
2281
+ // seen one — the same "no guess in the blank" rule as every other fact here.
2282
+ if (Array.isArray(memoryView.entries) && memoryView.entries.length) {
2283
+ facts.memoryCount = memoryView.entries.length;
2284
+ }
2285
+ if (lastUpdateState && lastUpdateState.status === 'downloaded' && lastUpdateState.version) {
2286
+ facts.updatePending = String(lastUpdateState.version);
2287
+ }
2288
+ if (classOptions.length && els.modelSelect && els.modelSelect.options.length > 1) {
2289
+ facts.modelCount = els.modelSelect.options.length;
2290
+ }
2291
+ return facts;
2292
+ }
2293
+
2294
+ function renderCompanion() {
2295
+ if (!window.aegisCompanion || !els.companionCard || !els.companionText) return;
2296
+ const now = new Date();
2297
+ let dismissed = null;
2298
+ try {
2299
+ dismissed = JSON.parse(localStorage.getItem(COMPANION_KEY) || 'null');
2300
+ } catch {
2301
+ dismissed = null;
2302
+ }
2303
+ if (window.aegisCompanion.dismissedToday(dismissed, now)) {
2304
+ els.companionCard.hidden = true;
2305
+ return;
2306
+ }
2307
+ const msg = window.aegisCompanion.pickMessage(companionFacts(), now);
2308
+ if (!msg || !msg.text) {
2309
+ els.companionCard.hidden = true;
2310
+ return;
2311
+ }
2312
+ els.companionText.textContent = msg.text;
2313
+ els.companionCard.dataset.kind = msg.kind;
2314
+ els.companionCard.dataset.messageId = msg.id;
2315
+ els.companionCard.hidden = false;
2316
+ }
2317
+
2318
+ function wireCompanion() {
2319
+ if (els.companionDismiss) {
2320
+ els.companionDismiss.addEventListener('click', () => {
2321
+ localStorage.setItem(COMPANION_KEY, JSON.stringify({ day: window.aegisCompanion
2322
+ ? window.aegisCompanion.dayKey(new Date()) : '', id: els.companionCard.dataset.messageId || '' }));
2323
+ els.companionCard.hidden = true;
2324
+ });
2325
+ }
2326
+ renderCompanion();
2327
+ }
2328
+
2128
2329
  /** "3m ago" / "2d ago" from epoch ms. Empty string when unknown. */
2129
2330
  function relTime(ms) {
2130
2331
  if (!Number.isFinite(ms)) return '';
@@ -2156,7 +2357,6 @@ function normalizeMemoryEntry(raw) {
2156
2357
  source: asString(r.source) || '(unknown source)',
2157
2358
  role: asString(r.role),
2158
2359
  tags: asArray(r.tags),
2159
- topics: asArray(r.topics),
2160
2360
  entities: asArray(r.entities),
2161
2361
  session: asString(r.session),
2162
2362
  sentiment: asString(r.sentiment),
@@ -2307,7 +2507,7 @@ async function searchMemory(query) {
2307
2507
 
2308
2508
  // ------------------------------------------------- memory inspector overlay
2309
2509
 
2310
- /** Small coloured label used for source / role / tag / topic / entity. */
2510
+ /** Small coloured label used for source / role / tag / entity. */
2311
2511
  function memoryChip(text, cls) {
2312
2512
  const span = document.createElement('span');
2313
2513
  span.className = `mem-chip${cls ? ` ${cls}` : ''}`;
@@ -2345,7 +2545,7 @@ function memoryCard(e) {
2345
2545
  body.textContent = e.content || '(empty)';
2346
2546
  li.appendChild(body);
2347
2547
 
2348
- const pills = [...e.tags, ...e.topics, ...e.entities];
2548
+ const pills = [...e.tags, ...e.entities];
2349
2549
  if (pills.length) {
2350
2550
  const row = document.createElement('div');
2351
2551
  row.className = 'mem-card-pills';
@@ -2381,7 +2581,6 @@ function memoryMatches(e, q) {
2381
2581
  e.session,
2382
2582
  e.sentiment,
2383
2583
  ...e.tags,
2384
- ...e.topics,
2385
2584
  ...e.entities,
2386
2585
  ].join('\n').toLowerCase();
2387
2586
  return hay.includes(String(q == null ? '' : q).toLowerCase());
@@ -2644,16 +2843,262 @@ function applyGreeting() {
2644
2843
  : 'Working late?';
2645
2844
  }
2646
2845
 
2647
- /** Prefill the composer with a starter question, caret at the end. */
2648
- function quickAction(text) {
2649
- const inp = els.prompt;
2650
- if (!inp) return;
2651
- inp.value = text;
2652
- inp.focus();
2846
+ /** Pack the facts above into the shape renderer/companion.js consumes.
2847
+ *
2848
+ * The welcome line and the sidebar's daily message answer the same question —
2849
+ * "what does this install actually know that is worth saying?" — so they read
2850
+ * the SAME fact bag rather than growing a second, drifting opinion of what is
2851
+ * true. Everything absent is left undefined on purpose: companion.js drops a
2852
+ * branch whose facts are missing instead of filling the gap with a guess.
2853
+ */
2854
+ function personalizeFacts() {
2855
+ const facts = companionFacts();
2856
+ // companionFacts() only returns `keyConfigured` when the status read has
2857
+ // landed (null means "not read yet"). The welcome panel is painted before
2858
+ // that read on a cold start, and the panel is the one place where "paste your
2859
+ // key" is the useful thing to say — so an unread status, not a known keyless
2860
+ // machine, must NOT be reported as keyConfigured === false.
2861
+ if (facts.keyConfigured === undefined) delete facts.keyConfigured;
2862
+ /*
2863
+ * The provider-class-with-models-but-no-key case is deliberately NOT passed
2864
+ * here. It is a sidebar diagnosis (it names the Provider settings card the
2865
+ * user was already looking at); in the welcome panel the byok route below is
2866
+ * the same information written as an invitation, and showing both in one
2867
+ * column reads as two warnings about one thing.
2868
+ */
2869
+ return facts;
2870
+ }
2871
+
2872
+ /**
2873
+ * The one personalized line in the welcome panel.
2874
+ *
2875
+ * This replaced five generic topic pills ("Write code", "Explain a concept", …)
2876
+ * that every install showed identically. A topic menu asks the user to invent
2877
+ * an intent that fits a canned frame; a line built from a fact about THEIR
2878
+ * install either saves them a step (a downloaded update, a key they have not
2879
+ * pasted yet) or tells them something true that they already own (memory
2880
+ * entries, sessions). Where no such fact exists it rotates one true tip — and
2881
+ * where even that is unavailable, the node stays hidden rather than printing an
2882
+ * empty box or a guess.
2883
+ *
2884
+ * Returns `{ text, kind }` or null. `kind` is 'action' (a concrete step) or
2885
+ * 'tip' (a true statement about the build); it is written to the dataset so CSS
2886
+ * can style an action line a little louder than a rotation.
2887
+ */
2888
+ function welcomePersonalize(now) {
2889
+ const panel = window.aegisCompanion;
2890
+ if (!panel || typeof panel.pickMessage !== 'function') return null;
2891
+ const msg = panel.pickMessage(personalizeFacts(), now || new Date());
2892
+ if (!msg || !msg.text) return null;
2893
+ return { text: msg.text, kind: msg.kind || 'tip' };
2894
+ }
2895
+
2896
+ /** Paint the personalized line into the cloned panel. */
2897
+ function applyWelcomePersonal() {
2898
+ const el = document.getElementById('welcome-personal');
2899
+ if (!el) return;
2900
+ const line = welcomePersonalize();
2901
+ if (!line) {
2902
+ // Nothing true to say: hidden, and empty, so a stale line can never be left
2903
+ // behind by a second render in the same session.
2904
+ el.textContent = '';
2905
+ el.hidden = true;
2906
+ return;
2907
+ }
2908
+ el.textContent = line.text;
2909
+ el.dataset.kind = line.kind;
2910
+ el.hidden = false;
2911
+ }
2912
+
2913
+ // ------------------------------------------------ welcome: the AI's own line
2914
+ //
2915
+ // The line above is written by this app, from facts it holds. It is always true
2916
+ // and it is always the same sentence, which is exactly why it stops being read
2917
+ // after the third launch: the same install gets the same words every day.
2918
+ //
2919
+ // So the panel asks the model instead — one short turn, once per local day,
2920
+ // given the facts (the local time of day, how many memory entries there are,
2921
+ // which model is selected, whether a key is present) and told to write ONE
2922
+ // sentence for this user. It is cached per day, so a New chat re-render costs
2923
+ // nothing, and the app's own line is what paints first: the panel never waits
2924
+ // on a network round trip to have something to say.
2925
+ //
2926
+ // WHAT THIS DELIBERATELY IS NOT. It is not a free-form agent turn. It carries
2927
+ // no tools, no history and no user text; `singlePass` keeps a pooled model id
2928
+ // from silently fanning out to (workers + 1) calls, and the budget is the small
2929
+ // fixed one below. A greeting that bills a multi-worker dispatch on every cold
2930
+ // start would be the most expensive sentence in the app.
2931
+ //
2932
+ // AND IT IS GATED, not assumed: a turn is only sent when something can answer
2933
+ // it — an AEGIS key for the pooled class, or a local model list with a model in
2934
+ // it. With neither, no request is made at all and the fact line stands alone.
2935
+ // Nothing is invented when the model cannot be reached; a failed call leaves the
2936
+ // fact line exactly as it was.
2937
+
2938
+ const AI_GREETING_KEY = 'aegis.welcomeAiLine';
2939
+ /** One sentence. Long enough for a model to finish a thought, short enough that
2940
+ * a truncated answer cannot fill the panel — the renderer trims to the last
2941
+ * sentence boundary below rather than showing half a clause. */
2942
+ const AI_GREETING_MAX_TOKENS = 120;
2943
+ /** Hard cap on what is put on screen, characters. A model that ignores the
2944
+ * length instruction must not be able to push the composer off the panel. */
2945
+ const AI_GREETING_MAX_CHARS = 200;
2946
+
2947
+ /** Local calendar day, YYYY-MM-DD. Local, for the same reason companion.js is:
2948
+ * "today" means the user's today, not UTC's. */
2949
+ function aiGreetingDay(now) {
2950
+ const d = now instanceof Date ? now : new Date(now == null ? Date.now() : now);
2951
+ if (Number.isNaN(d.getTime())) return '';
2952
+ const p = (n) => String(n).padStart(2, '0');
2953
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
2954
+ }
2955
+
2956
+ /** Can a turn actually be sent right now? Read from what the process knows. */
2957
+ function aiGreetingReachable() {
2958
+ if (keyConfigured === true) return true;
2959
+ // Local needs no account. A listed model means the daemon answered, which is
2960
+ // the only evidence this renderer has that anything is listening.
2961
+ return !!(els.modelSelect && els.modelSelect.options && els.modelSelect.options.length > 1);
2962
+ }
2963
+
2964
+ /** The cached line for today, or null. Cache is `{ day, text }`. */
2965
+ function aiGreetingCached(now) {
2966
+ let rec = null;
2653
2967
  try {
2654
- inp.setSelectionRange(text.length, text.length);
2655
- } catch (err) {
2656
- /* not supported on every input type; focus alone is enough */
2968
+ rec = JSON.parse(localStorage.getItem(AI_GREETING_KEY) || 'null');
2969
+ } catch {
2970
+ rec = null;
2971
+ }
2972
+ if (!rec || typeof rec.text !== 'string' || !rec.text) return null;
2973
+ if (rec.day !== aiGreetingDay(now)) return null;
2974
+ return rec.text;
2975
+ }
2976
+
2977
+ /** Trim a model's answer to one presentable sentence.
2978
+ *
2979
+ * Models wrap greetings in quotes, prefix them with "Sure!" or emit three
2980
+ * sentences when asked for one. Rather than trusting the instruction, this
2981
+ * takes the first sentence and drops the scaffolding — and returns '' when
2982
+ * what is left is too short to be a greeting, so the caller keeps the fact
2983
+ * line instead of printing a fragment. */
2984
+ function trimAiGreeting(raw) {
2985
+ let t = String(raw == null ? '' : raw).trim();
2986
+ if (!t) return '';
2987
+ // Reasoning models sometimes lead with a labelled preamble line.
2988
+ t = t.replace(/^(assistant|greeting|response)\s*:\s*/i, '');
2989
+ // ...and chat models lead with agreement ("Sure!", "Of course.") or an
2990
+ // announcement of what follows ("Here's your greeting:"). Neither is the
2991
+ // sentence that was asked for, and both read as a machine clearing its
2992
+ // throat at the top of the panel. Stripped repeatedly, so "Sure! Here you
2993
+ // go:" composed of two such segments goes too.
2994
+ let prev;
2995
+ do {
2996
+ prev = t;
2997
+ t = t.replace(
2998
+ /^(?:sure|certainly|of course|absolutely|okay|ok|got it|no problem|here(?:'s| is)\b[^.!?:]*)\s*[.!?:,—–-]\s*/i,
2999
+ '',
3000
+ );
3001
+ } while (t !== prev && t);
3002
+ // A quoted one-liner: keep what is inside the outermost quotes.
3003
+ const q = t.match(/^["'“”'']([\s\S]+)["'“”'']$/);
3004
+ if (q) t = q[1].trim();
3005
+ t = t.replace(/\s+/g, ' ');
3006
+ // First sentence, on a boundary that is followed by a space or end of string,
3007
+ // so "llama3.2:3b" and "a.m." are not cut in half.
3008
+ const m = t.match(/^[\s\S]*?[.!?](?=\s|$)/);
3009
+ if (m) t = m[0].trim();
3010
+ if (t.length > AI_GREETING_MAX_CHARS) {
3011
+ const cut = t.slice(0, AI_GREETING_MAX_CHARS);
3012
+ const at = Math.max(cut.lastIndexOf('. '), cut.lastIndexOf('! '), cut.lastIndexOf('? '));
3013
+ t = at > 40 ? cut.slice(0, at + 1) : `${cut.replace(/[,;:\s]+$/, '')}…`;
3014
+ }
3015
+ return t.length >= 12 ? t : '';
3016
+ }
3017
+
3018
+ /** The one sentence the model is asked for. Facts only — no user text, no
3019
+ * history, nothing that could carry a conversation in. */
3020
+ function aiGreetingPrompt(facts) {
3021
+ const h = new Date().getHours();
3022
+ const when =
3023
+ h >= 5 && h < 12 ? 'morning'
3024
+ : h >= 12 && h < 17 ? 'afternoon'
3025
+ : h >= 17 && h < 22 ? 'evening'
3026
+ : 'late night';
3027
+ const known = [];
3028
+ if (typeof facts.memoryCount === 'number') {
3029
+ known.push(`${facts.memoryCount} entries saved in the user's memory`);
3030
+ }
3031
+ if (typeof facts.modelCount === 'number') known.push(`${facts.modelCount} models available`);
3032
+ if (typeof facts.updatePending === 'string') {
3033
+ known.push(`update ${facts.updatePending} is downloaded and installs on quit`);
3034
+ }
3035
+ if (facts.keyConfigured === true) known.push('the account key is connected');
3036
+ if (facts.keyConfigured === false) known.push('no account key is connected yet');
3037
+ return [
3038
+ 'Write the one sentence shown at the top of a coding assistant\'s empty',
3039
+ `chat panel. It is ${when} for the person reading it.`,
3040
+ known.length ? `What you know about their setup: ${known.join('; ')}.` : '',
3041
+ 'Rules: one sentence, at most 25 words, second person, no greeting cliché',
3042
+ 'like "Welcome back", no exclamation marks, no quotes, no preamble, no',
3043
+ 'markdown. Say something specific and useful about their work right now, or',
3044
+ 'ask one short question that helps them start. Reply with the sentence only.',
3045
+ ].filter(Boolean).join(' ');
3046
+ }
3047
+
3048
+ /** Ask the model for the line and paint it. Never throws, never blocks paint. */
3049
+ async function applyWelcomeAiLine() {
3050
+ const el = document.getElementById('welcome-personal');
3051
+ if (!el) return;
3052
+ if (typeof models === 'undefined' || !models || typeof models.chat !== 'function') return;
3053
+ if (!aiGreetingReachable()) return;
3054
+
3055
+ const now = new Date();
3056
+ const cached = aiGreetingCached(now);
3057
+ if (cached) {
3058
+ el.textContent = cached;
3059
+ el.dataset.kind = 'ai';
3060
+ el.hidden = false;
3061
+ return;
3062
+ }
3063
+
3064
+ const facts = personalizeFacts();
3065
+ const classId = els.classSelect && els.classSelect.value ? els.classSelect.value : 'aegis';
3066
+ const modelId = els.modelSelect && els.modelSelect.value ? els.modelSelect.value : '';
3067
+ const payload = {
3068
+ class: classId,
3069
+ prompt: aiGreetingPrompt(facts),
3070
+ maxTokens: AI_GREETING_MAX_TOKENS,
3071
+ // One cheap pass: no tools, no history, no fan-out. See the block comment.
3072
+ tools: false,
3073
+ singlePass: true,
3074
+ effort: 'low',
3075
+ };
3076
+ if (modelId) payload.model = modelId;
3077
+
3078
+ let data = null;
3079
+ try {
3080
+ data = await models.chat(payload);
3081
+ } catch {
3082
+ // Unreachable, refused, out of balance: the fact line already on screen
3083
+ // stands. Saying "could not write your greeting" would be noise about a
3084
+ // sentence the user never asked for.
3085
+ return;
3086
+ }
3087
+ const choice = (data && data.choices && data.choices[0]) || {};
3088
+ const text = trimAiGreeting((choice.message && choice.message.content) || '');
3089
+ if (!text) return;
3090
+
3091
+ // The panel may have been replaced (New chat, another session opened) while
3092
+ // the turn was in flight. Only paint into a node still in the document.
3093
+ const live = document.getElementById('welcome-personal');
3094
+ if (!live) return;
3095
+ live.textContent = text;
3096
+ live.dataset.kind = 'ai';
3097
+ live.hidden = false;
3098
+ try {
3099
+ localStorage.setItem(AI_GREETING_KEY, JSON.stringify({ day: aiGreetingDay(now), text }));
3100
+ } catch {
3101
+ /* storage disabled — the line is regenerated next launch, nothing breaks */
2657
3102
  }
2658
3103
  }
2659
3104
 
@@ -2664,9 +3109,11 @@ function renderWelcome() {
2664
3109
  els.messages.innerHTML = '';
2665
3110
  els.messages.appendChild(tpl.content.cloneNode(true));
2666
3111
  applyGreeting();
2667
- for (const btn of els.messages.querySelectorAll('.chat-quick-pill')) {
2668
- btn.addEventListener('click', () => quickAction(btn.dataset.quick || ''));
2669
- }
3112
+ applyWelcomePersonal();
3113
+ // Then, if a model can be reached, let it write the line (cached per day).
3114
+ // Deliberately not awaited: the panel is already complete without it, and a
3115
+ // slow or dead backend must not hold up the first paint.
3116
+ applyWelcomeAiLine();
2670
3117
  // The connect block's three controls. Bound here (not inline, not at boot)
2671
3118
  // because they only exist in the cloned panel; CSP `script-src 'self'` would
2672
3119
  // drop an inline handler anyway.
@@ -4304,7 +4751,14 @@ async function loadSettings() {
4304
4751
  const byokProviders = Array.isArray(byokData && byokData.providers) ? byokData.providers : [];
4305
4752
  for (const p of byokProviders) {
4306
4753
  if (!p || !p.id) continue;
4754
+ // Offered to the "your own models" datalist either way: `custom` is a
4755
+ // provider id the relay takes a key for, and a hand-declared model under
4756
+ // it is legitimate.
4307
4757
  byokProviderIds.push({ id: p.id, label: p.label || p.id });
4758
+ // ...but not rendered as a key row here. Its own card (below) collects the
4759
+ // base URL that makes the key spendable; a row here would save a key with
4760
+ // nowhere to send it, which is exactly the state this split removes.
4761
+ if (p.id === CUSTOM_PROVIDER) continue;
4308
4762
  const provider = `byok:${p.id}`;
4309
4763
  const local = settings.find((s) => s.provider === provider) || {
4310
4764
  provider, baseURL: '', configured: false, keyMask: null,
@@ -4355,6 +4809,19 @@ async function loadSettings() {
4355
4809
  els.settingsHint.textContent =
4356
4810
  `your own models: ${err && err.message ? err.message : err}`;
4357
4811
  }
4812
+
4813
+ // The custom endpoint's own card (#custom-provider-card) is painted from the
4814
+ // same two stores this function just read — the settings row it owns and the
4815
+ // declarations the block above lists — so the two surfaces cannot disagree
4816
+ // about whether `custom` is configured.
4817
+ try {
4818
+ await loadCustomProvider();
4819
+ } catch (err) {
4820
+ if (els.customStatus) {
4821
+ els.customStatus.textContent =
4822
+ `custom provider: ${err && err.message ? err.message : err}`;
4823
+ }
4824
+ }
4358
4825
  }
4359
4826
 
4360
4827
  /**
@@ -4638,6 +5105,166 @@ async function renderUserModelRows(byokProviderIds) {
4638
5105
  els.settingsList.appendChild(block);
4639
5106
  }
4640
5107
 
5108
+ /**
5109
+ * The custom-provider card: address + key + model id, one Save.
5110
+ *
5111
+ * WHY A CARD OF ITS OWN. Every other BYOK provider is reachable by key alone —
5112
+ * its upstream host is a constant aegis1 already knows (services/nexus_provider/
5113
+ * catalog.py), so the client's only input is the credential. `custom` is the
5114
+ * inverse: the HOST is the user's to name, and the server validates it per call
5115
+ * (`_byok_custom_base_url`: https, and no loopback/private/link-local target,
5116
+ * because that route is otherwise an SSRF primitive). So the row has a field no
5117
+ * other provider has, and it is not the same decision as "paste a key" — hence
5118
+ * its own card instead of a special case inside the catalog list.
5119
+ *
5120
+ * The model id is part of the same save because aegis1's `custom` descriptor
5121
+ * pins no `default_model`, so the relay catalog contributes no custom model row:
5122
+ * the picker can only offer what the user-models file declares. Saving the key
5123
+ * without declaring a model would leave a configured provider with nothing
5124
+ * selectable — half a setup that looks finished.
5125
+ *
5126
+ * Order of writes, and why: the settings row first (that is what holds the
5127
+ * address), the model declaration second, the re-render last. A failure between
5128
+ * them leaves a saved endpoint and no model, which the status line says outright
5129
+ * rather than reporting a clean save.
5130
+ */
5131
+ function paintCustomRow(cfg, declared) {
5132
+ if (!els.customBaseUrl) return;
5133
+ const saved = cfg || {};
5134
+ const declaredModels = Array.isArray(declared) ? declared : [];
5135
+ if (!els.customBaseUrl.value && saved.baseURL) els.customBaseUrl.value = saved.baseURL;
5136
+ if (els.customKey) {
5137
+ els.customKey.placeholder = saved.configured
5138
+ ? `key ${saved.keyMask || '••••'} (blank = keep)`
5139
+ : 'sk-…';
5140
+ els.customKey.value = '';
5141
+ }
5142
+ if (els.customRemove) els.customRemove.disabled = !saved.configured && !saved.baseURL;
5143
+ if (!els.customStatus) return;
5144
+ const parts = [];
5145
+ if (saved.baseURL) parts.push(`endpoint ${saved.baseURL}`);
5146
+ else parts.push('no endpoint saved');
5147
+ parts.push(saved.configured ? `key ${saved.keyMask || 'saved'}` : 'no key');
5148
+ parts.push(declaredModels.length
5149
+ ? `model${declaredModels.length === 1 ? '' : 's'} ${declaredModels.join(', ')}`
5150
+ : 'no model declared');
5151
+ els.customStatus.textContent = parts.join(' · ');
5152
+ }
5153
+
5154
+ /** Read the custom provider's saved state back (settings row + declarations). */
5155
+ async function loadCustomProvider() {
5156
+ if (!els.customBaseUrl) return;
5157
+ let cfg = null;
5158
+ let declared = [];
5159
+ try {
5160
+ const rows = (await models.settings.get()) || [];
5161
+ const found = (Array.isArray(rows) ? rows : []).find(
5162
+ (s) => s && s.provider === `byok:${CUSTOM_PROVIDER}`
5163
+ );
5164
+ if (found) {
5165
+ // `baseURL` IS part of the row `settings.get()` returns (settings.js
5166
+ // `get()`: provider, baseURL, configured, keyMask) — only the key itself
5167
+ // is masked. So the address is read, never re-written to be read back.
5168
+ cfg = {
5169
+ baseURL: found.baseURL || '',
5170
+ configured: Boolean(found.configured),
5171
+ keyMask: found.keyMask,
5172
+ };
5173
+ }
5174
+ } catch {
5175
+ /* store unreadable: the status line below says what is missing */
5176
+ }
5177
+ try {
5178
+ const report = await models.userModels.get();
5179
+ const map = (report && report.map) || {};
5180
+ declared = Array.isArray(map[CUSTOM_PROVIDER]) ? map[CUSTOM_PROVIDER] : [];
5181
+ } catch {
5182
+ /* no declarations readable: treat as none */
5183
+ }
5184
+ paintCustomRow(cfg, declared);
5185
+ }
5186
+
5187
+ /** Save the custom endpoint: settings row (address + key), then the model id. */
5188
+ async function saveCustomProvider() {
5189
+ if (!els.customBaseUrl) return;
5190
+ const baseURL = String(els.customBaseUrl.value || '').trim();
5191
+ const key = els.customKey ? String(els.customKey.value || '').trim() : '';
5192
+ const model = els.customModel ? String(els.customModel.value || '').trim() : '';
5193
+ const say = (t) => { if (els.customStatus) els.customStatus.textContent = t; };
5194
+
5195
+ if (!baseURL) {
5196
+ say('an address is required — aegis1 dials the endpoint you name, and refuses a custom call that names none.');
5197
+ return;
5198
+ }
5199
+ // Checked here as well as server-side so the refusal is a sentence next to the
5200
+ // field instead of a 400 that arrives after the model was declared. aegis1
5201
+ // refuses http:// and every non-public target for this provider; saying so up
5202
+ // front is the difference between a fixable typo and "custom is broken".
5203
+ if (!/^https:\/\//i.test(baseURL)) {
5204
+ say('refused: only an https:// endpoint is dialed — aegis1 rejects a plain-http or scheme-less base URL for this provider.');
5205
+ return;
5206
+ }
5207
+ if (!model) {
5208
+ say('a model id is required — the `custom` provider pins no default, so nothing would be selectable in the picker.');
5209
+ return;
5210
+ }
5211
+
5212
+ say('saving…');
5213
+ const provider = `byok:${CUSTOM_PROVIDER}`;
5214
+ try {
5215
+ const cfg = {};
5216
+ cfg.baseURL = baseURL;
5217
+ if (key) cfg.key = key;
5218
+ await models.settings.set(provider, cfg);
5219
+ } catch (err) {
5220
+ say(`endpoint not saved: ${err && err.message ? err.message : err}`);
5221
+ return;
5222
+ }
5223
+ try {
5224
+ await models.userModels.add(CUSTOM_PROVIDER, model);
5225
+ } catch (err) {
5226
+ say(`endpoint saved, model NOT declared: ${err && err.message ? err.message : err}`);
5227
+ await loadCustomProvider();
5228
+ await loadModels(els.classSelect.value).catch(() => {});
5229
+ return;
5230
+ }
5231
+ if (els.customModel) els.customModel.value = '';
5232
+ say(`saved ${baseURL} with model ${model} — pick it under provider "byok", then the model.`);
5233
+ await loadCustomProvider();
5234
+ await loadSettings();
5235
+ await loadModels(els.classSelect.value).catch(() => {});
5236
+ }
5237
+
5238
+ /** Forget the custom endpoint: the key row, then every declared custom model. */
5239
+ async function removeCustomProvider() {
5240
+ if (!els.customBaseUrl) return;
5241
+ const say = (t) => { if (els.customStatus) els.customStatus.textContent = t; };
5242
+ say('removing…');
5243
+ let removedModels = 0;
5244
+ try {
5245
+ const report = await models.userModels.get();
5246
+ const map = (report && report.map) || {};
5247
+ const declared = Array.isArray(map[CUSTOM_PROVIDER]) ? map[CUSTOM_PROVIDER] : [];
5248
+ for (const model of declared) {
5249
+ await models.userModels.remove(CUSTOM_PROVIDER, model);
5250
+ removedModels += 1;
5251
+ }
5252
+ } catch {
5253
+ /* declarations already gone, or unreadable — the key removal still runs */
5254
+ }
5255
+ try {
5256
+ await models.settings.remove(`byok:${CUSTOM_PROVIDER}`);
5257
+ } catch (err) {
5258
+ say(`remove failed: ${err && err.message ? err.message : err}`);
5259
+ return;
5260
+ }
5261
+ if (els.customBaseUrl) els.customBaseUrl.value = '';
5262
+ say(`removed the custom endpoint${removedModels ? ` and ${removedModels} declared model(s)` : ''}.`);
5263
+ await loadCustomProvider();
5264
+ await loadSettings();
5265
+ await loadModels(els.classSelect.value).catch(() => {});
5266
+ }
5267
+
4641
5268
  async function saveSetting(provider, key) {
4642
5269
  els.settingsHint.textContent = 'saving…';
4643
5270
  try {
@@ -5540,6 +6167,14 @@ async function init() {
5540
6167
  // File > Save as… / Export Session… — same "menu pings, renderer acts"
5541
6168
  // pattern as New Chat/Search above; both call exportSession() with the
5542
6169
  // format the menu label promised (see main.js buildAppMenu).
6170
+ // View > Authorship Panel… — the sidebar card that used to open the φ(α)
6171
+ // sheet is gone (sealing runs in the background), so the menu is the entry
6172
+ // point. `fpPanel` is mount()'s handle, assigned below in init().
6173
+ if (aegis.onMenuFingerprint) {
6174
+ aegis.onMenuFingerprint(() => {
6175
+ if (fpPanel && typeof fpPanel.open === 'function') fpPanel.open();
6176
+ });
6177
+ }
5543
6178
  if (aegis.onMenuExportMarkdown) aegis.onMenuExportMarkdown(() => exportSession('markdown'));
5544
6179
  if (aegis.onMenuExportJson) aegis.onMenuExportJson(() => exportSession('json'));
5545
6180
  // aegis:// deep link (main.js sendDeepLinkToWindow) — delivered once the
@@ -5562,6 +6197,20 @@ async function init() {
5562
6197
  }
5563
6198
  });
5564
6199
 
6200
+ // The custom-provider card (#custom-provider-card). Its three fields are one
6201
+ // decision, so Enter in any of them runs the same Save the button does.
6202
+ if (els.customSave) els.customSave.addEventListener('click', saveCustomProvider);
6203
+ if (els.customRemove) els.customRemove.addEventListener('click', removeCustomProvider);
6204
+ for (const box of [els.customBaseUrl, els.customKey, els.customModel]) {
6205
+ if (!box) continue;
6206
+ box.addEventListener('keydown', (e) => {
6207
+ if (e.key === 'Enter') {
6208
+ e.preventDefault();
6209
+ saveCustomProvider();
6210
+ }
6211
+ });
6212
+ }
6213
+
5565
6214
  // Billing actions in the Status card — see startBilling()/renderBillingError().
5566
6215
  els.upgradePlan.addEventListener('click', () => startBilling('upgrade'));
5567
6216
  els.topupBtn.addEventListener('click', () => startBilling('topup'));
@@ -5869,6 +6518,16 @@ async function init() {
5869
6518
  // (a host that predates the IPC handlers) leaves the card on "checking…"
5870
6519
  // instead of crashing boot. Not awaited: the panel's first status read is a
5871
6520
  // filesystem stat, and the welcome panel must not wait on it.
6521
+ // The provider reference card and the daily line. Both are `?`-guarded by
6522
+ // their own module presence, so a window whose build predates these scripts
6523
+ // boots normally instead of throwing on a missing global.
6524
+ try {
6525
+ mountProviderToolbar();
6526
+ } catch (e) {
6527
+ if (els.ptHint) els.ptHint.textContent = `provider list unavailable: ${(e && e.message) || e}`;
6528
+ }
6529
+ wireCompanion();
6530
+
5872
6531
  if (window.aegisFingerprint) {
5873
6532
  try {
5874
6533
  fpPanel = window.aegisFingerprint.mount({ api: aegis });