@0perator/operator 0.1.222 → 0.1.261

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 (110) hide show
  1. package/README.md +6 -5
  2. package/dashboard/server.mjs +1 -1
  3. package/dist/acp/agent.js +320 -53
  4. package/dist/acp/auth.js +44 -0
  5. package/dist/acp/config-options.js +34 -0
  6. package/dist/acp/prompt.js +41 -0
  7. package/dist/acp/run.js +116 -10
  8. package/dist/acp/tool-map.js +48 -0
  9. package/dist/auth/byo.js +125 -0
  10. package/dist/auth/client.js +12 -6
  11. package/dist/auth/commands.js +71 -3
  12. package/dist/auth/identity.js +136 -0
  13. package/dist/auth/store.js +7 -5
  14. package/dist/autonomy/board.js +3 -2
  15. package/dist/autonomy/cron.js +332 -0
  16. package/dist/autonomy/delegate.js +168 -0
  17. package/dist/autonomy/dream.js +1 -1
  18. package/dist/autonomy/index.js +16 -2
  19. package/dist/autonomy/media-robot.js +137 -0
  20. package/dist/autonomy/profile.js +77 -0
  21. package/dist/autonomy/routines.js +5 -4
  22. package/dist/autonomy/session-factory.js +19 -10
  23. package/dist/background/index.js +8 -1
  24. package/dist/browser/cdp.js +266 -0
  25. package/dist/browser/session.js +286 -0
  26. package/dist/cli.js +207 -106
  27. package/dist/compose/client.js +56 -0
  28. package/dist/config/brand.js +3 -3
  29. package/dist/config/home.js +70 -0
  30. package/dist/config/managed.js +230 -0
  31. package/dist/config/persona.js +243 -21
  32. package/dist/config/scaffold.js +142 -0
  33. package/dist/config/settings.js +87 -20
  34. package/dist/config/skills-index.js +175 -0
  35. package/dist/consolidation/scheduler.js +10 -7
  36. package/dist/consolidation/sleep.js +17 -3
  37. package/dist/engine/agent.js +231 -21
  38. package/dist/engine/aurora.js +79 -14
  39. package/dist/engine/batch-scheduler.js +128 -0
  40. package/dist/engine/compaction.js +129 -2
  41. package/dist/engine/computer-event.js +139 -0
  42. package/dist/engine/continuation.js +55 -0
  43. package/dist/engine/contract.js +3 -1
  44. package/dist/engine/grandmaster.js +13 -3
  45. package/dist/engine/json-repair.js +105 -0
  46. package/dist/engine/messages.js +52 -5
  47. package/dist/engine/redact.js +25 -0
  48. package/dist/engine/rolling-summary.js +28 -11
  49. package/dist/engine/router-adapter.js +2 -0
  50. package/dist/engine/unrestricted.js +51 -0
  51. package/dist/engine/verify-gate.js +6 -0
  52. package/dist/enterprise/cli.js +137 -0
  53. package/dist/flywheel/processor.js +30 -2
  54. package/dist/flywheel/secret-gate.js +123 -0
  55. package/dist/index.browser.js +4 -0
  56. package/dist/index.js +4 -0
  57. package/dist/mcp/index.js +18 -24
  58. package/dist/memory/index.js +0 -0
  59. package/dist/memory/session-index.js +324 -0
  60. package/dist/memory/session-rewind.js +92 -0
  61. package/dist/memory/state-maintenance.js +441 -0
  62. package/dist/observability/index.js +3 -3
  63. package/dist/permissions/audit.js +4 -1
  64. package/dist/permissions/index.js +24 -12
  65. package/dist/permissions/policy.js +4 -3
  66. package/dist/permissions/tier.js +31 -14
  67. package/dist/remote/host.js +9 -2
  68. package/dist/router/models.js +62 -2
  69. package/dist/selfimprove/index.js +9 -7
  70. package/dist/session.js +129 -42
  71. package/dist/skills/catalogue.js +167 -0
  72. package/dist/telemetry/audit-verify.js +94 -0
  73. package/dist/telemetry/events.js +92 -7
  74. package/dist/telemetry/lifecycle.js +18 -0
  75. package/dist/tools/computer.js +1 -1
  76. package/dist/tools/deferred.js +117 -0
  77. package/dist/tools/executor.js +27 -23
  78. package/dist/tools/memory.js +117 -0
  79. package/dist/tools/mutating.js +6 -0
  80. package/dist/tools/registry.js +1022 -46
  81. package/dist/tools/sandbox.js +63 -17
  82. package/dist/tools/searxng.js +2 -2
  83. package/dist/tools/shell-session.js +36 -1
  84. package/dist/tools/tool-output-spill.js +4 -4
  85. package/dist/ui/ActivitySpinner.js +17 -6
  86. package/dist/ui/App.js +36 -14
  87. package/dist/ui/ArtifactPicker.js +109 -0
  88. package/dist/ui/Composer.js +39 -8
  89. package/dist/ui/Markdown.js +5 -3
  90. package/dist/ui/MouseProvider.js +99 -19
  91. package/dist/ui/QuestionPrompt.js +24 -3
  92. package/dist/ui/ThinkingSpinner.js +9 -5
  93. package/dist/ui/ToolStep.js +17 -12
  94. package/dist/ui/Transcript.js +28 -9
  95. package/dist/ui/capabilities.js +0 -9
  96. package/dist/ui/listhit.js +23 -0
  97. package/dist/ui/mouse.js +22 -0
  98. package/dist/ui/osc.js +7 -4
  99. package/dist/ui/progressbar.js +46 -0
  100. package/dist/ui/shimmer.js +43 -0
  101. package/dist/ui/theme.js +2 -0
  102. package/dist/ui/tick.js +48 -0
  103. package/dist/ui/toolicons.js +69 -0
  104. package/dist/ui/useInputHistory.js +3 -3
  105. package/dist/util/slash.js +1 -0
  106. package/dist/vault/cli.js +48 -0
  107. package/dist/vault/store.js +157 -0
  108. package/dist/vault/tool.js +50 -0
  109. package/package.json +3 -5
  110. package/CHANGELOG.md +0 -1629
@@ -15,6 +15,7 @@
15
15
  // bundle (registry.ts pulls this module in, and it reaches the mobile JSCore engine). HOME comes from
16
16
  // the env; a minimal single-arg POSIX resolve() is inlined below. These sandbox functions only ever
17
17
  // run on the node CLI (tools execute natively on mobile), so this changes no behavior there.
