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,530 +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
- * Cloud conversation sync for the terminal host.
10
- *
11
- * The desktop has had this since P4.5 (`desktop/lib/sync/sessions.js` +
12
- * `desktop/main.js`'s sync handlers, behind the "Sync now" button). The CLI had
13
- * the transport for it — `client.conversationSyncPush/Pull` are the same two
14
- * shared-client methods the desktop calls — and no code that used them, plus a
15
- * `/cloud` command whose reply was "managed by the aegis CLI: run `aegis login`
16
- * — aegiscode does not store cloud keys." That was a dead end twice over: the
17
- * key *is* storable now (credentials.js), and nothing else was going to push
18
- * this host's sessions anywhere.
19
- *
20
- * Shape of the local store: the sessions that sync are the ones the CLI
21
- * already persists in `history.jsonl` (one record per exchange, keyed by
22
- * sessionId). Building a second session store for sync would mean `/resume`
23
- * and cloud sync disagreed about which sessions exist, so there is exactly one
24
- * and this module reads it, then writes imported remote sessions back into it —
25
- * which is what makes a pulled session show up in `/resume` like any other.
26
- *
27
- * What is tracked locally, in `sync-state.json`:
28
- *
29
- * sessions[id] = { syncedAt, localUpdatedAt, remoteUpdatedAt, importedRemoteAt, lastError }
30
- *
31
- * "Pending" is derived, never stored as a flag that can go stale: a session is
32
- * pending when its newest local record is newer than the last successful push.
33
- *
34
- * Quota note, because it is the difference between a working sync and a
35
- * surprise: the server charges a push for the *growth* of a session
36
- * (`_session_token_delta` in aegis1's conversation_sync), refuses with 402 once
37
- * the plan's synced-token ceiling would be exceeded (FREE_SYNC_TOKENS = 1 MB,
38
- * PRO_SYNC_TOKENS = 10 MB), and always serves pulls. So a 402 is reported as the
39
- * quota error it is instead of being swallowed into "sync failed".
40
- *
41
- * This used to be the reason sync was opt-IN (config `cloudSync`, default off):
42
- * automatic writes against a metered ceiling felt like spending someone else's
43
- * money. It is now default ON (config `memoryPersist` — see config.js for the
44
- * migration), because the ceiling is not a hard stop: aegis1's
45
- * `_memory_sync_access()` enforces the limit on WRITES only, so an over-quota
46
- * account still reads back everything it stored. What was missing was not
47
- * caution, it was honesty: a free account passes ~1 MB of transcript in weeks,
48
- * and the old failure mode was a silent stop with no visible state. So this
49
- * module now records the quota it is told about (`status().quota`) and
50
- * classifies the refusal as "writes paused, reads fine" rather than as a
51
- * generic failure — `/cloud memory` (and the first-run notice) say exactly
52
- * that, and `/cloud memory off` is the explicit opt-out.
53
- */
54
-
55
- const fs = require('node:fs');
56
- const path = require('node:path');
57
- const { aegisDir } = require('./config.js');
58
- const {
59
- historyPath,
60
- appendHistoryEntries,
61
- readHistoryEntries,
62
- readSessionTranscript,
63
- } = require('./history.js');
64
- const { estimateTokens } = require('./tokens.js');
65
-
66
- /** Recorded on every session this host pushes, so the server can tell hosts apart. */
67
- const SOURCE = 'aegiscode-cli';
68
- const SYNC_FILE = 'sync-state.json';
69
- const DEFAULT_LIMIT = 50;
70
-
71
- function syncStatePath() {
72
- return path.join(aegisDir(), SYNC_FILE);
73
- }
74
-
75
- /** The sync ledger, or an empty one. Never throws on a missing/corrupt file. */
76
- function loadState() {
77
- try {
78
- const parsed = JSON.parse(fs.readFileSync(syncStatePath(), 'utf8'));
79
- if (parsed && typeof parsed === 'object') {
80
- return {
81
- sessions: parsed.sessions && typeof parsed.sessions === 'object' ? parsed.sessions : {},
82
- lastPushAt: parsed.lastPushAt || null,
83
- lastPullAt: parsed.lastPullAt || null,
84
- importedRemoteAt: parsed.importedRemoteAt || {},
85
- // How many messages of each remote session are already in the local
86
- // store. Without this a session that grew by one turn re-imported its
87
- // whole transcript, so every pull duplicated every earlier exchange and
88
- // /cost doubled with each sync.
89
- importedRemoteCount: parsed.importedRemoteCount || {},
90
- // The last quota the server told us about — `{ used, limit, at, over }`.
91
- // Persisted because it is the only way the NEXT run can say "you are at
92
- // the ceiling, only new writes are paused" before it has re-attempted a
93
- // push: without it, a restarted session looks identical to a fresh one
94
- // and the over-quota state is invisible until the next refused write.
95
- quota: parsed.quota && typeof parsed.quota === 'object' ? parsed.quota : null,
96
- };
97
- }
98
- } catch {}
99
- return {
100
- sessions: {},
101
- lastPushAt: null,
102
- lastPullAt: null,
103
- importedRemoteAt: {},
104
- importedRemoteCount: {},
105
- quota: null,
106
- };
107
- }
108
-
109
- /**
110
- * The quota numbers off a sync response, or null when it carried none.
111
- *
112
- * aegis1 `_token_quota_fields` emits **camelCase** — `tokensUsed`,
113
- * `tokenLimit`, `tokensRemaining` — and its docstring is explicit that the
114
- * session-named keys were *replaced* rather than aliased. The snake_case
115
- * spellings are the pre-rename wire and are read only as a fallback.
116
- *
117
- * Reading snake_case alone here meant every successful push threw its quota
118
- * reading away: `state.quota` stayed null, so `/sync status` printed "quota:
119
- * not reported yet" forever no matter how many pushes succeeded, and the
120
- * over-quota notice could only ever appear from a 402 body. The account was
121
- * reporting 10 MB of 10.4 MB used the whole time.
122
- */
123
- function readQuota(payload) {
124
- if (!payload || typeof payload !== 'object') return null;
125
- const used = payload.tokensUsed != null ? payload.tokensUsed : payload.tokens_used;
126
- const limit = payload.tokenLimit != null ? payload.tokenLimit : payload.token_limit;
127
- if (used == null || limit == null) return null;
128
- const u = Number(used);
129
- const l = Number(limit);
130
- if (!Number.isFinite(u) || !Number.isFinite(l)) return null;
131
- return { used: u, limit: l };
132
- }
133
-
134
- /**
135
- * Remember a quota reading from either half of a response — the numbers ride on
136
- * a successful push as well as on the 402 body, and both are worth keeping.
137
- *
138
- * `over` is derived here, once, so every surface (status panel, first-run
139
- * notice, auto-sync refusal) agrees about what "at the ceiling" means instead
140
- * of each comparing used >= limit on its own.
141
- */
142
- function recordQuota(state, used, limit) {
143
- const u = Number(used);
144
- const l = Number(limit);
145
- if (!state || !Number.isFinite(u) || !Number.isFinite(l) || l <= 0) return null;
146
- state.quota = { used: u, limit: l, over: u >= l, at: Date.now() };
147
- return state.quota;
148
- }
149
-
150
- function saveState(state) {
151
- try {
152
- fs.mkdirSync(aegisDir(), { recursive: true });
153
- const tmp = syncStatePath() + '.tmp';
154
- fs.writeFileSync(tmp, JSON.stringify(state, null, 2) + '\n');
155
- fs.renameSync(tmp, syncStatePath());
156
- return true;
157
- } catch (e) {
158
- if (process.env.AEGIS_HIST_DEBUG) console.error('[cloudsync] write failed:', e);
159
- return false;
160
- }
161
- }
162
-
163
- /** Local sessions from history.jsonl, newest activity first. One pass. */
164
- function localSessions({ limit = DEFAULT_LIMIT } = {}) {
165
- const byId = new Map();
166
- for (const e of readHistoryEntries()) {
167
- if (!e || !e.sessionId) continue;
168
- const cur = byId.get(e.sessionId) || {
169
- id: e.sessionId,
170
- cwd: e.cwd || '',
171
- firstPrompt: '',
172
- updatedAt: '',
173
- exchanges: 0,
174
- };
175
- cur.exchanges += 1;
176
- if (!cur.firstPrompt && e.prompt) cur.firstPrompt = String(e.prompt);
177
- if (String(e.ts || '') > String(cur.updatedAt || '')) cur.updatedAt = e.ts || '';
178
- byId.set(e.sessionId, cur);
179
- }
180
- return [...byId.values()]
181
- .sort((a, b) => (String(a.updatedAt) < String(b.updatedAt) ? 1 : -1))
182
- .slice(0, Math.max(1, limit));
183
- }
184
-
185
- /** Title for a session: its first prompt, collapsed to one line. */
186
- function titleFor(session) {
187
- const raw = String((session && session.firstPrompt) || '').replace(/\s+/g, ' ').trim();
188
- return raw.slice(0, 80);
189
- }
190
-
191
- /**
192
- * A pulled/pushed transcript in the wire shape.
193
- *
194
- * `messages` is `{role, content}` — the same keys the desktop pushes, because
195
- * the server stores this array verbatim and a different spelling here would
196
- * make one host's sessions unreadable to the other.
197
- */
198
- function buildTranscript(session, o = {}) {
199
- const rows = o.transcript || readSessionTranscript(session.id);
200
- const messages = rows
201
- .filter((r) => r && (r.role === 'user' || r.role === 'assistant'))
202
- .map((r) => ({ role: r.role, content: String(r.text == null ? '' : r.text) }));
203
- return {
204
- session_id: session.id,
205
- title: o.title != null ? o.title : titleFor(session),
206
- messages,
207
- source: o.source || SOURCE,
208
- };
209
- }
210
-
211
- function isPending(session, state) {
212
- const rec = state.sessions[session.id];
213
- if (!rec || !rec.syncedAt) return true;
214
- return String(session.updatedAt || '') > String(rec.localUpdatedAt || '');
215
- }
216
-
217
- /**
218
- * Sessions with local changes the cloud has not seen, oldest first.
219
- *
220
- * The candidate set is the whole store, never the recency slice
221
- * `localSessions()` defaults to (the newest 50). `isPending` is a property of
222
- * a session — "the cloud has not seen this version" — and not of how recently
223
- * it was touched, so filtering a 50-session window silently drops every older
224
- * unsynced session. On this machine that produced two contradictory answers
225
- * from one state: `status()` scans in full and reported "pending: 8", while
226
- * `push()` asked for the newest 50, found nothing pending in it, and `/sync
227
- * now` said "nothing to push — every local session is already in the cloud".
228
- * Whatever `limit` a caller passes now caps how many pending sessions are
229
- * *returned* (oldest first, the documented drain order); it no longer changes
230
- * which sessions count as pending.
231
- */
232
- function listPending(o = {}) {
233
- const state = o.state || loadState();
234
- const pending = localSessions({ ...o, limit: Number.MAX_SAFE_INTEGER })
235
- .filter((s) => isPending(s, state))
236
- .reverse();
237
- return o.limit ? pending.slice(0, o.limit) : pending;
238
- }
239
-
240
- function markSynced(state, id, o = {}) {
241
- const prev = state.sessions[id] || {};
242
- state.sessions[id] = {
243
- ...prev,
244
- syncedAt: Date.now(),
245
- localUpdatedAt: o.localUpdatedAt || prev.localUpdatedAt || '',
246
- remoteUpdatedAt: o.remoteUpdatedAt || prev.remoteUpdatedAt || null,
247
- lastError: null,
248
- };
249
- return state.sessions[id];
250
- }
251
-
252
- function markFailed(state, id, err) {
253
- const prev = state.sessions[id] || {};
254
- state.sessions[id] = { ...prev, lastError: err, failedAt: Date.now() };
255
- return state.sessions[id];
256
- }
257
-
258
- /** Flatten a remote messages array into history records for the local store. */
259
- function entriesFromRemote(session, now, skip = 0) {
260
- const out = [];
261
- const all = Array.isArray(session.messages) ? session.messages : [];
262
- // Only the messages this host has not already written: a resync after a new
263
- // turn must add that turn, not the whole thread again.
264
- const messages = skip > 0 && skip <= all.length ? all.slice(skip) : all;
265
- let pendingPrompt = null;
266
- const flush = (prompt, reply) => {
267
- if (prompt == null && reply == null) return;
268
- out.push({
269
- ts: session.updated_at || now,
270
- sessionId: session.session_id,
271
- cwd: '',
272
- prompt: prompt == null ? '' : String(prompt),
273
- reply: reply == null ? '' : String(reply),
274
- status: 'done',
275
- imported: true,
276
- importedFrom: String(session.source || 'cloud'),
277
- tokens: {
278
- input: estimateTokens(String(prompt || '')),
279
- output: estimateTokens(String(reply || '')),
280
- cacheRead: 0,
281
- cacheWrite: 0,
282
- real: false,
283
- },
284
- });
285
- };
286
- for (const m of messages) {
287
- const role = m && m.role;
288
- const text = m && (m.content != null ? m.content : m.text);
289
- if (role === 'user') {
290
- if (pendingPrompt != null) flush(pendingPrompt, null);
291
- pendingPrompt = text == null ? '' : text;
292
- } else if (role === 'assistant' || role === 'system') {
293
- flush(pendingPrompt, text);
294
- pendingPrompt = null;
295
- }
296
- }
297
- if (pendingPrompt != null) flush(pendingPrompt, null);
298
- return out;
299
- }
300
-
301
- /** A quota refusal is not a transport failure — say which one it is. */
302
- function describeError(err) {
303
- const status = err && (err.status || (err.response && err.response.status));
304
- const message = (err && err.message) || String(err);
305
- if (status === 402) {
306
- // The 402 body carries the quota (`tokensUsed` / `tokenLimit`, from aegis1
307
- // `_token_quota_fields`); the legacy session-named keys are read only as a
308
- // fallback for a server that predates the rename.
309
- const data = (err && err.data) || {};
310
- const used = data.tokensUsed != null ? data.tokensUsed : data.sessionsUsed;
311
- const limit = data.tokenLimit != null ? data.tokenLimit : data.freeSessionLimit;
312
- return {
313
- kind: 'quota',
314
- status,
315
- message,
316
- used: used != null ? Number(used) : null,
317
- limit: limit != null ? Number(limit) : null,
318
- // The refusal is about WRITES only — say what still works and how to stop
319
- // trying, instead of implying the account lost its memory.
320
- hint:
321
- 'the plan’s synced-token ceiling is reached — everything already stored stays readable, only NEW writes pause: /cloud memory shows the quota, /cloud memory off stops syncing',
322
- };
323
- }
324
- if (status === 401) {
325
- return { kind: 'auth', status, message, hint: 'the memory token was refused — run /key <api_key> to re-exchange it' };
326
- }
327
- return { kind: 'error', status: status || null, message, hint: null };
328
- }
329
-
330
- /**
331
- * Push every pending session, one request each.
332
- *
333
- * A single failure does not abort the run: the sessions that did go out are
334
- * recorded as synced, and the ones that did not keep their `lastError` so the
335
- * next attempt (or `/cloud status`) reports the real reason rather than a
336
- * session that silently looks in sync.
337
- */
338
- async function push(client, o = {}) {
339
- const state = o.state || loadState();
340
- const limit = o.limit || DEFAULT_LIMIT;
341
- const pending = o.sessionIds
342
- ? o.sessionIds.map((id) => localSessions({ limit: Number.MAX_SAFE_INTEGER, state }).find((s) => s.id === id)).filter(Boolean)
343
- : listPending({ ...o, limit, state });
344
-
345
- const pushed = [];
346
- const failed = [];
347
- const skipped = [];
348
- for (const session of pending) {
349
- const transcript = buildTranscript(session, {});
350
- if (!transcript.messages.length) {
351
- skipped.push({ id: session.id, reason: 'no messages' });
352
- continue;
353
- }
354
- try {
355
- const res = await client.conversationSyncPush(transcript);
356
- const remoteId = (res && (res.session_id || res.id)) || session.id;
357
- markSynced(state, session.id, {
358
- localUpdatedAt: session.updatedAt,
359
- remoteUpdatedAt: (res && res.updated_at) || new Date().toISOString(),
360
- });
361
- const quota = readQuota(res);
362
- pushed.push({
363
- id: session.id,
364
- remoteId,
365
- messages: transcript.messages.length,
366
- title: transcript.title,
367
- quota,
368
- });
369
- // A successful push is also a quota reading — the response reports the
370
- // running total, which is how the status panel can show "43k of 1M" on a
371
- // healthy account instead of only ever saying something when it breaks.
372
- if (quota) recordQuota(state, quota.used, quota.limit);
373
- if (typeof o.onProgress === 'function') o.onProgress({ phase: 'push', id: session.id });
374
- } catch (err) {
375
- const info = describeError(err);
376
- markFailed(state, session.id, info.message);
377
- failed.push({ id: session.id, ...info });
378
- // Record the ceiling state even when the body carried no numbers: the
379
- // point of the honesty fix is that the stopped state is visible, and a
380
- // server that refuses without reporting a limit must not produce a status
381
- // panel that looks healthy.
382
- if (info.kind === 'quota' && !recordQuota(state, info.used, info.limit)) {
383
- state.quota = { used: null, limit: null, over: true, at: Date.now() };
384
- }
385
- if (info.kind === 'quota' || info.kind === 'auth') break; // every later one fails the same way
386
- }
387
- }
388
- if (pushed.length) state.lastPushAt = Date.now();
389
- saveState(state);
390
- // The remainder is counted over the WHOLE store, not the batch window — the
391
- // caller prints this as "N still waiting", and counting only the drain cap
392
- // would report a drained queue while sessions were still unsynced.
393
- return { pushed, failed, skipped, pending: listPending({ state }).length };
394
- }
395
-
396
- /**
397
- * Pull the account's remote sessions.
398
- *
399
- * `import` writes remote transcripts into history.jsonl so `/resume` sees them.
400
- * Re-pulling an unchanged session imports nothing — otherwise every pull would
401
- * duplicate the whole account into the local store, and `/cost` would double
402
- * with each sync.
403
- */
404
- async function pull(client, o = {}) {
405
- const state = o.state || loadState();
406
- const importRemote = o.import !== false;
407
- let data;
408
- try {
409
- data = await client.conversationSyncPull();
410
- } catch (err) {
411
- return { ok: false, sessions: [], imported: 0, failed: [describeError(err)] };
412
- }
413
- const sessions = (data && data.sessions) || [];
414
- const imported = [];
415
- const now = new Date().toISOString();
416
- const batch = [];
417
-
418
- for (const remote of sessions) {
419
- const id = remote && remote.session_id;
420
- if (!id) continue;
421
- const seenAt = state.importedRemoteAt[id];
422
- const total = Array.isArray(remote.messages) ? remote.messages.length : 0;
423
- const seenCount = Number((state.importedRemoteCount || {})[id] || 0);
424
- const changed = !seenAt || seenAt !== remote.updated_at || total !== seenCount;
425
- if (importRemote && changed) {
426
- const entries = entriesFromRemote(remote, now, total >= seenCount ? seenCount : 0);
427
- if (entries.length) batch.push(...entries);
428
- state.importedRemoteAt[id] = remote.updated_at || now;
429
- state.importedRemoteCount = { ...(state.importedRemoteCount || {}), [id]: total };
430
- }
431
- // A session that came back from the cloud is in sync by definition; without
432
- // this the very next `push` would send it straight back up.
433
- markSynced(state, id, {
434
- localUpdatedAt: remote.updated_at || now,
435
- remoteUpdatedAt: remote.updated_at || now,
436
- });
437
- imported.push({
438
- id,
439
- title: remote.title || '',
440
- messages: (remote.messages || []).length,
441
- source: remote.source || '',
442
- updatedAt: remote.updated_at || null,
443
- imported: importRemote && changed,
444
- });
445
- }
446
-
447
- const written = batch.length ? appendHistoryEntries(batch) : 0;
448
- state.lastPullAt = Date.now();
449
- saveState(state);
450
- return {
451
- ok: true,
452
- sessions: imported,
453
- remote: sessions.length,
454
- imported: written,
455
- failed: [],
456
- };
457
- }
458
-
459
- /** Push then pull. Either half can fail without hiding the other's result. */
460
- async function syncNow(client, o = {}) {
461
- const state = o.state || loadState();
462
- const out = { ok: true, push: null, pull: null };
463
- try {
464
- out.push = await push(client, { ...o, state });
465
- } catch (err) {
466
- out.ok = false;
467
- out.push = { pushed: [], failed: [describeError(err)], skipped: [] };
468
- }
469
- try {
470
- out.pull = await pull(client, { ...o, state });
471
- if (out.pull && out.pull.ok === false) out.ok = false;
472
- } catch (err) {
473
- out.ok = false;
474
- out.pull = { ok: false, sessions: [], imported: 0, failed: [describeError(err)] };
475
- }
476
- return out;
477
- }
478
-
479
- /** Counts for a status panel, with no network access. */
480
- function status() {
481
- const state = loadState();
482
- const sessions = localSessions({ limit: Number.MAX_SAFE_INTEGER });
483
- const pending = sessions.filter((s) => isPending(s, state));
484
- const errors = sessions
485
- .filter((s) => state.sessions[s.id] && state.sessions[s.id].lastError)
486
- .map((s) => ({ id: s.id, error: state.sessions[s.id].lastError }));
487
- const quota = state.quota || null;
488
- const overQuota = Boolean(quota && quota.over);
489
- return {
490
- local: sessions.length,
491
- pending: pending.length,
492
- synced: sessions.length - pending.length,
493
- lastPushAt: state.lastPushAt,
494
- lastPullAt: state.lastPullAt,
495
- importedRemote: Object.keys(state.importedRemoteAt || {}).length,
496
- errors,
497
- // The ceiling, as last reported by the server, plus whether new writes are
498
- // currently stopped by it. `paused` is the combination the panels print:
499
- // there is local work waiting AND the last thing the server said was "no
500
- // room". Both halves matter — a full account with nothing pending is not
501
- // stuck, it is caught up.
502
- quota,
503
- overQuota,
504
- paused: overQuota && pending.length > 0,
505
- path: syncStatePath(),
506
- historyPath: historyPath(),
507
- };
508
- }
509
-
510
- module.exports = {
511
- SOURCE,
512
- syncStatePath,
513
- loadState,
514
- saveState,
515
- localSessions,
516
- titleFor,
517
- buildTranscript,
518
- isPending,
519
- listPending,
520
- markSynced,
521
- markFailed,
522
- entriesFromRemote,
523
- describeError,
524
- recordQuota,
525
- readQuota,
526
- push,
527
- pull,
528
- syncNow,
529
- status,
530
- };
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{historyPath:historyPath,appendHistoryEntries:appendHistoryEntries,readHistoryEntries:readHistoryEntries,readSessionTranscript:readSessionTranscript}=require("./history.js"),{estimateTokens:estimateTokens}=require("./tokens.js"),SOURCE="aegiscode-cli",SYNC_FILE="sync-state.json",DEFAULT_LIMIT=50;function syncStatePath(){return path.join(aegisDir(),SYNC_FILE)}function loadState(){try{const t=JSON.parse(fs.readFileSync(syncStatePath(),"utf8"));if(t&&"object"==typeof t)return{sessions:t.sessions&&"object"==typeof t.sessions?t.sessions:{},lastPushAt:t.lastPushAt||null,lastPullAt:t.lastPullAt||null,importedRemoteAt:t.importedRemoteAt||{},importedRemoteCount:t.importedRemoteCount||{},quota:t.quota&&"object"==typeof t.quota?t.quota:null}}catch{}return{sessions:{},lastPushAt:null,lastPullAt:null,importedRemoteAt:{},importedRemoteCount:{},quota:null}}function readQuota(t){if(!t||"object"!=typeof t)return null;const e=null!=t.tokensUsed?t.tokensUsed:t.tokens_used,s=null!=t.tokenLimit?t.tokenLimit:t.token_limit;if(null==e||null==s)return null;const n=Number(e),o=Number(s);return Number.isFinite(n)&&Number.isFinite(o)?{used:n,limit:o}:null}function recordQuota(t,e,s){const n=Number(e),o=Number(s);return!t||!Number.isFinite(n)||!Number.isFinite(o)||o<=0?null:(t.quota={used:n,limit:o,over:n>=o,at:Date.now()},t.quota)}function saveState(t){try{fs.mkdirSync(aegisDir(),{recursive:!0});const e=syncStatePath()+".tmp";return fs.writeFileSync(e,JSON.stringify(t,null,2)+"\n"),fs.renameSync(e,syncStatePath()),!0}catch(t){return process.env.AEGIS_HIST_DEBUG&&console.error("[cloudsync] write failed:",t),!1}}function localSessions({limit:t=DEFAULT_LIMIT}={}){const e=new Map;for(const t of readHistoryEntries()){if(!t||!t.sessionId)continue;const s=e.get(t.sessionId)||{id:t.sessionId,cwd:t.cwd||"",firstPrompt:"",updatedAt:"",exchanges:0};s.exchanges+=1,!s.firstPrompt&&t.prompt&&(s.firstPrompt=String(t.prompt)),String(t.ts||"")>String(s.updatedAt||"")&&(s.updatedAt=t.ts||""),e.set(t.sessionId,s)}return[...e.values()].sort(((t,e)=>String(t.updatedAt)<String(e.updatedAt)?1:-1)).slice(0,Math.max(1,t))}function titleFor(t){return String(t&&t.firstPrompt||"").replace(/\s+/g," ").trim().slice(0,80)}function buildTranscript(t,e={}){const s=(e.transcript||readSessionTranscript(t.id)).filter((t=>t&&("user"===t.role||"assistant"===t.role))).map((t=>({role:t.role,content:String(null==t.text?"":t.text)})));return{session_id:t.id,title:null!=e.title?e.title:titleFor(t),messages:s,source:e.source||SOURCE}}function isPending(t,e){const s=e.sessions[t.id];return!s||!s.syncedAt||String(t.updatedAt||"")>String(s.localUpdatedAt||"")}function listPending(t={}){const e=t.state||loadState(),s=localSessions({...t,limit:Number.MAX_SAFE_INTEGER}).filter((t=>isPending(t,e))).reverse();return t.limit?s.slice(0,t.limit):s}function markSynced(t,e,s={}){const n=t.sessions[e]||{};return t.sessions[e]={...n,syncedAt:Date.now(),localUpdatedAt:s.localUpdatedAt||n.localUpdatedAt||"",remoteUpdatedAt:s.remoteUpdatedAt||n.remoteUpdatedAt||null,lastError:null},t.sessions[e]}function markFailed(t,e,s){const n=t.sessions[e]||{};return t.sessions[e]={...n,lastError:s,failedAt:Date.now()},t.sessions[e]}function entriesFromRemote(t,e,s=0){const n=[],o=Array.isArray(t.messages)?t.messages:[],i=s>0&&s<=o.length?o.slice(s):o;let r=null;const a=(s,o)=>{null==s&&null==o||n.push({ts:t.updated_at||e,sessionId:t.session_id,cwd:"",prompt:null==s?"":String(s),reply:null==o?"":String(o),status:"done",imported:!0,importedFrom:String(t.source||"cloud"),tokens:{input:estimateTokens(String(s||"")),output:estimateTokens(String(o||"")),cacheRead:0,cacheWrite:0,real:!1}})};for(const t of i){const e=t&&t.role,s=t&&(null!=t.content?t.content:t.text);"user"===e?(null!=r&&a(r,null),r=null==s?"":s):"assistant"!==e&&"system"!==e||(a(r,s),r=null)}return null!=r&&a(r,null),n}function describeError(t){const e=t&&(t.status||t.response&&t.response.status),s=t&&t.message||String(t);if(402===e){const n=t&&t.data||{},o=null!=n.tokensUsed?n.tokensUsed:n.sessionsUsed,i=null!=n.tokenLimit?n.tokenLimit:n.freeSessionLimit;return{kind:"quota",status:e,message:s,used:null!=o?Number(o):null,limit:null!=i?Number(i):null,hint:"the plan’s synced-token ceiling is reached — everything already stored stays readable, only NEW writes pause: /cloud memory shows the quota, /cloud memory off stops syncing"}}return 401===e?{kind:"auth",status:e,message:s,hint:"the memory token was refused — run /key <api_key> to re-exchange it"}:{kind:"error",status:e||null,message:s,hint:null}}async function push(t,e={}){const s=e.state||loadState(),n=e.limit||DEFAULT_LIMIT,o=e.sessionIds?e.sessionIds.map((t=>localSessions({limit:Number.MAX_SAFE_INTEGER,state:s}).find((e=>e.id===t)))).filter(Boolean):listPending({...e,limit:n,state:s}),i=[],r=[],a=[];for(const n of o){const o=buildTranscript(n,{});if(o.messages.length)try{const r=await t.conversationSyncPush(o),a=r&&(r.session_id||r.id)||n.id;markSynced(s,n.id,{localUpdatedAt:n.updatedAt,remoteUpdatedAt:r&&r.updated_at||(new Date).toISOString()});const l=readQuota(r);i.push({id:n.id,remoteId:a,messages:o.messages.length,title:o.title,quota:l}),l&&recordQuota(s,l.used,l.limit),"function"==typeof e.onProgress&&e.onProgress({phase:"push",id:n.id})}catch(t){const e=describeError(t);if(markFailed(s,n.id,e.message),r.push({id:n.id,...e}),"quota"!==e.kind||recordQuota(s,e.used,e.limit)||(s.quota={used:null,limit:null,over:!0,at:Date.now()}),"quota"===e.kind||"auth"===e.kind)break}else a.push({id:n.id,reason:"no messages"})}return i.length&&(s.lastPushAt=Date.now()),saveState(s),{pushed:i,failed:r,skipped:a,pending:listPending({state:s}).length}}async function pull(t,e={}){const s=e.state||loadState(),n=!1!==e.import;let o;try{o=await t.conversationSyncPull()}catch(t){return{ok:!1,sessions:[],imported:0,failed:[describeError(t)]}}const i=o&&o.sessions||[],r=[],a=(new Date).toISOString(),l=[];for(const t of i){const e=t&&t.session_id;if(!e)continue;const o=s.importedRemoteAt[e],i=Array.isArray(t.messages)?t.messages.length:0,u=Number((s.importedRemoteCount||{})[e]||0),d=!o||o!==t.updated_at||i!==u;if(n&&d){const n=entriesFromRemote(t,a,i>=u?u:0);n.length&&l.push(...n),s.importedRemoteAt[e]=t.updated_at||a,s.importedRemoteCount={...s.importedRemoteCount||{},[e]:i}}markSynced(s,e,{localUpdatedAt:t.updated_at||a,remoteUpdatedAt:t.updated_at||a}),r.push({id:e,title:t.title||"",messages:(t.messages||[]).length,source:t.source||"",updatedAt:t.updated_at||null,imported:n&&d})}const u=l.length?appendHistoryEntries(l):0;return s.lastPullAt=Date.now(),saveState(s),{ok:!0,sessions:r,remote:i.length,imported:u,failed:[]}}async function syncNow(t,e={}){const s=e.state||loadState(),n={ok:!0,push:null,pull:null};try{n.push=await push(t,{...e,state:s})}catch(t){n.ok=!1,n.push={pushed:[],failed:[describeError(t)],skipped:[]}}try{n.pull=await pull(t,{...e,state:s}),n.pull&&!1===n.pull.ok&&(n.ok=!1)}catch(t){n.ok=!1,n.pull={ok:!1,sessions:[],imported:0,failed:[describeError(t)]}}return n}function status(){const t=loadState(),e=localSessions({limit:Number.MAX_SAFE_INTEGER}),s=e.filter((e=>isPending(e,t))),n=e.filter((e=>t.sessions[e.id]&&t.sessions[e.id].lastError)).map((e=>({id:e.id,error:t.sessions[e.id].lastError}))),o=t.quota||null,i=Boolean(o&&o.over);return{local:e.length,pending:s.length,synced:e.length-s.length,lastPushAt:t.lastPushAt,lastPullAt:t.lastPullAt,importedRemote:Object.keys(t.importedRemoteAt||{}).length,errors:n,quota:o,overQuota:i,paused:i&&s.length>0,path:syncStatePath(),historyPath:historyPath()}}module.exports={SOURCE:SOURCE,syncStatePath:syncStatePath,loadState:loadState,saveState:saveState,localSessions:localSessions,titleFor:titleFor,buildTranscript:buildTranscript,isPending:isPending,listPending:listPending,markSynced:markSynced,markFailed:markFailed,entriesFromRemote:entriesFromRemote,describeError:describeError,recordQuota:recordQuota,readQuota:readQuota,push:push,pull:pull,syncNow:syncNow,status:status};