@0perator/operator 0.1.222 → 0.1.235

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 (70) hide show
  1. package/CHANGELOG.md +858 -0
  2. package/README.md +4 -4
  3. package/dist/acp/agent.js +42 -3
  4. package/dist/acp/config-options.js +34 -0
  5. package/dist/acp/run.js +83 -2
  6. package/dist/auth/byo.js +118 -0
  7. package/dist/auth/commands.js +34 -1
  8. package/dist/autonomy/dream.js +1 -1
  9. package/dist/autonomy/index.js +16 -2
  10. package/dist/autonomy/media-robot.js +138 -0
  11. package/dist/autonomy/profile.js +77 -0
  12. package/dist/autonomy/session-factory.js +13 -9
  13. package/dist/background/index.js +8 -1
  14. package/dist/cli.js +132 -95
  15. package/dist/compose/client.js +56 -0
  16. package/dist/config/persona.js +186 -14
  17. package/dist/config/settings.js +49 -16
  18. package/dist/consolidation/scheduler.js +7 -4
  19. package/dist/consolidation/sleep.js +15 -1
  20. package/dist/engine/agent.js +152 -9
  21. package/dist/engine/aurora.js +73 -14
  22. package/dist/engine/compaction.js +129 -2
  23. package/dist/engine/computer-event.js +139 -0
  24. package/dist/engine/continuation.js +55 -0
  25. package/dist/engine/contract.js +3 -1
  26. package/dist/engine/grandmaster.js +13 -3
  27. package/dist/engine/messages.js +2 -2
  28. package/dist/engine/redact.js +25 -0
  29. package/dist/engine/rolling-summary.js +22 -7
  30. package/dist/engine/router-adapter.js +2 -0
  31. package/dist/engine/unrestricted.js +51 -0
  32. package/dist/engine/verify-gate.js +6 -0
  33. package/dist/index.browser.js +4 -0
  34. package/dist/index.js +4 -0
  35. package/dist/memory/index.js +0 -0
  36. package/dist/permissions/audit.js +4 -1
  37. package/dist/permissions/policy.js +4 -3
  38. package/dist/permissions/tier.js +31 -14
  39. package/dist/remote/host.js +9 -2
  40. package/dist/router/models.js +43 -2
  41. package/dist/session.js +113 -36
  42. package/dist/telemetry/events.js +8 -3
  43. package/dist/tools/computer.js +1 -1
  44. package/dist/tools/executor.js +22 -17
  45. package/dist/tools/mutating.js +6 -0
  46. package/dist/tools/registry.js +872 -27
  47. package/dist/tools/shell-session.js +36 -1
  48. package/dist/tools/tool-output-spill.js +2 -2
  49. package/dist/ui/ActivitySpinner.js +17 -6
  50. package/dist/ui/App.js +36 -14
  51. package/dist/ui/ArtifactPicker.js +109 -0
  52. package/dist/ui/BusTray.js +70 -0
  53. package/dist/ui/Composer.js +39 -8
  54. package/dist/ui/Markdown.js +5 -3
  55. package/dist/ui/MouseProvider.js +99 -19
  56. package/dist/ui/QuestionPrompt.js +24 -3
  57. package/dist/ui/ThinkingSpinner.js +9 -5
  58. package/dist/ui/ToolStep.js +17 -12
  59. package/dist/ui/Transcript.js +14 -7
  60. package/dist/ui/capabilities.js +0 -9
  61. package/dist/ui/listhit.js +23 -0
  62. package/dist/ui/mouse.js +22 -0
  63. package/dist/ui/osc.js +7 -4
  64. package/dist/ui/progressbar.js +46 -0
  65. package/dist/ui/shimmer.js +43 -0
  66. package/dist/ui/theme.js +2 -0
  67. package/dist/ui/tick.js +48 -0
  68. package/dist/ui/toolicons.js +69 -0
  69. package/dist/util/slash.js +1 -0
  70. package/package.json +2 -2
