aegisone 1.0.34 → 1.0.35

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 (226) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +1 -1
  3. package/SOURCE-OFFER.txt +9 -0
  4. package/bin/aegis.js +1 -322
  5. package/package.json +4 -5
  6. package/scripts/bump.mjs +1 -211
  7. package/scripts/bundle.js +1 -129
  8. package/scripts/predist.mjs +1 -976
  9. package/src/child.js +1 -285
  10. package/src/dispatch.js +1 -269
  11. package/src/doctor.js +1 -639
  12. package/src/host.js +1 -111
  13. package/src/permissions.js +1 -383
  14. package/src/probes.js +1 -159
  15. package/src/release.js +1 -409
  16. package/vendor/cli/package.json +3 -7
  17. package/vendor/cli/scripts/check.mjs +1 -52
  18. package/vendor/cli/scripts/demo.mjs +1 -94
  19. package/vendor/cli/scripts/predist.mjs +1 -75
  20. package/vendor/cli/scripts/runtests.mjs +1 -56
  21. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  22. package/vendor/cli/src/agents.js +1 -139
  23. package/vendor/cli/src/app.js +1 -2957
  24. package/vendor/cli/src/art.js +1 -289
  25. package/vendor/cli/src/chatflow.js +1 -3023
  26. package/vendor/cli/src/checkpoint.js +1 -90
  27. package/vendor/cli/src/clipboard.js +1 -424
  28. package/vendor/cli/src/cloudsync.js +1 -528
  29. package/vendor/cli/src/commands.js +1 -4089
  30. package/vendor/cli/src/config.js +1 -581
  31. package/vendor/cli/src/connect.js +1 -349
  32. package/vendor/cli/src/credentials.js +1 -33
  33. package/vendor/cli/src/deps.js +1 -232
  34. package/vendor/cli/src/devrun.js +1 -187
  35. package/vendor/cli/src/diff.js +1 -333
  36. package/vendor/cli/src/diffview.js +1 -296
  37. package/vendor/cli/src/engine.js +1 -297
  38. package/vendor/cli/src/entitlement.js +1 -355
  39. package/vendor/cli/src/events.js +1 -707
  40. package/vendor/cli/src/export.js +1 -67
  41. package/vendor/cli/src/filepreview.js +1 -153
  42. package/vendor/cli/src/fingerprint.js +1 -592
  43. package/vendor/cli/src/format.js +1 -259
  44. package/vendor/cli/src/fuzzy.js +1 -119
  45. package/vendor/cli/src/history.js +1 -423
  46. package/vendor/cli/src/init.js +1 -175
  47. package/vendor/cli/src/input.js +1 -139
  48. package/vendor/cli/src/keys.js +1 -183
  49. package/vendor/cli/src/markdown.js +1 -306
  50. package/vendor/cli/src/models.js +1 -507
  51. package/vendor/cli/src/naming.js +1 -57
  52. package/vendor/cli/src/overlays.js +1 -462
  53. package/vendor/cli/src/panels.js +1 -1418
  54. package/vendor/cli/src/ping.js +1 -226
  55. package/vendor/cli/src/presence.js +1 -238
  56. package/vendor/cli/src/render.js +1 -516
  57. package/vendor/cli/src/screen.js +1 -518
  58. package/vendor/cli/src/screens.js +1 -896
  59. package/vendor/cli/src/secret.js +1 -59
  60. package/vendor/cli/src/securefs.js +1 -359
  61. package/vendor/cli/src/settings.js +1 -155
  62. package/vendor/cli/src/shared.js +1 -52
  63. package/vendor/cli/src/sharedpaths.js +1 -53
  64. package/vendor/cli/src/signup.js +1 -156
  65. package/vendor/cli/src/summarize.js +1 -95
  66. package/vendor/cli/src/sysdiag.js +1 -585
  67. package/vendor/cli/src/system.js +1 -40
  68. package/vendor/cli/src/theme.js +1 -570
  69. package/vendor/cli/src/title.js +1 -220
  70. package/vendor/cli/src/todos.js +1 -115
  71. package/vendor/cli/src/tokens.js +1 -263
  72. package/vendor/cli/src/topup.js +1 -210
  73. package/vendor/cli/src/update.js +1 -191
  74. package/vendor/cli/vendor/client/aegis.js +1 -2441
  75. package/vendor/cli/vendor/client/attest.js +1 -518
  76. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  77. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  78. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  79. package/vendor/cli/vendor/client/byok-catalog.js +1 -199
  80. package/vendor/cli/vendor/client/catalog-client.js +1 -487
  81. package/vendor/cli/vendor/client/conversation-export.js +1 -177
  82. package/vendor/cli/vendor/client/credentials.js +1 -494
  83. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  84. package/vendor/cli/vendor/client/drive-connect.js +1 -110
  85. package/vendor/cli/vendor/client/drive-upload.js +1 -234
  86. package/vendor/cli/vendor/client/env-file.js +1 -1273
  87. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  88. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  89. package/vendor/cli/vendor/client/google-signin.js +1 -133
  90. package/vendor/cli/vendor/client/hooks.js +1 -430
  91. package/vendor/cli/vendor/client/model-discovery.js +1 -373
  92. package/vendor/cli/vendor/client/naming.js +1 -283
  93. package/vendor/cli/vendor/client/platform.js +1 -937
  94. package/vendor/cli/vendor/client/prefs.js +1 -351
  95. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  96. package/vendor/cli/vendor/client/presence.js +1 -438
  97. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  98. package/vendor/cli/vendor/client/session-store.js +1 -575
  99. package/vendor/cli/vendor/client/topup.js +1 -297
  100. package/vendor/cli/vendor/client/touch.js +1 -458
  101. package/vendor/cli/vendor/client/update.js +1 -763
  102. package/vendor/cli/vendor/client/user-models.js +1 -381
  103. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  104. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -276
  105. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  106. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1028
  107. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -125
  108. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3666
  109. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
  110. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  111. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2145
  112. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -280
  113. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  114. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -238
  115. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -75
  116. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  117. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  118. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  119. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  120. package/vendor/cli/vendor/hosts/install.js +1 -638
  121. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  122. package/vendor/cli/vendor/hosts/spec.js +1 -164
  123. package/vendor/cli/vendor/hosts/targets.js +1 -346
  124. package/vendor/cli/vendor/mcp/server.js +1 -221
  125. package/vendor/cli/vendor/mcp/tools.js +1 -408
  126. package/vendor/cli/vendor/one/src/child.js +1 -285
  127. package/vendor/cli/vendor/one/src/permissions.js +1 -383
  128. package/vendor/desktop/bin/aegis.js +1 -32
  129. package/vendor/desktop/lib/account-key.js +1 -56
  130. package/vendor/desktop/lib/auto.js +1 -461
  131. package/vendor/desktop/lib/avatar/companion.js +1 -698
  132. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  133. package/vendor/desktop/lib/avatar/events.js +1 -344
  134. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  135. package/vendor/desktop/lib/avatar/holders.js +1 -612
  136. package/vendor/desktop/lib/avatar/identity.js +1 -641
  137. package/vendor/desktop/lib/avatar/level.js +1 -368
  138. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  139. package/vendor/desktop/lib/avatar/persona.js +1 -388
  140. package/vendor/desktop/lib/avatar/profile.js +1 -977
  141. package/vendor/desktop/lib/avatar/register.js +1 -307
  142. package/vendor/desktop/lib/avatar/store.js +1 -472
  143. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  144. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  145. package/vendor/desktop/lib/avatar/turn.js +1 -216
  146. package/vendor/desktop/lib/avatar/voice.js +1 -328
  147. package/vendor/desktop/lib/avatar/xp.js +1 -404
  148. package/vendor/desktop/lib/deep-link.js +1 -120
  149. package/vendor/desktop/lib/fingerprint.js +2 -347
  150. package/vendor/desktop/lib/google-connect.js +1 -323
  151. package/vendor/desktop/lib/local/agents.js +1 -105
  152. package/vendor/desktop/lib/local/attachments.js +1 -276
  153. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  154. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  155. package/vendor/desktop/lib/local/context.js +1 -125
  156. package/vendor/desktop/lib/local/engine.js +1 -3666
  157. package/vendor/desktop/lib/local/entitlement.js +1 -660
  158. package/vendor/desktop/lib/local/git-scope.js +1 -228
  159. package/vendor/desktop/lib/local/local.js +1 -2145
  160. package/vendor/desktop/lib/local/prompt.js +1 -280
  161. package/vendor/desktop/lib/local/queue.js +1 -560
  162. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  163. package/vendor/desktop/lib/local/spill.js +1 -75
  164. package/vendor/desktop/lib/local/telemetry.js +1 -470
  165. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  166. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  167. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  168. package/vendor/desktop/lib/quick-launcher.js +1 -84
  169. package/vendor/desktop/lib/settings.js +1 -890
  170. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  171. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  172. package/vendor/desktop/lib/sync/sessions.js +1 -106
  173. package/vendor/desktop/lib/window-state.js +1 -66
  174. package/vendor/desktop/package.json +2 -4
  175. package/vendor/desktop/preload.js +1 -679
  176. package/vendor/desktop/renderer/app.js +1 -7250
  177. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  178. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  179. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  180. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  181. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  182. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  183. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  184. package/vendor/desktop/renderer/budget.js +1 -172
  185. package/vendor/desktop/renderer/companion.js +1 -223
  186. package/vendor/desktop/renderer/diff.js +1 -359
  187. package/vendor/desktop/renderer/diffview.js +1 -336
  188. package/vendor/desktop/renderer/filepreview.js +1 -211
  189. package/vendor/desktop/renderer/fingerprint.js +3 -789
  190. package/vendor/desktop/renderer/markdown.js +1 -168
  191. package/vendor/desktop/renderer/provider-mark.js +1 -311
  192. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  193. package/vendor/desktop/renderer/providers.js +1 -259
  194. package/vendor/desktop/renderer/quick.js +1 -285
  195. package/vendor/desktop/renderer/stream-policy.js +1 -387
  196. package/vendor/desktop/renderer/transcript-view.js +1 -323
  197. package/vendor/desktop/renderer/usage.js +1 -1239
  198. package/vendor/desktop/vendor/aegis.js +1 -2441
  199. package/vendor/desktop/vendor/attest.js +1 -518
  200. package/vendor/desktop/vendor/authorship-key.js +1 -410
  201. package/vendor/desktop/vendor/auto-provision.js +1 -134
  202. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  203. package/vendor/desktop/vendor/byok-catalog.js +1 -199
  204. package/vendor/desktop/vendor/catalog-client.js +1 -487
  205. package/vendor/desktop/vendor/conversation-export.js +1 -177
  206. package/vendor/desktop/vendor/credentials.js +1 -494
  207. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  208. package/vendor/desktop/vendor/drive-connect.js +1 -110
  209. package/vendor/desktop/vendor/drive-upload.js +1 -234
  210. package/vendor/desktop/vendor/env-file.js +1 -1273
  211. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  212. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  213. package/vendor/desktop/vendor/google-signin.js +1 -133
  214. package/vendor/desktop/vendor/hooks.js +1 -430
  215. package/vendor/desktop/vendor/model-discovery.js +1 -373
  216. package/vendor/desktop/vendor/naming.js +1 -283
  217. package/vendor/desktop/vendor/platform.js +1 -937
  218. package/vendor/desktop/vendor/prefs.js +1 -351
  219. package/vendor/desktop/vendor/presence-constants.js +1 -107
  220. package/vendor/desktop/vendor/presence.js +1 -438
  221. package/vendor/desktop/vendor/record-vault.js +3 -1055
  222. package/vendor/desktop/vendor/session-store.js +1 -575
  223. package/vendor/desktop/vendor/topup.js +1 -297
  224. package/vendor/desktop/vendor/touch.js +1 -458
  225. package/vendor/desktop/vendor/update.js +1 -763
  226. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -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
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=2e3,LOCK_WAIT_MS=500;function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS;for(let e=0;e<200;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(e>LOCK_STALE_MS){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;const s=Date.now()+5;for(;Date.now()<s;);}return!1}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){const n=acquireLock(e);try{const n=load(e),s=t(n);return save(e,n),s}finally{n&&releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=MAX_MESSAGES_PER_SESSION?e:e.slice(e.length-MAX_MESSAGES_PER_SESSION):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,(e=>{const s=e[n]||{messages:[]};return e[n]={...s,...t,id:n,version:2},!0===s.named&&"string"==typeof s.title&&s.title&&(e[n].title=s.title,e[n].named=!0),!1!==t.pending&&(e[n].pending=!0),e[n].updatedAt||(e[n].updatedAt=Date.now()),e[n].seq=nextSeq(e),e[n]}))}function appendMessage(e,t,n){if(!t)throw new Error("sessionId is required");return mutate(e,(e=>{const s=e[t]||{id:t,messages:[]},r=Array.isArray(s.messages)?s.messages:[];return s.messages=trimMessages(r.concat(n)),s.updatedAt=Date.now(),s.pending=!0,s.seq=nextSeq(e),e[t]=s,s}))}function recordExchange(e,t){const n=t||{};if(!n.sessionId)return null;const s=n.sessionId;return mutate(e,(e=>{const t=e[s]||{id:s,messages:[]},r=Array.isArray(t.messages)?t.messages:[],o=n.ts||(new Date).toISOString(),i={role:"user",content:null==n.prompt?"":String(n.prompt),ts:o},a={role:"assistant",content:null==n.reply?"":String(n.reply),ts:o};return n.tokens&&(a.tokens=n.tokens),"number"==typeof n.costUsd&&(a.costUsd=n.costUsd),n.status&&(a.status=n.status),n.model&&(a.model=n.model),n.provider&&(a.provider=n.provider),n.origin&&(i.origin=n.origin,a.origin=n.origin),t.messages=trimMessages(r.concat([i,a])),t.title=t.title||String(n.prompt||"").slice(0,60),n.cwd&&(t.cwd=n.cwd),t.origin=n.origin||t.origin||"unknown",t.updatedAt=Date.now(),t.pending=!0===n.pending,t.seq=nextSeq(e),e[s]=t,t}))}function setTitle(e,t,n,s){const r=String(null==n?"":n).trim().slice(0,200);if(!t||!r)return null;const o=s&&!0===s.named;return mutate(e,(e=>{const n=e[t];return n?(n.title=r,o&&(n.named=!0),n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null}))}function listSessions(e){const t=load(e);return Object.values(t).filter((e=>e&&e.id)).sort(((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)||(t.seq||0)-(e.seq||0)))}function getSession(e,t){return load(e)[t]||null}function deleteSession(e,t){return mutate(e,(e=>(delete e[t],{ok:!0})))}function markSynced(e,t,n){return mutate(e,(e=>{const s=e[t];return s?(s.pending=!1,s.lastSyncedAt=Date.now(),n&&n.remoteId&&(s.remoteId=n.remoteId),s.seq=nextSeq(e),s):null}))}function markPending(e,t){return mutate(e,(e=>{const n=e[t];return n?(n.pending=!0,n.seq=nextSeq(e),n):null}))}function listPending(e){return listSessions(e).filter((e=>!1!==e.pending))}function mergeRemoteSessions(e,t){const n=Array.isArray(t)?t:[];return n.length?mutate(e,(e=>{let t=0;for(const s of n){const n=s&&(s.session_id||s.id);if(!n)continue;const r=e[n],o=toEpochMs(s.updated_at??s.updatedAt);r&&(r.pending||(r.updatedAt||0)>=o)||(e[n]={id:n,title:s.title||r&&r.title||"",messages:Array.isArray(s.messages)?s.messages:[],updatedAt:o||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:s.session_id||s.id,origin:s.source||r&&r.origin||"cloud",version:2},e[n].seq=nextSeq(e),t+=1)}return t})):0}function listSummaries(e,t=8){return listSessions(e).slice(0,t).map((e=>{const t=Array.isArray(e.messages)?e.messages:[],n=t.find((e=>e&&"user"===e.role));return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||n&&n.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:t.length,pending:!0===e.pending,dir:String(e.cwd||"")}}))}function readTranscript(e,t){const n=getSession(e,t);return n?(Array.isArray(n.messages)?n.messages:[]).filter((e=>e&&("user"===e.role||"assistant"===e.role))).map((e=>({role:e.role,text:null==e.content?"":String(e.content)}))):[]}function adopt(e,t){const n=storeFile(t);if(!(()=>{try{return fs.existsSync(n)}catch{return!1}})())return{adopted:!1,sessions:0,from:n,reason:"no legacy store"};const s=(()=>{try{const e=JSON.parse(fs.readFileSync(n,"utf8"));return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}})(),r=Object.values(s).filter((e=>e&&e.id));return r.length?listSessions(e).length?{adopted:!1,sessions:0,from:n,reason:"store already has sessions"}:(mutate(e,(e=>{for(const t of r)e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null})),{adopted:!0,sessions:r.length,from:n}):{adopted:!1,sessions:0,from:n,reason:"legacy store empty"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:MAX_MESSAGES_PER_SESSION,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:LOCK_STALE_MS,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};