aegiscode 7.0.14 → 7.0.15

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 (109) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +3 -2
  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 -2932
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3020
  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 -4003
  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/fingerprint.js +1 -592
  28. package/src/format.js +1 -259
  29. package/src/fuzzy.js +1 -119
  30. package/src/history.js +1 -401
  31. package/src/init.js +1 -175
  32. package/src/input.js +1 -139
  33. package/src/keys.js +1 -183
  34. package/src/markdown.js +1 -306
  35. package/src/models.js +1 -487
  36. package/src/naming.js +1 -229
  37. package/src/overlays.js +1 -461
  38. package/src/panels.js +1 -1418
  39. package/src/ping.js +1 -226
  40. package/src/presence.js +1 -238
  41. package/src/render.js +1 -515
  42. package/src/screen.js +1 -518
  43. package/src/screens.js +1 -896
  44. package/src/secret.js +1 -59
  45. package/src/securefs.js +1 -359
  46. package/src/settings.js +1 -155
  47. package/src/shared.js +1 -52
  48. package/src/sharedpaths.js +1 -53
  49. package/src/signup.js +1 -156
  50. package/src/summarize.js +1 -95
  51. package/src/sysdiag.js +1 -585
  52. package/src/system.js +1 -40
  53. package/src/theme.js +1 -570
  54. package/src/title.js +1 -220
  55. package/src/todos.js +1 -115
  56. package/src/tokens.js +1 -263
  57. package/src/topup.js +1 -210
  58. package/src/update.js +1 -181
  59. package/vendor/client/aegis.js +1 -2179
  60. package/vendor/client/attest.js +1 -442
  61. package/vendor/client/authorship-key.js +1 -410
  62. package/vendor/client/auto-provision.js +1 -134
  63. package/vendor/client/brain-catalog.js +1 -268
  64. package/vendor/client/byok-catalog.js +1 -230
  65. package/vendor/client/credentials.js +1 -494
  66. package/vendor/client/device-fingerprint.js +1 -141
  67. package/vendor/client/drive-connect.js +1 -110
  68. package/vendor/client/drive-upload.js +1 -174
  69. package/vendor/client/env-file.js +1 -1273
  70. package/vendor/client/fingerprint.js +1 -1064
  71. package/vendor/client/foreign-memory.js +1 -669
  72. package/vendor/client/google-signin.js +1 -133
  73. package/vendor/client/hooks.js +1 -430
  74. package/vendor/client/model-discovery.js +1 -373
  75. package/vendor/client/platform.js +1 -937
  76. package/vendor/client/prefs.js +1 -351
  77. package/vendor/client/presence-constants.js +1 -107
  78. package/vendor/client/presence.js +1 -438
  79. package/vendor/client/record-vault.js +3 -1055
  80. package/vendor/client/session-store.js +1 -548
  81. package/vendor/client/topup.js +1 -297
  82. package/vendor/client/touch.js +1 -458
  83. package/vendor/client/update.js +1 -704
  84. package/vendor/client/user-models.js +1 -381
  85. package/vendor/desktop/lib/local/agents.js +1 -105
  86. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  87. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  88. package/vendor/desktop/lib/local/context.js +1 -95
  89. package/vendor/desktop/lib/local/engine.js +1 -3301
  90. package/vendor/desktop/lib/local/entitlement.js +1 -660
  91. package/vendor/desktop/lib/local/git-scope.js +1 -228
  92. package/vendor/desktop/lib/local/local.js +1 -2135
  93. package/vendor/desktop/lib/local/prompt.js +1 -275
  94. package/vendor/desktop/lib/local/queue.js +1 -560
  95. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  96. package/vendor/desktop/lib/local/shell.js +1 -680
  97. package/vendor/desktop/lib/local/tools.js +1 -1238
  98. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  99. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  100. package/vendor/desktop/lib/settings.js +1 -890
  101. package/vendor/desktop/renderer/usage.js +1 -1239
  102. package/vendor/hosts/install.js +1 -638
  103. package/vendor/hosts/openai-shim.js +1 -515
  104. package/vendor/hosts/spec.js +1 -164
  105. package/vendor/hosts/targets.js +1 -346
  106. package/vendor/mcp/server.js +1 -221
  107. package/vendor/mcp/tools.js +1 -408
  108. package/vendor/one/src/child.js +1 -285
  109. package/vendor/one/src/permissions.js +1 -369