@@ -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
+ }
@@ -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
+ }
@@ -0,0 +1,70 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // BusTray — live Switchboard messages surfaced in the Operator TUI as click-to-expand cards. Top-anchored
3
+ // in the fullscreen layout so each card's absolute terminal row is deterministic (topRow + Σ heights above),
4
+ // which is what makes mouse hit-testing reliable without Ink absolute-position measurement. Clicking a card
5
+ // toggles its body (the Phase-1 mouse layer in action). In inline mode (no mouse) the cards still render,
6
+ // just not clickable. Messages are DATA from other agents — shown, never executed.
7
+ import { useEffect, useState } from "react";
8
+ import { Box, Text } from "ink";
9
+ import { useMouse } from "./MouseProvider.js";
10
+ const MAX_BODY_LINES = 8; // cap an expanded card's body so one big message can't dominate the screen
11
+ function wrap(line, width) {
12
+ const w = Math.max(1, width);
13
+ if (line.length <= w)
14
+ return [line];
15
+ const out = [];
16
+ for (let i = 0; i < line.length; i += w)
17
+ out.push(line.slice(i, i + w));
18
+ return out;
19
+ }
20
+ /** Pure layout: assign each message a card with an absolute row (y) and height, given which ids are
21
+ * expanded and the terminal width. Deterministic top-to-bottom stacking from `topRow` — the basis for both
22
+ * render order and click hit-testing. Exported for unit tests. */
23
+ export function trayLayout(messages, expanded, cols, topRow = 1) {
24
+ const width = cols > 0 ? cols : 80;
25
+ const cards = [];
26
+ let y = topRow;
27
+ for (const msg of messages) {
28
+ const isExp = expanded.has(msg.id);
29
+ const bodyLines = isExp
30
+ ? msg.body.split("\n").flatMap((l) => wrap(l, width - 2)).slice(0, MAX_BODY_LINES)
31
+ : [];
32
+ const height = 1 + bodyLines.length;
33
+ cards.push({ msg, y, height, expanded: isExp, bodyLines });
34
+ y += height;
35
+ }
36
+ return cards;
37
+ }
38
+ function preview(body, cols) {
39
+ const one = body.replace(/\s+/g, " ").trim();
40
+ const budget = Math.max(10, (cols > 0 ? cols : 80) - 28);
41
+ return one.length > budget ? one.slice(0, budget - 1) + "…" : one;
42
+ }
43
+ /** The tray. `cols` is the terminal width (for wrapping + region width). Renders nothing when empty. */
44
+ export function BusTray({ messages, cols }) {
45
+ const { registerRegion, enabled } = useMouse();
46
+ const [expanded, setExpanded] = useState(() => new Set());
47
+ const cards = trayLayout(messages, expanded, cols);
48
+ // Register every card's clickable region imperatively (one effect, not a hook-per-card — the message
49
+ // count varies, which would violate rules-of-hooks). A left-press anywhere on a card toggles its body.
50
+ const sig = cards.map((c) => `${c.msg.id}:${c.y}:${c.height}`).join("|");
51
+ useEffect(() => {
52
+ if (!enabled || !cards.length)
53
+ return;
54
+ const disposers = cards.map((c) => registerRegion({ id: `bus:${c.msg.id}`, x: 1, y: c.y, width: Math.max(1, cols), height: c.height }, () => {
55
+ setExpanded((prev) => {
56
+ const next = new Set(prev);
57
+ if (next.has(c.msg.id))
58
+ next.delete(c.msg.id);
59
+ else
60
+ next.add(c.msg.id);
61
+ return next;
62
+ });
63
+ }));
64
+ return () => disposers.forEach((d) => d());
65
+ // eslint-disable-next-line react-hooks/exhaustive-deps
66
+ }, [enabled, registerRegion, cols, sig]);
67
+ if (!messages.length)
68
+ return null;
69
+ return (_jsx(Box, { flexDirection: "column", children: cards.map((c) => (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { color: "cyan", children: [c.expanded ? "▾" : "▸", " ", "📨 ", c.msg.from, c.msg.subject ? ` [${c.msg.subject}]` : "", c.expanded ? "" : `: ${preview(c.msg.body, cols)}`, enabled && !c.expanded ? _jsx(Text, { dimColor: true, children: " \u00B7 click to expand" }) : null] }), c.expanded ? c.bodyLines.map((l, i) => _jsx(Text, { dimColor: true, children: " " + l }, i)) : null] }, c.msg.id))) }));
70
+ }
@@ -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++}`));