aegiscode 6.5.8 → 6.6.0

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/bin/aegiscode.js CHANGED
@@ -29,6 +29,12 @@ Account:
29
29
  aegiscode logout remove the saved key
30
30
  aegiscode key status show which key is in use and where it came from
31
31
 
32
+ Autonomous work queue (no terminal needed — cron/systemd/ssh friendly):
33
+ aegiscode autonomous add "task" queue a task to run unattended
34
+ aegiscode autonomous list show the queue (--json for machines)
35
+ aegiscode autonomous proceed drain every pending task, then exit
36
+ aegiscode autonomous help all subcommands and their flags
37
+
32
38
  Options:
33
39
  -m, --model <id> pin a model id (see /models; default: server choice)
34
40
  --base <url> API base (default $AEGIS_API_BASE or aegiscloud.org)
@@ -67,6 +73,9 @@ function parseArgs(argv) {
67
73
  version: false,
68
74
  command: null,
69
75
  commandArg: null,
76
+ // `autonomous` owns the rest of the line verbatim (its flags are the
77
+ // subcommand's, not this parser's) — see the `head === 'autonomous'` branch.
78
+ commandArgv: null,
70
79
  };
71
80
  const rest = [];
72
81
 
@@ -79,6 +88,17 @@ function parseArgs(argv) {
79
88
  opts.command = head;
80
89
  opts.commandArg = arg && !arg.startsWith('-') ? arg : null;
81
90
  argv = argv.slice(opts.commandArg ? 2 : 1);
91
+ } else if (head === 'autonomous') {
92
+ // Same position-0 rule, one difference: a queue subcommand owns the REST of
93
+ // the line (including flags, which are the subcommand's, not the session
94
+ // parser's), so the tail is handed over verbatim instead of parsed here.
95
+ // `aegiscode autonomous "write a file"` is not a thing — `add` is — so a
96
+ // bare `autonomous` is help, not a prompt.
97
+ const sub = argv[1] && !argv[1].startsWith('-') ? argv[1] : 'help';
98
+ opts.command = 'autonomous';
99
+ opts.commandArg = sub;
100
+ opts.commandArgv = argv.slice(argv[1] && !argv[1].startsWith('-') ? 2 : 1);
101
+ argv = [];
82
102
  }
83
103
 
84
104
  for (let i = 0; i < argv.length; i++) {
@@ -322,6 +342,25 @@ async function main(argv = process.argv.slice(2)) {
322
342
  });
323
343
  }
324
344
 
345
+ // The work queue. Parsed at position 0 like the account subcommands (see
346
+ // parseArgs), but dispatched here rather than there because it is the one
347
+ // surface that must work with NO terminal at all: a systemd timer runs
348
+ // `aegiscode autonomous proceed` from a unit with stdin on /dev/null, and a
349
+ // cron job reads the exit status to decide whether to page somebody. So the
350
+ // subcommand's own argv is handed over untouched, the process's real streams
351
+ // are passed through, and the subcommand's exit code is what the shell sees
352
+ // (0 done, 1 a task failed / another drain holds the lock, 2 usage or no
353
+ // credential) — never the interactive chat path's "no terminal and no prompt".
354
+ if (opts.command === 'autonomous') {
355
+ const { runQueueCommand } = require('../src/autonomous.js');
356
+ return runQueueCommand(opts.commandArg, opts.commandArgv || [], {
357
+ json: opts.json,
358
+ stdin: process.stdin,
359
+ stdout: process.stdout,
360
+ stderr: process.stderr,
361
+ });
362
+ }
363
+
325
364
  const { createApp } = require('../src/app.js');
326
365
 
327
366
  let prompt = opts.prompt;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.5.8",
4
+ "version": "6.6.0",
5
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",
@@ -62,6 +62,14 @@ const FILES = [
62
62
  'desktop/lib/local/turn-guard.js',
63
63
  'desktop/lib/local/worktree-lock.js',
64
64
  'desktop/lib/local/git-scope.js',
65
+ // The autonomous work queue (`queue.js`) and its unattended worker
66
+ // (`autonomous.js`), which `src/deps.js` requires at load time along with
67
+ // everything above — a named interface, not a lazy one, so a vendor tree
68
+ // missing either throws MODULE_NOT_FOUND before the CLI can print its usage.
69
+ // `autonomous.js` requires `./queue.js` and `./git-scope.js` at load time and
70
+ // both sit above; `queue.js` requires only node builtins.
71
+ 'desktop/lib/local/queue.js',
72
+ 'desktop/lib/local/autonomous.js',
65
73
  ];
66
74
 
67
75
  function main() {
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
  }