aegiscode 6.8.30 → 6.8.31

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.
@@ -186,10 +186,146 @@ function updateNotice({
186
186
  return { latest, behind: !!(latest && isNewer(latest, current)) };
187
187
  }
188
188
 
189
- /** One line for the welcome box, or null when there is nothing to say. */
189
+ /**
190
+ * "What happens next", from a check result — the ONE verdict every applier
191
+ * consumes (AEGISONE, decision D7).
192
+ *
193
+ * There are two *mechanics* — `npm i -g` for the CLI's channel and
194
+ * `electron-updater` for the window's — and that is deliberate: they install
195
+ * different things. What must not be duplicated is the *decision*: whether
196
+ * there is anything to do, which version it is, which applier owns it and what
197
+ * the user is told to run. Both hosts ask this function, so the sentence a
198
+ * user reads in the terminal and the sentence the window shows cannot drift.
199
+ *
200
+ * Pure: no fetch, no clock, no cache. Feed it a result from `checkPublished`
201
+ * (or from the cached `updateNotice`) and it names the next action.
202
+ *
203
+ * @param {{current: string, latest: ?string, behind: boolean, channel?: 'npm'|'desktop', pkg?: string}} input
204
+ */
205
+ function updatePlan({ current, latest, behind, channel = 'npm', pkg = PKG } = {}) {
206
+ const currentText = String(current == null ? '' : current);
207
+ const latestText = latest ? String(latest) : null;
208
+ const pending = Boolean(behind) && Boolean(latestText);
209
+ if (!pending) {
210
+ return {
211
+ channel,
212
+ current: currentText,
213
+ latest: latestText,
214
+ behind: false,
215
+ action: 'none',
216
+ applier: 'none',
217
+ instruction: null,
218
+ };
219
+ }
220
+ if (channel === 'desktop') {
221
+ // The window installs its own build: there is nothing for the user to type,
222
+ // and offering `npm i -g aegis-desktop` here would install a *second* copy
223
+ // beside the running app. The applier is the app's own updater.
224
+ return {
225
+ channel,
226
+ current: currentText,
227
+ latest: latestText,
228
+ behind: true,
229
+ action: 'desktop-update',
230
+ applier: 'electron-updater',
231
+ instruction: 'Aegis Desktop → Check for Updates…',
232
+ };
233
+ }
234
+ return {
235
+ channel,
236
+ current: currentText,
237
+ latest: latestText,
238
+ behind: true,
239
+ action: 'npm-update',
240
+ applier: 'npm',
241
+ instruction: `npm i -g ${pkg}@latest`,
242
+ };
243
+ }
244
+
245
+ /**
246
+ * The same once-a-day check as `updateNotice`, but *awaited* and detailed.
247
+ *
248
+ * Why both exist: `updateNotice` answers immediately from cache and lets the
249
+ * refresh land later, which is right for a CLI that must never block a launch.
250
+ * A host that is *showing the user a banner about it* — the window, or
251
+ * `aegis doctor` — needs the full result (`.ok`, `.reason`, `.status`) and is
252
+ * willing to wait for it. So this is not a second check: it is the same probe
253
+ * (`fetchLatestDetailed`, same `TIMEOUT_MS`, same `REASONS` taxonomy) and the
254
+ * same `CHECK_INTERVAL_MS` cache rule, extracted so that the desktop applier
255
+ * stops carrying its own copy of the fetching logic (D7: the desktop keeps its
256
+ * applier and loses its version fetch).
257
+ *
258
+ * Never throws: a failure is a result with `ok: false` and a reason.
259
+ *
260
+ * @returns {Promise<{ok: boolean, latest: ?string, behind: boolean, reason: ?string,
261
+ * status: ?number, cached: boolean, checkedAt: ?number}>}
262
+ */
263
+ async function checkPublished({
264
+ current,
265
+ cache,
266
+ save,
267
+ now = Date.now(),
268
+ fetchImpl = fetchLatestDetailed,
269
+ intervalMs = CHECK_INTERVAL_MS,
270
+ timeoutMs = TIMEOUT_MS,
271
+ pkg = PKG,
272
+ } = {}) {
273
+ const c = cache || null;
274
+ const fresh = Boolean(c) && typeof c.checkedAt === 'number' && now - c.checkedAt < intervalMs;
275
+ if (fresh) {
276
+ const latest = c.latest || null;
277
+ return {
278
+ ok: Boolean(latest),
279
+ latest,
280
+ behind: !!(latest && isNewer(latest, current)),
281
+ reason: latest ? null : c.reason || null,
282
+ status: latest ? 200 : c.status == null ? null : c.status,
283
+ cached: true,
284
+ checkedAt: c.checkedAt,
285
+ };
286
+ }
287
+
288
+ let res;
289
+ try {
290
+ res = await fetchImpl({ pkg, timeoutMs });
291
+ } catch (err) {
292
+ res = { ok: false, latest: null, reason: REASONS.NETWORK, status: null, error: String((err && err.message) || err) };
293
+ }
294
+ const record = {
295
+ checkedAt: now,
296
+ latest: res && res.latest ? res.latest : null,
297
+ reason: (res && res.reason) || null,
298
+ status: res && res.status != null ? res.status : null,
299
+ };
300
+ if (typeof save === 'function') {
301
+ try {
302
+ save(record);
303
+ } catch {
304
+ /* failing to persist a notice is never worth failing the call */
305
+ }
306
+ }
307
+ return {
308
+ ok: Boolean(res && res.ok && res.latest),
309
+ latest: record.latest,
310
+ behind: !!(record.latest && isNewer(record.latest, current)),
311
+ reason: record.reason,
312
+ status: record.status,
313
+ cached: false,
314
+ checkedAt: now,
315
+ };
316
+ }
317
+
318
+ /**
319
+ * One line for the welcome box, or null when there is nothing to say.
320
+ *
321
+ * Rendered from `updatePlan`, not from a second copy of the sentence: the
322
+ * command the terminal tells the user to run and the command the window's
323
+ * banner offers are the same string produced by the same verdict.
324
+ */
190
325
  function updateLine({ current, latest, behind, pkg = PKG }) {
191
- if (!behind) return null;
192
- return `Update available: ${current} → ${latest} run: npm i -g ${pkg}@latest`;
326
+ const plan = updatePlan({ current, latest, behind, channel: 'npm', pkg });
327
+ if (plan.action !== 'npm-update') return null;
328
+ return `Update available: ${plan.current} → ${plan.latest} run: ${plan.instruction}`;
193
329
  }
194
330
 
195
331
  module.exports = {
@@ -198,6 +334,8 @@ module.exports = {
198
334
  fetchLatestDetailed,
199
335
  isTransientReason,
200
336
  updateNotice,
337
+ checkPublished,
338
+ updatePlan,
201
339
  updateLine,
202
340
  PKG,
203
341
  CHECK_INTERVAL_MS,
@@ -0,0 +1,92 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * context.js — token-budget trimmer for very large inputs (plan P1 §5.1 /
5
+ * P2 §6.4).
6
+ *
7
+ * Pure Node, no Electron imports. Estimates tokens with a ~4 chars/token
8
+ * heuristic, keeps the system message plus the newest turns, and drops the
9
+ * oldest turns that exceed the budget. The full transcript always stays in
10
+ * the local session record — this only trims what is sent to the wire.
11
+ */
12
+
13
+ const CHARS_PER_TOKEN = 4;
14
+ const MESSAGE_OVERHEAD = 4; // per-message framing + role overhead
15
+
16
+ /** Rough token count for a string (no tokenizer in a zero-dep shell). */
17
+ function estimateTokens(text) {
18
+ if (text == null) return 0;
19
+ const s = typeof text === 'string' ? text : String(text);
20
+ return Math.max(0, Math.ceil(s.length / CHARS_PER_TOKEN));
21
+ }
22
+
23
+ /** Rough token cost of one { role, content } message. */
24
+ function messageTokens(message) {
25
+ if (!message) return 0;
26
+ const content =
27
+ message.content != null
28
+ ? message.content
29
+ : message.text != null
30
+ ? message.text
31
+ : '';
32
+ return MESSAGE_OVERHEAD + estimateTokens(content);
33
+ }
34
+
35
+ /**
36
+ * Trim a message list to fit a token budget, keeping the newest turns.
37
+ *
38
+ * @param {object} opts
39
+ * @param {Array<{role:string,content:string}>} [opts.messages=[]]
40
+ * @param {string} [opts.system='']
41
+ * @param {number} [opts.budgetTokens=8192] total tokens allowed on the wire
42
+ * @param {number} [opts.reserveTokens=0] tokens reserved for the reply
43
+ * @param {number} [opts.fixedTokens=0] wire cost that is NOT a message and
44
+ * cannot be dropped (the tool schemas), counted before any turn is kept
45
+ * @returns {{messages:Array, system:string, dropped:number, estimatedTokens:number, fixedTokens:number}}
46
+ */
47
+ function trimContext({
48
+ messages = [],
49
+ system = '',
50
+ budgetTokens = 8192,
51
+ reserveTokens = 0,
52
+ fixedTokens = 0,
53
+ } = {}) {
54
+ const limit = Math.max(0, budgetTokens - reserveTokens);
55
+ const kept = [];
56
+ // Tool schemas go on the wire every round and cannot be trimmed away, so they
57
+ // are charged against the budget FIRST. Without this the trimmer believed a
58
+ // 4096-token window had 4096 tokens for history when the schemas had already
59
+ // spent ~1971 of them (measured: 10 schemas, 7882 chars) — and the daemon,
60
+ // run with `--context-shift`, discarded the SYSTEM row to make room instead
61
+ // of erroring. Counting them here is what keeps the system row alive.
62
+ const fixed = Math.max(0, Number(fixedTokens) || 0);
63
+ let used = fixed;
64
+
65
+ if (system) used += MESSAGE_OVERHEAD + estimateTokens(system);
66
+
67
+ // Walk newest -> oldest; keep a turn if it fits, else stop (older turns are
68
+ // even less relevant). Always keep at least the newest turn so a single
69
+ // oversized message is still sent rather than silently emptied.
70
+ for (let i = messages.length - 1; i >= 0; i--) {
71
+ const cost = messageTokens(messages[i]);
72
+ if (used + cost > limit && kept.length > 0) break;
73
+ kept.unshift(messages[i]);
74
+ used += cost;
75
+ }
76
+
77
+ return {
78
+ messages: kept,
79
+ system,
80
+ dropped: messages.length - kept.length,
81
+ estimatedTokens: used,
82
+ fixedTokens: fixed,
83
+ };
84
+ }
85
+
86
+ module.exports = {
87
+ CHARS_PER_TOKEN,
88
+ MESSAGE_OVERHEAD,
89
+ estimateTokens,
90
+ messageTokens,
91
+ trimContext,
92
+ };
@@ -2114,6 +2114,18 @@ function createLocalEngine({
2114
2114
  return { ok: Boolean(controller) };
2115
2115
  }
2116
2116
 
2117
+ /**
2118
+ * Unload every local model this engine warmed, across every daemon it
2119
+ * talked to (local.js `unloadAll`). The desktop host calls this on its quit
2120
+ * path so closing the app also closes the model — the local lane bills
2121
+ * nothing precisely because it is YOUR hardware, and hardware left running
2122
+ * a model nobody is using anymore after the app exits is the one cost that
2123
+ * lane was supposed to never have.
2124
+ */
2125
+ function unloadLocalModels() {
2126
+ return localT.unloadAll();
2127
+ }
2128
+
2117
2129
  return {
2118
2130
  CLASSES,
2119
2131
  listClasses,
@@ -2123,6 +2135,7 @@ function createLocalEngine({
2123
2135
  respondApproval,
2124
2136
  clearSessionApprovals,
2125
2137
  settings,
2138
+ unloadLocalModels,
2126
2139
  };
2127
2140
  }
2128
2141