aegiscode 6.5.7 → 6.5.9

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/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.5.7",
5
- "description": "aegiscode \u2014 the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
4
+ "version": "6.5.9",
5
+ "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
8
8
  "email": "nborneklint@gmail.com"
package/src/app.js CHANGED
@@ -175,9 +175,19 @@ function createApp(options = {}) {
175
175
  tokens: 0,
176
176
  inputTokens: 0,
177
177
  outputTokens: 0,
178
- cost: 0, // € spent, from ledger rows observed this session
178
+ cost: 0, // € spent, from the ledger rows that landed AFTER the baseline
179
179
  balance: null,
180
- lastLedgerAt: null,
180
+ // How many times each ledger-row identity is already accounted for.
181
+ // A COUNT, not a Set — see ledgerRowKey for why identity is content-based
182
+ // and refreshSpend for why the multiplicity matters.
183
+ seenLedgerRows: new Map(),
184
+ // Whether the account's existing ledger has been snapshotted as history.
185
+ // The balance endpoint returns the ACCOUNT's ledger, so the rows visible on
186
+ // the first refresh are everything the customer ever spent. Until this is
187
+ // true, no row may be folded into `cost`: session.cost is rendered as
188
+ // "This session" and would otherwise print the account's lifetime spend
189
+ // under it. See refreshSpend.
190
+ ledgerBaselined: false,
181
191
  startedAt: Date.now(),
182
192
  };
183
193
 