18
+ import { get_operator_home } from "../config/home.js";
18
19
  function resolve(p) {
19
20
  const abs = p.startsWith("/") ? p : `${process.cwd()}/${p}`;
20
21
  const out = [];
@@ -32,6 +33,16 @@ export function sandboxMode() {
32
33
  const m = (process.env.KODE_SANDBOX ?? "off").toLowerCase();
33
34
  return m === "workspace" || m === "strict" ? m : "off";
34
35
  }
36
+ // macOS (APFS) and Windows default to CASE-INSENSITIVE filesystems — the Mac Studio fleet — so a denylist
37
+ // compared byte-exact is bypassable with a case variant: `file_write ~/.axe/operator/Settings.json` (or
38
+ // `~/.Ssh/authorized_keys`) resolves to the same real file but misses a lowercase `settings.json` match, so
39
+ // the agent rewrites its own policy or reads a secret. Fold case on those platforms for EVERY path
40
+ // comparison. Direction is safe: a deny-list that over-matches blocks MORE (never less); the strict-mode
41
+ // allow-roots also fold, which is correct because the case variants ARE the same directory there. A
42
+ // case-sensitive volume (rare on macOS, opt-in) is unaffected. Per-volume detection would be exact but needs
43
+ // fs on a hot path; the platform default is the safe, dependency-free call. (verified bypass, 2026-10-07 review)
44
+ const CASE_INSENSITIVE_FS = process.platform === "darwin" || process.platform === "win32";
45
+ const cf = (s) => (CASE_INSENSITIVE_FS ? s.toLowerCase() : s);
35
46
  const HOME = process.env.HOME ?? "";
36
47
  // Never writable when the sandbox is on, even inside home — protects credentials/keys/shell rc from an
37
48
  // errant model action. (Reads are unaffected; only writes are blocked.)
@@ -53,17 +64,41 @@ const SECRET_READ_SUBPATHS = [
53
64
  `${HOME}/.axe/secrets`, `${HOME}/.kube`, `${HOME}/.docker`,
54
65
  ];
55
66
  const SECRET_READ_FILES = [`${HOME}/.netrc`, `${HOME}/.git-credentials`];
67
+ // The Operator home guards ITS OWN policy, credentials and audit trail from the agent it hosts. A
68
+ // prompt-injected model that can `file_write` ~/.axe/operator/settings.json simply rewrites its own
69
+ // permissions to bypass+admin for the next launch, and one that can truncate events.jsonl erases the
70
+ // evidence — so the sandbox treats these exactly like ~/.ssh. Resolved per call (KODE_HOME / KODE_PROFILE
71
+ // can differ per process); ordinary state (memories, skills, sessions) stays writable.
72
+ const OP_WRITE_PROTECTED_FILES = ["settings.json", "settings.local.json", "managed-settings.json", "identity.json", "home.json", "credentials.json", "byo.json", "events.jsonl"];
73
+ const OP_WRITE_PROTECTED_DIRS = ["vault", "audit"];
74
+ const OP_SECRET_FILES = ["credentials.json", "byo.json"];
75
+ const OP_SECRET_DIRS = ["vault"];
76
+ const opPaths = (names) => names.map((n) => resolve(`${get_operator_home()}/${n}`));
77
+ function denyWriteSubpaths() { return [...DENY_WRITE_SUBPATHS, ...opPaths(OP_WRITE_PROTECTED_DIRS)]; }
78
+ function denyWriteFiles() { return [...DENY_WRITE_FILES, ...opPaths(OP_WRITE_PROTECTED_FILES)]; }
79
+ function secretReadSubpaths() { return [...SECRET_READ_SUBPATHS, ...opPaths(OP_SECRET_DIRS)]; }
80
+ function secretReadFiles() { return [...SECRET_READ_FILES, ...opPaths(OP_SECRET_FILES)]; }
81
+ // Session roots registered at runtime (an ACP editor session rooted outside process.cwd()): strict mode
82
+ // confines writes to the workspace, and "the workspace" is the session's root, not the host process cwd.
83
+ const extraWriteRoots = new Set();
84
+ export function allowSandboxWriteRoot(root) {
85
+ const r = resolve(root);
86
+ extraWriteRoots.add(r);
87
+ return () => { extraWriteRoots.delete(r); };
88
+ }
56
89
  // In strict mode, writes must land under one of these roots.
57
90
  function allowedWriteRoots() {
58
- return [process.cwd(), HOME + "/.axe/operator", "/tmp", "/private/tmp", process.env.TMPDIR ?? "/tmp"].map((p) => resolve(p));
91
+ const opHome = get_operator_home();
92
+ return [process.cwd(), opHome, "/tmp", "/private/tmp", process.env.TMPDIR ?? "/tmp", ...extraWriteRoots].filter(Boolean).map((p) => resolve(p));
59
93
  }
60
94
  /** Core check on an already-resolved absolute path (lexical or realpath'd). */
61
95
  function checkDenied(p, original) {
62
- const under = (root) => p === root || p.startsWith(root.endsWith("/") ? root : root + "/");
63
- for (const f of DENY_WRITE_FILES)
64
- if (p === resolve(f))
96
+ const pf = cf(p);
97
+ const under = (root) => { const rf = cf(root); return pf === rf || pf.startsWith(rf.endsWith("/") ? rf : rf + "/"); };
98
+ for (const f of denyWriteFiles())
99
+ if (pf === cf(resolve(f)))
65
100
  return `sandbox: writing ${original} is blocked (protected file)`;
66
- for (const d of DENY_WRITE_SUBPATHS)
101
+ for (const d of denyWriteSubpaths())
67
102
  if (under(resolve(d)))
68
103
  return `sandbox: writing under ${d} is blocked (protected path)`;
69
104
  if (sandboxMode() === "strict" && !allowedWriteRoots().some(under)) {
@@ -133,11 +168,12 @@ export async function deniedWriteAsync(path) {
133
168
  * outside the workspace + deny network). */
134
169
  /** Core secret-read check on an already-resolved absolute path. */
135
170
  function checkReadDenied(p, original) {
136
- const under = (root) => p === root || p.startsWith(root.endsWith("/") ? root : root + "/");
137
- for (const f of SECRET_READ_FILES)
138
- if (p === resolve(f))
171
+ const pf = cf(p);
172
+ const under = (root) => { const rf = cf(root); return pf === rf || pf.startsWith(rf.endsWith("/") ? rf : rf + "/"); };
173
+ for (const f of secretReadFiles())
174
+ if (pf === cf(resolve(f)))
139
175
  return `sandbox: reading ${original} is blocked (secret file)`;
140
- for (const d of SECRET_READ_SUBPATHS)
176
+ for (const d of secretReadSubpaths())
141
177
  if (under(resolve(d)))
142
178
  return `sandbox: reading under ${d} is blocked (secret path)`;
143
179
  return null;
@@ -166,16 +202,19 @@ export async function deniedReadAsync(path) {
166
202
  }
167
203
  export function seatbeltProfile(mode) {
168
204
  const q = (s) => s.replace(/"/g, '\\"');
169
- const denySub = DENY_WRITE_SUBPATHS.map((d) => `(subpath "${q(d)}")`).join(" ");
170
- const denyFiles = DENY_WRITE_FILES.map((f) => `(literal "${q(f)}")`).join(" ");
205
+ const denySub = denyWriteSubpaths().map((d) => `(subpath "${q(d)}")`).join(" ");
206
+ const denyFiles = denyWriteFiles().map((f) => `(literal "${q(f)}")`).join(" ");
171
207
  // Read-containment: block reads of credential paths in BOTH modes so a shell command can't read+exfil
172
208
  // secrets. Scoped to real secrets so /usr,/etc,/bin stay readable and normal commands still run.
173
- const denyReadSub = SECRET_READ_SUBPATHS.map((d) => `(subpath "${q(d)}")`).join(" ");
174
- const denyReadFiles = SECRET_READ_FILES.map((f) => `(literal "${q(f)}")`).join(" ");
209
+ const denyReadSub = secretReadSubpaths().map((d) => `(subpath "${q(d)}")`).join(" ");
210
+ const denyReadFiles = secretReadFiles().map((f) => `(literal "${q(f)}")`).join(" ");
175
211
  const denyRead = `(deny file-read* ${denyReadSub} ${denyReadFiles})`;
176
212
  if (mode === "strict") {
177
213
  const allow = allowedWriteRoots().concat("/dev").map((r) => `(subpath "${q(r)}")`).join(" ");
178
- return `(version 1)(allow default)(deny file-write*)(allow file-write* ${allow})${denyRead}(deny network*)`;
214
+ // SBPL is last-match-wins: the operator home is an allowed root (memory, sessions…), so its protected
215
+ // policy/secret/audit paths are re-denied AFTER the allow.
216
+ const opHome = [...opPaths(OP_WRITE_PROTECTED_DIRS).map((d) => `(subpath "${q(d)}")`), ...opPaths(OP_WRITE_PROTECTED_FILES).map((f) => `(literal "${q(f)}")`)].join(" ");
217
+ return `(version 1)(allow default)(deny file-write*)(allow file-write* ${allow})(deny file-write* ${opHome})${denyRead}(deny network*)`;
179
218
  }
180
219
  return `(version 1)(allow default)(deny file-write* ${denySub} ${denyFiles})${denyRead}`;
181
220
  }
@@ -194,21 +233,28 @@ export function bwrapArgs(mode) {
194
233
  a.push("--proc", "/proc", "--dev", "/dev");
195
234
  for (const root of allowedWriteRoots())
196
235
  a.push("--bind-try", root, root); // … except the allow-roots
236
+ // the operator home is an allow-root, so its policy/audit paths are re-bound read-only on top of it
237
+ for (const d of opPaths(OP_WRITE_PROTECTED_DIRS))
238
+ a.push("--ro-bind-try", d, d);
239
+ for (const f of opPaths(OP_WRITE_PROTECTED_FILES))
240
+ a.push("--ro-bind-try", f, f);
197
241
  a.push("--unshare-net"); // strict: no network
198
242
  }
199
243
  else {
200
244
  a.push("--bind", "/", "/"); // workspace: FS writable …
201
245
  a.push("--proc", "/proc", "--dev", "/dev");
202
- for (const d of DENY_WRITE_SUBPATHS)
246
+ for (const d of denyWriteSubpaths())
203
247
  a.push("--ro-bind-try", resolve(d), resolve(d)); // … protected dirs read-only
204
248
  for (const f of DENY_WRITE_FILES)
205
249
  a.push("--ro-bind-try", "/dev/null", resolve(f)); // protected files masked
250
+ for (const f of opPaths(OP_WRITE_PROTECTED_FILES))
251
+ a.push("--ro-bind-try", f, f); // operator policy files: readable, not writable
206
252
  }
207
253
  // Read-containment (BOTH modes): mask secret dirs with an empty tmpfs, secret files with /dev/null,
208
254
  // so a shell command can't read + exfil credentials. Placed last so it wins over the writable binds.
209
- for (const d of SECRET_READ_SUBPATHS)
255
+ for (const d of secretReadSubpaths())
210
256
  a.push("--tmpfs", resolve(d));
211
- for (const f of SECRET_READ_FILES)
257
+ for (const f of secretReadFiles())
212
258
  a.push("--ro-bind", "/dev/null", resolve(f));
213
259
  a.push("--die-with-parent");
214
260
  return a;
@@ -69,8 +69,8 @@ async function dockerAvailable() {
69
69
  /** Write ~/.axe/operator/searxng/settings.yml (json API on + a secret) if absent; return the dir. */
70
70
  async function ensureSettingsDir() {
71
71
  const fs = await nodeImport("node:fs/promises");
72
- const home = process.env.HOME || "";
73
- const dir = `${home}/.axe/operator/searxng`;
72
+ const { operatorPath } = await import("../config/home.js");
73
+ const dir = operatorPath("searxng");
74
74
  await fs.mkdir(dir, { recursive: true });
75
75
  const file = `${dir}/settings.yml`;
76
76
  try {
@@ -67,13 +67,19 @@ export class ShellSession {
67
67
  p.stdin?.unref?.();
68
68
  }
69
69
  catch { /* */ }
70
+ // GW-35 pipefail: without it, `npm test | tail` reports TAIL's exit — a failing check hidden
71
+ // behind a pipe looked like success to the model AND silently cleared the verify-before-done
72
+ // gate (verify-gate.ts treats a missing [exit N] trailer as pass). This was not theoretical:
73
+ // it bit every agent on this box all day, including three self-merges' worth of `| tail -1`
74
+ // output where the merge had actually failed. With pipefail, ANY non-zero stage surfaces as
75
+ // the run's exit code — the semantics every CI system and the model already assume.
70
76
  // Merge stderr into stdout AT THE SHELL (fd2→fd1) so both stream through ONE ordered pipe —
71
77
  // "merged like a terminal" for real. Merging two separate OS pipes in JS (stdout + stderr
72
78
  // handlers) is racy: the two pipes flush independently, so a command's stderr chunk can land
73
79
  // in the buffer AFTER the sentinel that follows it on stdout, and get sliced off (the
74
80
  // "stderr is merged" test flaking on `echo err 1>&2`). `exec 2>&1` removes the race entirely.
75
81
  // Quiet the shell and disable history expansion so commands frame cleanly.
76
- p.stdin.write("exec 2>&1; export PS1='' PROMPT_COMMAND=''; set +o history 2>/dev/null; true\n");
82
+ p.stdin.write("exec 2>&1; set -o pipefail; export PS1='' PROMPT_COMMAND=''; set +o history 2>/dev/null; true\n");
77
83
  await new Promise((r) => setTimeout(r, 30));
78
84
  this.buf = "";
79
85
  })();
@@ -235,3 +241,32 @@ export class ShellSession {
235
241
  this.buf = "";
236
242
  }
237
243
  }
244
+ /** GW-35: honest exit-code annotation for the shell tool. Pure + exported so the rules are testable
245
+ * without a live shell. Returns { exitForTrailer, notes } — `exitForTrailer` is the code the tool
246
+ * reports (141/SIGPIPE from an intentional `| head` truncation is normalized to 0 WITH a note; any
247
+ * other non-zero passes through under pipefail semantics: first failing stage wins). `notes` carries
248
+ * actionable hints for the two failure classes that cost this fleet hours: BSD-vs-GNU flag drift and
249
+ * swallowed-pipe results. */
250
+ export function shellResultNotes(command, exitCode, output) {
251
+ const notes = [];
252
+ let code = exitCode;
253
+ if (code === 141 && command.includes("|")) {
254
+ // 141 = 128+SIGPIPE: upstream died because a downstream (head/tail) closed the pipe EARLY — a
255
+ // deliberate truncation, not a failure. Report as pass with the truth preserved in the note.
256
+ code = 0;
257
+ notes.push("[exit 141 normalized: the pipeline was truncated by `| head`/`| tail` (SIGPIPE), not failed]");
258
+ }
259
+ if (code) {
260
+ const out = output.toLowerCase();
261
+ if (/invalid option|illegal option|unrecognized option|invalid command code|usage: sed|usage: grep|gnu_/.test(out)) {
262
+ notes.push("[hint: macOS ships BSD sed/grep/awk — GNU-isms fail here: `sed -n 'X,+Np'` (use a computed 'X,Yp' range or `awk 'NR>=X&&NR<X+N'`), `grep -P` (use grep -E), `date -d` (use date -j -f). Rewrite and retry.]");
263
+ }
264
+ if (out.includes("command not found") && /\btimeout\b|\bsed -i\b|\brealpath\b|\breadlink -f\b/.test(command)) {
265
+ notes.push("[hint: not installed on macOS by default — use `gtimeout` (brew coreutils), `sed -i ''`, or a python one-liner.]");
266
+ }
267
+ if (command.includes("|") && code === 1) {
268
+ notes.push("[note: pipefail is ON — exit 1 may come from ANY stage; if an early stage legitimately exits 1 (grep no-match), split the pipeline to see which part failed.]");
269
+ }
270
+ }
271
+ return { exitForTrailer: code, notes };
272
+ }
@@ -11,14 +11,14 @@
11
11
  import { createHash } from "node:crypto";
12
12
  import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
13
13
  import { join } from "node:path";
14
- import { homedir } from "node:os";
14
+ import { operatorPath } from "../config/home.js";
15
15
  const RETENTION_MS = 14 * 24 * 3600_000; // spill files older than 14 days are pruned
16
16
  const MAX_DIR_BYTES = 500 * 1024 * 1024; // hard ceiling on the spill dir (500MB)
17
17
  const SWEEP_INTERVAL_MS = 3600_000; // at most once per hour, from spillToolOutput
18
18
  /** Where spilled tool outputs live. A flat dir under the operator home; the model is handed absolute paths.
19
19
  * KODE_TOOL_OUTPUT_DIR overrides it (tests/CI/second-user isolation). */
20
20
  export function toolOutputDir() {
21
- return process.env.KODE_TOOL_OUTPUT_DIR || join(homedir(), ".axe", "operator", "tool-outputs");
21
+ return process.env.KODE_TOOL_OUTPUT_DIR || operatorPath("tool-outputs");
22
22
  }
23
23
  let _lastSweep = 0;
24
24
  /** Best-effort retention sweep: age out >RETENTION_MS files, then cap the dir at MAX_DIR_BYTES oldest-first.
@@ -72,11 +72,11 @@ export function sweepToolOutputs(dir = toolOutputDir(), opts = {}) {
72
72
  export function spillToolOutput(full) {
73
73
  try {
74
74
  const dir = toolOutputDir();
75
- mkdirSync(dir, { recursive: true });
75
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
76
76
  sweepToolOutputs(dir);
77
77
  const hash = createHash("sha1").update(full).digest("hex").slice(0, 12);
78
78
  const path = join(dir, `${Date.now().toString(36)}-${hash}.txt`);
79
- writeFileSync(path, full);
79
+ writeFileSync(path, full, { mode: 0o600 }); // H4: spilled tool output is transcript-grade secret material
80
80
  return path;
81
81
  }
82
82
  catch {
@@ -5,9 +5,11 @@ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
5
5
  // tofu (same font-safety rule as the star).
6
6
  // • StepSpinner — a tool batch is executing (braille run-spinner, cyan)
7
7
  // • OrbitSpinner — a background sub-agent is working (rotating arc, violet)
8
- import { useEffect, useState } from "react";
8
+ import { useEffect, useRef, useState } from "react";
9
9
  import { Text } from "ink";
10
10
  import { theme } from "./theme.js";
11
+ import { useTick } from "./tick.js";
12
+ import { renderBar } from "./progressbar.js";
11
13
  function useFrame(frames, active, tickMs) {
12
14
  const [i, setI] = useState(0);
13
15
  useEffect(() => {
@@ -39,11 +41,20 @@ export function OrbitSpinner({ active, label, tickMs = 120 }) {
39
41
  export function OrbitGlyph({ tickMs = 120 }) {
40
42
  return _jsx(Text, { color: theme.accent, children: useFrame(ORBIT, true, tickMs) });
41
43
  }
42
- /** Self-heal in progress (context compaction / reconnect). Shown INSTEAD of a raw "http 400" so a
43
- * recovery reads as the agent working it out, not an error — amber turning disc + a calm label. */
44
- export function RecoverSpinner({ active, label, tickMs = 130 }) {
45
- const glyph = useFrame(SETTLE, active, tickMs);
44
+ /** Self-heal in progress (context compaction / reconnect). Shown INSTEAD of a raw "http 400" so a recovery
45
+ * reads as the agent working it out, not an error — a PINK turning disc + a calm label + a PINK bar that
46
+ * FILLS as it works (full ≈ done). Compaction reports no percentage, so the fill is elapsed-based: it grows
47
+ * toward a typical duration and caps just shy of full, then the spinner unmounts the moment compaction
48
+ * finishes (status leaves "compacting"). Disc + fill advance off the ONE shared ticker (tick.ts). */
49
+ const COMPACT_FILL_TICKS = 150; // ~18s at ~120ms/tick — the bar fills over a typical compaction, capped <100%
50
+ export function RecoverSpinner({ active, label }) {
51
+ const frame = useTick(active);
52
+ const startRef = useRef(null);
53
+ useEffect(() => { startRef.current = active ? frame : null; }, [active]); // reset the fill each time it (re)activates
46
54
  if (!active)
47
55
  return null;
48
- return (_jsxs(Text, { color: theme.running, children: [glyph, " ", label ?? "adjusting", "\u2026"] }));
56
+ const elapsed = startRef.current == null ? 0 : frame - startRef.current;
57
+ const fraction = Math.min(0.96, elapsed / COMPACT_FILL_TICKS); // fills toward near-full; snaps away (unmounts) when done
58
+ const glyph = SETTLE[frame % SETTLE.length];
59
+ return (_jsxs(Text, { color: theme.compactProgress, children: [glyph, " ", label ?? "adjusting", "\u2026 ", _jsx(Text, { color: theme.compactProgress, children: renderBar(fraction) })] }));
49
60
  }
package/dist/ui/App.js CHANGED
@@ -2,11 +2,11 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
2
2
  // Composes the UI lane into the SPEC §6 shell. This is the whole UI/engine contract surface —
3
3
  // the engine lane wires state + callbacks into these props; nothing below reaches into
4
4
  // src/engine, src/tools, or src/router.
5
- import { useEffect, useState } from "react";
6
- import { Box, Text } from "ink";
5
+ import { useEffect, useRef, useState } from "react";
6
+ import { Box, Text, measureElement } from "ink";
7
7
  import { termRows } from "./term.js";
8
8
  import { caps } from "./capabilities.js";
9
- import { MouseProvider, useOnWheel } from "./MouseProvider.js";
9
+ import { MouseProvider, useOnWheel, useMouse } from "./MouseProvider.js";
10
10
  import { StatusRule } from "./StatusRule.js";
11
11
  import { InputRule } from "./InputRule.js";
12
12
  import { Transcript } from "./Transcript.js";
@@ -18,13 +18,14 @@ import { PlanPane } from "./PlanPane.js";
18
18
  import { ToolStep } from "./ToolStep.js";
19
19
  import { ApprovalPrompt } from "./ApprovalPrompt.js";
20
20
  import { QuestionPrompt } from "./QuestionPrompt.js";
21
+ import { ArtifactPicker } from "./ArtifactPicker.js";
21
22
  // Cap on live rows shown at once for a parallel tool batch — keeps the dynamic (non-Static) frame
22
23
  // bounded (same render-collapse concern liveTail guards in Transcript.tsx: Ink corrupts the frame once
23
24
  // the non-Static portion approaches the terminal height). A batch rarely runs more than a handful of
24
25
  // calls at once; anything past the cap is summarized as a count instead of another row.
25
26
  const MAX_LIVE_TOOL_ROWS = 6;
26
27
  export function App(props) {
27
- const { messages, live = null, status, thinkingVerb, verbs, stepLabel, liveTools = [], route, ctxPct, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, tasks = [], onSubmit, onQueue, onInterrupt, onCycleMode, opMode, approval = null, onApprovalDecide, question = null, modelPicker = null, planExitPicker = null } = props;
28
+ const { messages, live = null, status, thinkingVerb, verbs, stepLabel, liveTools = [], route, ctxPct, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, tasks = [], onSubmit, onQueue, onInterrupt, onCycleMode, opMode, approval = null, onApprovalDecide, question = null, modelPicker = null, planExitPicker = null, artifactsPicker = null } = props;
28
29
  const thinking = status === "thinking" || status === "streaming";
29
30
  // A parallel batch (2+ live rows) gets its own per-call view instead of the single-line StepSpinner —
30
31
  // a lone call isn't worth a bordered block, the braille spinner + name already says enough.
@@ -36,21 +37,42 @@ export function App(props) {
36
37
  : _jsx(ThinkingSpinner, { active: true, verb: thinkingVerb, verbs: verbs, metrics: metrics }) })), showParallelRows && (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, paddingLeft: 1, children: [_jsxs(Text, { dimColor: true, children: ["running ", liveTools.length, " tools in parallel"] }), liveTools.slice(0, MAX_LIVE_TOOL_ROWS).map((step) => _jsx(ToolStep, { step: step }, step.id)), liveTools.length > MAX_LIVE_TOOL_ROWS ? _jsxs(Text, { dimColor: true, children: [" +", liveTools.length - MAX_LIVE_TOOL_ROWS, " more\u2026"] }) : null] })), _jsx(PlanPane, { tasks: tasks }), _jsx(BgPanel, { agents: bgAgents }), (thinking || status === "executing" || status === "recovering") && (_jsx(Text, { dimColor: true, children: ` ${status === "executing" ? "running tools" : status === "recovering" ? "recovering" : status === "streaming" ? "writing" : "reasoning"} · esc to interrupt` }))] }));
