aegiscode 6.8.2 → 6.8.4

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/src/title.js ADDED
@@ -0,0 +1,217 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The terminal title bar — the session's *topic*.
5
+ *
6
+ * Claude Code keeps the window/tab title pointed at what the session is about
7
+ * ("✳ Fixing the nexus hang") rather than at a static product string, so a row
8
+ * of terminal tabs is readable at a glance. This host shipped the static half
9
+ * only: `chatflow.js`'s `setTitle()` wrote "AEGIS Code" forever, spinning a
10
+ * braille frame while a turn ran and never naming the work. Every tab of every
11
+ * session read the same, which is exactly the problem the topic solves.
12
+ *
13
+ * The topic is derived from the user's own prompt, locally — no model call, so
14
+ * it costs nothing, adds no latency to the first frame, and cannot invent a
15
+ * task the user never asked for. It is re-derived per prompt and adopted only
16
+ * when the ask is about something new (`adoptTopic`), so a follow-up like
17
+ * "now add a test for that" keeps the title it inherited.
18
+ *
19
+ * Everything here is pure and returns strings, so the whole surface is
20
+ * assertable without a TTY; `writeTitle` is the one function that touches a
21
+ * stream, and it swallows a non-writable one.
22
+ */
23
+
24
+ /** The title the app wears before a topic exists (and after one is cleared). */
25
+ const DEFAULT_TITLE = 'AEGIS Code';
26
+
27
+ /** The braille frames the title spins while a turn runs (the reference's). */
28
+ const TITLE_SPIN = ['⠐', '⠂', '⠄', '⠆', '⠈', '⠠', '⠰', '⠁'];
29
+
30
+ /** Longest topic, in cells, before it is clipped on a word boundary. */
31
+ const TOPIC_MAX = 48;
32
+
33
+ /** Longest string that ever reaches the terminal (topic + " · AEGIS Code"). */
34
+ const TITLE_MAX = 96;
35
+
36
+ /**
37
+ * Politeness and throat-clearing, stripped from the front of a prompt so the
38
+ * title says "Add a retry to the fetcher" instead of "Please can you add a
39
+ * retry to the fetcher". Applied repeatedly — "ok so please can you…" is one
40
+ * habit, not four.
41
+ */
42
+ const FILLER =
43
+ /^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and|i'?m trying to|i am trying to|i'?m working on|i am working on)\b[\s,:;-]*/i;
44
+
45
+ /** Leading markdown/list/quote noise: `> `, `- `, `1. `, `## `. */
46
+ const LEADING_NOISE = /^(?:[>#*•·\-–—]+|\d+[.)])\s*/;
47
+
48
+ /** Words that carry no topic signal when comparing two asks. */
49
+ const STOPWORDS = new Set([
50
+ 'the', 'and', 'for', 'with', 'that', 'this', 'these', 'those', 'you', 'your', 'yours',
51
+ 'can', 'could', 'would', 'should', 'will', 'please', 'pls', 'hey', 'now', 'then',
52
+ 'from', 'into', 'onto', 'over', 'under', 'about', 'also', 'just', 'like', 'want',
53
+ 'need', 'make', 'made', 'use', 'using', 'get', 'got', 'let', 'lets', 'its', 'it',
54
+ 'are', 'was', 'were', 'been', 'has', 'have', 'had', 'but', 'not', 'all', 'any',
55
+ 'how', 'what', 'when', 'where', 'which', 'who', 'why', 'there', 'here', 'some',
56
+ 'one', 'two', 'add', 'new', 'fix', 'fixing', 'help', 'doing', 'does', 'did', 'me',
57
+ 'my', 'our', 'we', 'i', 'a', 'an', 'to', 'of', 'in', 'on', 'at', 'is', 'be', 'do',
58
+ ]);
59
+
60
+ /** Strip anything that could break out of the OSC title sequence. */
61
+ function sanitize(text, max = TITLE_MAX) {
62
+ const flat = String(text == null ? '' : text)
63
+ // Control chars (including ESC, BEL, CR, LF, TAB) become a space, so a
64
+ // prompt can never inject an escape sequence into the title bar — the one
65
+ // place in this UI where user text reaches the terminal unsanitized.
66
+ .replace(/[\u0000-\u001f\u007f]/g, ' ')
67
+ .replace(/\s+/g, ' ')
68
+ .trim();
69
+ if (flat.length <= max) return flat;
70
+ return `${flat.slice(0, Math.max(0, max - 1)).trimEnd()}…`;
71
+ }
72
+
73
+ /**
74
+ * A short, single-line topic for a user prompt.
75
+ *
76
+ * Uses the first line that has anything on it (a pasted block's first line is
77
+ * its subject), drops politeness and list noise, collapses whitespace, and
78
+ * clips on a word boundary with an ellipsis. Returns '' when there is nothing
79
+ * to say — the caller then keeps the title it already had.
80
+ */
81
+ function topicFrom(text, { max = TOPIC_MAX } = {}) {
82
+ if (text == null) return '';
83
+ const lines = String(text).split(/[\r\n]+/);
84
+ let line = '';
85
+ for (const raw of lines) {
86
+ const cleaned = sanitize(raw, 4_000).replace(LEADING_NOISE, '').trim();
87
+ // A pasted block's fence marker is not the topic; the code under it is.
88
+ if (!cleaned || /^```/.test(cleaned)) continue;
89
+ line = cleaned;
90
+ break;
91
+ }
92
+ if (!line) return '';
93
+ let body = line;
94
+ for (let i = 0; i < 6; i++) {
95
+ const next = body.replace(FILLER, '');
96
+ if (next === body) break;
97
+ body = next.replace(LEADING_NOISE, '').trim();
98
+ }
99
+ body = body.replace(/[.!?]+$/, '').trim();
100
+ if (!body) body = line;
101
+ if (/^[a-z]/.test(body)) body = body[0].toUpperCase() + body.slice(1);
102
+ return sanitize(body, max);
103
+ }
104
+
105
+ /** Topic-defining words of a phrase: lowercase, deduped, stopwords dropped. */
106
+ function keywords(phrase) {
107
+ const out = new Set();
108
+ for (const word of String(phrase || '').toLowerCase().match(/[\p{L}\p{N}_]+/gu) || []) {
109
+ if (word.length < 3 || STOPWORDS.has(word)) continue;
110
+ out.add(word);
111
+ }
112
+ return [...out];
113
+ }
114
+
115
+ /**
116
+ * Does `next` read as a *different* task from `prev`?
117
+ *
118
+ * The overlap is measured against the shorter keyword set, so a long follow-up
119
+ * that repeats the subject ("also add a test for the config loader") is not
120
+ * mistaken for a new task, while a genuinely unrelated ask ("now write the
121
+ * changelog") is. An empty `next` is never a shift — it means "no topic", and
122
+ * the caller keeps what it had.
123
+ */
124
+ function titleShift(prev, next, { threshold = 0.34 } = {}) {
125
+ if (!next) return false;
126
+ if (!prev) return true;
127
+ const a = keywords(prev);
128
+ const b = keywords(next);
129
+ if (!a.length || !b.length) return true;
130
+ const set = new Set(a);
131
+ let hits = 0;
132
+ for (const word of b) if (set.has(word)) hits++;
133
+ return hits / Math.min(a.length, b.length) < threshold;
134
+ }
135
+
136
+ /** The topic after this prompt: the new one only when it is a new task. */
137
+ function adoptTopic(prev, prompt, opts) {
138
+ const next = topicFrom(prompt);
139
+ if (!next) return prev || '';
140
+ return titleShift(prev, next, opts) ? next : prev || '';
141
+ }
142
+
143
+ /**
144
+ * The composed title.
145
+ *
146
+ * working, with topic `⠂ Fixing the config loader`
147
+ * idle, with topic `Fixing the config loader · AEGIS Code`
148
+ * no topic `AEGIS Code`
149
+ *
150
+ * The idle form keeps the product name so a tab is still identifiable as this
151
+ * CLI; the working form is the topic alone, which is what Claude Code shows
152
+ * while a turn runs.
153
+ */
154
+ function titleText({ topic = '', frame = null, app = DEFAULT_TITLE } = {}) {
155
+ const clean = sanitize(topic, TOPIC_MAX);
156
+ if (!clean) return sanitize(app, TITLE_MAX) || DEFAULT_TITLE;
157
+ const head = frame ? `${frame} ` : '';
158
+ return sanitize(frame ? `${head}${clean}` : `${clean} · ${app}`, TITLE_MAX);
159
+ }
160
+
161
+ /** Truthiness for the env flags: `1`, `true`, `yes`, `on` (any case). */
162
+ function flagOn(value) {
163
+ if (value === true) return true;
164
+ if (value == null || value === false) return false;
165
+ return /^(?:1|true|yes|on)$/i.test(String(value).trim());
166
+ }
167
+
168
+ /**
169
+ * Is the title bar ours to write?
170
+ *
171
+ * On by default — a title that follows the work is the feature. Off via
172
+ * `AEGIS_DISABLE_TERMINAL_TITLE=1` (and Claude Code's own
173
+ * `CLAUDE_CODE_DISABLE_TERMINAL_TITLE`, so a shell configured for the
174
+ * reference behaves the same here), or `terminalTitle: false` in config.json.
175
+ * `AEGIS_TERMINAL_TITLE=1` wins over the config, for a one-off run.
176
+ */
177
+ function titleEnabled(env = {}, config = {}) {
178
+ const e = env || {};
179
+ if (flagOn(e.AEGIS_TERMINAL_TITLE)) return true;
180
+ if (flagOn(e.AEGIS_DISABLE_TERMINAL_TITLE)) return false;
181
+ if (flagOn(e.CLAUDE_CODE_DISABLE_TERMINAL_TITLE)) return false;
182
+ const cfg = config || {};
183
+ if (cfg.terminalTitle === false || cfg.terminalTitleBar === false) return false;
184
+ return true;
185
+ }
186
+
187
+ /**
188
+ * Write one title to a stream as an OSC 0 sequence. `''` clears it (what the
189
+ * teardown wants, so the shell that gets the terminal back is not left wearing
190
+ * this app's title). Never throws: a stubbed, closed or non-TTY stream is a
191
+ * missing nicety, not a reason to lose a turn.
192
+ */
193
+ function writeTitle(text, out) {
194
+ const stream = out || process.stdout;
195
+ if (!stream || typeof stream.write !== 'function') return false;
196
+ try {
197
+ stream.write(`\x1b]0;${sanitize(text, TITLE_MAX)}\x07`);
198
+ return true;
199
+ } catch {
200
+ return false;
201
+ }
202
+ }
203
+
204
+ module.exports = {
205
+ DEFAULT_TITLE,
206
+ TITLE_SPIN,
207
+ TOPIC_MAX,
208
+ TITLE_MAX,
209
+ sanitize,
210
+ topicFrom,
211
+ keywords,
212
+ titleShift,
213
+ adoptTopic,
214
+ titleText,
215
+ titleEnabled,
216
+ writeTitle,
217
+ };
package/src/tokens.js CHANGED
@@ -3,92 +3,36 @@
3
3
  /**
4
4
  * Token + cost estimation. Tokens are estimated from text length (~4
5
5
  * chars/token, the usual rule of thumb) and priced against the per-model rates
6
- * below. Everything is labeled approximate in the UI.
6
+ * in the SHARED table. Everything is labeled approximate in the UI.
7
7
  *
8
- * Ported from aegiscodex-dev/src/tokens.js (ESM → CommonJS).
8
+ * The rate table itself is not here — see the block below.
9
9
  */
10
10
 
11
- // Per-million-token USD rates. Cache-read/write matter for long sessions.
11
+ // ── The rate table is NOT defined here ─────────────────────────────────────
12
12
  //
13
- // These are the PROVIDER's rates, for the fallback path where a turn has no
14
- // server-settled charge (a direct provider, ollama, a custom endpoint). A
15
- // pooled turn reports the ledger figure instead — see accountingFromUsage's
16
- // `costUsd` — because the pool's bill carries a margin and a prompt-cache
17
- // discount this table cannot see.
13
+ // This file used to carry its own copy of `RATES`, and that copy is how the
14
+ // DeepSeek row came to be wrong in one host and right in the other: the table
15
+ // existed twice (here and desktop/renderer/usage.js), so a rate read off the
16
+ // vendor's pricing page reached whichever copy someone happened to edit. The
17
+ // CLI's copy still said $0.14/$0.28 — the retired V4-Flash tier — while the
18
+ // desktop's had been corrected, and `/cost` would have disagreed with the GUI
19
+ // about the same turn on the same engine.
18
20
  //
19
- // Keys are matched by exact id first, then by prefix (ratesFor below), so a
20
- // family row covers every dated variant of it.
21
- const RATES = {
22
- sonnet: { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
23
- default: { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
24
- fable: { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
25
- opus: { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
26
- // DeepSeek V4 — the provider's published rate, independently corroborated by
27
- // aegis1 services/nexus_provider/catalog.py (cost_per_1k_input=0.00014,
28
- // cost_per_1k_output=0.00028) and referenced in services/pricing.py.
29
- //
30
- // This row was MISSING, and usageCost fell through to RATES.sonnet for every
31
- // DeepSeek turn: $3.00/$15.00 per M against a real $0.14/$0.28 — 21x the
32
- // input rate and 54x the output rate, on every direct DeepSeek call. That is
33
- // the number that made a local turn look like it cost a fraction of the
34
- // cloud's, when most of the reported gap was the meter itself.
35
- //
36
- // cacheRead is 0.1x input (aegis1 services/pricing.py
37
- // CACHE_READ_FRACTION_BY_COMPANY["deepseek"] = 0.1 -> $0.014/M).
38
- // cacheWrite is the input rate: DeepSeek bills a cache write as ordinary
39
- // input tokens and charges no separate write premium, unlike Anthropic's
40
- // 1.25x. A zero here would understate a session that writes cache.
41
- deepseek: { input: 0.14, output: 0.28, cacheRead: 0.014, cacheWrite: 0.14 },
42
- };
21
+ // So the table lives in exactly one place. `desktop/renderer/usage.js` is
22
+ // already the declared single source of truth for turning a provider's usage
23
+ // object into a display number (cli/src/deps.js resolves it, and
24
+ // test/cli-tools.test.mjs asserts the function identity), so the rates belong
25
+ // there too rather than in a second table that can only drift.
26
+ //
27
+ // `sharedpaths.js` is used rather than `deps.js` because deps.js eagerly
28
+ // requires the engine, the client and the tool registry — pulling all of that
29
+ // in to read a number would be a require cycle for anything in that graph.
30
+ const path = require('node:path');
43
31
 
44
- /**
45
- * Rate rows a model id may name as a whole word rather than as a prefix.
46
- * Anthropic spells its family *inside* the id — "claude-opus-4" matches no
47
- * prefix — so prefix matching alone cannot see it.
48
- */
49
- const RATE_FAMILIES = Object.keys(RATES).filter((k) => k !== 'default');
32
+ const { resolveShared } = require('./sharedpaths.js');
33
+ const shared = require(resolveShared(path.join('desktop', 'renderer', 'usage.js')));
50
34
 
51
- /**
52
- * The rate row for a model id, provider, or alias. Exact id wins, then the
53
- * longest matching prefix, then a family named inside the id, then the
54
- * Sonnet-class default — the same resolution order contextWindowFor uses, so
55
- * the cost meter and the context meter cannot disagree about which family a
56
- * model belongs to.
57
- */
58
- function ratesFor(model) {
59
- const raw = String(model || '').toLowerCase();
60
- if (!raw) return RATES.default;
61
- // `/class byok` selects a "provider:model" id, and the provider half is a
62
- // routing label, not a rate: rating it as written fell through every prefix
63
- // to RATES.default, so an Opus BYOK turn was priced at Sonnet's $3/$15
64
- // against the vendor's real $5/$25.
65
- const ids = [raw];
66
- const tail = raw.slice(raw.lastIndexOf(':') + 1);
67
- if (tail && tail !== raw) ids.push(tail);
68
- for (const id of ids) {
69
- if (RATES[id]) return RATES[id];
70
- let best = null;
71
- let bestLen = 0;
72
- for (const [prefix, rates] of Object.entries(RATES)) {
73
- if (id.startsWith(prefix) && prefix.length > bestLen) {
74
- best = rates;
75
- bestLen = prefix.length;
76
- }
77
- }
78
- if (best) return best;
79
- }
80
- // Longest family-key hit wins, so an overlapping pair resolves the same way
81
- // twice running rather than by object key order.
82
- let family = null;
83
- let familyLen = 0;
84
- for (const key of RATE_FAMILIES) {
85
- if (raw.includes(key) && key.length > familyLen) {
86
- family = RATES[key];
87
- familyLen = key.length;
88
- }
89
- }
90
- return family || RATES.default;
91
- }
35
+ const { RATES, RATE_BASIS, UNPRICED_BY_DESIGN, isPeak, ratesFor, costBreakdown, cacheHitRate } = shared;
92
36
 
93
37
  // System prompt + tool definitions overhead, roughly, in tokens.
94
38
  const SYSTEM_TOKENS = 18000;
@@ -127,11 +71,11 @@ const CONTEXT_WINDOWS = {
127
71
  function contextWindowFor(model) {
128
72
  const raw = String(model || '').toLowerCase();
129
73
  if (!raw) return CONTEXT_WINDOW;
130
- // Same two-candidate lookup as ratesFor above, for the same reason: a byok
131
- // id ("deepseek:deepseek-v4-flash") carries a routing label in front of the
132
- // model, and matching it as written left the 1M-token DeepSeek window reading
133
- // as the 200k default — a meter that would have told a user they were at 20%
134
- // of a context that was 4% full.
74
+ // Same two-candidate lookup as ratesFor in the shared table, for the same
75
+ // reason: a byok id ("deepseek:deepseek-v4-flash") carries a routing label in
76
+ // front of the model, and matching it as written left the 1M-token DeepSeek
77
+ // window reading as the 200k default — a meter that would have told a user
78
+ // they were at 20% of a context that was 4% full.
135
79
  const ids = [raw];
136
80
  const tail = raw.slice(raw.lastIndexOf(':') + 1);
137
81
  if (tail && tail !== raw) ids.push(tail);
@@ -168,14 +112,24 @@ function transcriptUsage(transcript, model = 'sonnet') {
168
112
  return { input, output, cacheRead, cacheWrite };
169
113
  }
170
114
 
171
- /** Dollar cost of a usage record at the given model's rates. */
172
- function usageCost(usage, model = 'sonnet') {
173
- const r = ratesFor(model);
174
- const toD = (n, rate) => (n / 1_000_000) * rate;
175
- return toD(usage.input, r.input)
176
- + toD(usage.output, r.output)
177
- + toD(usage.cacheRead, r.cacheRead)
178
- + toD(usage.cacheWrite, r.cacheWrite);
115
+ /**
116
+ * Dollar cost of a usage record at the given model's rates.
117
+ *
118
+ * Returns a number for backward compatibility, but the basis is not lost: use
119
+ * `costBreakdown` when the caller needs to know whether the figure is real.
120
+ * (`usageCost` in the shared module, which also folds the record through
121
+ * `usageBuckets` first — so a wire usage object is normalized identically in
122
+ * both hosts, where this file's old copy read `usage.input` directly.)
123
+ *
124
+ * `model` has no `= 'sonnet'` default here either, and that matters for more
125
+ * than tidiness: a default parameter in THIS file would re-introduce exactly
126
+ * the split the shared module just removed, and only on the CLI side — so
127
+ * `usageCost(u)` would report `basis: 'exact'` in the terminal and
128
+ * `basis: 'default'` in the GUI for the same turn on the same engine. The
129
+ * whole point of delegating is that both hosts answer identically.
130
+ */
131
+ function usageCost(usage, model, opts = {}) {
132
+ return shared.usageCost(usage, model, opts);
179
133
  }
180
134
 
181
135
  /** Full session accounting: per-bucket tokens, cost, and context used %. */
@@ -186,6 +140,14 @@ function sessionAccounting(transcript, model = 'sonnet') {
186
140
  const history = usage.input + usage.output;
187
141
  const used = system + tools + history;
188
142
  const contextWindow = contextWindowFor(model);
143
+ // ONE breakdown, not a cost call plus a separate basis call: ratesFor reads
144
+ // the wall clock for peak/off-peak, so two evaluations straddling a peak
145
+ // boundary would report a peak cost with an off-peak basis (or vice versa) —
146
+ // two different claims about the same number, which is the thing this return
147
+ // shape exists to prevent. aegiscodex-dev's sessionAccounting is written the
148
+ // same way; if one host folds this into two calls again the two will disagree
149
+ // about the same turn, which is how the rate table split in the first place.
150
+ const breakdown = costBreakdown(usage, model);
189
151
  return {
190
152
  usage,
191
153
  system,
@@ -194,7 +156,12 @@ function sessionAccounting(transcript, model = 'sonnet') {
194
156
  used,
195
157
  contextWindow,
196
158
  pct: Math.min(100, Math.round((used / contextWindow) * 100)),
197
- cost: usageCost(usage, model),
159
+ cost: breakdown.cost,
160
+ // Which rate row priced this. 'default' means the model is unpriced and
161
+ // `cost` is a Sonnet-class placeholder — surfaced rather than swallowed so
162
+ // /cost can label it instead of printing a fabricated figure.
163
+ costBasis: breakdown.basis,
164
+ costPriced: breakdown.priced,
198
165
  };
199
166
  }
200
167
 
@@ -204,8 +171,9 @@ function sessionAccounting(transcript, model = 'sonnet') {
204
171
  * already includes system prompt + tools in cacheRead, so `used` counts
205
172
  * input + output + cache instead of re-adding the constants.
206
173
  */
207
- function accountingFromUsage(usage, model = 'sonnet', { exchanges = 0, real = false, costUsd } = {}) {
208
- const cost = typeof costUsd === 'number' ? costUsd : usageCost(usage, model);
174
+ function accountingFromUsage(usage, model = 'sonnet', { exchanges = 0, real = false, costUsd, at } = {}) {
175
+ const breakdown = costBreakdown(usage, model, { at });
176
+ const cost = typeof costUsd === 'number' ? costUsd : breakdown.cost;
209
177
  const used = real
210
178
  ? usage.input + usage.output + usage.cacheRead + usage.cacheWrite
211
179
  : SYSTEM_TOKENS + TOOL_TOKENS + usage.input + usage.output;
@@ -219,6 +187,12 @@ function accountingFromUsage(usage, model = 'sonnet', { exchanges = 0, real = fa
219
187
  contextWindow,
220
188
  pct: Math.min(100, Math.round((used / contextWindow) * 100)),
221
189
  cost,
190
+ // A settled charge (costUsd) is the ledger's own truth, so it is 'settled'
191
+ // rather than a table match — the pool's bill carries a margin and a
192
+ // prompt-cache discount the table cannot see, so the two must never be
193
+ // conflated.
194
+ costBasis: typeof costUsd === 'number' ? 'settled' : breakdown.basis,
195
+ costPriced: typeof costUsd === 'number' ? true : breakdown.priced,
222
196
  exchanges,
223
197
  real,
224
198
  };
@@ -235,12 +209,17 @@ function fmtCost(d) {
235
209
 
236
210
  module.exports = {
237
211
  RATES,
212
+ RATE_BASIS,
213
+ UNPRICED_BY_DESIGN,
214
+ isPeak,
238
215
  SYSTEM_TOKENS,
239
216
  TOOL_TOKENS,
240
217
  CONTEXT_WINDOW,
241
218
  CONTEXT_WINDOWS,
242
219
  contextWindowFor,
243
220
  ratesFor,
221
+ costBreakdown,
222
+ cacheHitRate,
244
223
  estimateTokens,
245
224
  transcriptUsage,
246
225
  usageCost,
package/src/update.js CHANGED
@@ -7,7 +7,81 @@
7
7
  * the same thing for `aegis-desktop`: two hosts, two package names, one
8
8
  * checker. Resolved through deps.js so the in-repo and published-vendor
9
9
  * layouts both work.
10
+ *
11
+ * On top of the shared checker this module carries the three pieces /upgrade
12
+ * needs — `compareVersions`, `upgradeAdvice` and `latestPublishedVersion` —
13
+ * ported from the reference (`aegiscodex-dev/src/session.js`). They belong
14
+ * here, next to `isNewer`/`updateLine`, so the CLI has ONE idea of "is there a
15
+ * newer published version": the welcome-box notice and /upgrade now answer
16
+ * from the same place and compare versions the same way. The shared module's
17
+ * own functions are spread through unchanged, keeping the identity the
18
+ * update-channel test pins (the shim and the shared file must be the SAME
19
+ * code, not a copy).
10
20
  */
11
21
 
22
+ const { execFileSync } = require('node:child_process');
23
+
12
24
  const { resolveShared } = require('./deps.js');
13
- module.exports = require(resolveShared('client/update.js'));
25
+
26
+ const shared = require(resolveShared('client/update.js'));
27
+
28
+ const VERSION = require('../package.json').version;
29
+ /** Both hosts publish from npm; the CLI is `aegiscode`. */
30
+ const PKG = shared.PKG || 'aegiscode';
31
+
32
+ // ── /upgrade ─────────────────────────────────────────────────────────────────
33
+
34
+ /** Compare two dotted version strings: -1 | 0 | 1 (prerelease tags ignored). */
35
+ function compareVersions(a, b) {
36
+ const pa = String(a || '0').split('-')[0].split('.').map((n) => Number.parseInt(n, 10) || 0);
37
+ const pb = String(b || '0').split('-')[0].split('.').map((n) => Number.parseInt(n, 10) || 0);
38
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
39
+ const d = (pa[i] || 0) - (pb[i] || 0);
40
+ if (d) return d > 0 ? 1 : -1;
41
+ }
42
+ return 0;
43
+ }
44
+
45
+ /** What /upgrade should say, given the local and published versions. */
46
+ function upgradeAdvice({ current = VERSION, latest = null, packageName = PKG } = {}) {
47
+ if (!latest) {
48
+ return {
49
+ upToDate: null,
50
+ lines: [` Could not read the npm registry — local version is ${current}.`],
51
+ };
52
+ }
53
+ const cmp = compareVersions(latest, current);
54
+ if (cmp > 0) {
55
+ return {
56
+ upToDate: false,
57
+ lines: [
58
+ ` Installed: ${current}`,
59
+ ` Published: ${latest}`,
60
+ ` Upgrade: npm i -g ${packageName}@latest`,
61
+ ],
62
+ };
63
+ }
64
+ return {
65
+ upToDate: true,
66
+ lines: [` Installed ${current} is the published ${latest} — nothing to upgrade.`],
67
+ };
68
+ }
69
+
70
+ /** Best-effort registry lookup (5s cap). Returns a version string or null. */
71
+ function latestPublishedVersion({ packageName = PKG, timeoutMs = 5000 } = {}) {
72
+ try {
73
+ const out = execFileSync('npm', ['view', packageName, 'version'], {
74
+ encoding: 'utf8', timeout: timeoutMs, stdio: ['ignore', 'pipe', 'ignore'],
75
+ });
76
+ const v = String(out).trim();
77
+ return /^\d+\.\d+\.\d+/.test(v) ? v : null;
78
+ } catch { return null; }
79
+ }
80
+
81
+ module.exports = {
82
+ ...shared,
83
+ VERSION,
84
+ compareVersions,
85
+ upgradeAdvice,
86
+ latestPublishedVersion,
87
+ };
@@ -437,6 +437,18 @@ function createLocalEngine({
437
437
  settings,
438
438
  tools,
439
439
  promptBuilder,
440
+ // Phase 20 — the level's recall breadth, injected by the host that owns the
441
+ // avatar ledger (desktop/main.js builds one from lib/avatar/turn.js). It is a
442
+ // SEAM rather than a call into lib/avatar/* because this engine is shared with
443
+ // the CLI (cli/src/deps.js loads this file): the engine must not grow a
444
+ // dependency on the desktop's avatar directory, and a host with no avatar
445
+ // simply passes nothing and gets the exact pre-Phase-20 turn.
446
+ //
447
+ // `recallProvider({ payload, env, system })` may be sync or async and returns
448
+ // either the final system prompt or `{ system }`. It runs once per turn,
449
+ // before the first dispatch, and its result is the system prompt every round
450
+ // of that turn travels with.
451
+ recallProvider,
440
452
  env,
441
453
  getConfirmMode,
442
454
  // Injectable for tests; defaults to the real transport so every existing
@@ -1532,6 +1544,12 @@ function createLocalEngine({
1532
1544
  statedMaxTokens: opts.statedMaxTokens ? doubledBudget(opts.statedMaxTokens) : undefined,
1533
1545
  });
1534
1546
  addUsage(res);
1547
+ // Same guard as line ~1499, for the same reason: an abort landing
1548
+ // during THIS dispatch also resolves as empty text, and without
1549
+ // this check that "no answer" would fall straight into the
1550
+ // empty-turn nudge below instead of ending the turn — a cancelled
1551
+ // request quietly buying a THIRD billed call.
1552
+ if (signal.aborted) return withTurnUsage(res);
1535
1553
  }
1536
1554
 
1537
1555
  const calls = toolSchemas.length ? extractToolCalls(res) : [];
@@ -1562,6 +1580,12 @@ function createLocalEngine({
1562
1580
  tools: [],
1563
1581
  });
1564
1582
  addUsage(res);
1583
+ // Same guard again: a cancel landing during the synthesis pass
1584
+ // resolves empty too, and without this check it fell through to
1585
+ // emptyTurnError — a real exception, so the renderer painted a red
1586
+ // "no answer" failure over what was actually just the user hitting
1587
+ // Cancel.
1588
+ if (signal.aborted) return withTurnUsage(res);
1565
1589
  if (!assistantText(res)) {
1566
1590
  throw emptyTurnError({
1567
1591
  cls,