@@ -186,26 +196,131 @@ function createApp(options = {}) {
186
196
 
187
197
  // --- helpers --------------------------------------------------------------
188
198
 
199
+ /**
200
+ * How much one ledger row is worth to the customer, in EUR (always >= 0).
201
+ *
202
+ * `amount_eur` is signed from the user's side (negative = spent) and is what
203
+ * /api/token-bank/balance actually returns. `charged_micros` is the raw
204
+ * column with the OPPOSITE sign, kept only as a fallback for a server build
205
+ * that drops amount_eur — which is why it is negated here.
206
+ *
207
+ * Returns null for a row that is not a charge at all, or that carries no
208
+ * usable number. Anything non-finite is null rather than NaN: a NaN that
209
+ * reaches a tally poisons it for the rest of the session, and a NaN written
210
+ * into history.jsonl is invisible until /cost renders it.
211
+ */
212
+ function ledgerRowEur(row) {
213
+ if (!row || typeof row !== 'object') return null;
214
+ // A top-up is money IN, not a charge. Folding one into the spend tally
215
+ // would report a customer who just added €20 as having spent €20.
216
+ if (row.kind !== 'usage') return null;
217
+ const raw = row.amount_eur != null ? Number(row.amount_eur) : -Number(row.charged_micros || 0) / 1e6;
218
+ if (!Number.isFinite(raw)) return null;
219
+ // The magnitude is the charge either way; the server's sign convention for
220
+ // a spend row is not something this client should depend on.
221
+ return Math.abs(raw);
222
+ }
223
+
224
+ /**
225
+ * The identity of a ledger row, used to decide "is this new?".
226
+ *
227
+ * Deliberately NOT `created_at`. That column is stamped to the second, so two
228
+ * turns inside the same second collide: the second row compared equal to the
229
+ * first, was skipped as "already counted", and — because chatflow persists the
230
+ * turn with whatever this returned — the exchange was written to history.jsonl
231
+ * with NO charge attached. /cost then fell back to the local rate table for
232
+ * that turn and reported a figure that was not the bill. Every column the
233
+ * endpoint returns that can distinguish two rows is folded in here.
234
+ *
235
+ * The endpoint returns no unique row id (see mcp/tools.js, which reads the
236
+ * same columns), so this is content-based and two genuinely identical charges
237
+ * — same model, same token counts, same second — hash the same. That is why
238
+ * callers count occurrences rather than merely testing membership: a Set
239
+ * would treat the second identical charge as already-counted and silently
240
+ * under-bill it, which is the original defect wearing a different hat.
241
+ */
242
+ function ledgerRowKey(row) {
243
+ return [
244
+ row.created_at || '',
245
+ row.kind || '',
246
+ row.amount_eur != null ? row.amount_eur : '',
247
+ row.charged_micros != null ? row.charged_micros : '',
248
+ row.id != null ? row.id : '',
249
+ row.note != null ? row.note : '',
250
+ ].join('|');
251
+ }
252
+
189
253
  /** Refresh the balance and fold any *new* usage row into the session tally.
190
- * Best-effort: an accounting refresh must never break a turn.
254
+ *
255
+ * The first successful refresh of a session is a BASELINE: it observes the
256
+ * account's whole ledger and folds nothing. Each entry point therefore calls
257
+ * this once at session start, so the baseline can never swallow a real
258
+ * turn's charge. Best-effort: an accounting refresh must never break a turn.
259
+ *
191
260
  * @returns {Promise<{balance:number, lastCost:number|null}|null>} */
192
261
  async function refreshSpend() {
193
262
  try {
194
263
  const data = await client.tokenBankBalance();
195
- session.balance = Number(data.balance_eur || 0);
264
+ const balance = Number(data.balance_eur);
265
+ if (Number.isFinite(balance)) session.balance = balance;
196
266
  let lastCost = null;
197
- const row = (data.ledger || [])[0];
198
- if (row && row.kind === 'usage' && row.created_at && row.created_at !== session.lastLedgerAt) {
199
- session.lastLedgerAt = row.created_at;
200
- // amount_eur is signed from the user's side (negative = spent); the
201
- // ledger fallback inverts the raw micros column, which has the
202
- // opposite sign.
203
- const eur = Math.abs(
204
- Number(row.amount_eur != null ? row.amount_eur : -Number(row.charged_micros || 0) / 1e6)
205
- );
206
- session.cost += eur;
207
- lastCost = eur;
267
+ const ledger = Array.isArray(data.ledger) ? data.ledger : [];
268
+
269
+ // Fold every row that is new since the last refresh, not just the head of
270
+ // the list. A single refresh can legitimately see more than one unseen
271
+ // charge — a refresh skipped while the balance endpoint was down, a long
272
+ // tool turn that dispatched two billed provider calls, or the first
273
+ // refresh after /billing already consumed the head — and taking only
274
+ // ledger[0] silently dropped the rest from the session tally.
275
+ //
276
+ // Count occurrences within the pass BEFORE folding, so two identical rows
277
+ // are billed twice. Testing membership one row at a time cannot tell the
278
+ // first occurrence from the second and under-charges by one.
279
+ const seenHere = new Map(); // key -> { n, row }
280
+ for (const row of ledger) {
281
+ const key = ledgerRowKey(row);
282
+ const hit = seenHere.get(key);
283
+ if (hit) hit.n += 1;
284
+ else seenHere.set(key, { n: 1, row });
285
+ }
286
+
287
+ for (const [key, { n, row }] of seenHere) {
288
+ const already = session.seenLedgerRows.get(key) || 0;
289
+ session.seenLedgerRows.set(key, n);
290
+
291
+ // This endpoint returns the ACCOUNT's ledger, so on the opening refresh
292
+ // it holds everything the customer has ever spent. Those rows are
293
+ // history — mark them seen and fold nothing, so `cost` starts at zero.
294
+ //
295
+ // Reaching this loop at all means the endpoint answered, so this pass
296
+ // really did observe the full ledger and it is safe to call it the
297
+ // baseline. That is deliberately self-healing: if the session-start
298
+ // call failed (offline, no balance rights) the NEXT successful refresh
299
+ // becomes the baseline, and the worst case is one turn under-reported.
300
+ // The reverse — folding an unobserved ledger — would report the
301
+ // customer's lifetime spend as "This session", a number they already
302
+ // paid and are not being charged again.
303
+ if (!session.ledgerBaselined) continue;
304
+
305
+ // Only the occurrences beyond those already accounted for are new.
306
+ const fresh = n - already;
307
+ if (fresh <= 0) continue;
308
+
309
+ const eur = ledgerRowEur(row);
310
+ if (eur != null && eur > 0) {
311
+ session.cost += eur * fresh;
312
+ // The charge to attribute to this turn. The endpoint returns the
313
+ // ledger NEWEST-FIRST (mcp/tools.js takes `.slice(0, 5)` as "Recent
314
+ // activity" and renders those as the latest rows), and the folds above
315
+ // run in that order, so the first charge seen here is the newest —
316
+ // i.e. the row this turn just produced. Taking the first rather than
317
+ // the largest matters when one pass sees several: the max would
318
+ // report an older, pricier call as this turn's cost.
319
+ if (lastCost == null) lastCost = eur;
320
+ }
208
321
  }
322
+ session.ledgerBaselined = true;
323
+
209
324
  return { balance: session.balance, lastCost };
210
325
  } catch {
211
326
  return null; // no balance rights / offline: keep showing tokens
@@ -620,9 +735,22 @@ function createApp(options = {}) {
620
735
  if (res.text) transcript.push({ role: 'assistant', text: res.text });
621
736
 
622
737
  const tokens = recordTurn(res);
623
- persistTurn(prompt, res, res.interrupted ? 'stopped' : res.error ? 'error' : 'done');
624
738
 
625
- const spend = await refreshSpend();
739
+ // Ask the ledger what this call settled at BEFORE persisting it. The order
740
+ // is the whole point: the charge is the server's number (pool margin and
741
+ // prompt-cache discount included) and only the ledger knows it. Persisting
742
+ // first wrote the exchange with no charge attached, so /cost recomputed it
743
+ // from a local rate table that knows about neither — and the figure the
744
+ // customer read did not match the bill they paid. Same ordering as the
745
+ // chatflow session loop.
746
+ let settledCost = null;
747
+ try {
748
+ const spend = await refreshSpend();
749
+ settledCost = spend ? spend.lastCost : null;
750
+ } catch {
751
+ /* accounting must never break a turn */
752
+ }
753
+ persistTurn(prompt, res, res.interrupted ? 'stopped' : res.error ? 'error' : 'done', settledCost);
626
754
 
627
755
  printTurn({
628
756
  role: 'assistant',
@@ -639,7 +767,7 @@ function createApp(options = {}) {
639
767
  },
640
768
  // What this call settled at, from the ledger row it produced — the
641
769
  // number that has to agree with the token count beside it.
642
- eur: spend && spend.lastCost != null ? spend.lastCost : null,
770
+ eur: settledCost,
643
771
  ms: res.ms,
644
772
  calls: 1,
645
773
  },
@@ -1011,6 +1139,11 @@ function createApp(options = {}) {
1011
1139
  err.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`);
1012
1140
  return 2;
1013
1141
  }
1142
+ // Snapshot the account's existing ledger BEFORE the billed call. Without
1143
+ // this the refresh after the turn would treat every historical row as new,
1144
+ // and the reported charge would be whatever the account spent last rather
1145
+ // than what this call cost.
1146
+ await refreshSpend();
1014
1147
  const res = await ask(prompt);
1015
1148
  await refreshSpend();
1016
1149
  const tokens = usageTokens(res.usage);
@@ -1183,7 +1316,15 @@ function createApp(options = {}) {
1183
1316
  refreshSpend: () => refreshSpend(),
1184
1317
  updateConfig: (patch) => updateConfig(patch),
1185
1318
  showThemePicker: () => showThemePicker(),
1186
- persistTurn: (prompt, res, status) => persistTurn(prompt, res, status),
1319
+ // `costEur` MUST be forwarded. chatflow's session loop passes the settled
1320
+ // charge as its fourth argument, and this binding used to accept only
1321
+ // three — so the argument was dropped, persistTurn fell back to
1322
+ // costEur = null, and every interactive turn was written to
1323
+ // history.jsonl with no charge attached. /cost then recomputed each of
1324
+ // them from the local rate table (no pool margin, no prompt-cache
1325
+ // discount) and reported a number the customer never paid. The parameter
1326
+ // is the whole reason the ledger is consulted before persisting.
1327
+ persistTurn: (prompt, res, status, costEur) => persistTurn(prompt, res, status, costEur),
1187
1328
  visibleCommands: () => visibleCommands(),
1188
1329
  tokensFor: (usage) => usageTokens(usage),
1189
1330
  recordTurn: (res) => recordTurn(res),
@@ -1340,6 +1481,10 @@ function createApp(options = {}) {
1340
1481
  await resumeSession({ id: last.id });
1341
1482
  }
1342
1483
  }
1484
+ // Snapshot the account's ledger before the loop's first billed turn, so
1485
+ // the session tally cannot absorb the customer's existing spend and the
1486
+ // first turn's charge is not mistaken for pre-existing history.
1487
+ await refreshSpend();
1343
1488
  await chatflow.runSession(makeHost());
1344
1489
  return 0;
1345
1490
  }
package/src/chatflow.js CHANGED
@@ -397,16 +397,46 @@ function joinBits(bits, t) {
397
397
  return line;
398
398
  }
399
399
 
400
+ /** Longest directory a row prints before it is contracted from the front. */
401
+ const DIR_MAX = 40;
402
+
403
+ /**
404
+ * A row's working directory, contracted for display: the home prefix becomes
405
+ * `~`, and a path still too long keeps its tail — the leaf is what identifies
406
+ * the checkout, the ancestors are the part a reader can spare. Returns '' when
407
+ * the host didn't say, so a row never implies a directory it doesn't know.
408
+ */
409
+ function shortDir(dir) {
410
+ let p = String(dir == null ? '' : dir).trim().replace(/\/+$/, '');
411
+ if (!p) return '';
412
+ const home = String(process.env.HOME || process.env.USERPROFILE || '').replace(/\/+$/, '');
413
+ if (home && (p === home || p.startsWith(`${home}/`))) p = `~${p.slice(home.length)}`;
414
+ if (p.length > DIR_MAX) p = `${GLYPH.ellipse}${p.slice(-(DIR_MAX - 1))}`;
415
+ return p;
416
+ }
417
+
400
418
  /** Render one transcript row to span lines. */
401
419
  function rowLines(msg, cols, ctx, now = Date.now()) {
402
420
  const t = themeOf(ctx);
403
421
  const out = [];
404
422
  if (msg.role === 'tool') {
423
+ // One ellipsis per row. The label already ends in one ("Running 1 shell
424
+ // command…") and this appended a second after the seconds, so the row read
425
+ // "Running 1 shell command… · 3s…" — two ellipses on one line. Normalising
426
+ // the label here rather than at the call site means the row stays correct
427
+ // whatever a host puts in `label`.
428
+ const label = String(msg.label || '').replace(/(?:…|\.\.\.)+$/, '');
429
+ // Where it runs. A tool row's args are the command or the path, so without
430
+ // this the transcript cannot answer "where is it working in".
431
+ const where = msg.cwd ? ` · ${shortDir(msg.cwd)}` : '';
405
432
  if (msg.phase === 'run') {
406
433
  const secs = msg.start ? Math.max(1, Math.round((now - msg.start) / 1000)) : 0;
407
- out.push([span(t.white, GLYPH.block), span(t.gray, ` ${msg.label} · ${secs}s…`)]);
434
+ out.push([
435
+ span(t.white, GLYPH.block),
436
+ span(t.gray, ` ${label}${GLYPH.ellipse} · ${secs}s${where}`),
437
+ ]);
408
438
  } else {
409
- out.push([span(t.gray, msg.label)]);
439
+ out.push([span(t.gray, `${label}${where}`)]);
410
440
  }
411
441
  const argsStr =
412
442
  typeof msg.args === 'string'
@@ -911,7 +941,20 @@ async function runSession(host) {
911
941
  // from one that produced nothing at all.
912
942
  reasoning: () => { sawReasoning = true; },
913
943
  tool: (tool) => {
914
- turnTools.push(tool);
944
+ // One entry per tool call, not one per frame. The engine opens a `run`
945
+ // frame before the tool executes and closes it with a `done` frame
946
+ // after (see desktop/lib/local/engine.js), so pushing both made the
947
+ // turn summary report every tool twice. An id-bearing done frame
948
+ // replaces the run frame it closes; frames with no id keep the old
949
+ // push-every-frame behaviour, so a host that reports a tool once is
950
+ // unaffected.
951
+ if (tool && tool.id !== undefined) {
952
+ const at = turnTools.findIndex((x) => x && x.id !== undefined && x.id === tool.id);
953
+ if (at >= 0) turnTools[at] = tool;
954
+ else turnTools.push(tool);
955
+ } else {
956
+ turnTools.push(tool);
957
+ }
915
958
  if (tool.phase === 'run') {
916
959
  const n = ++toolSeq;
917
960
  const prefix = tool.agent ? `${tool.agent} ▸ ` : '';
@@ -946,6 +946,11 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
946
946
  let shell = null;
947
947
  const getShell = () => shell || (shell = new ShellSession({ cwd: envFor(payload).cwd }));
948
948
  const toolCtx = { getShell, signal };
949
+ // The turn's working directory. It rides on every tool frame because a
950
+ // tool row's args are the command or the path — never the directory the
951
+ // command runs in — which left "where is it working in" unanswerable from
952
+ // the transcript.
953
+ const turnCwd = envFor(payload).cwd;
949
954
 
950
955
  try {
951
956
  const cfg = cls === 'aegis' || cls === 'ollama' ? {} : settings.get(cls) || {};
@@ -1207,6 +1212,18 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
1207
1212
  });
1208
1213
 
1209
1214
  for (const call of calls) {
1215
+ // Open the live row BEFORE the tool runs. The CLI paints
1216
+ // `Running N … · 3s` off a `phase: 'run'` frame and ticks it while
1217
+ // the tool is still going; reporting the tool only once, after it
1218
+ // finished, left the transcript showing a spinner verb and nothing
1219
+ // else for the whole exec timeout (120s, up to 600s) — which reads
1220
+ // as a wedged turn rather than a working one.
1221
+ if (onDelta) {
1222
+ onDelta({
1223
+ delta: '',
1224
+ tool: { name: call.name, args: call.args, id: call.id, cwd: turnCwd, phase: 'run' },
1225
+ });
1226
+ }
1210
1227
  const result = call.name === T.SUBAGENT_TOOL
1211
1228
  ? await runSubagent(call.args, {
1212
1229
  cls, model, statedMaxTokens, effort: payload && payload.effort,
@@ -1215,7 +1232,15 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
1215
1232
  : await gatedExecuteTool(call, { toolCtx, rootSessionId, rootOnDelta, signal });
1216
1233
  // A subagent's spend rides back on its tool result (see runSubagent).
1217
1234
  if (result && result.usage) addUsage({ usage: result.usage });
1218
- if (onDelta) onDelta({ delta: '', tool: { name: call.name, args: call.args, ok: result.ok } });
1235
+ // The id is carried on both frames: the CLI pairs them by id first,
1236
+ // precisely so parallel same-name calls don't collapse into one row
1237
+ // with the wrong plural.
1238
+ if (onDelta) {
1239
+ onDelta({
1240
+ delta: '',
1241
+ tool: { name: call.name, args: call.args, ok: result.ok, id: call.id, cwd: turnCwd, phase: 'done' },
1242
+ });
1243
+ }
1219
1244
  history.push({
1220
1245
  role: 'tool',
1221
1246
  tool_call_id: call.id,