aegiscode 7.0.26 → 7.0.27

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 (118) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +4 -7
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2957
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3023
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4089
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/filepreview.js +1 -153
  28. package/src/fingerprint.js +1 -592
  29. package/src/format.js +1 -259
  30. package/src/fuzzy.js +1 -119
  31. package/src/history.js +1 -423
  32. package/src/init.js +1 -175
  33. package/src/input.js +1 -139
  34. package/src/keys.js +1 -183
  35. package/src/markdown.js +1 -306
  36. package/src/models.js +1 -507
  37. package/src/naming.js +1 -57
  38. package/src/overlays.js +1 -462
  39. package/src/panels.js +1 -1418
  40. package/src/ping.js +1 -226
  41. package/src/presence.js +1 -238
  42. package/src/render.js +1 -516
  43. package/src/screen.js +1 -518
  44. package/src/screens.js +1 -896
  45. package/src/secret.js +1 -59
  46. package/src/securefs.js +1 -359
  47. package/src/settings.js +1 -155
  48. package/src/shared.js +1 -52
  49. package/src/sharedpaths.js +1 -53
  50. package/src/signup.js +1 -156
  51. package/src/summarize.js +1 -95
  52. package/src/sysdiag.js +1 -585
  53. package/src/system.js +1 -40
  54. package/src/theme.js +1 -570
  55. package/src/title.js +1 -220
  56. package/src/todos.js +1 -115
  57. package/src/tokens.js +1 -263
  58. package/src/topup.js +1 -210
  59. package/src/update.js +1 -191
  60. package/vendor/client/aegis.js +1 -2441
  61. package/vendor/client/attest.js +1 -518
  62. package/vendor/client/authorship-key.js +1 -410
  63. package/vendor/client/auto-provision.js +1 -134
  64. package/vendor/client/brain-catalog.js +1 -268
  65. package/vendor/client/byok-catalog.js +1 -199
  66. package/vendor/client/catalog-client.js +1 -487
  67. package/vendor/client/conversation-export.js +1 -177
  68. package/vendor/client/credentials.js +1 -494
  69. package/vendor/client/device-fingerprint.js +1 -141
  70. package/vendor/client/drive-connect.js +1 -110
  71. package/vendor/client/drive-upload.js +1 -234
  72. package/vendor/client/env-file.js +1 -1273
  73. package/vendor/client/fingerprint.js +1 -1064
  74. package/vendor/client/foreign-memory.js +1 -669
  75. package/vendor/client/google-signin.js +1 -133
  76. package/vendor/client/hooks.js +1 -430
  77. package/vendor/client/model-discovery.js +1 -373
  78. package/vendor/client/naming.js +1 -283
  79. package/vendor/client/platform.js +1 -937
  80. package/vendor/client/prefs.js +1 -351
  81. package/vendor/client/presence-constants.js +1 -107
  82. package/vendor/client/presence.js +1 -438
  83. package/vendor/client/record-vault.js +3 -1055
  84. package/vendor/client/session-store.js +1 -575
  85. package/vendor/client/topup.js +1 -297
  86. package/vendor/client/touch.js +1 -458
  87. package/vendor/client/update.js +1 -763
  88. package/vendor/client/user-models.js +1 -381
  89. package/vendor/desktop/lib/local/agents.js +1 -105
  90. package/vendor/desktop/lib/local/attachments.js +1 -276
  91. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  92. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  93. package/vendor/desktop/lib/local/context.js +1 -125
  94. package/vendor/desktop/lib/local/engine.js +1 -3666
  95. package/vendor/desktop/lib/local/entitlement.js +1 -660
  96. package/vendor/desktop/lib/local/exec-plan.js +1 -269
  97. package/vendor/desktop/lib/local/git-scope.js +1 -228
  98. package/vendor/desktop/lib/local/integrity.js +1 -163
  99. package/vendor/desktop/lib/local/local.js +1 -2145
  100. package/vendor/desktop/lib/local/prompt.js +1 -280
  101. package/vendor/desktop/lib/local/queue.js +1 -560
  102. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  103. package/vendor/desktop/lib/local/shell.js +1 -712
  104. package/vendor/desktop/lib/local/spill.js +1 -75
  105. package/vendor/desktop/lib/local/tools.js +1 -1328
  106. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  107. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  108. package/vendor/desktop/lib/settings.js +1 -890
  109. package/vendor/desktop/main.js +3 -4890
  110. package/vendor/desktop/renderer/usage.js +1 -1239
  111. package/vendor/hosts/install.js +1 -638
  112. package/vendor/hosts/openai-shim.js +1 -515
  113. package/vendor/hosts/spec.js +1 -164
  114. package/vendor/hosts/targets.js +1 -346
  115. package/vendor/mcp/server.js +1 -221
  116. package/vendor/mcp/tools.js +1 -408
  117. package/vendor/one/src/child.js +1 -285
  118. package/vendor/one/src/permissions.js +1 -383
