aegiscode 6.8.3 → 6.8.5

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.
Files changed (53) hide show
  1. package/README.md +2 -2
  2. package/bin/aegiscode.js +35 -5
  3. package/package.json +1 -6
  4. package/scripts/predist.mjs +99 -0
  5. package/src/agents.js +1 -1
  6. package/src/app.js +41 -9
  7. package/src/caps.js +1 -1
  8. package/src/chatflow.js +182 -34
  9. package/src/checkpoint.js +1 -1
  10. package/src/clipboard.js +1 -1
  11. package/src/commands.js +158 -21
  12. package/src/config.js +2 -2
  13. package/src/deps.js +2 -1
  14. package/src/devrun.js +1 -1
  15. package/src/diff.js +1 -1
  16. package/src/events.js +38 -15
  17. package/src/export.js +1 -1
  18. package/src/fuzzy.js +1 -1
  19. package/src/history.js +3 -3
  20. package/src/init.js +1 -1
  21. package/src/input.js +1 -1
  22. package/src/keys.js +1 -1
  23. package/src/markdown.js +2 -2
  24. package/src/mcp.js +683 -0
  25. package/src/overlays.js +2 -2
  26. package/src/panels.js +52 -19
  27. package/src/permissions.js +2 -2
  28. package/src/render.js +2 -2
  29. package/src/screen.js +133 -8
  30. package/src/screens.js +1 -1
  31. package/src/summarize.js +1 -1
  32. package/src/system.js +2 -2
  33. package/src/theme.js +6 -6
  34. package/src/title.js +217 -0
  35. package/src/tokens.js +75 -96
  36. package/src/update.js +75 -1
  37. package/vendor/desktop/lib/local/agents.js +1 -1
  38. package/vendor/desktop/lib/local/autonomous.js +1 -1
  39. package/vendor/desktop/lib/local/engine.js +32 -8
  40. package/vendor/desktop/lib/local/git-scope.js +1 -1
  41. package/vendor/desktop/lib/local/prompt.js +3 -3
  42. package/vendor/desktop/lib/local/queue.js +2 -2
  43. package/vendor/desktop/lib/local/shell.js +1 -1
  44. package/vendor/desktop/lib/local/tools.js +2 -2
  45. package/vendor/desktop/lib/local/turn-guard.js +1 -1
  46. package/vendor/desktop/lib/local/worktree-lock.js +1 -1
  47. package/vendor/desktop/lib/settings.js +67 -0
  48. package/vendor/desktop/renderer/usage.js +377 -46
  49. package/vendor/hosts/install.js +638 -0
  50. package/vendor/hosts/openai-shim.js +419 -0
  51. package/vendor/hosts/spec.js +164 -0
  52. package/vendor/hosts/targets.js +346 -0
  53. package/vendor/mcp/server.js +186 -0
package/src/chatflow.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * The chatflow — the full-screen session loop, and the row/render helpers it
5
5
  * runs on.
6
6
  *
7
- * This is the aegiscodex-dev session loop: an alternate-screen frame of
7
+ * This is the upstream engine session loop: an alternate-screen frame of
8
8
  *
9
9
  * ╭──── AEGIS Code v6.2.0 ────╮ header rule
10
10
  * …transcript viewport… user rows, assistant markdown, tool rows
@@ -38,6 +38,7 @@ const {
38
38
  enterAltScreen, leaveAltScreen,
39
39
  enableBracketedPaste, disableBracketedPaste,
40
40
  enableMouseTracking, disableMouseTracking,
41
+ selectionRange, selectionText, applySelection,
41
42
  } = require('./screen.js');
