aegiscode 6.8.30 → 6.8.33

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/chatflow.js CHANGED
@@ -57,7 +57,10 @@ const { copyToClipboard, describeCopy, readClipboardText, readClipboardImage } =
57
57
  const { transcriptToMarkdown } = require('./export.js');
58
58
  const fs = require('node:fs');
59
59
  const path = require('node:path');
60
- const { aegisDir } = require('./config.js');
60
+ const { aegisDir, loadConfig } = require('./config.js');
61
+ // /ping — the terminal's half of the desktop's "reply ready" alert. Pure, so
62
+ // the loop only has to supply the stream and the elapsed time.
63
+ const { pingTurn } = require('./ping.js');
61
64
 
62
65
  /** The rotating placeholder shown on an empty input line. */
63
66
  const SUGGESTIONS = [
@@ -1268,6 +1271,30 @@ async function runSession(host) {
1268
1271
  turnCount++;
1269
1272
  abort = null;
1270
1273
 
1274
+ // /ping — the same notice the desktop raises from
1275
+ // `notifyReplyIfUnfocused()`, re-derived for a terminal that has no
1276
+ // `isFocused()`: the proxy is TIME (a turn the user walked away from is
1277
+ // one that took longer than `pingMinSeconds`), and the gate is
1278
+ // `process.stdout.isTTY` (a piped or headless run has no one to notify).
1279
+ // Written to `process.stdout` rather than through the renderer on
1280
+ // purpose: a notification escape goes past the screen buffer, so it works
1281
+ // while the renderer still owns the terminal. Guarded, and last, so a
1282
+ // notice can never break the turn it is reporting on.
1283
+ try {
1284
+ const pingCfg = loadConfig();
1285
+ const notice = pingTurn({
1286
+ stream: process.stdout,
1287
+ mode: pingCfg.ping,
1288
+ minSeconds: pingCfg.pingMinSeconds,
1289
+ elapsedMs: Date.now() - startedAt,
1290
+ isTTY: !!process.stdout.isTTY,
1291
+ aborted: abortedFlag,
1292
+ });
1293
+ if (notice) push({ role: 'note', text: notice }, { follow: false });
1294
+ } catch {
1295
+ /* a notice must never break a turn */
1296
+ }
1297
+
1271
1298
  // Accounting: fold the turn's usage into the session tallies, ask the
1272
1299
  // ledger what it settled at, and show both — tokens beside €.
1273
1300
  host.recordTurn(result);
package/src/commands.js CHANGED
@@ -53,6 +53,10 @@ const overlays = require('./overlays.js');
53
53
  const {
54
54
  updateConfig, loadConfig, loadPermissions, savePermissions, addPermissionRule,
55
55
  DEFAULT_PERMISSIONS, permissionsPath, configPath, aegisDir,
56
+ // ON8 / D8 rule 1: the posture writers. Every "confirmations on/off" command
57
+ // below goes through these rather than writing `defaultMode` itself, so the
58
+ // window's switch and this face's gate cannot end up holding two answers.
59
+ setConfirmPosture, setPermissionDefaultMode,
56
60
  memoryPersistState, setMemoryPersist,
57
61
  } = require('./config.js');
58
62
  const { auditExposure, repairExposure } = require('./securefs.js');
@@ -64,6 +68,20 @@ const { summarizeTranscript, recapLine } = require('./summarize.js');
64
68
  const { sessionAccounting, accountingFromUsage, estimateTokens } = require('./tokens.js');
65
69
  const { transcriptToMarkdown, transcriptToJSON, writeExportFile, lastAssistantText } = require('./export.js');
66
70
  const { detectDevCommand, runDevServer } = require('./devrun.js');
71
+ // /ping — the terminal half of the desktop's "reply ready" alert. Pure and
72
+ // dependency-free (no config, no TTY), so it is unit-testable on its own.
73
+ const {
74
+ PING_MODES, DEFAULT_PING_MODE, normalizePingMode, normalizePingSeconds,
75
+ buildPing, writePing,
76
+ } = require('./ping.js');
77
+ // /todos — the session list. Owns its own file; shares only `aegisDir`.
78
+ const { addTodo, completeTodo, clearTodos, formatTodos, todosFile } = require('./todos.js');
79
+ // /config — the settings surface. Store-aware, so it cannot write a preference
80
+ // to the host file (or the reverse) and re-open the drift ON8/D8 closed.
81
+ const {
82
+ configRows, formatConfigRows, setConfigValue, resetConfigValue,
83
+ fullValue, summarizeValue, configStore,
84
+ } = require('./settings.js');
67
85
  const credentials = require('./credentials.js');
68
86
  const cloudsync = require('./cloudsync.js');
69
87
  const { maskKey, fmtTokens, shortCwd } = require('./format.js');
@@ -195,8 +213,10 @@ async function multiData(c, task) {
195
213
  */
196
214
  async function runMultiCommand(c, task, { yolo = false, title = 'ÆGIS Multi' } = {}) {
197
215
  if (yolo) {
198
- const rules = loadPermissions();
199
- savePermissions({ ...rules, defaultMode: 'allow' });
216
+ // ON8: through the posture writer, not a bare `defaultMode` write — /multiyolo
217
+ // means "stop confirming", and that is now ONE fact in two stores rather than
218
+ // a rule-file edit the window would never see.
219
+ setConfirmPosture(false);
200
220
  panel(c, panels.buildYolo(c.state(), c.ctx));
201
221
  }
202
222
  note(c, 'Running the multi-agent fan-out — the engine delegates to specialist subagents (headless: this skips aegis-cli\'s own confirmation step).');
@@ -876,6 +896,172 @@ const COMMANDS = [
876
896
  return true;
877
897
  },
878
898
  },
899
+ {
900
+ name: 'ping', args: ['mode', 'seconds'], hint: '[off|bell|notify|both] [seconds] | test', category: 'model',
901
+ desc: 'Alert me when a long turn finishes, if I am looking elsewhere',
902
+ handler: async (c, args) => {
903
+ const cfg = loadConfig();
904
+ const raw = ((args._rest || '').trim()).split(/\s+/).filter(Boolean);
905
+ const first = (raw[0] || '').toLowerCase();
906
+ const mode = normalizePingMode(cfg.ping);
907
+ const seconds = normalizePingSeconds(cfg.pingMinSeconds);
908
+
909
+ // No argument: report the state AND the vocabulary, so the command is its
910
+ // own help. Silence here would be indistinguishable from a broken config.
911
+ if (!first) {
912
+ note(c, `[ping] ${mode} — a turn longer than ${seconds}s raises a terminal notification.`);
913
+ note(c, ` /ping ${PING_MODES.filter((m) => m !== mode).join('|')} ${mode === 'off' ? 'turn it back on' : 'change the channel'}`);
914
+ note(c, ` /ping <mode> <seconds> move the threshold (0 pings every turn)`);
915
+ note(c, ' /ping test fire one now, to check this terminal supports it');
916
+ c.render();
917
+ return true;
918
+ }
919
+
920
+ if (first === 'test') {
921
+ const text = buildPing({ mode: mode === 'off' ? DEFAULT_PING_MODE : mode });
922
+ // The test deliberately ignores the threshold and the abort rule — it is
923
+ // the user asking "does this terminal show anything?", and the only
924
+ // condition worth keeping is the one that makes the answer meaningful.
925
+ const wrote = process.stdout.isTTY ? writePing(process.stdout, text) : false;
926
+ note(c, wrote
927
+ ? '[ping] sent one just now. If nothing appeared or sounded, this terminal implements neither OSC 9 nor OSC 777 — /ping bell is the fallback.'
928
+ : '[ping] nothing sent: stdout is not a TTY (a piped or headless run has no one to notify).');
929
+ c.render();
930
+ return true;
931
+ }
932
+
933
+ if (!PING_MODES.includes(first)) {
934
+ note(c, `Unknown ping mode "${raw[0]}". Use ${PING_MODES.join(', ')}.`);
935
+ c.render();
936
+ return true;
937
+ }
938
+
939
+ const patch = { ping: first };
940
+ if (raw[1] != null) {
941
+ const n = Number(raw[1]);
942
+ if (!Number.isFinite(n) || n < 0) {
943
+ note(c, `"${raw[1]}" is not a number of seconds. Use /ping ${first} 30.`);
944
+ c.render();
945
+ return true;
946
+ }
947
+ patch.pingMinSeconds = normalizePingSeconds(n);
948
+ }
949
+ updateConfig(patch);
950
+
951
+ if (first === 'off') {
952
+ note(c, '[ping] off — no notice will be raised, and nothing is reported as sent.');
953
+ } else {
954
+ note(c, `[ping] ${first} — turns longer than ${normalizePingSeconds(patch.pingMinSeconds ?? cfg.pingMinSeconds)}s will notify you.`);
955
+ note(c, ' Escape never pings (you were watching), and neither does a piped or headless run.');
956
+ }
957
+ c.render();
958
+ return true;
959
+ },
960
+ },
961
+ {
962
+ name: 'todos', aliases: ['todo'], args: ['sub', 'text'], hint: '[add <text> | done <n|text> | clear]', category: 'session',
963
+ desc: 'A session todo list that survives compaction',
964
+ handler: async (c, args) => {
965
+ const sub = (args.sub || '').toLowerCase();
966
+ const rest = (args._rest || '').trim();
967
+ // Everything after the subcommand. `_rest` is the whole line, so
968
+ // `/todos add buy milk` would otherwise store the literal string
969
+ // "add buy milk" — the subcommand has to come off first.
970
+ const tail = rest.replace(/^\S+\s*/, '');
971
+
972
+ if (!sub) {
973
+ panel(c, formatTodos());
974
+ note(c, ` ${todosFile()}`);
975
+ note(c, ' /todos add <text> · /todos done <n|text> · /todos clear');
976
+ c.render();
977
+ return true;
978
+ }
979
+
980
+ if (sub === 'add') {
981
+ const res = addTodo(tail);
982
+ if (res.error) { note(c, res.error); c.render(); return true; }
983
+ panel(c, formatTodos(res.list));
984
+ c.render();
985
+ return true;
986
+ }
987
+
988
+ if (sub === 'done' || sub === 'do') {
989
+ const res = completeTodo(tail);
990
+ if (res.error) { note(c, res.error); c.render(); return true; }
991
+ note(c, `[todos] "${res.item.text}" is now ${res.item.done ? 'done' : 'open'}.`);
992
+ panel(c, formatTodos(res.list));
993
+ c.render();
994
+ return true;
995
+ }
996
+
997
+ if (sub === 'clear') {
998
+ clearTodos();
999
+ note(c, '[todos] cleared.');
1000
+ c.render();
1001
+ return true;
1002
+ }
1003
+
1004
+ note(c, `Unknown /todos subcommand "${args.sub}". Use add, done or clear.`);
1005
+ c.render();
1006
+ return true;
1007
+ },
1008
+ },
1009
+ {
1010
+ name: 'config', args: ['key', 'value'], hint: '[<key> | <key> <value> | reset <key>]', category: 'session',
1011
+ desc: 'Show or change any setting, and say which store holds it',
1012
+ handler: async (c, args) => {
1013
+ const rest = (args._rest || '').trim();
1014
+ const key = (args.key || '').trim();
1015
+ // The value is everything after the key, not the next token: a string
1016
+ // setting may contain spaces, and `_rest` is the whole line.
1017
+ const value = rest.replace(/^\S+\s*/, '');
1018
+
1019
+ if (!key) {
1020
+ // The list summarizes structured values rather than dumping them —
1021
+ // `models` is a model table and `updateCheck` is an object, and printing
1022
+ // them whole is how this command becomes unreadable.
1023
+ panel(c, formatConfigRows(configRows()));
1024
+ note(c, ' /config <key> show one value in full');
1025
+ note(c, ' /config <key> <value> set it (true/false/null, numbers, JSON, or text)');
1026
+ note(c, ' /config reset <key> back to the shipped value');
1027
+ note(c, ' "shared" keys live in the store AEGIS Desktop writes too; "host" keys are this shell\'s own.');
1028
+ c.render();
1029
+ return true;
1030
+ }
1031
+
1032
+ if (key === 'reset') {
1033
+ const res = resetConfigValue(value);
1034
+ if (res.error) { note(c, res.error); c.render(); return true; }
1035
+ note(c, `[config] ${res.key} reset to ${summarizeValue(res.value)} (${res.store}).`);
1036
+ c.render();
1037
+ return true;
1038
+ }
1039
+
1040
+ if (!value) {
1041
+ const cfg = loadConfig();
1042
+ if (!Object.prototype.hasOwnProperty.call(cfg, key)) {
1043
+ note(c, `unknown config key "${key}" — run /config to list the keys`);
1044
+ c.render();
1045
+ return true;
1046
+ }
1047
+ note(c, `${key} (${configStore(key)}):`);
1048
+ c.push({ role: 'panel', lines: fullValue(cfg[key]).split('\n').map((l) => ` ${l}`) });
1049
+ c.render();
1050
+ return true;
1051
+ }
1052
+
1053
+ const res = setConfigValue(key, value);
1054
+ if (res.error) { note(c, res.error); c.render(); return true; }
1055
+ note(c, `[config] ${res.key} = ${summarizeValue(res.value)} (${res.store}).`);
1056
+ // A model/class/effort change is a live session decision, not just a file
1057
+ // write; say so rather than leaving the user to wonder when it applies.
1058
+ if (['model', 'currentModelId', 'modelClass', 'effort', 'themeIndex', 'vim'].includes(res.key)) {
1059
+ note(c, ` This takes effect on the next turn; /${res.key === 'currentModelId' ? 'model' : res.key} shows the live session value.`);
1060
+ }
1061
+ c.render();
1062
+ return true;
1063
+ },
1064
+ },
879
1065
  {
880
1066
  name: 'effort', args: ['level'], hint: '[auto|low|medium|high]', category: 'model',
881
1067
  desc: 'Set the token budget the pool sizes each turn from',
@@ -1528,13 +1714,21 @@ const COMMANDS = [
1528
1714
  return true;
1529
1715
  }
1530
1716
  if (mode === 'clear') {
1717
+ // A reset is a posture change too: DEFAULT_PERMISSIONS' residual is
1718
+ // `ask`, i.e. confirmations ON, and leaving the shared key where it was
1719
+ // would keep the gate off in the window while this face asks.
1720
+ setPermissionDefaultMode(DEFAULT_PERMISSIONS.defaultMode);
1531
1721
  savePermissions({ ...DEFAULT_PERMISSIONS, allow: [], deny: [], ask: [] });
1532
1722
  note(c, 'Permissions reset to defaults (no rules).');
1533
1723
  c.render();
1534
1724
  return true;
1535
1725
  }
1536
1726
  if (mode === 'default' && ['ask', 'allow', 'deny'].includes(pattern)) {
1537
- savePermissions({ ...rules, defaultMode: pattern });
1727
+ // ON8: `ask`/`allow` are the posture, so this moves the shared gate too
1728
+ // (a `/permissions default ask` in the shell must close the window's
1729
+ // switch, which is the whole point of rule 1). `deny` is not a posture:
1730
+ // it writes the rule residual and leaves the gate UP.
1731
+ setPermissionDefaultMode(pattern);
1538
1732
  note(c, `Default permission mode: ${pattern}`);
1539
1733
  c.render();
1540
1734
  return true;
@@ -1896,7 +2090,9 @@ const COMMANDS = [
1896
2090
  const mode = (args.mode || '').toLowerCase();
1897
2091
  if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /confirm [on|off]'); c.render(); return true; }
1898
2092
  const want = mode === 'on' ? true : mode === 'off' ? false : rules.defaultMode !== 'allow';
1899
- savePermissions({ ...rules, defaultMode: want ? 'ask' : 'allow' });
2093
+ // ON8: one writer for the posture — the shared key the window's switch
2094
+ // reads, plus the rule residual this face's gate reads.
2095
+ setConfirmPosture(want);
1900
2096
  note(c, `Confirmation prompts: ${want ? 'on' : 'off'} (default permission mode: ${want ? 'ask' : 'allow'})`);
1901
2097
  c.render();
1902
2098
  return true;
@@ -1910,7 +2106,9 @@ const COMMANDS = [
1910
2106
  const mode = (args.mode || '').toLowerCase();
1911
2107
  if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /yolo [on|off]'); c.render(); return true; }
1912
2108
  const want = mode === 'on' ? true : mode === 'off' ? false : rules.defaultMode !== 'allow';
1913
- savePermissions({ ...rules, defaultMode: want ? 'allow' : 'ask' });
2109
+ // ON8: `/yolo` is the posture's OFF state, written through the one writer,
2110
+ // so the window's switch shows it and the two faces cannot disagree.
2111
+ setConfirmPosture(!want);
1914
2112
  if (want) panel(c, panels.buildYolo(c.state(), c.ctx));
1915
2113
  else note(c, 'YOLO mode off — confirmations restored.');
1916
2114
  c.render();
@@ -2043,6 +2241,101 @@ const COMMANDS = [
2043
2241
  return true;
2044
2242
  },
2045
2243
  },
2244
+ {
2245
+ // The in-session top-up. `/billing` printed a link and that was the whole
2246
+ // funding story in the terminal; the link is real but it lands on `/topup`,
2247
+ // which is `@login_required` against a browser SESSION, and the account this
2248
+ // product auto-provisions is a device key with no password anyone holds and
2249
+ // an email at `@device.aegiscloud`. So the user who needs to fund a free
2250
+ // account could not sign in to the page that funds it — they paid a visit to
2251
+ // a login wall and read it as "my payment failed".
2252
+ //
2253
+ // This does what the desktop does, over the SAME shared core
2254
+ // (`client/topup.js`): the credential that creates the checkout is the one
2255
+ // that can read the bank, so the confirmation comes from the API rather than
2256
+ // from a page the account cannot open. Bounds and payload reading are shared,
2257
+ // never re-derived here.
2258
+ name: 'topup', aliases: ['fund'], args: ['amount'], hint: '[EUR]', category: 'support',
2259
+ desc: 'Top up the token bank — opens the payment page and confirms the credit here',
2260
+ handler: async (c, args) => {
2261
+ const raw = String(args.amount || args._rest || '').trim();
2262
+ let shared;
2263
+ try {
2264
+ // Lazy: the TUI pays for this only when someone asks to pay.
2265
+ shared = require(require('./sharedpaths.js').resolveShared('client/topup.js'));
2266
+ } catch (e) {
2267
+ note(c, `top-up is unavailable in this build — ${e.message}`);
2268
+ c.render();
2269
+ return true;
2270
+ }
2271
+ const parsed = shared.parseTopupAmount(raw);
2272
+ if (!parsed.ok) {
2273
+ note(c, parsed.message);
2274
+ c.render();
2275
+ return true;
2276
+ }
2277
+ if (!c.client.apiKey) {
2278
+ // Same honest refusal the rest of the account surfaces give, and the
2279
+ // same fix: the key is what pays. Auto-provisioning happens on session
2280
+ // start (app.js ensureApiKey), so this is the offline/failed case.
2281
+ note(c, `no AEGIS key on this machine — ${credentials.HOW_TO_SET}, then /topup ${parsed.amount}`);
2282
+ c.render();
2283
+ return true;
2284
+ }
2285
+ const started = c.withWorking
2286
+ ? await c.withWorking(() => shared.startTopup(c.client, parsed.amount))
2287
+ : await shared.startTopup(c.client, parsed.amount);
2288
+ if (!started.ok) {
2289
+ note(c, `the top-up could not be started — ${started.message}`);
2290
+ if (started.hint) note(c, started.hint);
2291
+ c.render();
2292
+ return true;
2293
+ }
2294
+ // The URL rides its own row: `note` rows are a single unwrapped span
2295
+ // (chatflow.js), so appending it to that sentence pushes the tail past
2296
+ // `cols` where `padLine()` cuts it — and the tail is the URL.
2297
+ note(c, `opening the payment page — ${parsed.amount} EUR`);
2298
+ note(c, started.url);
2299
+ const seconds = Math.round((shared.TOPUP_POLL_MS * shared.TOPUP_POLL_TRIES) / 1000);
2300
+ note(c, `watching this account's bank for up to ${seconds}s; the credit is confirmed here, not in the browser`);
2301
+ c.render();
2302
+ const open = openUrl(started.url);
2303
+ if (!open) note(c, 'could not open a browser — use the URL above');
2304
+
2305
+ // A recursive timeout rather than an interval: the balance call can take
2306
+ // longer than one period on a slow link, and an interval would start a
2307
+ // second read on top of the first — two reads, two announcements of one
2308
+ // credit. Unref'd so an unfinished payment never keeps the TUI alive.
2309
+ const watch = shared.createCreditWatch(c.client);
2310
+ let timer = null;
2311
+ let done = false;
2312
+ const settle = () => {
2313
+ done = true;
2314
+ if (timer) clearTimeout(timer);
2315
+ };
2316
+ const step = async () => {
2317
+ if (done) return;
2318
+ const res = await watch.tick();
2319
+ if (res.state === 'credited') {
2320
+ settle();
2321
+ note(c, `credit confirmed — the bank is now ${res.amount.toFixed(2)} EUR`);
2322
+ c.render();
2323
+ return;
2324
+ }
2325
+ if (res.state === 'expired') {
2326
+ settle();
2327
+ note(c, 'no credit observed within the watch window — if you completed the payment it may still land; /billing shows the bank');
2328
+ c.render();
2329
+ return;
2330
+ }
2331
+ timer = setTimeout(step, shared.TOPUP_POLL_MS);
2332
+ if (timer && typeof timer.unref === 'function') timer.unref();
2333
+ };
2334
+ timer = setTimeout(step, shared.TOPUP_POLL_MS);
2335
+ if (timer && typeof timer.unref === 'function') timer.unref();
2336
+ return true;
2337
+ },
2338
+ },
2046
2339
  {
2047
2340
  name: 'cloud', args: ['sub', 'value'], hint: '[status|key <api_key>|activate|deactivate|memory [on|off]|sync [on|off|now]]', category: 'support',
2048
2341
  desc: 'Show and control ÆGIS cloud sync',