37
38
  // Interactive prompts own the keyboard while up; kept out of the fullscreen clip region so they can't
38
39
  // be scrolled off. The Composer is `suspended` (keystrokes route to the decision, not the draft).
39
- const prompts = (_jsxs(_Fragment, { children: [_jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(QuestionPrompt, { pending: modelPicker }), _jsx(QuestionPrompt, { pending: planExitPicker })] }));
40
+ const prompts = (_jsxs(_Fragment, { children: [_jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(QuestionPrompt, { pending: modelPicker }), _jsx(QuestionPrompt, { pending: planExitPicker }), _jsx(ArtifactPicker, { pending: artifactsPicker })] }));
40
41
  // The pinned bottom band: status rule, composer, bottom rule, then the mode/cycle FOOTER below the rule.
41
- const bottom = (_jsxs(_Fragment, { children: [_jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker || !!planExitPicker }), _jsx(InputRule, {}), opMode && (_jsx(Text, { dimColor: true, children: ` ${opMode === "auto" ? "◆ Autonomous" : opMode === "manual" ? "◈ Manual" : "◔ Plan"} · shift+tab to cycle` }))] }));
42
+ const bottom = (_jsxs(_Fragment, { children: [_jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker || !!planExitPicker || !!artifactsPicker }), _jsx(InputRule, {}), opMode && (_jsx(Text, { dimColor: true, children: ` ${opMode === "auto" ? "◆ Autonomous" : opMode === "manual" ? "◈ Manual" : "◔ Plan"} · shift+tab to cycle` }))] }));
42
43
  // Fullscreen (opt-in): a full-terminal-height column. The transcript fills a clipped, bottom-anchored
