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,577 +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
- * session-store.js — the ONE local session/memory store shared by every AEGIS
10
- * host.
11
- *
12
- * Before this module the repo had two private stores:
13
- *
14
- * CLI ~/.aegiscode/history.jsonl one line per exchange
15
- * desktop <userData>/sessions.json one record per session
16
- *
17
- * Both hosts pushed "the same wire shape" to the cloud, so a session started in
18
- * the GUI reached the terminal only after a network round trip — and a CLI
19
- * session could not reach the GUI at all unless the account had cloud sync on.
20
- * Offline, or on an account with no key, the two hosts simply could not see each
21
- * other's work.
22
- *
23
- * This module is the single store they now both read and write:
24
- *
25
- * <dir>/sessions.json { __seq, "<id>": { id, title, messages[], ... } }
26
- *
27
- * `dir` is resolved by `aegisHome()` (client/credentials.js) — `$AEGISCODE_HOME`
28
- * or `~/.aegiscode` — so the desktop's *sessions* now live beside the CLI's and
29
- * the MCP plugin's view of the same account, while the desktop keeps its
30
- * settings (safeStorage-encrypted key, window state) in Electron's userData
31
- * where they belong.
32
- *
33
- * The record shape is the desktop's, extended — not replaced. Every field the
34
- * existing store wrote (`pending`, `seq`, `updatedAt`, `remoteId`,
35
- * `lastSyncedAt`, `__seq`) keeps its meaning, because the sync surface and the
36
- * renderer's session list read them.
37
- *
38
- * Pure Node + injectable dir, so it unit-tests without Electron or a network.
39
- */
40
-
41
- const fs = require('node:fs');
42
- const path = require('node:path');
43
- const { aegisHome } = require('./credentials.js');
44
-
45
- const STORE_FILE = 'sessions.json';
46
- const STORE_VERSION = 2;
47
- /** Bound on a single session's transcript, so one runaway session cannot make
48
- * every later load of the store O(huge). Oldest messages drop first. */
49
- const MAX_MESSAGES_PER_SESSION = 2000;
50
-
51
- /** Where the store lives when the caller doesn't name a dir. */
52
- function storeDir(dir) {
53
- return dir || aegisHome();
54
- }
55
-
56
- function storeFile(dir) {
57
- return path.join(storeDir(dir), STORE_FILE);
58
- }
59
-
60
- /**
61
- * Monotonic write counter stored in the file's `__seq` field. Every mutation
62
- * bumps it, so sessions written in the same millisecond still order
63
- * deterministically (listSessions sorts by updatedAt, then by seq).
64
- */
65
- function nextSeq(sessions) {
66
- const seq = (typeof sessions.__seq === 'number' ? sessions.__seq : 0) + 1;
67
- sessions.__seq = seq;
68
- return seq;
69
- }
70
-
71
- /**
72
- * Normalize a remote `updated_at`/`updatedAt` to epoch milliseconds. The cloud
73
- * returns an ISO-8601 string (e.g. "2026-07-16T14:20:00"); the local store
74
- * uses `Date.now()` epoch-ms numbers. Comparing the two directly coerces the
75
- * string to NaN, which breaks last-write-wins ordering. ISO strings are
76
- * parsed; epoch-ms numbers pass through; anything else becomes 0.
77
- */
78
- function toEpochMs(value) {
79
- if (typeof value === 'number' && Number.isFinite(value)) return value;
80
- if (typeof value === 'string' && value.trim()) {
81
- const ms = Date.parse(value);
82
- if (Number.isFinite(ms)) return ms;
83
- }
84
- return 0;
85
- }
86
-
87
- function load(dir) {
88
- try {
89
- const parsed = JSON.parse(fs.readFileSync(storeFile(dir), 'utf8'));
90
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
91
- } catch {}
92
- return {};
93
- }
94
-
95
- /**
96
- * Sessions as a JSON object without the `__seq` bookkeeping key. Callers that
97
- * iterate the store (the renderer's list, `/resume`) must not meet `__seq` as
98
- * if it were a session with an undefined id.
99
- */
100
- function atomicWrite(file, data) {
101
- fs.mkdirSync(path.dirname(file), { recursive: true });
102
- const tmp = `${file}.tmp-${process.pid}`;
103
- // 0600: a transcript is private conversation content, and this file now holds
104
- // every host's sessions in one place.
105
- fs.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
106
- fs.renameSync(tmp, file);
107
- try {
108
- fs.chmodSync(file, 0o600);
109
- } catch {}
110
- }
111
-
112
- /** How long a lock may be held before another writer treats it as abandoned. */
113
- const LOCK_STALE_MS = 2000;
114
- /** Total time a writer will wait for the lock before proceeding unlocked. */
115
- const LOCK_WAIT_MS = 500;
116
-
117
- function lockFile(dir) {
118
- return `${storeFile(dir)}.lock`;
119
- }
120
-
121
- /**
122
- * Best-effort advisory lock around the read-modify-write in `mutate()`.
123
- *
124
- * A private store owned by one process did not need this. A *shared* one does:
125
- * the desktop app and a terminal session are two long-lived processes that both
126
- * rewrite this file wholesale, and interleaved read-modify-write would drop
127
- * whichever turn lost the race. The lock is deliberately soft — a crash must
128
- * not wedge every future write, so a lock older than LOCK_STALE_MS is stolen,
129
- * and a writer that cannot get it in LOCK_WAIT_MS proceeds anyway (losing at
130
- * worst the same race that exists today, rather than refusing to save).
131
- *
132
- * @returns {boolean} whether the lock was acquired
133
- */
134
- function acquireLock(dir) {
135
- const file = lockFile(dir);
136
- // The lock is taken *before* the write that used to create the directory, so
137
- // this is now the first thing to touch it — a first run (or a fresh
138
- // AEGISCODE_HOME) would otherwise spin here forever waiting on a lock it can
139
- // never create.
140
- try {
141
- fs.mkdirSync(path.dirname(file), { recursive: true });
142
- } catch {
143
- return false;
144
- }
145
- const deadline = Date.now() + LOCK_WAIT_MS;
146
- // Bounded, so no combination of "lock vanished" / "lock unreadable" can spin
147
- // this loop: a writer that cannot decide always proceeds unlocked instead.
148
- const MAX_ATTEMPTS = 200;
149
- for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
150
- try {
151
- const fd = fs.openSync(file, 'wx');
152
- fs.writeSync(fd, String(process.pid));
153
- fs.closeSync(fd);
154
- return true;
155
- } catch {
156
- let age = null;
157
- try {
158
- age = Date.now() - fs.statSync(file).mtimeMs;
159
- } catch {
160
- // Released between the open and the stat — try immediately.
161
- continue;
162
- }
163
- if (age > LOCK_STALE_MS) {
164
- try {
165
- fs.unlinkSync(file);
166
- } catch {}
167
- continue;
168
- }
169
- if (Date.now() >= deadline) return false;
170
- // Busy-wait: the critical section is a few hundred microseconds of
171
- // stringify + rename, so sleeping the event loop would cost more than it
172
- // saves, and this path is not on the streaming critical path.
173
- const until = Date.now() + 5;
174
- while (Date.now() < until) {
175
- /* spin a few ms */
176
- }
177
- }
178
- }
179
- return false;
180
- }
181
-
182
- function releaseLock(dir) {
183
- try {
184
- fs.unlinkSync(lockFile(dir));
185
- } catch {}
186
- }
187
-
188
- /**
189
- * Read-modify-write the whole store under the lock. Every mutation goes through
190
- * here so the locking is one behaviour, not a thing each caller must remember.
191
- */
192
- function mutate(dir, mutator) {
193
- const locked = acquireLock(dir);
194
- try {
195
- const sessions = load(dir);
196
- const result = mutator(sessions);
197
- save(dir, sessions);
198
- return result;
199
- } finally {
200
- if (locked) releaseLock(dir);
201
- }
202
- }
203
-
204
- function save(dir, sessions) {
205
- atomicWrite(storeFile(dir), sessions);
206
- }
207
-
208
- function trimMessages(messages) {
209
- if (!Array.isArray(messages)) return [];
210
- if (messages.length <= MAX_MESSAGES_PER_SESSION) return messages;
211
- return messages.slice(messages.length - MAX_MESSAGES_PER_SESSION);
212
- }
213
-
214
- /**
215
- * Create or merge a full session record. Any local write (`upsertSession` /
216
- * `appendMessage` / `recordExchange`) marks the session `pending: true` — it has
217
- * local content the cloud hasn't seen yet. Only `markSynced()` clears the flag,
218
- * so a push that fails (offline/no key) never silently drops the session from
219
- * the retry queue.
220
- */
221
- function upsertSession(dir, session) {
222
- const id = session && session.id;
223
- if (!id) throw new Error('session.id is required');
224
- return mutate(dir, (sessions) => {
225
- const prev = sessions[id] || { messages: [] };
226
- sessions[id] = { ...prev, ...session, id, version: STORE_VERSION };
227
- // A real name outranks a seed. The renderer saves `prompt.slice(0, 60)` on
228
- // every turn so a row is never blank, and that write lands AFTER the
229
- // naming ladder has named the session — without this, the name survived
230
- // exactly one turn and the sidebar went back to showing a clipped prompt.
231
- // Only a seeded write is blocked (`named` is set by setTitle); an explicit
232
- // rename goes through setTitle and is unaffected.
233
- if (prev.named === true && typeof prev.title === 'string' && prev.title) {
234
- sessions[id].title = prev.title;
235
- sessions[id].named = true;
236
- }
237
- if (session.pending !== false) sessions[id].pending = true;
238
- if (!sessions[id].updatedAt) sessions[id].updatedAt = Date.now();
239
- sessions[id].seq = nextSeq(sessions);
240
- return sessions[id];
241
- });
242
- }
243
-
244
- /** Append one message to a session (crash-safe). */
245
- function appendMessage(dir, sessionId, message) {
246
- if (!sessionId) throw new Error('sessionId is required');
247
- return mutate(dir, (sessions) => {
248
- const session = sessions[sessionId] || { id: sessionId, messages: [] };
249
- const messages = Array.isArray(session.messages) ? session.messages : [];
250
- session.messages = trimMessages(messages.concat(message));
251
- session.updatedAt = Date.now();
252
- session.pending = true;
253
- session.seq = nextSeq(sessions);
254
- sessions[sessionId] = session;
255
- return session;
256
- });
257
- }
258
-
259
- /**
260
- * Record one finished exchange (the CLI's unit of work) as a session with a
261
- * user/assistant message pair. This is what makes a terminal turn visible to
262
- * the desktop, which lists sessions out of this same file.
263
- *
264
- * `pending` defaults to **false** here, unlike `appendMessage`: the CLI keeps
265
- * its own sync ledger (`cli/src/cloudsync.js` derives pending from
266
- * `sync-state.json`) and pushes through `/sync`. Marking these pending would
267
- * enrol every terminal session in the *desktop's* push queue as a side effect
268
- * of typing in a shell, spending the account's synced-token quota without being
269
- * asked. `origin` records which host wrote the record so either side can filter.
270
- *
271
- * @returns {object|null} the session record, or null on unwritable storage
272
- */
273
- function recordExchange(dir, exchange) {
274
- const e = exchange || {};
275
- if (!e.sessionId) return null;
276
- const id = e.sessionId;
277
- return mutate(dir, (sessions) => {
278
- const session = sessions[id] || { id, messages: [] };
279
- const messages = Array.isArray(session.messages) ? session.messages : [];
280
- const ts = e.ts || new Date().toISOString();
281
- const userMessage = { role: 'user', content: e.prompt == null ? '' : String(e.prompt), ts };
282
- const assistantMessage = { role: 'assistant', content: e.reply == null ? '' : String(e.reply), ts };
283
- if (e.tokens) assistantMessage.tokens = e.tokens;
284
- if (typeof e.costUsd === 'number') assistantMessage.costUsd = e.costUsd;
285
- if (e.status) assistantMessage.status = e.status;
286
- // What answered. The renderer has always put `model` on its own rows
287
- // (desktop/renderer/app.js `ledgerFields`) and this function silently
288
- // dropped it when a turn arrived through the CLI-mirror path — so the same
289
- // conversation carried a model in one host's writes and none in the other's,
290
- // and anything attesting the store (the AI axis reads `MODEL_KEYS`) saw
291
- // nothing. Copied verbatim only when present: absent stays absent.
292
- if (e.model) assistantMessage.model = e.model;
293
- if (e.provider) assistantMessage.provider = e.provider;
294
- if (e.origin) {
295
- userMessage.origin = e.origin;
296
- assistantMessage.origin = e.origin;
297
- }
298
- session.messages = trimMessages(messages.concat([userMessage, assistantMessage]));
299
- session.title = session.title || String(e.prompt || '').slice(0, 60);
300
- if (e.cwd) session.cwd = e.cwd;
301
- session.origin = e.origin || session.origin || 'unknown';
302
- session.updatedAt = Date.now();
303
- // Explicit, not merely "leave it unset": `listPending` treats an absent flag
304
- // as pending (sessions predating the field default to queued), so an
305
- // undefined here would quietly enrol every terminal session in the desktop's
306
- // push queue — the exact thing the `pending: false` default is for.
307
- session.pending = e.pending === true ? true : false;
308
- session.seq = nextSeq(sessions);
309
- sessions[id] = session;
310
- return session;
311
- });
312
- }
313
-
314
- /**
315
- * Stamp a conversation's name.
316
- *
317
- * The name is what the session LIST shows (the desktop app, the MCP plugin and
318
- * `/resume` all read it from here or from their own mirror), and it is NOT the
319
- * raw first message: `recordExchange` seeds `title` with the prompt so a
320
- * session has something to show before anything has named it, and this replaces
321
- * that seed with the real name once one exists (the CLI's `naming.js`).
322
- *
323
- * An empty name is refused rather than written: a namer that failed must not
324
- * blank a name that is already there.
325
- */
326
- function setTitle(dir, sessionId, title, opts) {
327
- const clean = String(title == null ? '' : title).trim().slice(0, 200);
328
- if (!sessionId || !clean) return null;
329
- // `named: true` records that this title came from the naming ladder rather
330
- // than from the raw-prompt SEED `recordExchange`/`upsertSession` writes.
331
- // That distinction is what stops a later turn from renaming a conversation
332
- // away from its topic: the seed is disposable, a name is not. The CLI keys
333
- // off `isGenericTitle`, but the desktop seeds with a slice of the prompt,
334
- // which is not generic and not a name either — so the fact has to be
335
- // recorded when it happens instead of guessed later.
336
- const named = opts && opts.named === true;
337
- return mutate(dir, (sessions) => {
338
- const session = sessions[sessionId];
339
- if (!session) return null;
340
- session.title = clean;
341
- if (named) session.named = true;
342
- session.updatedAt = Date.now();
343
- session.seq = nextSeq(sessions);
344
- return session;
345
- });
346
- }
347
-
348
- function listSessions(dir) {
349
- const sessions = load(dir);
350
- return Object.values(sessions)
351
- .filter((s) => s && s.id)
352
- .sort(
353
- (a, b) =>
354
- (b.updatedAt || 0) - (a.updatedAt || 0) ||
355
- (b.seq || 0) - (a.seq || 0)
356
- );
357
- }
358
-
359
- function getSession(dir, id) {
360
- return load(dir)[id] || null;
361
- }
362
-
363
- function deleteSession(dir, id) {
364
- return mutate(dir, (sessions) => {
365
- delete sessions[id];
366
- return { ok: true };
367
- });
368
- }
369
-
370
- /** Clear the pending flag after a successful cloud push. `remote.remoteId`,
371
- * when the server assigns its own conversation id, is stashed alongside. */
372
- function markSynced(dir, id, remote) {
373
- return mutate(dir, (sessions) => {
374
- const session = sessions[id];
375
- if (!session) return null;
376
- session.pending = false;
377
- session.lastSyncedAt = Date.now();
378
- if (remote && remote.remoteId) session.remoteId = remote.remoteId;
379
- session.seq = nextSeq(sessions);
380
- return session;
381
- });
382
- }
383
-
384
- /** Force a session back into the retry queue (e.g. a push that partially failed). */
385
- function markPending(dir, id) {
386
- return mutate(dir, (sessions) => {
387
- const session = sessions[id];
388
- if (!session) return null;
389
- session.pending = true;
390
- session.seq = nextSeq(sessions);
391
- return session;
392
- });
393
- }
394
-
395
- /** Sessions with local content the cloud hasn't confirmed yet (including
396
- * sessions predating this field, which default to pending). */
397
- function listPending(dir) {
398
- return listSessions(dir).filter((s) => s.pending !== false);
399
- }
400
-
401
- /**
402
- * Merge remote conversation-sync records into the local store (pull half of
403
- * sync). Last-write-wins by `updatedAt`, but a local session with unsynced
404
- * edits (`pending`) always wins over the remote copy — it will overwrite the
405
- * remote copy on the next push instead.
406
- */
407
- function mergeRemoteSessions(dir, remoteSessions) {
408
- const list = Array.isArray(remoteSessions) ? remoteSessions : [];
409
- if (!list.length) return 0;
410
- return mutate(dir, (sessions) => {
411
- let merged = 0;
412
- for (const remote of list) {
413
- const id = remote && (remote.session_id || remote.id);
414
- if (!id) continue;
415
- const local = sessions[id];
416
- const remoteUpdatedAt = toEpochMs(remote.updated_at ?? remote.updatedAt);
417
- if (local && (local.pending || (local.updatedAt || 0) >= remoteUpdatedAt)) {
418
- continue;
419
- }
420
- sessions[id] = {
421
- id,
422
- title: remote.title || (local && local.title) || '',
423
- messages: Array.isArray(remote.messages) ? remote.messages : [],
424
- updatedAt: remoteUpdatedAt || Date.now(),
425
- pending: false,
426
- lastSyncedAt: Date.now(),
427
- remoteId: remote.session_id || remote.id,
428
- origin: remote.source || (local && local.origin) || 'cloud',
429
- version: STORE_VERSION,
430
- };
431
- sessions[id].seq = nextSeq(sessions);
432
- merged += 1;
433
- }
434
- return merged;
435
- });
436
- }
437
-
438
- /**
439
- * Compact listing for a picker (`/resume`, the desktop's session list). Same
440
- * field names `history.js`'s readOwnSessions produced, so the two can be
441
- * concatenated without either side having to know which store a row came from.
442
- */
443
- function listSummaries(dir, limit = 8) {
444
- return listSessions(dir)
445
- .slice(0, limit)
446
- .map((s) => {
447
- const messages = Array.isArray(s.messages) ? s.messages : [];
448
- const first = messages.find((m) => m && m.role === 'user');
449
- // A named session lists by its name. `title` is seeded from the prompt at
450
- // record time, so for an unnamed session this is the same string the
451
- // first message would have produced — no visible change — while a real
452
- // name (setTitle) wins over the raw prompt, which is the whole point of
453
- // naming a conversation.
454
- return {
455
- id: s.id,
456
- cwd: (s.cwd || '').split(/[\\/]/).filter(Boolean).pop() || '~',
457
- summary: String(s.title || (first && first.content) || '').slice(0, 60),
458
- time: new Date(s.updatedAt || Date.now()).toISOString(),
459
- own: true,
460
- origin: s.origin || 'unknown',
461
- messages: messages.length,
462
- pending: s.pending === true,
463
- dir: String(s.cwd || ''),
464
- };
465
- });
466
- }
467
-
468
- /** Rebuild a transcript (user/assistant pairs) for a session, oldest first. */
469
- function readTranscript(dir, sessionId) {
470
- const session = getSession(dir, sessionId);
471
- if (!session) return [];
472
- return (Array.isArray(session.messages) ? session.messages : [])
473
- .filter((m) => m && (m.role === 'user' || m.role === 'assistant'))
474
- .map((m) => ({ role: m.role, text: m.content == null ? '' : String(m.content) }));
475
- }
476
-
477
- /**
478
- * Import a legacy store from another directory, ONE way and one time.
479
- *
480
- * The desktop wrote `<userData>/sessions.json` before this store existed. On an
481
- * upgrade that file is the user's entire GUI history, so the shared store
482
- * adopts it — but only when the shared store has nothing to lose (missing, or
483
- * empty), and only by copying: the legacy file is left where it is, so a user
484
- * who downgrades still finds their sessions.
485
- *
486
- * @returns {{adopted:boolean, sessions:number, from:string, reason?:string}}
487
- */
488
- function adopt(dir, fromDir) {
489
- const from = storeFile(fromDir);
490
- const exists = (() => {
491
- try {
492
- return fs.existsSync(from);
493
- } catch {
494
- return false;
495
- }
496
- })();
497
- if (!exists) return { adopted: false, sessions: 0, from, reason: 'no legacy store' };
498
- const legacy = (() => {
499
- try {
500
- const parsed = JSON.parse(fs.readFileSync(from, 'utf8'));
501
- return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
502
- } catch {
503
- return {};
504
- }
505
- })();
506
- const incoming = Object.values(legacy).filter((s) => s && s.id);
507
- if (!incoming.length) return { adopted: false, sessions: 0, from, reason: 'legacy store empty' };
508
- if (listSessions(dir).length) {
509
- return { adopted: false, sessions: 0, from, reason: 'store already has sessions' };
510
- }
511
- mutate(dir, (sessions) => {
512
- for (const s of incoming) {
513
- // Adopted sessions keep their own history; they are already local content.
514
- sessions[s.id] = { ...s, adoptedFrom: from, version: STORE_VERSION };
515
- sessions[s.id].seq = nextSeq(sessions);
516
- }
517
- sessions.__seq = Math.max(sessions.__seq || 0, legacy.__seq || 0);
518
- sessions.version = STORE_VERSION;
519
- return null;
520
- });
521
- return { adopted: true, sessions: incoming.length, from };
522
- }
523
-
524
- /**
525
- * Markdown export (session export, plan: Save as.../Export session). Each
526
- * message becomes a `## Role` heading followed by its content verbatim —
527
- * content is never re-escaped or re-wrapped, so any code fences a message
528
- * already contains (assistant replies routinely have them) survive untouched
529
- * instead of being nested inside an outer fence.
530
- */
531
- function toMarkdown(session) {
532
- const title = (session && (session.title || session.id)) || 'session';
533
- const messages = (session && Array.isArray(session.messages)) ? session.messages : [];
534
- const lines = [`# ${title}`, ''];
535
- for (const message of messages) {
536
- const role = (message && message.role) || 'unknown';
537
- const heading = role.charAt(0).toUpperCase() + role.slice(1);
538
- const content = (message && (message.content || message.text)) || '';
539
- lines.push(`## ${heading}`, '', content, '');
540
- }
541
- return lines.join('\n');
542
- }
543
-
544
- /** JSON export: the session record as stored, pretty-printed. */
545
- function toJson(session) {
546
- return JSON.stringify(session, null, 2);
547
- }
548
-
549
- module.exports = {
550
- STORE_FILE,
551
- STORE_VERSION,
552
- MAX_MESSAGES_PER_SESSION,
553
- storeDir,
554
- storeFile,
555
- lockFile,
556
- LOCK_STALE_MS,
557
- LOCK_WAIT_MS,
558
- toEpochMs,
559
- load,
560
- save,
561
- upsertSession,
562
- appendMessage,
563
- recordExchange,
564
- setTitle,
565
- listSessions,
566
- getSession,
567
- deleteSession,
568
- markSynced,
569
- markPending,
570
- listPending,
571
- mergeRemoteSessions,
572
- listSummaries,
573
- readTranscript,
574
- adopt,
575
- toMarkdown,
576
- toJson,
577
- };
3
+ const e=require("node:fs"),n=require("node:path"),{aegisHome:t}=require("./credentials.js"),r="sessions.json",s=2e3;function o(e){return e||t()}function i(e){return n.join(o(e),r)}function c(e){const n=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=n,n}function a(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const n=Date.parse(e);if(Number.isFinite(n))return n}return 0}function u(n){try{const t=JSON.parse(e.readFileSync(i(n),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function d(e){return`${i(e)}.lock`}function l(t,r){const s=function(t){const r=d(t);try{e.mkdirSync(n.dirname(r),{recursive:!0})}catch{return!1}const s=Date.now()+500;for(let n=0;n<200;n++)try{const n=e.openSync(r,"wx");return e.writeSync(n,String(process.pid)),e.closeSync(n),!0}catch{let n=null;try{n=Date.now()-e.statSync(r).mtimeMs}catch{continue}if(n>2e3){try{e.unlinkSync(r)}catch{}continue}if(Date.now()>=s)return!1;const t=Date.now()+5;for(;Date.now()<t;);}return!1}(t);try{const e=u(t),n=r(e);return g(t,e),n}finally{s&&function(n){try{e.unlinkSync(d(n))}catch{}}(t)}}function g(t,r){!function(t,r){e.mkdirSync(n.dirname(t),{recursive:!0});const s=`${t}.tmp-${process.pid}`;e.writeFileSync(s,JSON.stringify(r,null,2),{mode:384}),e.renameSync(s,t);try{e.chmodSync(t,384)}catch{}}(i(t),r)}function p(e){return Array.isArray(e)?e.length<=s?e:e.slice(e.length-s):[]}function f(e){const n=u(e);return Object.values(n).filter((e=>e&&e.id)).sort(((e,n)=>(n.updatedAt||0)-(e.updatedAt||0)||(n.seq||0)-(e.seq||0)))}function m(e,n){return u(e)[n]||null}module.exports={STORE_FILE:r,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:s,storeDir:o,storeFile:i,lockFile:d,LOCK_STALE_MS:2e3,LOCK_WAIT_MS:500,toEpochMs:a,load:u,save:g,upsertSession:function(e,n){const t=n&&n.id;if(!t)throw new Error("session.id is required");return l(e,(e=>{const r=e[t]||{messages:[]};return e[t]={...r,...n,id:t,version:2},!0===r.named&&"string"==typeof r.title&&r.title&&(e[t].title=r.title,e[t].named=!0),!1!==n.pending&&(e[t].pending=!0),e[t].updatedAt||(e[t].updatedAt=Date.now()),e[t].seq=c(e),e[t]}))},appendMessage:function(e,n,t){if(!n)throw new Error("sessionId is required");return l(e,(e=>{const r=e[n]||{id:n,messages:[]},s=Array.isArray(r.messages)?r.messages:[];return r.messages=p(s.concat(t)),r.updatedAt=Date.now(),r.pending=!0,r.seq=c(e),e[n]=r,r}))},recordExchange:function(e,n){const t=n||{};if(!t.sessionId)return null;const r=t.sessionId;return l(e,(e=>{const n=e[r]||{id:r,messages:[]},s=Array.isArray(n.messages)?n.messages:[],o=t.ts||(new Date).toISOString(),i={role:"user",content:null==t.prompt?"":String(t.prompt),ts:o},a={role:"assistant",content:null==t.reply?"":String(t.reply),ts:o};return t.tokens&&(a.tokens=t.tokens),"number"==typeof t.costUsd&&(a.costUsd=t.costUsd),t.status&&(a.status=t.status),t.model&&(a.model=t.model),t.provider&&(a.provider=t.provider),t.origin&&(i.origin=t.origin,a.origin=t.origin),n.messages=p(s.concat([i,a])),n.title=n.title||String(t.prompt||"").slice(0,60),t.cwd&&(n.cwd=t.cwd),n.origin=t.origin||n.origin||"unknown",n.updatedAt=Date.now(),n.pending=!0===t.pending,n.seq=c(e),e[r]=n,n}))},setTitle:function(e,n,t,r){const s=String(null==t?"":t).trim().slice(0,200);if(!n||!s)return null;const o=r&&!0===r.named;return l(e,(e=>{const t=e[n];return t?(t.title=s,o&&(t.named=!0),t.updatedAt=Date.now(),t.seq=c(e),t):null}))},listSessions:f,getSession:m,deleteSession:function(e,n){return l(e,(e=>(delete e[n],{ok:!0})))},markSynced:function(e,n,t){return l(e,(e=>{const r=e[n];return r?(r.pending=!1,r.lastSyncedAt=Date.now(),t&&t.remoteId&&(r.remoteId=t.remoteId),r.seq=c(e),r):null}))},markPending:function(e,n){return l(e,(e=>{const t=e[n];return t?(t.pending=!0,t.seq=c(e),t):null}))},listPending:function(e){return f(e).filter((e=>!1!==e.pending))},mergeRemoteSessions:function(e,n){const t=Array.isArray(n)?n:[];return t.length?l(e,(e=>{let n=0;for(const r of t){const t=r&&(r.session_id||r.id);if(!t)continue;const s=e[t],o=a(r.updated_at??r.updatedAt);s&&(s.pending||(s.updatedAt||0)>=o)||(e[t]={id:t,title:r.title||s&&s.title||"",messages:Array.isArray(r.messages)?r.messages:[],updatedAt:o||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:r.session_id||r.id,origin:r.source||s&&s.origin||"cloud",version:2},e[t].seq=c(e),n+=1)}return n})):0},listSummaries:function(e,n=8){return f(e).slice(0,n).map((e=>{const n=Array.isArray(e.messages)?e.messages:[],t=n.find((e=>e&&"user"===e.role));return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||t&&t.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:n.length,pending:!0===e.pending,dir:String(e.cwd||"")}}))},readTranscript:function(e,n){const t=m(e,n);return t?(Array.isArray(t.messages)?t.messages:[]).filter((e=>e&&("user"===e.role||"assistant"===e.role))).map((e=>({role:e.role,text:null==e.content?"":String(e.content)}))):[]},adopt:function(n,t){const r=i(t);if(!(()=>{try{return e.existsSync(r)}catch{return!1}})())return{adopted:!1,sessions:0,from:r,reason:"no legacy store"};const s=(()=>{try{const n=JSON.parse(e.readFileSync(r,"utf8"));return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}catch{return{}}})(),o=Object.values(s).filter((e=>e&&e.id));return o.length?f(n).length?{adopted:!1,sessions:0,from:r,reason:"store already has sessions"}:(l(n,(e=>{for(const n of o)e[n.id]={...n,adoptedFrom:r,version:2},e[n.id].seq=c(e);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null})),{adopted:!0,sessions:o.length,from:r}):{adopted:!1,sessions:0,from:r,reason:"legacy store empty"}},toMarkdown:function(e){const n=e&&(e.title||e.id)||"session",t=e&&Array.isArray(e.messages)?e.messages:[],r=[`# ${n}`,""];for(const e of t){const n=e&&e.role||"unknown",t=n.charAt(0).toUpperCase()+n.slice(1),s=e&&(e.content||e.text)||"";r.push(`## ${t}`,"",s,"")}return r.join("\n")},toJson:function(e){return JSON.stringify(e,null,2)}};