@@ -1,489 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * The SERVER's full provider/model catalog, cached on disk, layered under the
10
- * live payload.
11
- *
12
- * ── what this replaces ─────────────────────────────────────────────────────
13
- *
14
- * `client/byok-catalog.js` is a hand-written list of ids the server's catalog
15
- * did not name (its own header says the durable fix is the server catalog). The
16
- * server now has one — `services/catalog_store.py` in aegis1, seeded from
17
- * `PROVIDER_CATALOG` and fed by the aggregators — and publishes it as a static
18
- * artifact. This module is the client half: fetch it, cache it, and merge it
19
- * into the BYOK payload.
20
- *
21
- * ── the three layers, and why the order is that order ──────────────────────
22
- *
23
- * 1. the LIVE payload from `/api/v1/byok/providers` — the server's truth
24
- * about what *this* account's relay will accept. Nothing may contradict it.
25
- * 2. the CACHED catalog artifact — ids the vendor serves
26
- * that the live payload did not name. Cached precisely because it is the
27
- * fallback for a call that failed or has not happened yet.
28
- * 3. the USER's own `models.json` overlay — applied by
29
- * `user-models.js`, last, because it is the most specific opinion.
30
- *
31
- * ── rules inherited from byok-catalog.js, all kept ─────────────────────────
32
- *
33
- * - NEVER invent a provider. Only a provider the live payload already lists
34
- * is augmented. A row a client fabricated would invite a key for a slug the
35
- * relay may not accept, and the failure would land on the user's first turn.
36
- * - Additions are APPENDED and the server's order is preserved, so a
37
- * provider's `default_model` — which server order puts first, and which
38
- * pickers therefore treat as the default — stays first.
39
- * - Idempotent and non-mutating. A payload that already carries every id comes
40
- * back with the SAME provider objects, so a caller cannot tell it ran.
41
- *
42
- * ── why the cache is not the source of truth ───────────────────────────────
43
- *
44
- * A stale catalog is a list of ids that *were* valid. That is strictly better
45
- * than an empty picker on a failed call, and strictly worse than the live
46
- * answer — so this is stale-while-revalidate, never stale-instead-of. Every
47
- * entry point reports its own freshness (`stale`) rather than presenting a
48
- * week-old file as current, and nothing here ever blocks startup on a network
49
- * call: `read()` is synchronous and returns `null` when there is no cache.
50
- */
51
-
52
- const fs = require('fs');
53
- const path = require('path');
54
- const credentials = require('./credentials.js');
55
-
56
- /** Cached artifact name, beside `models.json` in the data dir. */
57
- const CATALOG_FILE = 'catalog.json';
58
-
59
- /**
60
- * How old a cache may be before callers should revalidate, in ms.
61
- *
62
- * The server's ingest is a daily job, so a day-old cache is normal and a
63
- * week-old one is not news. Chosen to be longer than one missed cron run and
64
- * shorter than anything a person would call "the catalog is wrong now".
65
- */
66
- const STALE_AFTER_MS = 24 * 60 * 60 * 1000;
67
-
68
- /** The data dir (`$AEGISCODE_HOME` or `~/.aegiscode`), from the ONE definition. */
69
- function catalogDir(opts) {
70
- return (opts && opts.dir) || credentials.aegisHome(opts && opts.env);
71
- }
72
-
73
- /** The absolute path of the cached catalog artifact. */
74
- function catalogPath(opts) {
75
- return path.join(catalogDir(opts), CATALOG_FILE);
76
- }
77
-
78
- /** Model ids out of a provider row in either shape (`string` or `{id}`). */
79
- function modelIdsOf(provider) {
80
- return (Array.isArray(provider && provider.models) ? provider.models : [])
81
- .map((m) => (typeof m === 'string' ? m : m && m.id))
82
- .map((m) => (typeof m === 'string' ? m.trim() : ''))
83
- .filter(Boolean);
84
- }
85
-
86
- /** The provider array out of either shape the server sends (or `null`). */
87
- function providerArray(providers) {
88
- if (Array.isArray(providers)) return providers;
89
- if (Array.isArray(providers && providers.providers)) return providers.providers;
90
- return null;
91
- }
92
-
93
- /**
94
- * Index an artifact's `models` rows as provider → [model_id].
95
- *
96
- * Takes the shape `scripts/catalog_sync.py` writes: `{providers: [...],
97
- * models: [{provider_id, model_id, status}, ...]}`. A retired row is skipped —
98
- * adding an id the server has marked deprecated would offer a row that pins and
99
- * then fails upstream, which is the failure `brain-catalog.js` exists to end.
100
- */
101
- function indexCatalog(catalog) {
102
- const out = Object.create(null);
103
- const rows = Array.isArray(catalog && catalog.models) ? catalog.models : [];
104
- for (const m of rows) {
105
- if (!m || typeof m !== 'object') continue;
106
- const pid = typeof m.provider_id === 'string' ? m.provider_id.trim() : '';
107
- const mid = typeof m.model_id === 'string' ? m.model_id.trim() : '';
108
- if (!pid || !mid) continue;
109
- const status = typeof m.status === 'string' ? m.status.toLowerCase() : 'active';
110
- if (status !== 'active') continue;
111
- (out[pid] || (out[pid] = [])).push(mid);
112
- }
113
- return out;
114
- }
115
-
116
- /**
117
- * Read the cached artifact.
118
- *
119
- * Never throws. A corrupt, truncated or absent file returns `null` and is
120
- * reported as such — the caller falls back to the live payload, which is always
121
- * the better answer anyway. Reading a catalog must not be able to take down a
122
- * startup path.
123
- *
124
- * @param {object} [opts] `{dir?, env?}` — `dir` makes this testable without a
125
- * real data dir, exactly as `user-models.js` does it.
126
- * @returns {{data: object, fetchedAt: number|null, ageMs: number|null,
127
- * stale: boolean, path: string}|null}
128
- */
129
- function read(opts) {
130
- const file = catalogPath(opts);
131
- let raw;
132
- try {
133
- raw = fs.readFileSync(file, 'utf8');
134
- } catch (e) {
135
- return null;
136
- }
137
- let data;
138
- try {
139
- data = JSON.parse(raw);
140
- } catch (e) {
141
- // A half-written file is the case the atomic write below exists to prevent;
142
- // if one is found anyway, say so and degrade rather than throw.
143
- return null;
144
- }
145
- if (!data || typeof data !== 'object' || !Array.isArray(data.providers)) return null;
146
-
147
- // `fetched_at` is the artifact's own stamp (what the server knew, when).
148
- // The file's mtime is the fallback for an artifact written without one.
149
- let fetchedAt = null;
150
- const stamp = data.snapshot && (data.snapshot.fetched_at || data.snapshot.fetchedAt);
151
- if (typeof stamp === 'string' && stamp) {
152
- const t = Date.parse(stamp);
153
- if (!Number.isNaN(t)) fetchedAt = t;
154
- }
155
- if (fetchedAt === null) {
156
- try {
157
- fetchedAt = fs.statSync(file).mtimeMs;
158
- } catch (e) {
159
- fetchedAt = null;
160
- }
161
- }
162
- const ageMs = fetchedAt === null ? null : Math.max(0, Date.now() - fetchedAt);
163
-
164
- // A 304 revalidation (`refresh` below) leaves `fetched_at` alone — that field
165
- // says when the DATA was fetched, and rewriting it on a no-change response
166
- // would make a month-old artifact claim to be new. But freshness is a
167
- // separate question: if the server confirmed the content this morning, the
168
- // cache IS current. So the newest of the two stamps decides `stale`, while
169
- // `fetchedAt`/`ageMs` keep reporting the age of the data itself. Without
170
- // this, every run would re-ask for a catalog the server just confirmed.
171
- let revalidatedAt = null;
172
- const rev = data.snapshot && data.snapshot.revalidated_at;
173
- if (typeof rev === 'string' && rev) {
174
- const t = Date.parse(rev);
175
- if (!Number.isNaN(t)) revalidatedAt = t;
176
- }
177
- const freshFrom = revalidatedAt !== null && (fetchedAt === null || revalidatedAt > fetchedAt)
178
- ? revalidatedAt
179
- : fetchedAt;
180
-
181
- return {
182
- data,
183
- fetchedAt,
184
- revalidatedAt,
185
- ageMs,
186
- stale: freshFrom === null ? true : (Date.now() - freshFrom) > STALE_AFTER_MS,
187
- path: file,
188
- };
189
- }
190
-
191
- /**
192
- * Write the artifact atomically, creating the data dir if needed.
193
- *
194
- * Temp file + `rename` because a client may read this while another process
195
- * writes it, and a truncated JSON file is indistinguishable from a broken
196
- * server — which would send every reader down the fallback path for no reason.
197
- *
198
- * @returns {string} the path written.
199
- */
200
- function write(catalog, opts) {
201
- const file = catalogPath(opts);
202
- fs.mkdirSync(path.dirname(file), { recursive: true });
203
- const tmp = `${file}.${process.pid}.tmp`;
204
- fs.writeFileSync(tmp, JSON.stringify(catalog), 'utf8');
205
- fs.renameSync(tmp, file);
206
- return file;
207
- }
208
-
209
- /**
210
- * The live payload with the cached catalog's ids filled in.
211
- *
212
- * @param {Array<object>|object} providers the live `/api/v1/byok/providers`
213
- * payload (array, or `{providers}`).
214
- * @param {object|null} [catalog] an artifact as `read().data`. Pass `null` to
215
- * mean "no cache" — deliberately explicit rather than "read the disk", so
216
- * callers that already have a catalog do not get a silent second read.
217
- * @param {object} [opts] `{dir?, env?}`; only used when `catalog` is undefined.
218
- * @returns {Array<object>} a NEW array. Providers that gained nothing come back
219
- * as the SAME objects, so a complete payload is byte-identical after this
220
- * pass. An empty/absent payload returns `[]` — this never invents a list.
221
- */
222
- function withCatalog(providers, catalog, opts) {
223
- const raw = providerArray(providers);
224
- if (!raw) return [];
225
-
226
- let art = catalog;
227
- if (art === undefined) {
228
- const hit = read(opts);
229
- art = hit ? hit.data : null;
230
- }
231
- const byProvider = indexCatalog(art);
232
- if (!Object.keys(byProvider).length) return raw.slice();
233
-
234
- const out = [];
235
- for (const p of raw) {
236
- if (!p || typeof p !== 'object') continue;
237
- const id = typeof p.id === 'string' ? p.id.trim() : '';
238
- // NEVER invent a provider: only a row the server already lists is extended.
239
- const known = id ? byProvider[id] : null;
240
- if (!known || !known.length) {
241
- out.push(p);
242
- continue;
243
- }
244
- const have = new Set(modelIdsOf(p));
245
- const missing = known.filter((m) => !have.has(m));
246
- if (!missing.length) {
247
- out.push(p); // same object: nothing to add, caller cannot tell it ran
248
- continue;
249
- }
250
- const models = Array.isArray(p.models) ? p.models : [];
251
- // Append, never prepend: the server's order puts `default_model` first and
252
- // pickers take the first entry as the default.
253
- out.push({ ...p, models: [...models, ...missing] });
254
- }
255
- return out;
256
- }
257
-
258
- /**
259
- * Ids the cached catalog knows for a provider that the live payload did not
260
- * name — for a host that wants to SAY what it added instead of only showing it.
261
- *
262
- * @returns {string[]} possibly empty; never throws.
263
- */
264
- function addedModelsFor(providerId, providers, catalog, opts) {
265
- const pid = typeof providerId === 'string' ? providerId.trim() : '';
266
- if (!pid) return [];
267
- let art = catalog;
268
- if (art === undefined) {
269
- const hit = read(opts);
270
- art = hit ? hit.data : null;
271
- }
272
- const known = indexCatalog(art)[pid] || [];
273
- const row = (providerArray(providers) || [])
274
- .find((p) => p && typeof p.id === 'string' && p.id.trim() === pid);
275
- const have = new Set(modelIdsOf(row));
276
- return known.filter((m) => !have.has(m));
277
- }
278
-
279
- /* ── refresh ──────────────────────────────────────────────────────────────── */
280
-
281
- /**
282
- * Most pages one refresh will walk, at `limit` rows each.
283
- *
284
- * The server clamps `limit` to 500, so 200 pages is ~100k models — far past
285
- * anything the ingest currently sees, and therefore a runaway guard rather than
286
- * a limit anyone will hit. Stopping is the right failure mode: a truncated
287
- * cache is a *reported* stale one, while an unbounded loop against a server
288
- * that never clears `has_more` would hang the refresh forever and write
289
- * nothing at all.
290
- */
291
- const MAX_PAGES = 200;
292
-
293
- /**
294
- * Rebuild the cached artifact from the paged catalog endpoint.
295
- *
296
- * ── why this takes a function instead of an HTTP client ────────────────────
297
- *
298
- * This module deliberately requires only `fs`, `path` and `credentials.js`.
299
- * It is vendored into three hosts (`client/`, `cli/vendor/`, `desktop/`) and
300
- * runs on startup paths, so a require of the API client here would drag the
301
- * whole HTTP stack — and its config — into a file that only needs to read and
302
- * write JSON. The caller owns the transport and passes it in.
303
- *
304
- * ── the contract the caller must honour ────────────────────────────────────
305
- *
306
- * `fetchPage({cursor, limit, etag})` resolves to one page:
307
- *
308
- * `{ models: [...], next_cursor?, has_more?, etag?, notModified? }`
309
- *
310
- * `notModified: true` (a 304, or an `If-None-Match` hit) means "the server's
311
- * answer has not changed" — the cache is already correct and this returns
312
- * `{ changed: false }` without touching the file. Rejecting is also fine: a
313
- * failed refresh never disturbs a good cache, and this never throws.
314
- *
315
- * ── what is preserved from the previous artifact ───────────────────────────
316
- *
317
- * `providers`. The models endpoint does not carry provider rows, and dropping
318
- * them would make a refreshed artifact strictly less useful than the one it
319
- * replaced — `indexCatalog` would still work, but any host reading provider
320
- * metadata would see it vanish on first refresh.
321
- *
322
- * @param {Function} fetchPage see above; required.
323
- * @param {object} [opts] `{dir?, env?, limit?, etag?, maxPages?, now?}`.
324
- * @returns {Promise<{ok: boolean, changed: boolean, written: string|null,
325
- * pages: number, models: number, providers: number, staleKept: boolean,
326
- * reason?: string}>} never rejects.
327
- */
328
- async function refresh(fetchPage, opts) {
329
- const o = opts || {};
330
- const limit = o.limit || 500;
331
- const maxPages = o.maxPages || MAX_PAGES;
332
- const previous = read(o);
333
- const prevData = (previous && previous.data) || null;
334
-
335
- const models = [];
336
- let cursor = null;
337
- let pages = 0;
338
- let etag = o.etag || null;
339
- // The ETag to persist: taken from the FIRST page only. It identifies the
340
- // whole response, so page two onward carries a different one and storing the
341
- // last one would make every future revalidation a guaranteed miss.
342
- let firstPageEtag = null;
343
- let notModified = false;
344
-
345
- try {
346
- for (;;) {
347
- const page = await fetchPage({ cursor, limit, etag });
348
- if (!page || page.notModified) {
349
- notModified = true;
350
- break;
351
- }
352
- if (pages === 0 && page.etag) firstPageEtag = page.etag;
353
- const rows = Array.isArray(page.models) ? page.models : [];
354
- for (const m of rows) {
355
- if (m && typeof m === 'object') models.push(m);
356
- }
357
- pages += 1;
358
- // A page that reports more but gives no cursor would loop forever
359
- // re-fetching the same rows. Treat it as the end and say so via `ok`.
360
- if (!page.has_more || !page.next_cursor) break;
361
- if (pages >= maxPages) {
362
- return _refreshResult({
363
- ok: false, changed: false, pages, models: models.length,
364
- providers: 0, staleKept: Boolean(prevData),
365
- reason: `stopped after ${pages} pages; cache left untouched`,
366
- });
367
- }
368
- cursor = page.next_cursor;
369
- // The ETag is only meaningful for the FIRST page: it identifies the whole
370
- // response body, and page two onward has a different one.
371
- etag = null;
372
- }
373
- } catch (err) {
374
- // A refresh is best-effort. The previous artifact is still a valid (if
375
- // older) answer, and `read()` reports its staleness, so nothing here
376
- // escalates into a startup failure.
377
- return _refreshResult({
378
- ok: false, changed: false, pages, models: 0,
379
- providers: 0, staleKept: Boolean(prevData),
380
- reason: (err && err.message) || String(err),
381
- });
382
- }
383
-
384
- if (notModified) {
385
- // A 304 says "this content is still current", so the cache needs no data
386
- // change — but its `fetched_at` is now misleading, and without a stamp
387
- // every future run would re-ask. Record the REVALIDATION separately rather
388
- // than overwriting `fetched_at`: that field answers "when was this data
389
- // fetched from the vendor catalog", and resetting it on a 304 would make a
390
- // month-old artifact claim to be new.
391
- let written = null;
392
- if (prevData) {
393
- try {
394
- const now = typeof o.now === 'function' ? o.now() : Date.now();
395
- written = write({
396
- ...prevData,
397
- snapshot: {
398
- ...(prevData.snapshot || {}),
399
- revalidated_at: new Date(now).toISOString(),
400
- ...(firstPageEtag ? { etag: firstPageEtag } : {}),
401
- },
402
- }, o);
403
- } catch {
404
- written = null;
405
- }
406
- }
407
- return _refreshResult({
408
- ok: true, changed: false, pages: 0, models: 0, providers: 0,
409
- staleKept: !written, written, reason: 'not-modified',
410
- });
411
- }
412
- if (!models.length) {
413
- // An empty catalog is the one result that must not overwrite a good cache:
414
- // a server mid-ingest would otherwise replace a full artifact with nothing,
415
- // and every picker would go empty on the next start.
416
- return _refreshResult({
417
- ok: false, changed: false, pages, models: 0, providers: 0,
418
- staleKept: Boolean(prevData), reason: 'empty catalog; cache left untouched',
419
- });
420
- }
421
-
422
- const providers = (prevData && Array.isArray(prevData.providers))
423
- ? prevData.providers
424
- : [];
425
- const now = typeof o.now === 'function' ? o.now() : Date.now();
426
- const artifact = {
427
- schema_version: (prevData && prevData.schema_version) || 1,
428
- providers,
429
- models,
430
- snapshot: {
431
- // `read()` prefers this stamp over mtime, so it must be the time of the
432
- // FETCH, not of the write — they are the same here, and writing it makes
433
- // the age survive a copy that resets mtime.
434
- fetched_at: new Date(now).toISOString(),
435
- models_seen: models.length,
436
- providers_seen: providers.length,
437
- source: 'catalog-api',
438
- // Persisted so the NEXT refresh can send If-None-Match and pay a 304
439
- // instead of walking every page. Without this the revalidation path
440
- // existed but could never be reached.
441
- ...(firstPageEtag ? { etag: firstPageEtag } : {}),
442
- },
443
- };
444
-
445
- let written = null;
446
- try {
447
- written = write(artifact, o);
448
- } catch (err) {
449
- return _refreshResult({
450
- ok: false, changed: false, pages, models: models.length,
451
- providers: providers.length, staleKept: Boolean(prevData),
452
- reason: (err && err.message) || String(err),
453
- });
454
- }
455
-
456
- return _refreshResult({
457
- ok: true, changed: true, pages, models: models.length,
458
- providers: providers.length, staleKept: false, written,
459
- });
460
- }
461
-
462
- /** Normalise the refresh result so every exit reports the same keys. */
463
- function _refreshResult(r) {
464
- return {
465
- ok: Boolean(r.ok),
466
- changed: Boolean(r.changed),
467
- written: r.written || null,
468
- pages: r.pages || 0,
469
- models: r.models || 0,
470
- providers: r.providers || 0,
471
- staleKept: Boolean(r.staleKept),
472
- ...(r.reason ? { reason: r.reason } : {}),
473
- };
474
- }
475
-
476
-
477
- module.exports = {
478
- CATALOG_FILE,
479
- STALE_AFTER_MS,
480
- MAX_PAGES,
481
- catalogDir,
482
- catalogPath,
483
- indexCatalog,
484
- read,
485
- write,
486
- refresh,
487
- withCatalog,
488
- addedModelsFor,
489
- };
3
+ "use strict";const fs=require("fs"),path=require("path"),credentials=require("./credentials.js"),CATALOG_FILE="catalog.json",STALE_AFTER_MS=864e5;function catalogDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function catalogPath(e){return path.join(catalogDir(e),CATALOG_FILE)}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function indexCatalog(e){const t=Object.create(null),r=Array.isArray(e&&e.models)?e.models:[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.provider_id?e.provider_id.trim():"",o="string"==typeof e.model_id?e.model_id.trim():"";r&&o&&("active"===("string"==typeof e.status?e.status.toLowerCase():"active")&&(t[r]||(t[r]=[])).push(o))}return t}function read(e){const t=catalogPath(e);let r,o;try{r=fs.readFileSync(t,"utf8")}catch(e){return null}try{o=JSON.parse(r)}catch(e){return null}if(!o||"object"!=typeof o||!Array.isArray(o.providers))return null;let n=null;const a=o.snapshot&&(o.snapshot.fetched_at||o.snapshot.fetchedAt);if("string"==typeof a&&a){const e=Date.parse(a);Number.isNaN(e)||(n=e)}if(null===n)try{n=fs.statSync(t).mtimeMs}catch(e){n=null}const s=null===n?null:Math.max(0,Date.now()-n);let i=null;const l=o.snapshot&&o.snapshot.revalidated_at;if("string"==typeof l&&l){const e=Date.parse(l);Number.isNaN(e)||(i=e)}const d=null!==i&&(null===n||i>n)?i:n;return{data:o,fetchedAt:n,revalidatedAt:i,ageMs:s,stale:null===d||Date.now()-d>STALE_AFTER_MS,path:t}}function write(e,t){const r=catalogPath(t);fs.mkdirSync(path.dirname(r),{recursive:!0});const o=`${r}.${process.pid}.tmp`;return fs.writeFileSync(o,JSON.stringify(e),"utf8"),fs.renameSync(o,r),r}function withCatalog(e,t,r){const o=providerArray(e);if(!o)return[];let n=t;if(void 0===n){const e=read(r);n=e?e.data:null}const a=indexCatalog(n);if(!Object.keys(a).length)return o.slice();const s=[];for(const e of o){if(!e||"object"!=typeof e)continue;const t="string"==typeof e.id?e.id.trim():"",r=t?a[t]:null;if(!r||!r.length){s.push(e);continue}const o=new Set(modelIdsOf(e)),n=r.filter((e=>!o.has(e)));if(!n.length){s.push(e);continue}const i=Array.isArray(e.models)?e.models:[];s.push({...e,models:[...i,...n]})}return s}function addedModelsFor(e,t,r,o){const n="string"==typeof e?e.trim():"";if(!n)return[];let a=r;if(void 0===a){const e=read(o);a=e?e.data:null}const s=indexCatalog(a)[n]||[],i=(providerArray(t)||[]).find((e=>e&&"string"==typeof e.id&&e.id.trim()===n)),l=new Set(modelIdsOf(i));return s.filter((e=>!l.has(e)))}const MAX_PAGES=200;async function refresh(e,t){const r=t||{},o=r.limit||500,n=r.maxPages||200,a=read(r),s=a&&a.data||null,i=[];let l=null,d=0,c=r.etag||null,u=null,f=!1;try{for(;;){const t=await e({cursor:l,limit:o,etag:c});if(!t||t.notModified){f=!0;break}0===d&&t.etag&&(u=t.etag);const r=Array.isArray(t.models)?t.models:[];for(const e of r)e&&"object"==typeof e&&i.push(e);if(d+=1,!t.has_more||!t.next_cursor)break;if(d>=n)return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:0,staleKept:Boolean(s),reason:`stopped after ${d} pages; cache left untouched`});l=t.next_cursor,c=null}}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:e&&e.message||String(e)})}if(f){let e=null;if(s)try{const t="function"==typeof r.now?r.now():Date.now();e=write({...s,snapshot:{...s.snapshot||{},revalidated_at:new Date(t).toISOString(),...u?{etag:u}:{}}},r)}catch{e=null}return _refreshResult({ok:!0,changed:!1,pages:0,models:0,providers:0,staleKept:!e,written:e,reason:"not-modified"})}if(!i.length)return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:"empty catalog; cache left untouched"});const p=s&&Array.isArray(s.providers)?s.providers:[],h="function"==typeof r.now?r.now():Date.now(),g={schema_version:s&&s.schema_version||1,providers:p,models:i,snapshot:{fetched_at:new Date(h).toISOString(),models_seen:i.length,providers_seen:p.length,source:"catalog-api",...u?{etag:u}:{}}};let m=null;try{m=write(g,r)}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:p.length,staleKept:Boolean(s),reason:e&&e.message||String(e)})}return _refreshResult({ok:!0,changed:!0,pages:d,models:i.length,providers:p.length,staleKept:!1,written:m})}function _refreshResult(e){return{ok:Boolean(e.ok),changed:Boolean(e.changed),written:e.written||null,pages:e.pages||0,models:e.models||0,providers:e.providers||0,staleKept:Boolean(e.staleKept),...e.reason?{reason:e.reason}:{}}}module.exports={CATALOG_FILE:CATALOG_FILE,STALE_AFTER_MS:STALE_AFTER_MS,MAX_PAGES:200,catalogDir:catalogDir,catalogPath:catalogPath,indexCatalog:indexCatalog,read:read,write:write,refresh:refresh,withCatalog:withCatalog,addedModelsFor:addedModelsFor};
@@ -1,179 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * conversation-export.js — the words at the TOP of a file that leaves this
10
- * machine, saying who wrote it.
11
- *
12
- * ## Why this file exists
13
- *
14
- * A backup that lands in someone's Google Drive has to answer one question
15
- * without the app that made it: **whose writing is this?** A transcript with no
16
- * header is indistinguishable from a transcript anyone could have typed. So
17
- * every file this app uploads carries an authorship stamp in its first screenful
18
- * — the key tag, the account, which of the two scopes was chosen, and when it
19
- * was taken.
20
- *
21
- * ## The two scopes, named the way a person would say them
22
- *
23
- * 'conversation' one conversation — a single chat, exactly as it happened
24
- * 'memory' the whole memory base — every stored memory entry
25
- *
26
- * These are deliberately separate acts with separate buttons. "Back up my
27
- * memory" and "save this conversation" are different intentions, and a UI that
28
- * collapses them into one control makes the user guess which one they got.
29
- *
30
- * ## The honesty rule
31
- *
32
- * With no authorship key, the stamp says so in words — `no key — this copy is
33
- * unsigned` — and never invents a tag. An unsigned export that admitted it is
34
- * useful; one that displayed a plausible-looking φ_… would be a forgery with
35
- * our name on it. `keyFingerprint` here is the 12-hex DERIVED tag
36
- * (client/authorship-key.js `keyFingerprint(secret)`), never the secret itself:
37
- * the tag proves two machines hold the same key without either one revealing it.
38
- *
39
- * Pure by construction — no `fs`, no clock of its own (`exportedAt` is passed
40
- * in), no network — so the exact bytes are testable without a Drive account.
41
- */
42
-
43
- /** The scope names, in one place, because both the stamp and the UI say them. */
44
- const SCOPE_CONVERSATION = 'conversation';
45
- const SCOPE_MEMORY = 'memory';
46
-
47
- /** What each scope is called in a sentence a person reads, not a token. */
48
- const SCOPE_TEXT = {
49
- [SCOPE_CONVERSATION]: 'one conversation',
50
- [SCOPE_MEMORY]: 'the whole memory base',
51
- };
52
-
53
- /** `6a1f4091b189` -> `φ_6a1f4091b189`; anything falsy -> null, never a fake. */
54
- function keyTag(keyFingerprint) {
55
- const fp = typeof keyFingerprint === 'string' ? keyFingerprint.trim() : '';
56
- return fp ? `φ_${fp}` : null;
57
- }
58
-
59
- /** The line that answers "who wrote this?". Unsigned is stated, not implied. */
60
- function authorLine(keyFingerprint) {
61
- const tag = keyTag(keyFingerprint);
62
- return tag || 'no key — this copy is unsigned';
63
- }
64
-
65
- /** A filename that cannot escape the folder it is written into. */
66
- function safeFileName(title, fallback) {
67
- const base = String(title || fallback || 'aegis-export')
68
- .normalize('NFKD')
69
- .replace(/[^\w.-]+/g, '-')
70
- .replace(/^-+|-+$/g, '')
71
- .slice(0, 80);
72
- return base || 'aegis-export';
73
- }
74
-
75
- /**
76
- * The stamp every export starts with.
77
- *
78
- * Rendered as bold-label markdown lines rather than YAML front matter on
79
- * purpose: front matter is machine food, and the first thing a human opens this
80
- * file in is Drive's own preview, which shows the markdown as plain text. Bold
81
- * labels read correctly in both.
82
- *
83
- * @param {{scope:string, keyFingerprint?:string|null, email?:string|null,
84
- * exportedAt?:string, subject?:string|null, count?:number|null}} opts
85
- * @returns {string} the header block, ending with `\n\n`
86
- */
87
- function stamp({
88
- scope,
89
- keyFingerprint = null,
90
- email = null,
91
- exportedAt = null,
92
- subject = null,
93
- count = null,
94
- } = {}) {
95
- const tag = keyTag(keyFingerprint);
96
- const lines = [];
97
- if (subject) lines.push(`**What this is:** ${subject}`);
98
- lines.push(`**Scope:** ${SCOPE_TEXT[scope] || String(scope || 'unknown')} (${scope || 'unknown'})`);
99
- lines.push(`**Author:** ${authorLine(keyFingerprint)}`);
100
- lines.push(`**Account:** ${email || 'not reported by the server'}`);
101
- if (count !== null && count !== undefined) {
102
- lines.push(`**Entries:** ${count}`);
103
- }
104
- lines.push(`**Exported:** ${exportedAt || 'timestamp not recorded'}`);
105
- lines.push(
106
- tag
107
- ? `**Sealed by:** ${tag} — this is a key tag, not the key. It proves the same machine wrote it.`
108
- : '**Sealed by:** nothing — no authorship key is set on this machine, so this copy cannot prove it came from you.'
109
- );
110
- return `${lines.join('\n')}\n\n`;
111
- }
112
-
113
- /**
114
- * One conversation, header + transcript.
115
- *
116
- * `transcript` is passed in already rendered (client/session-store.js
117
- * `toMarkdown`) rather than imported here: this module stays free of the store
118
- * and of `fs`, and the caller keeps one implementation of what a transcript
119
- * looks like.
120
- *
121
- * @param {object} session the session record (for title/id only)
122
- * @param {{transcript:string, keyFingerprint?:string|null, email?:string|null,
123
- * exportedAt?:string, count?:number|null}} opts
124
- * @returns {string}
125
- */
126
- function conversationMarkdown(session, opts = {}) {
127
- const title = (session && (session.title || session.id)) || 'Untitled conversation';
128
- const header = stamp({
129
- scope: SCOPE_CONVERSATION,
130
- subject: null,
131
- keyFingerprint: opts.keyFingerprint,
132
- email: opts.email,
133
- exportedAt: opts.exportedAt,
134
- count: opts.count === undefined ? null : opts.count,
135
- });
136
- return `# ${title}\n\n${header}---\n\n${opts.transcript || ''}`;
137
- }
138
-
139
- /**
140
- * The whole memory base. `content` is the serialised entries, unchanged — the
141
- * point of this call is the header above it, not a second export format.
142
- *
143
- * @param {string} content
144
- * @param {{keyFingerprint?:string|null, email?:string|null, exportedAt?:string,
145
- * count?:number|null}} opts
146
- */
147
- function memoryMarkdown(content, opts = {}) {
148
- const header = stamp({
149
- scope: SCOPE_MEMORY,
150
- subject: null,
151
- keyFingerprint: opts.keyFingerprint,
152
- email: opts.email,
153
- exportedAt: opts.exportedAt,
154
- count: opts.count === undefined ? null : opts.count,
155
- });
156
- return `${header}---\n\n${content || ''}`;
157
- }
158
-
159
- /** `aegis-conversation-my-chat-2026-10-24T12-00-00Z.md` — one new file per save. */
160
- function conversationFileName(session, exportedAt) {
161
- const stampText = String(exportedAt || '')
162
- .replace(/[:.]/g, '-')
163
- .replace(/[^\w-]+/g, '');
164
- const title = safeFileName(session && (session.title || session.id), 'conversation');
165
- return stampText ? `${title}-${stampText}.md` : `${title}.md`;
166
- }
167
-
168
- module.exports = {
169
- SCOPE_CONVERSATION,
170
- SCOPE_MEMORY,
171
- SCOPE_TEXT,
172
- keyTag,
173
- authorLine,
174
- safeFileName,
175
- stamp,
176
- conversationMarkdown,
177
- memoryMarkdown,
178
- conversationFileName,
179
- };
3
+ const e="conversation",n="memory",t={[e]:"one conversation",[n]:"the whole memory base"};function o(e){const n="string"==typeof e?e.trim():"";return n?`φ_${n}`:null}function r(e){return o(e)||"no key — this copy is unsigned"}function i(e,n){return String(e||n||"aegis-export").normalize("NFKD").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"aegis-export"}function u({scope:e,keyFingerprint:n=null,email:i=null,exportedAt:u=null,subject:s=null,count:c=null}={}){const l=o(n),a=[];return s&&a.push(`**What this is:** ${s}`),a.push(`**Scope:** ${t[e]||String(e||"unknown")} (${e||"unknown"})`),a.push(`**Author:** ${r(n)}`),a.push(`**Account:** ${i||"not reported by the server"}`),null!=c&&a.push(`**Entries:** ${c}`),a.push(`**Exported:** ${u||"timestamp not recorded"}`),a.push(l?`**Sealed by:** ${l} — this is a key tag, not the key. It proves the same machine wrote it.`:"**Sealed by:** nothing — no authorship key is set on this machine, so this copy cannot prove it came from you."),`${a.join("\n")}\n\n`}module.exports={SCOPE_CONVERSATION:e,SCOPE_MEMORY:n,SCOPE_TEXT:t,keyTag:o,authorLine:r,safeFileName:i,stamp:u,conversationMarkdown:function(n,t={}){return`# ${n&&(n.title||n.id)||"Untitled conversation"}\n\n${u({scope:e,subject:null,keyFingerprint:t.keyFingerprint,email:t.email,exportedAt:t.exportedAt,count:void 0===t.count?null:t.count})}---\n\n${t.transcript||""}`},memoryMarkdown:function(e,t={}){return`${u({scope:n,subject:null,keyFingerprint:t.keyFingerprint,email:t.email,exportedAt:t.exportedAt,count:void 0===t.count?null:t.count})}---\n\n${e||""}`},conversationFileName:function(e,n){const t=String(n||"").replace(/[:.]/g,"-").replace(/[^\w-]+/g,""),o=i(e&&(e.title||e.id),"conversation");return t?`${o}-${t}.md`:`${o}.md`}};