43
44
  // region (non-Static tail) so the newest output sits just above a composer pinned to the very bottom —
44
45
  // no dead space. Off by default: inline keeps the terminal's native scrollback (mouse-scroll + copy).
45
46
  if (fullscreen) {
46
- // Enable the SGR mouse layer ONLY in fullscreen on a mouse-capable TTY — inline keeps the terminal's
47
- // native scroll+copy, so it must never receive tracking. FullscreenBody (under the provider) turns
48
- // wheel events into scrollback over the alt-screen transcript, which otherwise has no way to scroll.
49
- return (_jsx(MouseProvider, { enabled: caps().mouse, children: _jsx(FullscreenBody, { messages: messages, live: live, activity: activity, prompts: prompts, bottom: bottom }) }));
47
+ // Fullscreen: SGR tracking stays ON (alwaysTrack) — wheel drives the alt-screen scrollback and the
48
+ // geometry is deterministic (composer pinned to the bottom), so click anchors need no DSR probe.
49
+ return (_jsx(MouseProvider, { enabled: caps().mouse, alwaysTrack: true, children: _jsx(FullscreenBody, { messages: messages, live: live, activity: activity, prompts: prompts, bottom: bottom }) }));
50
50
  }
51
- // Inline (default): the dynamic frame grows below the Static transcript; unused space sits below it and
52
- // fills as the conversation grows. Native scrollback preserved.
53
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Transcript, { entries: messages, live: live }), activity, prompts, bottom] }));
51
+ // Inline (default): the dynamic frame grows below the Static transcript. The mouse layer mounts here too,
52
+ // but DEMAND-DRIVEN — the provider only turns SGR tracking on while an overlay (picker/approval) is open,
53
+ // so the terminal's native scrollback (wheel-scroll + drag-to-copy) is untouched the rest of the time.
54
+ // The composer is measured (MeasuredComposer) so an open picker's click anchor knows what sits below it.
55
+ return (_jsx(MouseProvider, { enabled: caps().mouse, children: _jsxs(Box, { flexDirection: "column", children: [_jsx(Transcript, { entries: messages, live: live }), activity, _jsxs(MeasuredStack, { children: [prompts, bottom] })] }) }));
56
+ }
57
+ // Measures the overlay stack (open picker + the composer block below it) as ONE block and publishes its
58
+ // height to the mouse layer. An open picker is the top of this stack, so its top row = frameBottom −
59
+ // stackHeight + 1 — the single measurement folds in the composer height and every inter-element margin, so
60
+ // click anchoring carries no per-margin bookkeeping. A ref guards against re-reporting an unchanged height
61
+ // (which would loop through setState). Rendered inside MouseProvider by both layouts.
62
+ function MeasuredStack({ children }) {
63
+ const ref = useRef(null);
64
+ const last = useRef(0);
65
+ const { setStackHeight } = useMouse();
66
+ useEffect(() => {
67
+ if (!ref.current)
68
+ return;
69
+ const { height } = measureElement(ref.current);
70
+ if (height > 0 && height !== last.current) {
71
+ last.current = height;
72
+ setStackHeight(height);
73
+ }
74
+ });
75
+ return _jsx(Box, { ref: ref, flexDirection: "column", children: children });
54
76
  }
