aegiscode 7.0.26 → 7.0.28
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.
- package/SOURCE-OFFER.txt +9 -0
- package/package.json +4 -7
- package/scripts/check.mjs +1 -52
- package/scripts/demo.mjs +1 -94
- package/scripts/predist.mjs +1 -75
- package/scripts/runtests.mjs +1 -56
- package/scripts/seal-gate.mjs +1 -74
- package/src/agents.js +1 -139
- package/src/app.js +1 -2957
- package/src/art.js +1 -289
- package/src/chatflow.js +1 -3023
- package/src/checkpoint.js +1 -90
- package/src/clipboard.js +1 -424
- package/src/cloudsync.js +1 -528
- package/src/commands.js +1 -4089
- package/src/config.js +1 -581
- package/src/connect.js +1 -349
- package/src/credentials.js +1 -33
- package/src/deps.js +1 -232
- package/src/devrun.js +1 -187
- package/src/diff.js +1 -333
- package/src/diffview.js +1 -296
- package/src/engine.js +1 -297
- package/src/entitlement.js +1 -355
- package/src/events.js +1 -707
- package/src/export.js +1 -67
- package/src/filepreview.js +1 -153
- package/src/fingerprint.js +1 -592
- package/src/format.js +1 -259
- package/src/fuzzy.js +1 -119
- package/src/history.js +1 -423
- package/src/init.js +1 -175
- package/src/input.js +1 -139
- package/src/keys.js +1 -183
- package/src/markdown.js +1 -306
- package/src/models.js +1 -507
- package/src/naming.js +1 -57
- package/src/overlays.js +1 -462
- package/src/panels.js +1 -1418
- package/src/ping.js +1 -226
- package/src/presence.js +1 -238
- package/src/render.js +1 -516
- package/src/screen.js +1 -518
- package/src/screens.js +1 -896
- package/src/secret.js +1 -59
- package/src/securefs.js +1 -359
- package/src/settings.js +1 -155
- package/src/shared.js +1 -52
- package/src/sharedpaths.js +1 -53
- package/src/signup.js +1 -156
- package/src/summarize.js +1 -95
- package/src/sysdiag.js +1 -585
- package/src/system.js +1 -40
- package/src/theme.js +1 -570
- package/src/title.js +1 -220
- package/src/todos.js +1 -115
- package/src/tokens.js +1 -263
- package/src/topup.js +1 -210
- package/src/update.js +1 -191
- package/vendor/client/aegis.js +1 -2441
- package/vendor/client/attest.js +1 -518
- package/vendor/client/authorship-key.js +1 -410
- package/vendor/client/auto-provision.js +1 -134
- package/vendor/client/brain-catalog.js +1 -268
- package/vendor/client/byok-catalog.js +1 -199
- package/vendor/client/catalog-client.js +1 -487
- package/vendor/client/conversation-export.js +1 -177
- package/vendor/client/credentials.js +1 -494
- package/vendor/client/device-fingerprint.js +1 -141
- package/vendor/client/drive-connect.js +1 -110
- package/vendor/client/drive-upload.js +1 -234
- package/vendor/client/env-file.js +1 -1273
- package/vendor/client/fingerprint.js +1 -1064
- package/vendor/client/foreign-memory.js +1 -669
- package/vendor/client/google-signin.js +1 -133
- package/vendor/client/hooks.js +1 -430
- package/vendor/client/model-discovery.js +1 -373
- package/vendor/client/naming.js +1 -283
- package/vendor/client/platform.js +1 -937
- package/vendor/client/prefs.js +1 -351
- package/vendor/client/presence-constants.js +1 -107
- package/vendor/client/presence.js +1 -438
- package/vendor/client/record-vault.js +3 -1055
- package/vendor/client/session-store.js +1 -575
- package/vendor/client/topup.js +1 -297
- package/vendor/client/touch.js +1 -458
- package/vendor/client/update.js +1 -763
- package/vendor/client/user-models.js +1 -381
- package/vendor/desktop/lib/local/agents.js +1 -105
- package/vendor/desktop/lib/local/attachments.js +1 -276
- package/vendor/desktop/lib/local/autonomous.js +1 -1045
- package/vendor/desktop/lib/local/claude-pro.js +1 -1028
- package/vendor/desktop/lib/local/context.js +1 -125
- package/vendor/desktop/lib/local/engine.js +1 -3666
- package/vendor/desktop/lib/local/entitlement.js +1 -660
- package/vendor/desktop/lib/local/exec-plan.js +1 -269
- package/vendor/desktop/lib/local/git-scope.js +1 -228
- package/vendor/desktop/lib/local/integrity.js +1 -163
- package/vendor/desktop/lib/local/local.js +1 -2145
- package/vendor/desktop/lib/local/prompt.js +1 -280
- package/vendor/desktop/lib/local/queue.js +1 -560
- package/vendor/desktop/lib/local/session-rounds.js +1 -238
- package/vendor/desktop/lib/local/shell.js +1 -712
- package/vendor/desktop/lib/local/spill.js +1 -75
- package/vendor/desktop/lib/local/tools.js +1 -1328
- package/vendor/desktop/lib/local/turn-guard.js +1 -300
- package/vendor/desktop/lib/local/worktree-lock.js +1 -235
- package/vendor/desktop/lib/settings.js +1 -890
- package/vendor/desktop/main.js +1 -4890
- package/vendor/desktop/renderer/usage.js +1 -1239
- package/vendor/hosts/install.js +1 -638
- package/vendor/hosts/openai-shim.js +1 -515
- package/vendor/hosts/spec.js +1 -164
- package/vendor/hosts/targets.js +1 -346
- package/vendor/mcp/server.js +1 -221
- package/vendor/mcp/tools.js +1 -408
- package/vendor/one/src/child.js +1 -285
- package/vendor/one/src/permissions.js +1 -383
package/src/cloudsync.js
CHANGED
|
@@ -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
|
-
|
|
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};
|