@@ -1,550 +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
- if (session.pending !== false) sessions[id].pending = true;
228
- if (!sessions[id].updatedAt) sessions[id].updatedAt = Date.now();
229
- sessions[id].seq = nextSeq(sessions);
230
- return sessions[id];
231
- });
232
- }
233
-
234
- /** Append one message to a session (crash-safe). */
235
- function appendMessage(dir, sessionId, message) {
236
- if (!sessionId) throw new Error('sessionId is required');
237
- return mutate(dir, (sessions) => {
238
- const session = sessions[sessionId] || { id: sessionId, messages: [] };
239
- const messages = Array.isArray(session.messages) ? session.messages : [];
240
- session.messages = trimMessages(messages.concat(message));
241
- session.updatedAt = Date.now();
242
- session.pending = true;
243
- session.seq = nextSeq(sessions);
244
- sessions[sessionId] = session;
245
- return session;
246
- });
247
- }
248
-
249
- /**
250
- * Record one finished exchange (the CLI's unit of work) as a session with a
251
- * user/assistant message pair. This is what makes a terminal turn visible to
252
- * the desktop, which lists sessions out of this same file.
253
- *
254
- * `pending` defaults to **false** here, unlike `appendMessage`: the CLI keeps
255
- * its own sync ledger (`cli/src/cloudsync.js` derives pending from
256
- * `sync-state.json`) and pushes through `/sync`. Marking these pending would
257
- * enrol every terminal session in the *desktop's* push queue as a side effect
258
- * of typing in a shell, spending the account's synced-token quota without being
259
- * asked. `origin` records which host wrote the record so either side can filter.
260
- *
261
- * @returns {object|null} the session record, or null on unwritable storage
262
- */
263
- function recordExchange(dir, exchange) {
264
- const e = exchange || {};
265
- if (!e.sessionId) return null;
266
- const id = e.sessionId;
267
- return mutate(dir, (sessions) => {
268
- const session = sessions[id] || { id, messages: [] };
269
- const messages = Array.isArray(session.messages) ? session.messages : [];
270
- const ts = e.ts || new Date().toISOString();
271
- const userMessage = { role: 'user', content: e.prompt == null ? '' : String(e.prompt), ts };
272
- const assistantMessage = { role: 'assistant', content: e.reply == null ? '' : String(e.reply), ts };
273
- if (e.tokens) assistantMessage.tokens = e.tokens;
274
- if (typeof e.costUsd === 'number') assistantMessage.costUsd = e.costUsd;
275
- if (e.status) assistantMessage.status = e.status;
276
- if (e.origin) {
277
- userMessage.origin = e.origin;
278
- assistantMessage.origin = e.origin;
279
- }
280
- session.messages = trimMessages(messages.concat([userMessage, assistantMessage]));
281
- session.title = session.title || String(e.prompt || '').slice(0, 60);
282
- if (e.cwd) session.cwd = e.cwd;
283
- session.origin = e.origin || session.origin || 'unknown';
284
- session.updatedAt = Date.now();
285
- // Explicit, not merely "leave it unset": `listPending` treats an absent flag
286
- // as pending (sessions predating the field default to queued), so an
287
- // undefined here would quietly enrol every terminal session in the desktop's
288
- // push queue — the exact thing the `pending: false` default is for.
289
- session.pending = e.pending === true ? true : false;
290
- session.seq = nextSeq(sessions);
291
- sessions[id] = session;
292
- return session;
293
- });
294
- }
295
-
296
- /**
297
- * Stamp a conversation's name.
298
- *
299
- * The name is what the session LIST shows (the desktop app, the MCP plugin and
300
- * `/resume` all read it from here or from their own mirror), and it is NOT the
301
- * raw first message: `recordExchange` seeds `title` with the prompt so a
302
- * session has something to show before anything has named it, and this replaces
303
- * that seed with the real name once one exists (the CLI's `naming.js`).
304
- *
305
- * An empty name is refused rather than written: a namer that failed must not
306
- * blank a name that is already there.
307
- */
308
- function setTitle(dir, sessionId, title) {
309
- const clean = String(title == null ? '' : title).trim().slice(0, 200);
310
- if (!sessionId || !clean) return null;
311
- return mutate(dir, (sessions) => {
312
- const session = sessions[sessionId];
313
- if (!session) return null;
314
- session.title = clean;
315
- session.updatedAt = Date.now();
316
- session.seq = nextSeq(sessions);
317
- return session;
318
- });
319
- }
320
-
321
- function listSessions(dir) {
322
- const sessions = load(dir);
323
- return Object.values(sessions)
324
- .filter((s) => s && s.id)
325
- .sort(
326
- (a, b) =>
327
- (b.updatedAt || 0) - (a.updatedAt || 0) ||
328
- (b.seq || 0) - (a.seq || 0)
329
- );
330
- }
331
-
332
- function getSession(dir, id) {
333
- return load(dir)[id] || null;
334
- }
335
-
336
- function deleteSession(dir, id) {
337
- return mutate(dir, (sessions) => {
338
- delete sessions[id];
339
- return { ok: true };
340
- });
341
- }
342
-
343
- /** Clear the pending flag after a successful cloud push. `remote.remoteId`,
344
- * when the server assigns its own conversation id, is stashed alongside. */
345
- function markSynced(dir, id, remote) {
346
- return mutate(dir, (sessions) => {
347
- const session = sessions[id];
348
- if (!session) return null;
349
- session.pending = false;
350
- session.lastSyncedAt = Date.now();
351
- if (remote && remote.remoteId) session.remoteId = remote.remoteId;
352
- session.seq = nextSeq(sessions);
353
- return session;
354
- });
355
- }
356
-
357
- /** Force a session back into the retry queue (e.g. a push that partially failed). */
358
- function markPending(dir, id) {
359
- return mutate(dir, (sessions) => {
360
- const session = sessions[id];
361
- if (!session) return null;
362
- session.pending = true;
363
- session.seq = nextSeq(sessions);
364
- return session;
365
- });
366
- }
367
-
368
- /** Sessions with local content the cloud hasn't confirmed yet (including
369
- * sessions predating this field, which default to pending). */
370
- function listPending(dir) {
371
- return listSessions(dir).filter((s) => s.pending !== false);
372
- }
373
-
374
- /**
375
- * Merge remote conversation-sync records into the local store (pull half of
376
- * sync). Last-write-wins by `updatedAt`, but a local session with unsynced
377
- * edits (`pending`) always wins over the remote copy — it will overwrite the
378
- * remote copy on the next push instead.
379
- */
380
- function mergeRemoteSessions(dir, remoteSessions) {
381
- const list = Array.isArray(remoteSessions) ? remoteSessions : [];
382
- if (!list.length) return 0;
383
- return mutate(dir, (sessions) => {
384
- let merged = 0;
385
- for (const remote of list) {
386
- const id = remote && (remote.session_id || remote.id);
387
- if (!id) continue;
388
- const local = sessions[id];
389
- const remoteUpdatedAt = toEpochMs(remote.updated_at ?? remote.updatedAt);
390
- if (local && (local.pending || (local.updatedAt || 0) >= remoteUpdatedAt)) {
391
- continue;
392
- }
393
- sessions[id] = {
394
- id,
395
- title: remote.title || (local && local.title) || '',
396
- messages: Array.isArray(remote.messages) ? remote.messages : [],
397
- updatedAt: remoteUpdatedAt || Date.now(),
398
- pending: false,
399
- lastSyncedAt: Date.now(),
400
- remoteId: remote.session_id || remote.id,
401
- origin: remote.source || (local && local.origin) || 'cloud',
402
- version: STORE_VERSION,
403
- };
404
- sessions[id].seq = nextSeq(sessions);
405
- merged += 1;
406
- }
407
- return merged;
408
- });
409
- }
410
-
411
- /**
412
- * Compact listing for a picker (`/resume`, the desktop's session list). Same
413
- * field names `history.js`'s readOwnSessions produced, so the two can be
414
- * concatenated without either side having to know which store a row came from.
415
- */
416
- function listSummaries(dir, limit = 8) {
417
- return listSessions(dir)
418
- .slice(0, limit)
419
- .map((s) => {
420
- const messages = Array.isArray(s.messages) ? s.messages : [];
421
- const first = messages.find((m) => m && m.role === 'user');
422
- // A named session lists by its name. `title` is seeded from the prompt at
423
- // record time, so for an unnamed session this is the same string the
424
- // first message would have produced — no visible change — while a real
425
- // name (setTitle) wins over the raw prompt, which is the whole point of
426
- // naming a conversation.
427
- return {
428
- id: s.id,
429
- cwd: (s.cwd || '').split(/[\\/]/).filter(Boolean).pop() || '~',
430
- summary: String(s.title || (first && first.content) || '').slice(0, 60),
431
- time: new Date(s.updatedAt || Date.now()).toISOString(),
432
- own: true,
433
- origin: s.origin || 'unknown',
434
- messages: messages.length,
435
- pending: s.pending === true,
436
- dir: String(s.cwd || ''),
437
- };
438
- });
439
- }
440
-
441
- /** Rebuild a transcript (user/assistant pairs) for a session, oldest first. */
442
- function readTranscript(dir, sessionId) {
443
- const session = getSession(dir, sessionId);
444
- if (!session) return [];
445
- return (Array.isArray(session.messages) ? session.messages : [])
446
- .filter((m) => m && (m.role === 'user' || m.role === 'assistant'))
447
- .map((m) => ({ role: m.role, text: m.content == null ? '' : String(m.content) }));
448
- }
449
-
450
- /**
451
- * Import a legacy store from another directory, ONE way and one time.
452
- *
453
- * The desktop wrote `<userData>/sessions.json` before this store existed. On an
454
- * upgrade that file is the user's entire GUI history, so the shared store
455
- * adopts it — but only when the shared store has nothing to lose (missing, or
456
- * empty), and only by copying: the legacy file is left where it is, so a user
457
- * who downgrades still finds their sessions.
458
- *
459
- * @returns {{adopted:boolean, sessions:number, from:string, reason?:string}}
460
- */
461
- function adopt(dir, fromDir) {
462
- const from = storeFile(fromDir);
463
- const exists = (() => {
464
- try {
465
- return fs.existsSync(from);
466
- } catch {
467
- return false;
468
- }
469
- })();
470
- if (!exists) return { adopted: false, sessions: 0, from, reason: 'no legacy store' };
471
- const legacy = (() => {
472
- try {
473
- const parsed = JSON.parse(fs.readFileSync(from, 'utf8'));
474
- return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
475
- } catch {
476
- return {};
477
- }
478
- })();
479
- const incoming = Object.values(legacy).filter((s) => s && s.id);
480
- if (!incoming.length) return { adopted: false, sessions: 0, from, reason: 'legacy store empty' };
481
- if (listSessions(dir).length) {
482
- return { adopted: false, sessions: 0, from, reason: 'store already has sessions' };
483
- }
484
- mutate(dir, (sessions) => {
485
- for (const s of incoming) {
486
- // Adopted sessions keep their own history; they are already local content.
487
- sessions[s.id] = { ...s, adoptedFrom: from, version: STORE_VERSION };
488
- sessions[s.id].seq = nextSeq(sessions);
489
- }
490
- sessions.__seq = Math.max(sessions.__seq || 0, legacy.__seq || 0);
491
- sessions.version = STORE_VERSION;
492
- return null;
493
- });
494
- return { adopted: true, sessions: incoming.length, from };
495
- }
496
-
497
- /**
498
- * Markdown export (session export, plan: Save as.../Export session). Each
499
- * message becomes a `## Role` heading followed by its content verbatim —
500
- * content is never re-escaped or re-wrapped, so any code fences a message
501
- * already contains (assistant replies routinely have them) survive untouched
502
- * instead of being nested inside an outer fence.
503
- */
504
- function toMarkdown(session) {
505
- const title = (session && (session.title || session.id)) || 'session';
506
- const messages = (session && Array.isArray(session.messages)) ? session.messages : [];
507
- const lines = [`# ${title}`, ''];
508
- for (const message of messages) {
509
- const role = (message && message.role) || 'unknown';
510
- const heading = role.charAt(0).toUpperCase() + role.slice(1);
511
- const content = (message && (message.content || message.text)) || '';
512
- lines.push(`## ${heading}`, '', content, '');
513
- }
514
- return lines.join('\n');
515
- }
516
-
517
- /** JSON export: the session record as stored, pretty-printed. */
518
- function toJson(session) {
519
- return JSON.stringify(session, null, 2);
520
- }
521
-
522
- module.exports = {
523
- STORE_FILE,
524
- STORE_VERSION,
525
- MAX_MESSAGES_PER_SESSION,
526
- storeDir,
527
- storeFile,
528
- lockFile,
529
- LOCK_STALE_MS,
530
- LOCK_WAIT_MS,
531
- toEpochMs,
532
- load,
533
- save,
534
- upsertSession,
535
- appendMessage,
536
- recordExchange,
537
- setTitle,
538
- listSessions,
539
- getSession,
540
- deleteSession,
541
- markSynced,
542
- markPending,
543
- listPending,
544
- mergeRemoteSessions,
545
- listSummaries,
546
- readTranscript,
547
- adopt,
548
- toMarkdown,
549
- toJson,
550
- };
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 u(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 a(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=a(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 f(e){return Array.isArray(e)?e.length<=s?e:e.slice(e.length-s):[]}function p(e){const n=a(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 a(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:u,load:a,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},!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=f(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},u={role:"assistant",content:null==t.reply?"":String(t.reply),ts:o};return t.tokens&&(u.tokens=t.tokens),"number"==typeof t.costUsd&&(u.costUsd=t.costUsd),t.status&&(u.status=t.status),t.origin&&(i.origin=t.origin,u.origin=t.origin),n.messages=f(s.concat([i,u])),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){const r=String(null==t?"":t).trim().slice(0,200);return n&&r?l(e,(e=>{const t=e[n];return t?(t.title=r,t.updatedAt=Date.now(),t.seq=c(e),t):null})):null},listSessions:p,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 p(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=u(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 p(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?p(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)}};