55
77
  // Entries the transcript window slides per wheel notch. A notch is one detent of the physical wheel; 3
56
78
  // entries keeps scrollback brisk without leaping past short exchanges.
@@ -70,5 +92,5 @@ function FullscreenBody({ messages, live, activity, prompts, bottom }) {
70
92
  ? Math.min(s + WHEEL_STEP, Math.max(0, messages.length - 1)) // clamp: the oldest entry stays reachable
71
93
  : Math.max(0, s - WHEEL_STEP));
72
94
  });
73
- return (_jsxs(Box, { flexDirection: "column", height: rows, children: [_jsxs(Box, { flexGrow: 1, flexDirection: "column", overflow: "hidden", justifyContent: "flex-end", children: [_jsx(Transcript, { entries: messages, live: live, bounded: true, scrollBack: scrollBack }), activity] }), prompts, bottom] }));
95
+ return (_jsxs(Box, { flexDirection: "column", height: rows, children: [_jsxs(Box, { flexGrow: 1, flexDirection: "column", overflow: "hidden", justifyContent: "flex-end", children: [_jsx(Transcript, { entries: messages, live: live, bounded: true, scrollBack: scrollBack }), activity] }), _jsxs(MeasuredStack, { children: [prompts, bottom] })] }));
74
96
  }