42
43
  const {
43
44
  KEY, attachKeyStream, nextKey, nextKeyTimeout, requeueKeys, resetKeyStream,
@@ -51,6 +52,7 @@ const fuzzy = require('./fuzzy.js');
51
52
  const { fmtTokens, fmtEur, fmtElapsed } = require('./format.js');
52
53
  const { editPreview } = require('./diff.js');
53
54
  const { renderDiffBlock, defaultOpen } = require('./diffview.js');
55
+ const { copyToClipboard } = require('./clipboard.js');
54
56
 
55
57
  /** The rotating placeholder shown on an empty input line. */
56
58
  const SUGGESTIONS = [
@@ -61,8 +63,12 @@ const SUGGESTIONS = [
61
63
  'create a util logging.py that...',
62
64
  ];
63
65
 
64
- /** Terminal title spinner while a turn runs (the reference's frames). */
65
- const TITLE_SPIN = ['⠐', '⠂', '⠄', '⠆', '⠈', '⠠', '⠰', '⠁'];
66
+ /**
67
+ * Terminal title spinner while a turn runs (the reference's frames). Owned by
68
+ * `title.js`, which also derives the topic the title carries; re-exported here
69
+ * because this module's export list is part of the tested surface.
70
+ */
71
+ const { TITLE_SPIN, titleText, topicFrom, adoptTopic, titleEnabled, writeTitle } = require('./title.js');
66
72
 
67
73
  const FRAME_MS = 33; // ~30fps cap for streaming repaints
68
74
 
@@ -769,6 +775,15 @@ async function runSession(host) {
769
775
  // there. Rebuilt on every frame so it follows scrolling; a click reads it to
770
776
  // find which edit block to toggle.
771
777
  const clickHits = new Map();
778
+ // ── mouse marking (text selection) ────────────────────────────────────────
779
+ // The terminal's own selection can't see the alternate screen, so a drag is
780
+ // rebuilt here from the SGR stream (events.js) against the grid the last
781
+ // frame painted. `frameLines` is that grid — kept so selectionText() can read
782
+ // the cells the reader actually pointed at, not the transcript (which is
783
+ // re-wrapped, scrolled and clipped differently every frame).
784
+ let mark = null; // { anchor:{col,row}, head:{col,row} } — grid, 0-based
785
+ let pendingClick = null; // press awaiting its release: a click or a marking
786
+ let frameLines = [];
772
787
  let insertMode = false;
773
788
  let hintUntil = 0;
774
789
  let hintText = '';
@@ -776,18 +791,30 @@ async function runSession(host) {
776
791
  let streamJob = null;
777
792
  let streamStartedAt = 0;
778
793
  let tabCycle = null;
794
+ // The terminal title's topic — what this session is about, derived locally
795
+ // from the user's own prompts (see title.js). Empty until the first ask.
796
+ let topic = '';
797
+ let titleBar = true;
798
+ try {
799
+ titleBar = titleEnabled(process.env, host.loadConfig ? host.loadConfig() : host.config || {});
800
+ } catch {
801
+ titleBar = true;
802
+ }
779
803
 
780
804
  // ── rendering ──
781
805
  let renderPending = false;
782
806
  let lastPaintAt = 0;
783
807
 
784
- const setTitle = (text, spinning) => {
785
- const frame = spinning ? TITLE_SPIN[Math.floor(spinnerFrame / 2) % TITLE_SPIN.length] : '';
786
- try {
787
- process.stdout.write(`\x1b]0;${frame ? `${frame} ` : ''}${text}\x07`);
788
- } catch {
789
- /* not a TTY */
790
- }
808
+ /**
809
+ * Point the terminal title at the session's topic, spinning while a turn
810
+ * runs. Replaces the static "AEGIS Code" this used to write on every frame:
811
+ * that left every tab of every session reading identically, which is the one
812
+ * job a terminal title has.
813
+ */
814
+ const setTitle = (spinning) => {
815
+ if (!titleBar) return;
816
+ const frame = spinning ? TITLE_SPIN[Math.floor(spinnerFrame / 2) % TITLE_SPIN.length] : null;
817
+ writeTitle(titleText({ topic, frame }), process.stdout);
791
818
  };
792
819
 
793
820
  const buildFrame = () => {
@@ -840,7 +867,12 @@ async function runSession(host) {
840
867
  const cols = getSize().cols;
841
868
  const { lines, inputCol, rows, inputRow } = buildFrame();
842
869
  if (overlay) applyOverlay(lines, rows, cols);
843
- paint(lines);
870
+ // A marking paints over the grid the reader is dragging on; frameLines is
871
+ // kept for the copy on release (selectionText in screen.js). Assigned from
872
+ // the UNMARKED lines so the copied text is the text, not the reverse-video
873
+ // spans applySelection adds.
874
+ frameLines = lines;
875
+ paint(mark ? applySelection(lines, selectionRange(mark.anchor, mark.head), cols) : lines);
844
876
  lastPaintAt = Date.now();
845
877
  if (overlay) {
846
878
  hideCursor();
@@ -913,6 +945,34 @@ async function runSession(host) {
913
945
  return msg;
914
946
  };
915
947
 
948
+ /**
949
+ * Append a turn's tool row *before* the still-streaming answer row instead of
950
+ * after it.
951
+ *
952
+ * The answer row is created empty when the turn opens and grows in place as
953
+ * text streams, while each tool call appends a row of its own. Appending the
954
+ * tool rows after it left the growing answer ABOVE a run of tool rows: once
955
+ * the turn outgrew the window, the follow-the-bottom viewport showed only the
956
+ * newest tool row and the answer the reader was waiting for sat off the top
957
+ * of the window — "I have to scroll up to read the result". Inserting the
958
+ * tools ahead of the answer keeps the answer as the last row of the turn, so
959
+ * the bottom of the screen always holds the thing being waited for.
960
+ *
961
+ * `follow` is deliberately not re-applied: the rows this replaces were pushed
962
+ * with `{ follow: false }`, and a raw append never re-engaged the bottom.
963
+ *
964
+ * Known limit: a turn's text is already flattened into one `msg.text` (see
965
+ * the presenter's `text` hook), so text emitted *before* a tool call can't be
966
+ * split from text emitted after it. This trades that unrepresentable
967
+ * interleaving for the answer being on screen.
968
+ */
969
+ const pushToolRow = (msg, before) => {
970
+ const at = before ? transcript.indexOf(before) : -1;
971
+ if (at < 0) transcript.push(msg);
972
+ else transcript.splice(at, 0, msg);
973
+ return msg;
974
+ };
975
+
916
976
  const note = (text) => push({ role: 'note', text }, { follow: false });
917
977
 
918
978
  let streamedChars = 0;
@@ -961,14 +1021,17 @@ async function runSession(host) {
961
1021
  toolSeq = 0;
962
1022
  turnTools = [];
963
1023
  verb = VERBS[turnCount % VERBS.length];
1024
+ // Adopt the ask as this session's topic (kept when it is a follow-up), so
1025
+ // the tab reads what is being worked on from the first frame of the turn.
1026
+ topic = adoptTopic(topic, prompt);
964
1027
  abort = new AbortController();
965
1028
  spinnerTimer = setInterval(() => {
966
1029
  spinnerFrame++;
967
- setTitle('AEGIS Code', true);
1030
+ setTitle(true);
968
1031
  if (spinnerFrame % 3 === 0) render();
969
1032
  }, 100);
970
1033
  if (spinnerTimer.unref) spinnerTimer.unref();
971
-
1034
+ setTitle(true);
972
1035
  push({ role: 'user', text: prompt });
973
1036
  const msg = push({ role: 'assistant', text: '', streaming: true });
974
1037
  let sawReasoning = false;
@@ -1001,7 +1064,7 @@ async function runSession(host) {
1001
1064
  if (tool.phase === 'run') {
1002
1065
  const n = ++toolSeq;
1003
1066
  const prefix = tool.agent ? `${tool.agent} ▸ ` : '';
1004
- push(
1067
+ pushToolRow(
1005
1068
  {
1006
1069
  role: 'tool',
1007
1070
  phase: 'run',
@@ -1012,7 +1075,7 @@ async function runSession(host) {
1012
1075
  label: `Running ${n} ${prefix}${toolLabel(tool.name, n)}…`,
1013
1076
  start: Date.now(),
1014
1077
  },
1015
- { follow: false }
1078
+ msg
1016
1079
  );
1017
1080
  } else if (!resolveToolDone(transcript, tool)) {
1018
1081
  // A host that reports a tool once, after it ran, never opens a
@@ -1022,7 +1085,7 @@ async function runSession(host) {
1022
1085
  // turn silently showed no tool activity at all. Record the finished
1023
1086
  // tool directly instead.
1024
1087
  const n = ++toolSeq;
1025
- push(
1088
+ pushToolRow(
1026
1089
  {
1027
1090
  role: 'tool',
1028
1091
  phase: 'done',
@@ -1033,7 +1096,7 @@ async function runSession(host) {
1033
1096
  ok: tool.ok,
1034
1097
  label: `Ran ${n} ${tool.agent ? `${tool.agent} ▸ ` : ''}${toolLabel(tool.name, n)}`,
1035
1098
  },
1036
- { follow: false }
1099
+ msg
1037
1100
  );
1038
1101
  }
1039
1102
  scheduleRender();
@@ -1064,7 +1127,7 @@ async function runSession(host) {
1064
1127
  working = false;
1065
1128
  clearInterval(spinnerTimer);
1066
1129
  spinnerTimer = null;
1067
- setTitle('AEGIS Code', false);
1130
+ setTitle(false);
1068
1131
  const secs = Math.max(1, Math.round((Date.now() - startedAt) / 1000));
1069
1132
  const abortedFlag = !!(abort && abort.signal.aborted);
1070
1133
  msg.text = finalizeTurnText(msg.text, {
@@ -1185,9 +1248,14 @@ async function runSession(host) {
1185
1248
  abort = new AbortController();
1186
1249
  spinnerTimer = setInterval(() => {
1187
1250
  spinnerFrame++;
1251
+ // A slash command that runs long (an export, a compaction) is still this
1252
+ // session working, so the tab spins for it too and keeps the topic it
1253
+ // already had — no prompt here to derive a new one from.
1254
+ setTitle(true);
1188
1255
  if (spinnerFrame % 3 === 0) render();
1189
1256
  }, 100);
1190
1257
  if (spinnerTimer.unref) spinnerTimer.unref();
1258
+ setTitle(true);
1191
1259
  try {
1192
1260
  return await fn(abort.signal);
1193
1261
  } finally {
@@ -1195,6 +1263,7 @@ async function runSession(host) {
1195
1263
  clearInterval(spinnerTimer);
1196
1264
  spinnerTimer = null;
1197
1265
  abort = prev;
1266
+ setTitle(false);
1198
1267
  render();
1199
1268
  }
1200
1269
  };
@@ -1259,6 +1328,78 @@ async function runSession(host) {
1259
1328
  return c;
1260
1329
  };
1261
1330
 
1331
+ /**
1332
+ * Toggle the edit block painted on a screen row. Split out of the click
1333
+ * branch so the gesture resolver can call it for a press that never swept a
1334
+ * cell — the click path and the marking path must agree on what a click is.
1335
+ * Returns true when a block was toggled.
1336
+ */
1337
+ const toggleAtRow = (screenRow) => {
1338
+ const msg = clickHits.get(screenRow);
1339
+ if (msg && msg.diff) {
1340
+ msg.diffOpen = !msg.diffOpen;
1341
+ return true;
1342
+ }
1343
+ return false;
1344
+ };
1345
+
1346
+ // ── mouse gestures: click-to-toggle vs. drag-to-mark ──────────────────────
1347
+ // With DECSET 1002 (see screen.js enableMouseTracking) the terminal reports
1348
+ // every cell of a sweep, so the SAME left press can end as a click or as a
1349
+ // text marking — the press alone doesn't say which. The gesture is therefore
1350
+ // resolved on RELEASE:
1351
+ //
1352
+ // press → remember the cell; repaint nothing
1353
+ // drag → the press became a marking: anchor at the press, follow the
1354
+ // pointer (the reverse-video paint is the feedback)
1355
+ // release → marking swept more than one cell? copy it, drop it. Otherwise
1356
+ // it was a click: toggle the edit block under the press.
1357
+ //
1358
+ // Toggling on the press instead would flip an edit block open and shut as a
1359
+ // side effect of every drag that started inside one — the block would
1360
+ // collapse the moment the reader tried to select its contents.
1361
+ //
1362
+ // Coordinates arrive 1-based on the wire and grid rows are 0-based, hence the
1363
+ // -1 on both axes. Selection is read from `frameLines` (the last painted
1364
+ // grid), NOT the transcript, so the copied cells are the ones the reader
1365
+ // pointed at.
1366
+ const mouseGesture = (key) => {
1367
+ const cell = { col: key.col - 1, row: key.row - 1 };
1368
+ if (key.name === 'click') { pendingClick = cell; return false; }
1369
+ if (key.name === 'drag') {
1370
+ // A drag with no recorded press (the button went down before the stream
1371
+ // was attached, or a multiplexer dropped the press) still marks: DECSET
1372
+ // 1002 only reports motion while a button is held, so the anchor can be
1373
+ // seeded from the report itself.
1374
+ if (mark) mark.head = cell;
1375
+ else mark = { anchor: pendingClick || cell, head: cell };
1376
+ pendingClick = null;
1377
+ return true;
1378
+ }
1379
+ // release
1380
+ const pressed = pendingClick;
1381
+ pendingClick = null;
1382
+ const sel = mark ? selectionRange(mark.anchor, mark.head) : null;
1383
+ // A press that never swept a cell is a click, not a one-character marking:
1384
+ // an unsteady hand shouldn't leave a glyph on the clipboard.
1385
+ const swept = !!sel && !(sel.startRow === sel.endRow && sel.startCol === sel.endCol);
1386
+ mark = null;
1387
+ if (!swept) return toggleAtRow((pressed || cell).row);
1388
+ const text = selectionText(frameLines, sel);
1389
+ if (!text) return true;
1390
+ // Confirm in the transient hint slot (the line the Tab tip uses) rather
1391
+ // than in the transcript: a copy is a UI action, not a turn, and pushing a
1392
+ // note would edit the conversation the reader is copying FROM.
1393
+ const res = copyToClipboard(text);
1394
+ const n = text.split('\n').length;
1395
+ hintText = !res.ok ? 'Copy failed — no clipboard tool available'
1396
+ : res.via === 'file' ? `Marked ${n} line${n === 1 ? '' : 's'} → ${res.path}`
1397
+ : `Copied ${n} line${n === 1 ? '' : 's'}`;
1398
+ hintUntil = Date.now() + 2500;
1399
+ setTimeout(() => { if (Date.now() >= hintUntil) render(); }, 2600);
1400
+ return true;
1401
+ };
1402
+
1262
1403
  // ── live scroll while a turn runs ──
1263
1404
 
1264
1405
  const applyLiveScroll = (key) => {
@@ -1266,17 +1407,16 @@ async function runSession(host) {
1266
1407
  if (key.name === KEY.PAGE_UP) d = +5;
1267
1408
  else if (key.name === KEY.PAGE_DOWN) d = -5;
1268
1409
  else if (key.name === 'wheel') d = key.dir === 'up' ? +3 : -3;
1269
- else if (key.name === 'click') {
1270
- // A click on an edit row toggles its diff block. Not a scroll, but the
1271
- // same "act on the live frame, then repaint" shape — and routing it
1272
- // through here means it works both at the idle prompt and mid-turn,
1273
- // since drainWhileWorking feeds this same function.
1274
- const msg = clickHits.get(key.row);
1275
- if (msg && msg.diff) {
1276
- msg.diffOpen = !msg.diffOpen;
1277
- scheduleRender();
1278
- }
1279
- return true; // consumed: a click is never replayed as typed-ahead input
1410
+ // A click mid-turn toggles the same blocks it does when idle, and a drag
1411
+ // marks text mid-turn too: the transcript is already scrollable while the
1412
+ // model works, so it has to stay clickable and markable there — the answer
1413
+ // being streamed is exactly what a reader wants to copy. Resolved through
1414
+ // the shared gesture handler so the click/drag/release triplet can't be
1415
+ // handled two different ways depending on whether a turn happens to run.
1416
+ else if (key.name === 'click' || key.name === 'drag' || key.name === 'release') {
1417
+ if (!mouseGesture(key)) return true; // press: consumed, no repaint
1418
+ scheduleRender();
1419
+ return true;
1280
1420
  }
1281
1421
  else if (key.name === 'char' && ctx.vim && !insertMode && !editor.buf) {
1282
1422
  if (key.ch === 'j') d = +1;
@@ -1709,9 +1849,13 @@ async function runSession(host) {
1709
1849
  await dispatch('/permissions');
1710
1850
  return;
1711
1851
  }
1712
- if (key.name === 'click') {
1713
- // Consumed here: it either toggles an edit row's diff block or does
1714
- // nothing, but must never fall through to the input editor.
1852
+ if (key.name === 'click' || key.name === 'drag' || key.name === 'release') {
1853
+ // Consumed here: it toggles an edit row's diff block or marks/copies
1854
+ // text, but must never fall through to the input editor. Routed through
1855
+ // applyLiveScroll so the idle path and the mid-turn path share one
1856
+ // gesture resolver — handling only 'click' here left a drag-to-mark
1857
+ // silently dropped at the idle prompt (the release fell through to the
1858
+ // editor, which ignored it), so marking only worked mid-turn.
1715
1859
  applyLiveScroll(key);
1716
1860
  return;
1717
1861
  }
@@ -1804,7 +1948,11 @@ async function runSession(host) {
1804
1948
  /* not a TTY */
1805
1949
  }
1806
1950
  try {
1807
- process.stdout.write('\x1b]0;\x07');
1951
+ // Clear the title we wrote, so the shell that gets the terminal back is
1952
+ // not left wearing this app's title. Same OSC 0 writer as every other
1953
+ // title write, so there is exactly one place user text meets the bar —
1954
+ // and skipped entirely when the bar was never ours to write.
1955
+ if (titleBar) writeTitle('', process.stdout);
1808
1956
  } catch {
1809
1957
  /* not a TTY */
1810
1958
  }
@@ -1827,7 +1975,7 @@ async function runSession(host) {
1827
1975
  enterAltScreen();
1828
1976
  clearScreen();
1829
1977
  hideCursor();
1830
- setTitle('AEGIS Code', false);
1978
+ setTitle(false);
1831
1979
 
1832
1980
  const onResize = () => render();
1833
1981
  if (process.platform !== 'win32') process.on('SIGWINCH', onResize);
package/src/checkpoint.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * (bounded to the last CHECKPOINT_LIMIT), and /rewind lists or restores them.
7
7
  * Checkpoint 0 is the session start (empty transcript).
8
8
  *
9
- * Ported from aegiscodex-dev/src/checkpoint.js (ESM → CommonJS). The data dir
9
+ * Ported from the upstream engine reference (ESM → CommonJS). The data dir
10
10
  * now comes from config.js's shared `aegisDir()` helper.
11
11
  */
12
12
 
package/src/clipboard.js CHANGED
@@ -7,7 +7,7 @@
7
7
  * clipboard availability. Set AEGISCODE_NO_CLIPBOARD=1 to force the file
8
8
  * fallback (used by tests and headless setups).
9
9
  *
10
- * Ported from aegiscodex-dev/src/clipboard.js (ESM → CommonJS). The data dir
10
+ * Ported from the upstream engine reference (ESM → CommonJS). The data dir
11
11
  * comes from the shared `aegisDir()` helper and the force-fallback env var was
12
12
  * renamed AEGISCODEX_NO_CLIPBOARD → AEGISCODE_NO_CLIPBOARD.
13
13
  */
package/src/commands.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  /**
4
4
  * Slash commands — the CLI's full command vocabulary, ported from the sibling
5
- * `aegiscodex-dev` client (`src/registry.js`), on top of the AEGIS tool registry
5
+ * the upstream engine client (`src/registry.js`), on top of the AEGIS tool registry
6
6
  * (`mcp/tools.js`).
7
7
  *
8
8
  * Three kinds of entry live in one table:
@@ -10,7 +10,7 @@
10
10
  * (a) handler — a local `async (c, args) => bool` that runs against the
11
11
  * frozen command context `c` (see `cli/src/app.js`). It returns false to
12
12
  * end the session. This is the reference's own contract, so a handler
13
- * body reads the same here as it does in aegiscodex-dev — only the panels
13
+ * body reads the same here as it does in the upstream engine — only the panels
14
14
  * and support modules it calls are this client's.
15
15
  * (b) tool-backed — names a tool from `mcp/tools.js` and carries a
16
16
  * `build(arg) -> object` that turns the typed argument into the tool's
@@ -23,7 +23,7 @@
23
23
  * reason and a working `alt`; `parseLine` returns `{ kind: 'unavailable' }`
24
24
  * and `app.js` prints the reason rather than a fake success.
25
25
  *
26
- * The names, aliases, categories and descriptions come from aegiscodex-dev's
26
+ * The names, aliases, categories and descriptions come from the upstream engine's
27
27
  * `COMMANDS`/`CATEGORIES`. Where this client's capability genuinely differs from
28
28
  * the reference's the handler says so honestly (a note, an honest panel, or a
29
29
  * real command run through the ported support modules) rather than copying a
@@ -69,6 +69,7 @@ const { maskKey, fmtTokens } = require('./format.js');
69
69
  const { pickerEntries } = require('./models.js');
70
70
  const { openUrl, URLS } = require('./system.js');
71
71
  const { sniffProject, buildAegisMd } = require('./init.js');
72
+ const { upgradeAdvice, latestPublishedVersion } = require('./update.js');
72
73
  const {
73
74
  AGENT_PRESETS, agentRoles, composeAgentPrompt, composeResearchPrompt, composeDebatePrompt,
74
75
  } = require('./agents.js');
@@ -117,6 +118,106 @@ const tip = (c, text) => c.push({ role: 'tip', text });
117
118
  const done = (c, text) => c.push({ role: 'done', text });
118
119
  const shortCwd = () => process.cwd().split('/').filter(Boolean).pop() || '~';
119
120
 
121
+ // ── The multi-agent fan-out (/multi run, /multiyolo, /aegis-multi run) ────────
122
+ //
123
+ // These three commands used to only *compose* text: /multi <task> run and
124
+ // /aegis-multi <task> run printed "Running the task through the pooled brain
125
+ // (single-model — the reference fans it out)" and handed the raw task to
126
+ // c.runPrompt — a single turn, not a fan-out — while /multiyolo printed the
127
+ // paste-ready panel and never executed anything at all, so its `savePermissions
128
+ // ({ defaultMode: 'allow' })` turned YOLO on and then did nothing with it.
129
+ //
130
+ // The upstream engine calls `multiData(task, { signal })`, which
131
+ // shells out to aegis-cli (`aegis --print "/multi <task>"`) because the fan-out
132
+ // lives in that binary. This host has no aegis-cli, and a shell-out that fails
133
+ // on every machine without one is not a port — so the real multi-agent runtime
134
+ // here is the engine's own `task` tool (desktop/lib/local/engine.js
135
+ // `runSubagent`: a specialist subagent with its own tool loop, session id and
136
+ // approval card, primed from agents.js). One turn drives it, and the delegation
137
+ // is executed rather than described.
138
+
139
+ /** The fan-out prompt handed to the engine — the specialists are named so the delegation actually happens. */
140
+ function composeMultiFanoutPrompt(task) {
141
+ return [
142
+ 'Execute this task as a multi-agent fan-out.',
143
+ '',
144
+ `Task: ${task}`,
145
+ '',
146
+ `Workspace: ${process.cwd()}`,
147
+ '',
148
+ 'Use the task tool to delegate the independent parts to specialist subagents, in parallel where they do not depend on each other:',
149
+ '- reconnaissance first (scanner for secrets/unsafe patterns, analyzer for refactor targets),',
150
+ '- then design (architect, or planner when the work is a change to existing code),',
151
+ '- then an implementer subagent to make the change.',
152
+ 'Finally review the result (reviewer subagent), fix what it finds, and verify with the repository\'s real commands.',
153
+ '',
154
+ 'Return one consolidated report: what each subagent found, the files you changed, the exact commands you ran and their real output, and anything still blocked. No preamble.',
155
+ ].join('\n');
156
+ }
157
+
158
+ /**
159
+ * The this-host `multiData(task, { signal })`. Returns the reference's shape —
160
+ * `{ result, model, provider }`, `{ cancelled }`, or `{ error }` — so callers
161
+ * render it through `panels.buildAegisPrint` exactly as the reference does.
162
+ * `{ error }` is the honest fallback: the caller says why and still hands the
163
+ * user a paste-ready command instead of pretending the fan-out ran.
164
+ */
165
+ async function multiData(c, task) {
166
+ const prompt = composeMultiFanoutPrompt(task);
167
+ const run = c && c.withWorking ? (fn) => c.withWorking(fn) : (fn) => fn();
168
+ // A context with no agent loop at all (no ask, no runPrompt) is the one case
169
+ // this cannot execute — say so rather than returning an empty success.
170
+ if (!c || (typeof c.ask !== 'function' && typeof c.runPrompt !== 'function')) {
171
+ return { error: 'No agent loop in this context — the fan-out prompt was composed, not run.' };
172
+ }
173
+ try {
174
+ if (typeof c.ask === 'function') {
175
+ const res = await run((signal) => c.ask(prompt, { signal }));
176
+ const text = (res && res.text) || '';
177
+ if (res && res.interrupted && !text) return { cancelled: true };
178
+ if (!text) return { error: 'The multi-agent fan-out returned nothing (the turn failed before it could delegate).' };
179
+ return { result: text, model: (res && res.model) || (c.ctx && c.ctx.model) || null, provider: 'aegis' };
180
+ }
181
+ // No captured-answer path: still execute, streamed into the transcript.
182
+ await run(() => c.runPrompt(prompt));
183
+ return { streamed: true };
184
+ } catch (e) {
185
+ return { error: `ÆGIS multi failed — ${(e && e.message) || e}` };
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Drive one of the three fan-out commands end to end. `yolo` is /multiyolo's
191
+ * edge: the permission mode is set to allow *and* the task then executes under
192
+ * it (previously it was set and never used).
193
+ */
194
+ async function runMultiCommand(c, task, { yolo = false, title = 'ÆGIS Multi' } = {}) {
195
+ if (yolo) {
196
+ const rules = loadPermissions();
197
+ savePermissions({ ...rules, defaultMode: 'allow' });
198
+ panel(c, panels.buildYolo(c.state(), c.ctx));
199
+ }
200
+ note(c, 'Running the multi-agent fan-out — the engine delegates to specialist subagents (headless: this skips aegis-cli\'s own confirmation step).');
201
+ c.render();
202
+ const res = await multiData(c, task);
203
+ if (res.cancelled) { note(c, 'ÆGIS multi cancelled.'); c.render(); return true; }
204
+ if (res.error) {
205
+ note(c, res.error);
206
+ // Unreachable is not the same as useless: hand over the command that runs
207
+ // it in a real aegis-cli session.
208
+ panel(c, panels.buildAegisMulti(task, c.ctx));
209
+ c.render();
210
+ return true;
211
+ }
212
+ if (res.streamed) return true;
213
+ panel(c, panels.buildAegisPrint(title, res, c.ctx));
214
+ c.render();
215
+ return true;
216
+ }
217
+
218
+ /** /upgrade's advice as panel rows (the advice itself is plain strings). */
219
+ const upgradePanelLines = (lines) => lines.map((l) => [span(C.white, l)]);
220
+
120
221
  /**
121
222
  * The pinnable-model list for the class the session is on, fetched fresh.
122
223
  *
@@ -1002,7 +1103,13 @@ const COMMANDS = [
1002
1103
  const task = (args._rest || '').trim().replace(/^\S+\s*/, '').trim();
1003
1104
  if (!task) { note(c, `Usage: /agents <role> <task> — roles: ${agentRoles().join(', ')}`); c.render(); return true; }
1004
1105
  if (!AGENT_PRESETS[role]) { note(c, `Unknown agent role "${role}". Roles: ${agentRoles().join(', ')}`); c.render(); return true; }
1005
- await c.runPrompt(composeAgentPrompt(role, task));
1106
+ const prompt = composeAgentPrompt(role, task);
1107
+ if (c.runPrompt) {
1108
+ await c.runPrompt(prompt);
1109
+ return true;
1110
+ }
1111
+ note(c, `Composed ${role} prompt (${prompt.length} chars) — run in the TUI to send it.`);
1112
+ c.render();
1006
1113
  return true;
1007
1114
  }
1008
1115
  panel(c, panels.buildAgents(c.state(), c.ctx));
@@ -1181,6 +1288,22 @@ const COMMANDS = [
1181
1288
  return true;
1182
1289
  },
1183
1290
  },
1291
+ {
1292
+ name: 'upgrade', args: ['action'], hint: '[check]', category: 'support',
1293
+ desc: 'Check for a newer published version',
1294
+ handler: async (c) => {
1295
+ note(c, 'Checking the npm registry…');
1296
+ c.render();
1297
+ // The registry lookup is a blocking `npm view`, so it runs inside the
1298
+ // spinner when the context offers one (and is skipped entirely in demo
1299
+ // mode, where a network answer would be a lie).
1300
+ const run = c && c.withWorking ? (fn) => c.withWorking(fn) : (fn) => fn();
1301
+ const latest = c.ctx && c.ctx.demo ? null : await run(() => Promise.resolve(latestPublishedVersion()));
1302
+ panel(c, upgradePanelLines(upgradeAdvice({ latest }).lines));
1303
+ c.render();
1304
+ return true;
1305
+ },
1306
+ },
1184
1307
  {
1185
1308
  name: 'vim', args: ['mode'], hint: '[on|off]', category: 'model',
1186
1309
  desc: 'Toggle vim keymap',
@@ -1408,7 +1531,7 @@ const COMMANDS = [
1408
1531
  },
1409
1532
  },
1410
1533
 
1411
- // ── Phase 6 (part 2) families ─────────────────────────────────────────────
1534
+ // ── additional command families ─────────────────────────────────────────────
1412
1535
  {
1413
1536
  name: 'new', aliases: ['start'], hint: '', category: 'session',
1414
1537
  desc: 'Start a new session (clears the transcript, fresh session id)',
@@ -1581,13 +1704,10 @@ const COMMANDS = [
1581
1704
  handler: async (c, args) => {
1582
1705
  const task = (args._rest || args.task || '').trim();
1583
1706
  if (!task) { note(c, 'Usage: /multiyolo <task>'); c.render(); return true; }
1584
- const rules = loadPermissions();
1585
- savePermissions({ ...rules, defaultMode: 'allow' });
1586
- panel(c, panels.buildYolo(c.state(), c.ctx));
1587
- note(c, 'Composing ÆGIS /multiyolo — run it in aegis-cli (the confirmation prompt works there):');
1588
- panel(c, panels.buildAegisMulti(task, c.ctx));
1589
- c.render();
1590
- return true;
1707
+ // YOLO is the point of this alias: auto-approve, then actually run the
1708
+ // fan-out. Composing the text and stopping (what this used to do) left the
1709
+ // user with an enabled YOLO mode and an unexecuted task.
1710
+ return runMultiCommand(c, task, { yolo: true });
1591
1711
  },
1592
1712
  },
1593
1713
  {
@@ -1637,9 +1757,7 @@ const COMMANDS = [
1637
1757
  if (mode !== 'run' && /\s+run$/i.test(task)) { mode = 'run'; task = task.replace(/\s+run$/i, '').trim(); }
1638
1758
  if (!task) { note(c, 'Usage: /multi <task> [run]'); c.render(); return true; }
1639
1759
  if (mode !== 'run') { panel(c, panels.buildAegisMulti(task, c.ctx)); c.render(); return true; }
1640
- note(c, 'Running the task through the pooled brain (single-model — the reference fans it out).');
1641
- await c.runPrompt(task);
1642
- return true;
1760
+ return runMultiCommand(c, task);
1643
1761
  },
1644
1762
  },
1645
1763
  {
@@ -1648,7 +1766,16 @@ const COMMANDS = [
1648
1766
  handler: async (c, args) => {
1649
1767
  const q = (args._rest || args.question || '').trim();
1650
1768
  if (!q) { note(c, 'Usage: /research <question>'); c.render(); return true; }
1651
- await c.runPrompt(composeResearchPrompt(q, process.cwd()));
1769
+ const prompt = composeResearchPrompt(q, process.cwd());
1770
+ // Unguarded, `c.runPrompt` made this throw on any context without one
1771
+ // (the command smoke test caught the class of bug; the reference guards
1772
+ // it the same way). Composed-but-unrunnable is reported, not swallowed.
1773
+ if (c.runPrompt) {
1774
+ await c.runPrompt(prompt);
1775
+ return true;
1776
+ }
1777
+ note(c, `Composed research prompt (${prompt.length} chars) — run in the TUI to send it.`);
1778
+ c.render();
1652
1779
  return true;
1653
1780
  },
1654
1781
  },
@@ -1658,7 +1785,13 @@ const COMMANDS = [
1658
1785
  handler: async (c, args) => {
1659
1786
  const topic = (args._rest || args.topic || '').trim();
1660
1787
  if (!topic) { note(c, 'Usage: /debate <topic>'); c.render(); return true; }
1661
- await c.runPrompt(composeDebatePrompt(topic, c.ctx.model || ''));
1788
+ const prompt = composeDebatePrompt(topic, c.ctx.model || '');
1789
+ if (c.runPrompt) {
1790
+ await c.runPrompt(prompt);
1791
+ return true;
1792
+ }
1793
+ note(c, `Composed debate prompt (${prompt.length} chars) — run in the TUI to send it.`);
1794
+ c.render();
1662
1795
  return true;
1663
1796
  },
1664
1797
  },
@@ -1917,7 +2050,13 @@ const COMMANDS = [
1917
2050
  handler: async (c, args) => {
1918
2051
  const q = (args._rest || args.question || '').trim();
1919
2052
  if (!q) { note(c, 'Usage: /aegis-council <question>'); c.render(); return true; }
1920
- await c.runPrompt(composeResearchPrompt(`Deliberate as a council and vote on: ${q}`, process.cwd()));
2053
+ const prompt = composeResearchPrompt(`Deliberate as a council and vote on: ${q}`, process.cwd());
2054
+ if (c.runPrompt) {
2055
+ await c.runPrompt(prompt);
2056
+ return true;
2057
+ }
2058
+ note(c, `Composed council prompt (${prompt.length} chars) — run in the TUI to send it.`);
2059
+ c.render();
1921
2060
  return true;
1922
2061
  },
1923
2062
  },
@@ -1944,9 +2083,7 @@ const COMMANDS = [
1944
2083
  if (mode !== 'run' && /\s+run$/i.test(task)) { mode = 'run'; task = task.replace(/\s+run$/i, '').trim(); }
1945
2084
  if (!task) { note(c, 'Usage: /aegis-multi <task> [run]'); c.render(); return true; }
1946
2085
  if (mode !== 'run') { panel(c, panels.buildAegisMulti(task, c.ctx)); c.render(); return true; }
1947
- note(c, 'Running /multi headless — this skips aegis-cli\'s confirmation step.');
1948
- await c.runPrompt(task);
1949
- return true;
2086
+ return runMultiCommand(c, task);
1950
2087
  },
1951
2088
  },
1952
2089