aegiscode 6.8.2 → 6.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/aegiscode.js CHANGED
@@ -41,11 +41,14 @@ Account:
41
41
  aegiscode logout remove the saved key
42
42
  aegiscode key status show which key is in use and where it came from
43
43
 
44
- Autonomous work queue (no terminal needed — cron/systemd/ssh friendly):
45
- aegiscode autonomous add "task" queue a task to run unattended
46
- aegiscode autonomous list show the queue (--json for machines)
47
- aegiscode autonomous proceed drain every pending task, then exit
48
- aegiscode autonomous help all subcommands and their flags
44
+ Automation:
45
+ aegiscode autonomous help run queued tasks with no terminal at all
46
+ aegiscode mcp install put AEGIS inside VS Code / Cursor / Zed /
47
+ Cline / Windsurf / … ('mcp list' shows them)
48
+ aegiscode mcp status which editors are configured, and do they work
49
+ aegiscode mcp shim OpenAI-compatible endpoint for clients that
50
+ take a base URL but speak no MCP
51
+ aegiscode mcp help all subcommands and their flags
49
52
 
50
53
  Options:
51
54
  -m, --model <id> pin a model id (see /models; default: server choice)
@@ -128,6 +131,17 @@ function parseArgs(argv) {
128
131
  opts.commandArg = sub;
129
132
  opts.commandArgv = argv.slice(argv[1] && !argv[1].startsWith('-') ? 2 : 1);
130
133
  argv = [];
134
+ } else if (head === 'mcp') {
135
+ // The editor-integration surface, wired exactly like `autonomous` and for
136
+ // the same reason: everything after `mcp <sub>` is the subcommand's argv
137
+ // (`--target cursor,zed` is not this parser's flag), so the tail is handed
138
+ // over untouched. A bare `mcp` is the status report — the question a user
139
+ // actually has ("is AEGIS in my editors?") — not a prompt and not an error.
140
+ const sub = argv[1] && !argv[1].startsWith('-') ? argv[1] : 'status';
141
+ opts.command = 'mcp';
142
+ opts.commandArg = sub;
143
+ opts.commandArgv = argv.slice(argv[1] && !argv[1].startsWith('-') ? 2 : 1);
144
+ argv = [];
131
145
  }
132
146
 
133
147
  for (let i = 0; i < argv.length; i++) {
@@ -472,6 +486,22 @@ async function main(argv = process.argv.slice(2)) {
472
486
  });
473
487
  }
474
488
 
489
+ // The editor-integration surface. Dispatched here rather than among the
490
+ // account commands because it is not about THIS run: `mcp install` edits files
491
+ // other programs read, and `mcp serve` / `mcp shim` are long-running
492
+ // processes that must not be wrapped in a session (they are what an editor
493
+ // spawns behind a session of its own). Loaded lazily so `--help`,
494
+ // `--version` and an ordinary prompt never pay for the host registry.
495
+ if (opts.command === 'mcp') {
496
+ const { runMcpCommand } = require('../src/mcp.js');
497
+ return runMcpCommand(opts.commandArg, opts.commandArgv || [], {
498
+ json: opts.json,
499
+ stdin: process.stdin,
500
+ stdout: process.stdout,
501
+ stderr: process.stderr,
502
+ });
503
+ }
504
+
475
505
  const { createApp } = require('../src/app.js');
476
506
 
477
507
  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.8.2",
