aegisone 1.0.22 → 1.0.24

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 -939
  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 -369
  14. package/src/probes.js +1 -159
  15. package/src/release.js +1 -409
  16. package/vendor/cli/bin/aegiscode.js +2 -914
  17. package/vendor/cli/package.json +3 -7
  18. package/vendor/cli/scripts/check.mjs +1 -52
  19. package/vendor/cli/scripts/demo.mjs +1 -94
  20. package/vendor/cli/scripts/predist.mjs +1 -75
  21. package/vendor/cli/scripts/runtests.mjs +1 -56
  22. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  23. package/vendor/cli/src/agents.js +1 -139
  24. package/vendor/cli/src/app.js +1 -2932
  25. package/vendor/cli/src/art.js +1 -289
  26. package/vendor/cli/src/autonomous.js +1 -515
  27. package/vendor/cli/src/caps.js +1 -879
  28. package/vendor/cli/src/chatflow.js +1 -3020
  29. package/vendor/cli/src/checkpoint.js +1 -90
  30. package/vendor/cli/src/clipboard.js +1 -424
  31. package/vendor/cli/src/cloudsync.js +1 -528
  32. package/vendor/cli/src/commands.js +1 -4003
  33. package/vendor/cli/src/config.js +1 -581
  34. package/vendor/cli/src/connect.js +1 -349
  35. package/vendor/cli/src/credentials.js +1 -33
  36. package/vendor/cli/src/deps.js +1 -232
  37. package/vendor/cli/src/devrun.js +1 -187
  38. package/vendor/cli/src/diff.js +1 -333
  39. package/vendor/cli/src/diffview.js +1 -296
  40. package/vendor/cli/src/engine.js +1 -297
  41. package/vendor/cli/src/entitlement.js +1 -355
  42. package/vendor/cli/src/events.js +1 -707
  43. package/vendor/cli/src/export.js +1 -67
  44. package/vendor/cli/src/fingerprint.js +1 -592
  45. package/vendor/cli/src/format.js +1 -259
  46. package/vendor/cli/src/fuzzy.js +1 -119
  47. package/vendor/cli/src/gate.js +1 -55
  48. package/vendor/cli/src/history.js +1 -401
  49. package/vendor/cli/src/init.js +1 -175
  50. package/vendor/cli/src/input.js +1 -139
  51. package/vendor/cli/src/keys.js +1 -183
  52. package/vendor/cli/src/limits.js +1 -190
  53. package/vendor/cli/src/markdown.js +1 -306
  54. package/vendor/cli/src/mcp.js +1 -694
  55. package/vendor/cli/src/models.js +1 -487
  56. package/vendor/cli/src/naming.js +1 -229
  57. package/vendor/cli/src/overlays.js +1 -461
  58. package/vendor/cli/src/panels.js +1 -1418
  59. package/vendor/cli/src/permissions.js +1 -290
  60. package/vendor/cli/src/ping.js +1 -226
  61. package/vendor/cli/src/presence.js +1 -238
  62. package/vendor/cli/src/provenance.js +2 -182
  63. package/vendor/cli/src/render.js +1 -515
  64. package/vendor/cli/src/screen.js +1 -518
  65. package/vendor/cli/src/screens.js +1 -896
  66. package/vendor/cli/src/secret.js +1 -59
  67. package/vendor/cli/src/securefs.js +1 -359
  68. package/vendor/cli/src/settings.js +1 -155
  69. package/vendor/cli/src/shared.js +1 -52
  70. package/vendor/cli/src/sharedpaths.js +1 -53
  71. package/vendor/cli/src/signup.js +1 -156
  72. package/vendor/cli/src/summarize.js +1 -95
  73. package/vendor/cli/src/sysdiag.js +1 -585
  74. package/vendor/cli/src/system.js +1 -40
  75. package/vendor/cli/src/theme.js +1 -570
  76. package/vendor/cli/src/title.js +1 -220
  77. package/vendor/cli/src/todos.js +1 -115
  78. package/vendor/cli/src/tokens.js +1 -263
  79. package/vendor/cli/src/topup.js +1 -210
  80. package/vendor/cli/src/update.js +1 -181
  81. package/vendor/cli/vendor/client/aegis.js +1 -2179
  82. package/vendor/cli/vendor/client/attest.js +1 -442
  83. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  84. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  85. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  86. package/vendor/cli/vendor/client/byok-catalog.js +1 -230
  87. package/vendor/cli/vendor/client/credentials.js +1 -494
  88. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  89. package/vendor/cli/vendor/client/drive-connect.js +1 -110
  90. package/vendor/cli/vendor/client/drive-upload.js +1 -174
  91. package/vendor/cli/vendor/client/env-file.js +1 -1273
  92. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  93. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  94. package/vendor/cli/vendor/client/google-signin.js +1 -133
  95. package/vendor/cli/vendor/client/hooks.js +1 -430
  96. package/vendor/cli/vendor/client/model-discovery.js +1 -373
  97. package/vendor/cli/vendor/client/platform.js +1 -937
  98. package/vendor/cli/vendor/client/prefs.js +1 -351
  99. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  100. package/vendor/cli/vendor/client/presence.js +1 -438
  101. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  102. package/vendor/cli/vendor/client/session-store.js +1 -548
  103. package/vendor/cli/vendor/client/topup.js +1 -297
  104. package/vendor/cli/vendor/client/touch.js +1 -458
  105. package/vendor/cli/vendor/client/update.js +1 -704
  106. package/vendor/cli/vendor/client/user-models.js +1 -381
  107. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  108. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  109. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -993
  110. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -95
  111. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3301
  112. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
  113. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  114. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2135
  115. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -275
  116. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  117. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -208
  118. package/vendor/cli/vendor/desktop/lib/local/shell.js +1 -680
  119. package/vendor/cli/vendor/desktop/lib/local/tools.js +1 -1238
  120. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  121. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  122. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  123. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  124. package/vendor/cli/vendor/hosts/install.js +1 -638
  125. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  126. package/vendor/cli/vendor/hosts/spec.js +1 -164
  127. package/vendor/cli/vendor/hosts/targets.js +1 -346
  128. package/vendor/cli/vendor/mcp/server.js +1 -221
  129. package/vendor/cli/vendor/mcp/tools.js +1 -408
  130. package/vendor/cli/vendor/one/src/child.js +1 -285
  131. package/vendor/cli/vendor/one/src/permissions.js +1 -369
  132. package/vendor/desktop/bin/aegis.js +1 -32
  133. package/vendor/desktop/lib/account-key.js +1 -56
  134. package/vendor/desktop/lib/auto.js +1 -430
  135. package/vendor/desktop/lib/avatar/companion.js +1 -698
  136. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  137. package/vendor/desktop/lib/avatar/events.js +1 -344
  138. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  139. package/vendor/desktop/lib/avatar/holders.js +1 -612
  140. package/vendor/desktop/lib/avatar/identity.js +1 -641
  141. package/vendor/desktop/lib/avatar/level.js +1 -368
  142. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  143. package/vendor/desktop/lib/avatar/persona.js +1 -388
  144. package/vendor/desktop/lib/avatar/profile.js +1 -977
  145. package/vendor/desktop/lib/avatar/register.js +1 -307
  146. package/vendor/desktop/lib/avatar/store.js +1 -472
  147. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  148. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  149. package/vendor/desktop/lib/avatar/turn.js +1 -216
  150. package/vendor/desktop/lib/avatar/voice.js +1 -328
  151. package/vendor/desktop/lib/avatar/xp.js +1 -404
  152. package/vendor/desktop/lib/deep-link.js +1 -120
  153. package/vendor/desktop/lib/fingerprint.js +2 -347
  154. package/vendor/desktop/lib/google-connect.js +1 -227
  155. package/vendor/desktop/lib/local/agents.js +1 -105
  156. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  157. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  158. package/vendor/desktop/lib/local/context.js +1 -95
  159. package/vendor/desktop/lib/local/engine.js +1 -3301
  160. package/vendor/desktop/lib/local/entitlement.js +1 -660
  161. package/vendor/desktop/lib/local/git-scope.js +1 -228
  162. package/vendor/desktop/lib/local/local.js +1 -2135
  163. package/vendor/desktop/lib/local/prompt.js +1 -275
  164. package/vendor/desktop/lib/local/queue.js +1 -560
  165. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  166. package/vendor/desktop/lib/local/shell.js +1 -680
  167. package/vendor/desktop/lib/local/telemetry.js +1 -470
  168. package/vendor/desktop/lib/local/tools.js +1 -1238
  169. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  170. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  171. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  172. package/vendor/desktop/lib/quick-launcher.js +1 -84
  173. package/vendor/desktop/lib/settings.js +1 -890
  174. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  175. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  176. package/vendor/desktop/lib/sync/sessions.js +1 -106
  177. package/vendor/desktop/lib/window-state.js +1 -66
  178. package/vendor/desktop/main.js +1 -4529
  179. package/vendor/desktop/package.json +3 -5
  180. package/vendor/desktop/preload.js +1 -636
  181. package/vendor/desktop/renderer/app.js +1 -6660
  182. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  183. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  184. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  185. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  186. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  187. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  188. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  189. package/vendor/desktop/renderer/budget.js +1 -168
  190. package/vendor/desktop/renderer/companion.js +1 -223
  191. package/vendor/desktop/renderer/diff.js +1 -359
  192. package/vendor/desktop/renderer/diffview.js +1 -336
  193. package/vendor/desktop/renderer/fingerprint.js +3 -736
  194. package/vendor/desktop/renderer/markdown.js +1 -168
  195. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  196. package/vendor/desktop/renderer/providers.js +1 -259
  197. package/vendor/desktop/renderer/quick.js +1 -191
  198. package/vendor/desktop/renderer/stream-policy.js +1 -306
  199. package/vendor/desktop/renderer/transcript-view.js +1 -323
  200. package/vendor/desktop/renderer/usage.js +1 -1239
  201. package/vendor/desktop/vendor/aegis.js +1 -2179
  202. package/vendor/desktop/vendor/attest.js +1 -442
  203. package/vendor/desktop/vendor/authorship-key.js +1 -410
  204. package/vendor/desktop/vendor/auto-provision.js +1 -134
  205. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  206. package/vendor/desktop/vendor/byok-catalog.js +1 -230
  207. package/vendor/desktop/vendor/credentials.js +1 -494
  208. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  209. package/vendor/desktop/vendor/drive-connect.js +1 -110
  210. package/vendor/desktop/vendor/drive-upload.js +1 -174
  211. package/vendor/desktop/vendor/env-file.js +1 -1273
  212. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  213. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  214. package/vendor/desktop/vendor/google-signin.js +1 -133
  215. package/vendor/desktop/vendor/hooks.js +1 -430
  216. package/vendor/desktop/vendor/model-discovery.js +1 -373
  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 -548
  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 -704
  226. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -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
+ "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},!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.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){const s=String(null==n?"":n).trim().slice(0,200);return t&&s?mutate(e,(e=>{const n=e[t];return n?(n.title=s,n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null})):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};