@@ -0,0 +1,109 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // The /artifacts browser (Phase 1): a Compose (compose.casa) artifact picker, modelled on QuestionPrompt —
3
+ // a pure keystroke reducer (testable without a TTY) + useInput gated while the picker is up, rendered as a
4
+ // bordered inline box above the composer (Operator has no alt-screen modal system; see App.tsx prompts).
5
+ // P1 scope: the owner's library ("Mine") with live search, and per-row actions attach / copy-url / delete /
6
+ // refresh. Tabs All/Shared and rename/pin are Phase 2/3 (they need Compose backend work) — shown dim.
7
+ // Delete is destructive, so it is a two-step confirm (press d, then d again on the same row).
8
+ import { useEffect, useRef, useState } from "react";
9
+ import { Box, Text, useInput } from "ink";
10
+ import { useClickList } from "./MouseProvider.js";
11
+ const VISIBLE_ROWS = 12; // window height; longer libraries scroll within it (narrow with / search)
12
+ // Pure keystroke reducer: returns the next state and/or an intent to dispatch. No React, no I/O — the whole
13
+ // selection / search / delete-confirm behavior is unit-tested against this directly.
14
+ export function artifactKey(st, input, key, items) {
15
+ const n = items.length;
16
+ const hi = Math.min(Math.max(st.highlight, 0), Math.max(0, n - 1));
17
+ if (st.mode === "search") {
18
+ if (key.return)
19
+ return { state: { mode: "list", query: st.query, highlight: 0 }, intent: { kind: "search", query: st.query } };
20
+ if (key.escape)
21
+ return { state: { mode: "list", query: "", highlight: hi } };
22
+ if (key.backspace || key.delete)
23
+ return { state: { ...st, query: st.query.slice(0, -1) } };
24
+ if (input && !key.ctrl && !key.meta)
25
+ return { state: { ...st, query: st.query + input } };
26
+ return {};
27
+ }
28
+ // list mode — a pending delete-confirm is cleared by any action other than confirming it
29
+ const cleared = st.confirmDeleteId ? { ...st, confirmDeleteId: undefined } : st;
30
+ if (key.escape)
31
+ return { intent: { kind: "close" } };
32
+ if (key.upArrow)
33
+ return { state: { ...cleared, highlight: n ? (hi <= 0 ? n - 1 : hi - 1) : 0 } };
34
+ if (key.downArrow)
35
+ return { state: { ...cleared, highlight: n ? (hi >= n - 1 ? 0 : hi + 1) : 0 } };
36
+ if (input === "/")
37
+ return { state: { mode: "search", query: "", highlight: hi } };
38
+ if (input.toLowerCase() === "r")
39
+ return { state: cleared, intent: { kind: "refresh" } };
40
+ if (!n)
41
+ return {}; // the row actions below need a selected item
42
+ const item = items[hi];
43
+ if (key.return)
44
+ return { state: cleared, intent: { kind: "attach", id: item.id } };
45
+ if (input.toLowerCase() === "c")
46
+ return { state: cleared, intent: { kind: "copy", id: item.id } };
47
+ if (input.toLowerCase() === "d") {
48
+ if (st.confirmDeleteId === item.id)
49
+ return { state: { ...st, confirmDeleteId: undefined }, intent: { kind: "delete", id: item.id } };
50
+ return { state: { ...st, confirmDeleteId: item.id } }; // first press: arm the confirm
51
+ }
52
+ const num = Number(input);
53
+ if (Number.isInteger(num) && num >= 1 && num <= n)
54
+ return { state: { ...cleared, highlight: num - 1 } };
55
+ return {};
56
+ }
57
+ // The slice of rows to show: a window of VISIBLE_ROWS that keeps the highlighted row in view.
58
+ function windowFor(n, hi) {
59
+ if (n <= VISIBLE_ROWS)
60
+ return { start: 0, end: n };
61
+ let start = hi - Math.floor(VISIBLE_ROWS / 2);
62
+ start = Math.max(0, Math.min(start, n - VISIBLE_ROWS));
63
+ return { start, end: start + VISIBLE_ROWS };
64
+ }
65
+ export function ArtifactPicker({ pending }) {
66
+ const [st, setSt] = useState({ mode: "list", query: "", highlight: 0 });
67
+ const wasOpen = useRef(false);
68
+ useEffect(() => {
69
+ const open = !!pending;
70
+ if (open && !wasOpen.current)
71
+ setSt({ mode: "list", query: "", highlight: 0 }); // reset only on OPEN, not on item updates
72
+ wasOpen.current = open;
73
+ }, [pending]);
74
+ useInput((input, key) => {
75
+ if (!pending)
76
+ return;
77
+ const a = artifactKey(st, input, key, pending.items);
78
+ if (a.state)
79
+ setSt(a.state);
80
+ if (a.intent)
81
+ pending.onIntent(a.intent);
82
+ }, { isActive: !!pending });
83
+ // Row layout for click-to-select (hooks must run every render, so compute from safe defaults before the
84
+ // early return). Rows below the box top: 1 border + 1 title (+1 search line in search mode). Each item is
85
+ // one line. Click a row → highlight it; Enter still runs the primary action, per the footer help.
86
+ const items = pending?.items ?? [];
87
+ const n = items.length;
88
+ const hi = Math.min(Math.max(st.highlight, 0), Math.max(0, n - 1));
89
+ const { start, end } = windowFor(n, hi);
90
+ // Rows from the overlay-stack top to the first item: marginTop + top border + title (+ search line).
91
+ const headerLines = 1 /* marginTop */ + 1 /* top border */ + 1 /* title */ + (st.mode === "search" ? 1 : 0);
92
+ useClickList({
93
+ id: "artifact-list",
94
+ active: !!pending && !pending.loading && !pending.error,
95
+ headerLines, rowHeight: 1, windowStart: start, visibleCount: end - start,
96
+ onPick: (idx) => setSt((s) => ({ ...s, highlight: idx, confirmDeleteId: undefined })),
97
+ });
98
+ if (!pending)
99
+ return null;
100
+ const { loading, error, note } = pending;
101
+ return (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [_jsxs(Text, { color: "cyan", bold: true, children: ["◆ Artifacts ", _jsx(Text, { color: "cyan", bold: true, children: "[Mine]" }), _jsx(Text, { dimColor: true, children: " All Shared (soon)" })] }), st.mode === "search" ? (_jsxs(Text, { children: [_jsx(Text, { color: "magenta", children: "search› " }), st.query, _jsx(Text, { color: "cyan", children: "\u258C" })] })) : null, loading ? _jsx(Text, { dimColor: true, children: " loading…" }) : null, error ? _jsx(Text, { color: "red", children: " " + error }) : null, !loading && !error && n === 0 ? (_jsx(Text, { dimColor: true, children: st.query ? ` no artifacts match "${st.query}"` : " no artifacts yet — create one in Compose (compose.casa)" })) : null, !loading && !error && items.slice(start, end).map((it, i) => {
102
+ const idx = start + i;
103
+ const sel = idx === hi;
104
+ const armed = st.confirmDeleteId === it.id;
105
+ return (_jsxs(Text, { children: [" ", sel ? _jsx(Text, { color: "cyan", bold: true, children: "❯ " }) : _jsx(Text, { children: " " }), _jsx(Text, { bold: sel, children: it.title || "(untitled)" }), armed ? _jsx(Text, { color: "red", children: " delete? press d again" }) : _jsx(Text, { dimColor: true, children: ` compose${it.content_type ? " · " + it.content_type : ""}` })] }, it.id));
106
+ }), n > end ? _jsx(Text, { dimColor: true, children: ` ⋯ +${n - end} more · / to search` }) : null, note ? _jsx(Text, { color: "green", children: " " + note }) : null, _jsx(Text, { dimColor: true, children: st.mode === "search"
107
+ ? " type to filter · Enter to search · Esc for the list"
108
+ : " ↑/↓ move · Enter attach · c copy url · d delete · r refresh · / search · esc close" })] }));
109
+ }
@@ -104,6 +104,19 @@ export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended,
104
104
  process.stdout.write("\x1b[?2004l");