4
+ "version": "6.8.4",
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",
@@ -51,6 +51,29 @@ const FILES = [
51
51
  // quotes, and one stray one silently swallows the next real entry.)
52
52
  'client/env-file.js',
53
53
  'mcp/tools.js',
54
+ // The stdio MCP server itself — the process every editor config written by
55
+ // `aegiscode mcp install` points at. Staging the registry without it ships a
56
+ // package whose configs name a file that is not in the package, and an editor
57
+ // reports that as a server that simply never starts: no error the user can
58
+ // see. It exports nothing and registers its stdin handlers at load time, so
59
+ // it is verified by COMPILING it (see the probe below) and never required
60
+ // here — requiring it would switch the predist process stdin to flowing mode
61
+ // and it would then never exit.
62
+ 'mcp/server.js',
63
+ // The editor-integration layer: the host registry, the canonical server spec,
64
+ // and the merge-only installer behind `aegiscode mcp install|status|remove`.
65
+ // Staged under vendor/hosts/ so the tree keeps the repo shape — these files
66
+ // require ../client/*.js, which resolves INSIDE the vendor tree, and
67
+ // hosts/spec.js finds the server one level up as vendor/mcp/server.js.
68
+ 'hosts/spec.js',
69
+ 'hosts/targets.js',
70
+ 'hosts/install.js',
71
+ // The OpenAI-compatible shim (loopback /v1/chat/completions), for the many
72
+ // coding programs that take a base URL but speak no MCP. It resolves
73
+ // cli/src/models.js from either layout itself; in a checkout that is
74
+ // cli/src/models.js and in the package it is src/models.js, which ships
75
+ // because the CLI own source directory is published as-is.
76
+ 'hosts/openai-shim.js',
54
77
  'desktop/renderer/usage.js',
55
78
  // The agent-loop engine (persistent shell, editFile/grep/exec, Task
56
79
  // subagents) the desktop app already ships (desktop/lib/local/). The CLI
@@ -135,6 +158,82 @@ function main() {
135
158
  console.log(`predist: staged ${staged.length} shared modules into cli/vendor/`);
136
159
  for (const s of staged) console.log(` ${s}`);
137
160
  console.log(`predist: staged registry loads standalone (${count} tools)`);
161
+
162
+ // -------------------------------------------------------------------------
163
+ // The editor layer, proven from inside the staged tree.
164
+ // -------------------------------------------------------------------------
165
+ //
166
+ // Three things have to be true of the package we are about to publish, and
167
+ // none of them are visible from the repo:
168
+ //
169
+ // 1. the stdio server is present and is valid JavaScript;
170
+ // 2. `hosts/spec.js` resolves THAT copy of it, not a checkout path that
171
+ // only exists on this machine — an editor config pointing at a missing
172
+ // file fails silently, which is the worst failure mode there is;
173
+ // 3. `hosts/install.js` loads with its siblings resolved from vendor/.
174
+ //
175
+ // The server is compiled rather than required, deliberately: it registers
176
+ // process.stdin handlers at load time and exports nothing, so requiring it
177
+ // here would take over predist's own stdin and keep it alive forever.
178
+ const vm = require('node:vm');
179
+ const serverJs = path.join(VENDOR, 'mcp', 'server.js');
180
+ try {
181
+ new vm.Script(fs.readFileSync(serverJs, 'utf8'), { filename: serverJs });
182
+ } catch (err) {
183
+ console.error(`predist: staged mcp/server.js does not compile: ${err.message}`);
184
+ process.exit(1);
185
+ }
186
+
187
+ const hostsDir = path.join(VENDOR, 'hosts');
188
+ const spec = require(path.join(hostsDir, 'spec.js'));
189
+ const install = require(path.join(hostsDir, 'install.js'));
190
+ const targets = require(path.join(hostsDir, 'targets.js'));
191
+
192
+ // An empty AEGIS_MCP_SERVER so a developer's own override cannot mask a
193
+ // broken staged tree — the candidate we are asserting on must be the staged
194
+ // one, and nothing else.
195
+ const resolved = spec.resolveServer({ AEGIS_MCP_SERVER: '' });
196
+ const stagedServer = path.join(VENDOR, 'mcp', 'server.js');
197
+ if (!resolved.exists || resolved.path !== stagedServer) {
198
+ console.error(
199
+ `predist: staged hosts/spec.js resolves the server as ${resolved.path} ` +
200
+ `(exists: ${resolved.exists}), expected ${stagedServer}. An installed ` +
201
+ 'aegiscode would write editor configs pointing at a file the package ' +
202
+ `never shipped. Candidates were:\n ${resolved.candidates.join('\n ')}`
203
+ );
204
+ process.exit(1);
205
+ }
206
+
207
+ // Plan one real install against a throwaway home: this is the exact document
208
+ // `aegiscode mcp install vscode` would write, so it is the cheapest possible
209
+ // proof that the packaged command points at a file that exists.
210
+ const vscode = targets.getTarget('vscode');
211
+ const plan = install.planTarget(vscode, 'user', {
212
+ ctx: install.hostCtx({ home: path.join(VENDOR, '.predist-home'), env: {}, cwd: REPO_DIR }),
213
+ specOpts: { env: { AEGIS_MCP_SERVER: '' } },
214
+ });
215
+ const wrote = JSON.stringify(plan.after || '');
216
+ if (plan.error || !plan.changed || !wrote.includes(JSON.stringify(stagedServer).slice(1, -1))) {
217
+ console.error(
218
+ `predist: a planned vscode install does not name the staged server ` +
219
+ `(error: ${plan.error && plan.error.message}, changed: ${plan.changed})`
220
+ );
221
+ process.exit(1);
222
+ }
223
+
224
+ // The shim resolves cli/src/models.js from either layout on its own load; a
225
+ // checkout has it and the package ships it as src/models.js. Loading it here
226
+ // is what catches a repo-shaped require that only works in development.
227
+ const shim = require(path.join(hostsDir, 'openai-shim.js'));
228
+ if (typeof shim.createShimServer !== 'function') {
229
+ console.error('predist: staged hosts/openai-shim.js exposes no createShimServer');
230
+ process.exit(1);
231
+ }
232
+
233
+ console.log(
234
+ `predist: editor layer verified (${targets.targetIds().length} host targets, ` +
235
+ `server resolves to vendor/mcp/server.js, shim loads)`
236
+ );
138
237
  }
139
238
 
140
239
  main();
package/src/app.js CHANGED
@@ -21,7 +21,7 @@
21
21
  const readline = require('node:readline');
22
22
  const os = require('node:os');
23
23
  const { randomUUID } = require('node:crypto');
24
- const { createTools, createClient, usageTokens, buildSystemPrompt } = require('./deps.js');
24
+ const { createTools, createClient, usageTokens, usageBuckets, buildSystemPrompt } = require('./deps.js');
25
25
  const { createEngine, HOST_CLASSES, DEFAULT_CLASS, byokNamespace } = require('./engine.js');
26
26
  const { GLYPH, VERBS, themeOf, RESET, THEME_TABLE } = require('./theme.js');
27
27
  const { LiveRegion, termWidth, w } = require('./screen.js');
@@ -201,6 +201,8 @@ function createApp(options = {}) {
201
201
  tokens: 0,
202
202
  inputTokens: 0,
203
203
  outputTokens: 0,
204
+ cacheReadTokens: 0,
205
+ cacheWriteTokens: 0,
204
206
  cost: 0, // € spent, from the ledger rows that landed AFTER the baseline
205
207
  balance: null,
206
208
  // How many times each ledger-row identity is already accounted for.
@@ -1033,7 +1035,17 @@ function createApp(options = {}) {
1033
1035
  turns: session.turns,
1034
1036
  calls: session.calls,
1035
1037
  startedAt: session.startedAt,
1036
- tokens: { input: session.inputTokens, output: session.outputTokens, total: session.tokens },
1038
+ // The shared bucket shape `{input, output, cacheRead, cacheWrite}` — the
1039
+ // same object /cost's accounting and the ledger carry, so the panels
1040
+ // cannot render a different turn than the one that was billed. `input` is
1041
+ // the miss half; see recordTurn.
1042
+ tokens: {
1043
+ input: session.inputTokens,
1044
+ output: session.outputTokens,
1045
+ cacheRead: session.cacheReadTokens,
1046
+ cacheWrite: session.cacheWriteTokens,
1047
+ total: session.tokens,
1048
+ },
1037
1049
  costEur: session.cost,
1038
1050
  balance: session.balance,
1039
1051
  plan: session.plan || null,
@@ -1440,8 +1452,24 @@ function createApp(options = {}) {
1440
1452
  const tokens = usageTokens(usage);
1441
1453
  if (tokens != null) {
1442
1454
  session.tokens += tokens;
1443
- session.inputTokens += Number(usage.input_tokens ?? usage.prompt_tokens ?? 0) || 0;
1444
- session.outputTokens += Number(usage.output_tokens ?? usage.completion_tokens ?? 0) || 0;
1455
+ // The session tally is folded through the SHARED normaliser, not the raw
1456
+ // wire spellings. Reading `input_tokens ?? prompt_tokens` here is what
1457
+ // made the CLI's live tally disagree with its own ledger about the same
1458
+ // turn: the providers do not merely spell these fields differently, they
1459
+ // MEASURE them differently. Anthropic's `input_tokens` EXCLUDES
1460
+ // `cache_read_input_tokens`; OpenAI/DeepSeek's `prompt_tokens` INCLUDES
1461
+ // the hit. So `input + cacheRead` is right for the first and a
1462
+ // double-count of the prompt for the second. `usageBuckets` resolves
1463
+ // `input` to the MISS half in both cases (the same normalisation the
1464
+ // ledger row, the desktop roll and costBreakdown already use), which is
1465
+ // the only reading under which the /context prompt row means one thing on
1466
+ // every provider. Without this the CLI accumulated no cache buckets at
1467
+ // all, so /tokens drew two bars it could never fill.
1468
+ const b = usageBuckets(usage);
1469
+ session.inputTokens += b.input;
1470
+ session.outputTokens += b.output;
1471
+ session.cacheReadTokens += b.cacheRead;
1472
+ session.cacheWriteTokens += b.cacheWrite;
1445
1473
  }
1446
1474
  return tokens;
1447
1475
  }
@@ -1475,10 +1503,14 @@ function createApp(options = {}) {
1475
1503
  status,
1476
1504
  usage: usage
1477
1505
  ? {
1478
- input: Number(usage.input_tokens ?? usage.prompt_tokens ?? 0) || 0,
1479
- output: Number(usage.output_tokens ?? usage.completion_tokens ?? 0) || 0,
1480
- cacheRead: Number(usage.cache_read_input_tokens ?? 0) || 0,
1481
- cacheWrite: Number(usage.cache_creation_input_tokens ?? 0) || 0,
1506
+ // Not re-derived here. `usageBuckets` is the one module both
1507
+ // hosts resolve (deps.js), so the terminal and the GUI cannot
1508
+ // disagree about what a turn consumed — including whether a
1509
+ // provider's cached count sits INSIDE its prompt count
1510
+ // (OpenAI, DeepSeek) or BESIDE it (Anthropic). Reading only the
1511
+ // Anthropic spelling recorded cacheRead: 0 for every DeepSeek
1512
+ // turn, which priced the whole prompt at the miss rate.
1513
+ ...usageBuckets(usage),
1482
1514
  ...(settled != null ? { costUsd: settled } : {}),
1483
1515
  }
1484
1516
  : settled != null
package/src/chatflow.js CHANGED
@@ -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);