105
105
  };
106
106
  }, [stdin, isRawModeSupported]);
107
+ // Commit the current draft: expand paste chips to their real payloads, clear the buffer + paste
108
+ // state, and record it in history. Returns the full text, or null when the draft is empty (buffer
109
+ // left untouched). Shared by Enter and the ESC-flush path so the two can never drift apart.
110
+ const commitDraft = () => {
111
+ const text = expandPastes(value, pasteStoreRef.current);
112
+ if (!text.trim())
113
+ return null;
114
+ setValue("");
115
+ pasteStoreRef.current.clear();
116
+ pasteCountRef.current = 0;
117
+ historyRef.current.push(text);
118
+ return text;
119
+ };
107
120
  useInput((ch, key) => {
108
121
  if (suspended)
109
122
  return; // an approval prompt owns the keyboard — don't consume or echo keystrokes
@@ -115,8 +128,18 @@ export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended,
115
128
  onCycleMode?.();
116
129
  return;
117
130
  }
118
- if ((key.ctrl && ch === "c") || key.escape) {
119
- onInterrupt();
131
+ // ESC / Ctrl+C: apply the pure interruptPlan. ESC mid-turn with a pending draft flushes it into
132
+ // the queue (so it goes through right after the interrupt, via the turn-finally drain), then
133
+ // interrupts; an empty-draft ESC and every Ctrl+C are plain interrupts. See interruptPlan below.
134
+ if (key.escape || (key.ctrl && ch === "c")) {
135
+ const plan = interruptPlan({ escape: key.escape, ctrlC: key.ctrl && ch === "c" }, { disabled, hasQueue: !!onQueue, draftNonEmpty: !!expandPastes(value, pasteStoreRef.current).trim() });
136
+ if (plan.flushDraft) {
137
+ const text = commitDraft();
138
+ if (text && onQueue)
139
+ onQueue(text);
140
+ }
141
+ if (plan.interrupt)
142
+ onInterrupt();
120
143
  return;
121
144
  }
122
145
  if (key.return) {
@@ -128,13 +151,9 @@ export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended,
128
151
  setValue((v) => `${v}\n`); // more bytes queued — this Enter is mid-paste, not a real submit
129
152
  return;
130
153
  }
131
- const text = expandPastes(value, pasteStoreRef.current); // chips -> real payload; the model gets the full paste, not "[Pasted #1]"
132
- if (!text.trim())
154
+ const text = commitDraft(); // chips -> real payload; the model gets the full paste, not "[Pasted #1]"
155
+ if (text === null)
133
156
  return;
134
- setValue("");
135
- pasteStoreRef.current.clear(); // payloads consumed; restart chip numbering for the next message
136
- pasteCountRef.current = 0;
137
- historyRef.current.push(text);
138
157
  if (disabled && onQueue)
139
158
  onQueue(text);
140
159
  else
@@ -254,3 +273,15 @@ export function pasteChip(body) {
254
273
  export function expandPastes(text, store) {
255
274
  return text.replace(/\[Pasted #(\d+)[^\]]*\]/g, (m, n) => store.get(Number(n)) ?? m);
256
275
  }
276
+ /** Pure decision for the interrupt keys (ESC / Ctrl+C), extracted so the flush-on-ESC behavior is
277
+ * testable without a TTY. ESC while a turn is in flight, with a non-empty draft and a queue sink,
278
+ * flushes that draft into the queue and then interrupts — so the message goes through right after
279
+ * the turn stops (via the turn-finally drain). Every other ESC, and every Ctrl+C, is a pure
280
+ * interrupt; Ctrl+C never flushes a draft (the deliver-my-message gesture is ESC alone). */
281
+ export function interruptPlan(key, ctx) {
282
+ if (key.escape && ctx.disabled && ctx.hasQueue && ctx.draftNonEmpty)
283
+ return { flushDraft: true, interrupt: true };
284
+ if (key.escape || key.ctrlC)
285
+ return { flushDraft: false, interrupt: true };
286
+ return { flushDraft: false, interrupt: false };
287
+ }
@@ -24,11 +24,13 @@ function renderInline(text, kp) {
24
24
  nodes.push(_jsx(Text, { children: text.slice(last, m.index) }, `${kp}t${i++}`));
25
25
  const tok = m[0];
26
26
  if (tok.startsWith("[")) {
27
- // [label](url) → clickable label (OSC 8) where supported, else "label (url)".
27
+ // [label](url) → clickable label (OSC 8) where supported; otherwise the label PLUS the URL beside it
28
+ // in lower opacity, so Terminal.app (no OSC 8) still shows a URL you can see and copy.
28
29
  const mm = /^\[([^\]]+)\]\(([^)\s]+)\)$/.exec(tok);
29
30
  const [, label, url] = mm;
30
- const shown = hyperlinksEnabled() ? link(label, url) : `${label} (${url})`;
31
- nodes.push(_jsx(Text, { color: theme.info, underline: true, children: shown }, `${kp}l${i++}`));
31
+ nodes.push(hyperlinksEnabled()
32
+ ? _jsx(Text, { color: theme.info, underline: true, children: link(label, url) }, `${kp}l${i++}`)
33
+ : _jsxs(Text, { children: [_jsx(Text, { color: theme.info, underline: true, children: label }), _jsx(Text, { dimColor: true, children: " " + url })] }, `${kp}l${i++}`));
32
34
  }
33
35
  else if (tok.startsWith("**"))
34
36
  nodes.push(_jsx(Text, { bold: true, children: tok.slice(2, -2) }, `${kp}b${i++}`));