@phren/agent 0.1.8 → 0.1.9

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 (58) hide show
  1. package/dist/commands/info.js +1 -0
  2. package/dist/commands/model.js +5 -4
  3. package/dist/commands/session.js +24 -2
  4. package/dist/commands.js +36 -1
  5. package/dist/config.js +27 -11
  6. package/dist/cost.js +11 -74
  7. package/dist/index.js +92 -35
  8. package/dist/mcp-client.js +4 -2
  9. package/dist/memory/context.js +56 -24
  10. package/dist/memory/session.js +21 -88
  11. package/dist/models.js +390 -0
  12. package/dist/multi/agent-types.js +170 -0
  13. package/dist/multi/child-entry.js +248 -78
  14. package/dist/multi/coordinator.js +69 -1
  15. package/dist/multi/diff-renderer.js +193 -17
  16. package/dist/multi/markdown.js +49 -23
  17. package/dist/multi/model-picker.js +12 -21
  18. package/dist/multi/multi-events.js +17 -0
  19. package/dist/multi/multi-render.js +1 -0
  20. package/dist/multi/provider-manager.js +23 -13
  21. package/dist/multi/spawner.js +84 -7
  22. package/dist/multi/syntax-highlight.js +64 -48
  23. package/dist/multi/worktree.js +43 -0
  24. package/dist/package-metadata.js +11 -0
  25. package/dist/permissions/checker.js +21 -1
  26. package/dist/providers/codex-auth.js +48 -34
  27. package/dist/providers/codex.js +110 -40
  28. package/dist/providers/ollama.js +5 -4
  29. package/dist/providers/openrouter.js +12 -5
  30. package/dist/providers/resolve.js +50 -32
  31. package/dist/providers/types.js +0 -1
  32. package/dist/repl.js +19 -34
  33. package/dist/tools/grep.js +111 -23
  34. package/dist/tools/mcp-resources.js +32 -0
  35. package/dist/tools/registry.js +13 -2
  36. package/dist/tools/shell.js +101 -3
  37. package/dist/tools/skill.js +44 -0
  38. package/dist/tools/spawn-agent.js +158 -0
  39. package/dist/tui/ansi.js +15 -11
  40. package/dist/tui/components/App.js +179 -8
  41. package/dist/tui/components/Banner.js +7 -4
  42. package/dist/tui/components/InputArea.js +54 -12
  43. package/dist/tui/components/PhrenInput.js +329 -0
  44. package/dist/tui/components/StatusBar.js +3 -1
  45. package/dist/tui/components/SteerQueue.js +4 -2
  46. package/dist/tui/components/ThinkingIndicator.js +7 -5
  47. package/dist/tui/components/ToolCall.js +12 -8
  48. package/dist/tui/components/ToolSpinner.js +13 -0
  49. package/dist/tui/hooks/useKeyboardShortcuts.js +65 -24
  50. package/dist/tui/hooks/useSearch.js +47 -0
  51. package/dist/tui/hooks/useSlashCommands.js +16 -19
  52. package/dist/tui/ink-entry.js +373 -14
  53. package/dist/tui/mouse.js +71 -0
  54. package/dist/tui/terminal-control.js +62 -0
  55. package/dist/tui/themes.js +398 -0
  56. package/dist/tui/tool-render.js +12 -1
  57. package/dist/tui.js +2 -1
  58. package/package.json +1 -3
@@ -2,7 +2,8 @@ import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { render } from "ink";
3
3
  import { createSession, runTurn } from "../agent-loop.js";
4
4
  import { useSlashCommands } from "./hooks/useSlashCommands.js";
5
- import { decodeDiffPayload, DIFF_MARKER } from "../multi/diff-renderer.js";
5
+ import { decodeDiffPayload, DIFF_MARKER, renderInlineDiff } from "../multi/diff-renderer.js";
6
+ import { formatToolInput } from "./tool-render.js";
6
7
  import * as os from "os";
7
8
  import { execSync } from "node:child_process";
8
9
  import * as path from "node:path";
@@ -10,6 +11,9 @@ import { loadInputMode, saveInputMode, savePermissionMode } from "../settings.js
10
11
  import { nextPermissionMode } from "./ansi.js";
11
12
  import { App } from "./components/App.js";
12
13
  import { createRequire } from "node:module";
14
+ import { getTheme, THEME_NAMES } from "./themes.js";
15
+ import { TerminalControl } from "./terminal-control.js";
16
+ import { enableMouse, disableMouse, parseMouseEvent } from "./mouse.js";
13
17
  const _require = createRequire(import.meta.url);
14
18
  const AGENT_VERSION = _require("../../package.json").version;
15
19
  export async function startInkTui(config, spawner) {
@@ -22,7 +26,37 @@ export async function startInkTui(config, spawner) {
22
26
  const inputHistory = [];
23
27
  let running = false;
24
28
  let verbose = false;
29
+ let theme = getTheme();
25
30
  let msgCounter = 0;
31
+ const terminalControl = new TerminalControl();
32
+ // Mouse handler ref — assigned after agentTabs/handleSelectAgent are defined.
33
+ // Stored here so handleExit (defined before the handler) can call .off on it.
34
+ let mouseHandler = () => { };
35
+ // Permission prompt state — when set, input field captures y/n/a/s
36
+ let permissionResolve = null;
37
+ // Ink-compatible askUser: shows prompt in chat, waits for y/n in input
38
+ config.registry.askUser = async (toolName, input, reason) => {
39
+ const { addAllow } = await import("../permissions/allowlist.js");
40
+ const summary = Object.keys(input).length > 0
41
+ ? `${toolName}(${Object.entries(input).map(([k, v]) => `${k}: ${JSON.stringify(v).slice(0, 40)}`).join(", ")})`
42
+ : toolName;
43
+ completedMessages.push({
44
+ id: nextId(),
45
+ kind: "status",
46
+ text: `\x1b[1m\x1b[33m[PERMISSION]\x1b[0m ${toolName}\n ${reason}\n ${summary}\n \x1b[2m[y]es [n]o [a]llow-tool [s]ession-allow\x1b[0m`,
47
+ });
48
+ update();
49
+ return new Promise((resolve) => {
50
+ permissionResolve = (allowed) => {
51
+ permissionResolve = null;
52
+ resolve(allowed);
53
+ };
54
+ // Store the addAllow function for a/s responses
55
+ permissionResolve.toolName = toolName;
56
+ permissionResolve.input = input;
57
+ permissionResolve.addAllow = addAllow;
58
+ });
59
+ };
26
60
  // Mutable render state — updated then pushed to React via rerender()
27
61
  const completedMessages = [];
28
62
  let streamingText = "";
@@ -30,6 +64,7 @@ export async function startInkTui(config, spawner) {
30
64
  let thinkStartTime = 0;
31
65
  let thinkElapsed = null;
32
66
  let currentToolCalls = [];
67
+ let activeTool = null;
33
68
  function nextId() {
34
69
  return `msg-${++msgCounter}`;
35
70
  }
@@ -44,12 +79,49 @@ export async function startInkTui(config, spawner) {
44
79
  version: AGENT_VERSION,
45
80
  };
46
81
  }
82
+ function renderFixedStatus() {
83
+ if (!terminalControl.isEnabled)
84
+ return;
85
+ const s = getAppState();
86
+ const cols = process.stdout.columns || 80;
87
+ const left = ` \u25c6 phren \u00b7 ${s.provider}${s.project ? ` \u00b7 ${s.project}` : ""}`;
88
+ const right = `${s.permMode} T:${s.turns}${s.agentCount > 0 ? ` A:${s.agentCount}` : ""} `;
89
+ const pad = Math.max(0, cols - left.length - right.length);
90
+ const line = `\x1b[7m${left}${" ".repeat(pad)}${right}\x1b[0m`;
91
+ terminalControl.renderStatusBar(process.stdout, line);
92
+ }
47
93
  // Re-render the Ink app with current state
48
94
  let rerender = null;
95
+ // Ink app instance — set after render(), used by closures for clear()
96
+ let appInstance = null;
97
+ // Batched update for high-frequency events (streaming deltas)
98
+ let updateScheduled = false;
99
+ function scheduleUpdate() {
100
+ if (updateScheduled)
101
+ return;
102
+ updateScheduled = true;
103
+ queueMicrotask(() => {
104
+ updateScheduled = false;
105
+ update();
106
+ });
107
+ }
49
108
  function update() {
50
109
  if (!rerender)
51
110
  return;
52
- rerender(_jsx(App, { state: getAppState(), completedMessages: [...completedMessages], streamingText: streamingText, completedToolCalls: [...currentToolCalls], thinking: thinking, thinkStartTime: thinkStartTime, thinkElapsed: thinkElapsed, steerQueue: [...steerQueueBuf], running: running, showBanner: true, inputHistory: [...inputHistory], verbose: verbose, onSubmit: handleSubmit, onPermissionCycle: handlePermissionCycle, onCancelTurn: handleCancelTurn, onExit: handleExit }));
111
+ // Determine what to display based on selected view
112
+ const agentConvo = selectedAgentId ? agentConvos.get(selectedAgentId) : null;
113
+ // When viewing an agent: show their messages with fresh IDs (so Static re-renders after screen clear)
114
+ const prefix = `v${viewSwitchCounter}-`;
115
+ const displayMessages = agentConvo
116
+ ? agentConvo.messages.map((m) => ({ ...m, id: prefix + m.id }))
117
+ : completedMessages.map((m) => ({ ...m, id: prefix + m.id }));
118
+ const displayStreaming = agentConvo ? agentConvo.streamingText : streamingText;
119
+ const displayToolCalls = agentConvo ? [...agentConvo.toolCalls] : [...currentToolCalls];
120
+ const displayActiveTool = agentConvo ? agentConvo.activeTool : activeTool;
121
+ const displayThinking = agentConvo ? false : thinking;
122
+ const displayRunning = agentConvo ? (spawner?.getAgent(selectedAgentId)?.status === "running" || false) : running;
123
+ rerender(_jsx(App, { state: getAppState(), completedMessages: displayMessages, streamingText: displayStreaming, completedToolCalls: displayToolCalls, activeTool: displayActiveTool, thinking: displayThinking, thinkStartTime: thinkStartTime, thinkElapsed: agentConvo ? null : thinkElapsed, steerQueue: agentConvo ? [] : [...steerQueueBuf], running: displayRunning, showBanner: !selectedAgentId, inputHistory: [...inputHistory], verbose: verbose, theme: theme, onSubmit: handleSubmit, onPermissionCycle: handlePermissionCycle, onCancelTurn: handleCancelTurn, onExit: handleExit, agents: agentTabs.length > 0 ? [{ id: "__main__", name: "phren", status: running ? "running" : "idle", color: "magentaBright" }, ...agentTabs] : undefined, selectedAgentId: selectedAgentId ?? (agentTabs.length > 0 ? "__main__" : undefined), onCancelAgent: handleCancelAgent, onSelectAgent: (id) => handleSelectAgent(id === "__main__" ? null : id) }));
124
+ renderFixedStatus();
53
125
  }
54
126
  function handlePermissionCycle() {
55
127
  const next = nextPermissionMode(config.registry.permissionConfig.mode);
@@ -59,6 +131,11 @@ export async function startInkTui(config, spawner) {
59
131
  }
60
132
  let resolveSession = null;
61
133
  function handleExit() {
134
+ disableMouse(process.stdout);
135
+ if (process.stdin.isTTY) {
136
+ process.stdin.off("data", mouseHandler);
137
+ }
138
+ terminalControl.disable(process.stdout);
62
139
  if (resolveSession)
63
140
  resolveSession(session);
64
141
  }
@@ -76,6 +153,7 @@ export async function startInkTui(config, spawner) {
76
153
  undoStack: [],
77
154
  providerName: config.provider.name,
78
155
  currentModel: config.provider.model,
156
+ currentReasoning: config.provider.reasoningEffort ?? null,
79
157
  provider: config.provider,
80
158
  systemPrompt: config.systemPrompt,
81
159
  spawner,
@@ -86,7 +164,7 @@ export async function startInkTui(config, spawner) {
86
164
  onModelChange: async (result) => {
87
165
  try {
88
166
  const { resolveProvider } = await import("../providers/resolve.js");
89
- const newProvider = resolveProvider(config.provider.name, result.model);
167
+ const newProvider = resolveProvider(config.provider.name, result.model, undefined, result.reasoning ?? undefined);
90
168
  config.provider = newProvider;
91
169
  const { buildSystemPrompt } = await import("../system-prompt.js");
92
170
  config.systemPrompt = buildSystemPrompt(config.systemPrompt.split("\n## Last session")[0], null, { name: newProvider.name, model: result.model });
@@ -103,6 +181,31 @@ export async function startInkTui(config, spawner) {
103
181
  const line = input.trim();
104
182
  if (!line)
105
183
  return;
184
+ // Permission prompt active — intercept y/n/a/s
185
+ if (permissionResolve) {
186
+ const key = line.toLowerCase();
187
+ const meta = permissionResolve;
188
+ if (key === "y" || key === "yes") {
189
+ completedMessages.push({ id: nextId(), kind: "status", text: "\x1b[32m✓ Allowed\x1b[0m" });
190
+ permissionResolve(true);
191
+ }
192
+ else if (key === "a") {
193
+ completedMessages.push({ id: nextId(), kind: "status", text: "\x1b[32m✓ Allowed (tool for session)\x1b[0m" });
194
+ meta.addAllow(meta.toolName, meta.input, "tool");
195
+ permissionResolve(true);
196
+ }
197
+ else if (key === "s") {
198
+ completedMessages.push({ id: nextId(), kind: "status", text: "\x1b[32m✓ Allowed (session)\x1b[0m" });
199
+ meta.addAllow(meta.toolName, meta.input, "session");
200
+ permissionResolve(true);
201
+ }
202
+ else {
203
+ completedMessages.push({ id: nextId(), kind: "status", text: "\x1b[31m✗ Denied\x1b[0m" });
204
+ permissionResolve(false);
205
+ }
206
+ update();
207
+ return;
208
+ }
106
209
  // Track input history (skip duplicates of the last entry)
107
210
  if (inputHistory.length === 0 || inputHistory[inputHistory.length - 1] !== line) {
108
211
  inputHistory.push(line);
@@ -147,12 +250,63 @@ export async function startInkTui(config, spawner) {
147
250
  update();
148
251
  return;
149
252
  }
253
+ // /agent <name> — switch to an agent's conversation, /agent (no args) — back to main
254
+ if (line.startsWith("/agent")) {
255
+ const arg = line.slice(6).trim();
256
+ if (!arg || arg === "main" || arg === "phren") {
257
+ handleSelectAgent(null);
258
+ return;
259
+ }
260
+ // /agents — list all agents
261
+ if (arg === "s") {
262
+ const agents = spawner?.listAgents() ?? [];
263
+ if (agents.length === 0) {
264
+ completedMessages.push({ id: nextId(), kind: "status", text: "No agents spawned." });
265
+ }
266
+ else {
267
+ const lines = agents.map((a) => ` ${a.displayName || a.id} [${a.status}]`).join("\n");
268
+ completedMessages.push({ id: nextId(), kind: "status", text: `Agents:\n${lines}` });
269
+ }
270
+ update();
271
+ return;
272
+ }
273
+ // Find agent by name or id
274
+ const agents = spawner?.listAgents() ?? [];
275
+ const match = agents.find((a) => a.displayName === arg || a.id === arg || a.displayName?.includes(arg));
276
+ if (match) {
277
+ handleSelectAgent(match.id);
278
+ }
279
+ else {
280
+ completedMessages.push({ id: nextId(), kind: "status", text: `Agent "${arg}" not found. Use /agents to list.` });
281
+ update();
282
+ }
283
+ return;
284
+ }
150
285
  if (line === "/verbose") {
151
286
  verbose = !verbose;
152
287
  completedMessages.push({ id: nextId(), kind: "status", text: `Verbose: ${verbose ? "on" : "off"}` });
153
288
  update();
154
289
  return;
155
290
  }
291
+ if (line === "/theme") {
292
+ const idx = THEME_NAMES.indexOf(theme.name);
293
+ const next = THEME_NAMES[(idx + 1) % THEME_NAMES.length];
294
+ theme = getTheme(next);
295
+ completedMessages.push({ id: nextId(), kind: "status", text: `Theme: ${theme.name} (${THEME_NAMES.join(", ")})` });
296
+ update();
297
+ return;
298
+ }
299
+ // /clear — also wipe Ink completed messages and clear screen
300
+ if (line === "/clear") {
301
+ completedMessages.length = 0;
302
+ if (appInstance)
303
+ appInstance.clear();
304
+ else
305
+ process.stdout.write("\x1b[2J\x1b[H");
306
+ slashCommands.tryHandleCommand(line);
307
+ update();
308
+ return;
309
+ }
156
310
  // Slash commands — capture stderr output and display as status message
157
311
  if (line.startsWith("/")) {
158
312
  if (slashCommands.tryHandleCommand(line)) {
@@ -171,7 +325,21 @@ export async function startInkTui(config, spawner) {
171
325
  update();
172
326
  return;
173
327
  }
174
- // Normal user message — add to completed history and run agent turn
328
+ // If a spawned agent is selected, send input to THAT agent
329
+ if (selectedAgentId && selectedAgentId !== "__main__" && spawner) {
330
+ const agent = spawner.getAgent(selectedAgentId);
331
+ const agentName = agent?.displayName || selectedAgentId;
332
+ completedMessages.push({ id: nextId(), kind: "user", text: `[→ ${agentName}] ${line}` });
333
+ if (agent?.status === "idle") {
334
+ spawner.wakeAgent(selectedAgentId, { message: line, from: "user" });
335
+ }
336
+ else {
337
+ spawner.sendToAgent(selectedAgentId, line, "user");
338
+ }
339
+ update();
340
+ return;
341
+ }
342
+ // Normal user message — add to completed history and run main agent turn
175
343
  completedMessages.push({ id: nextId(), kind: "user", text: line });
176
344
  update();
177
345
  runAgentTurn(line);
@@ -181,7 +349,7 @@ export async function startInkTui(config, spawner) {
181
349
  onTextDelta: (text) => {
182
350
  thinking = false;
183
351
  streamingText += text;
184
- update();
352
+ scheduleUpdate();
185
353
  },
186
354
  onTextDone: () => {
187
355
  // streaming complete — finalized in runAgentTurn
@@ -189,16 +357,19 @@ export async function startInkTui(config, spawner) {
189
357
  onTextBlock: (text) => {
190
358
  thinking = false;
191
359
  streamingText += text;
192
- update();
360
+ scheduleUpdate();
193
361
  },
194
- onToolStart: (_name, _input, _count) => {
362
+ onToolStart: (name, input, _count) => {
195
363
  thinking = false;
364
+ activeTool = { name, preview: formatToolInput(name, input) };
196
365
  update();
197
366
  },
198
367
  onToolEnd: (name, input, output, isError, dur) => {
368
+ activeTool = null;
199
369
  const diffData = (name === "edit_file" || name === "write_file") ? decodeDiffPayload(output) : null;
200
370
  const cleanOutput = diffData ? output.slice(0, output.indexOf(DIFF_MARKER)) : output;
201
- currentToolCalls.push({ name, input, output: cleanOutput, isError, durationMs: dur });
371
+ const diffRendered = diffData ? renderInlineDiff(diffData.oldContent, diffData.newContent, diffData.filePath, theme.diff) : undefined;
372
+ currentToolCalls.push({ name, input, output: cleanOutput, isError, durationMs: dur, diffRendered });
202
373
  update();
203
374
  },
204
375
  getSteeringInput: () => {
@@ -223,6 +394,7 @@ export async function startInkTui(config, spawner) {
223
394
  thinkElapsed = null;
224
395
  streamingText = "";
225
396
  currentToolCalls = [];
397
+ activeTool = null;
226
398
  update();
227
399
  try {
228
400
  await runTurn(userInput, session, config, tuiHooks);
@@ -245,8 +417,10 @@ export async function startInkTui(config, spawner) {
245
417
  }
246
418
  streamingText = "";
247
419
  currentToolCalls = [];
420
+ activeTool = null;
248
421
  running = false;
249
422
  thinkElapsed = elapsed;
423
+ process.stdout.write("\x07"); // terminal bell on completion
250
424
  update();
251
425
  // Clear elapsed indicator after a brief display
252
426
  setTimeout(() => {
@@ -268,19 +442,204 @@ export async function startInkTui(config, spawner) {
268
442
  runAgentTurn(queued);
269
443
  }
270
444
  }
271
- // Enable bracketed paste
272
- process.stdout.write("\x1b[?2004h");
273
- // Clear screen before initial render — start clean
274
- process.stdout.write("\x1b[2J\x1b[H");
445
+ // ── Multi-agent state ──────────────────────────────────────────────────
446
+ // TeamAgents: each gets their OWN conversation (separate from main stream).
447
+ // Switch between them with /agent <name>. Clear screen + re-render on switch.
448
+ let selectedAgentId = null; // null = main orchestrator
449
+ let agentTabs = [];
450
+ const TAB_COLORS = ["cyan", "magenta", "yellow", "green", "blue", "red", "white", "cyanBright"];
451
+ const agentConvos = new Map();
452
+ function getOrCreateConvo(agentId) {
453
+ let convo = agentConvos.get(agentId);
454
+ if (!convo) {
455
+ convo = { messages: [], streamingText: "", toolCalls: [], activeTool: null };
456
+ agentConvos.set(agentId, convo);
457
+ }
458
+ return convo;
459
+ }
460
+ function rebuildAgentTabs() {
461
+ if (!spawner) {
462
+ agentTabs = [];
463
+ return;
464
+ }
465
+ agentTabs = spawner.listAgents().map((a, i) => ({
466
+ id: a.id,
467
+ name: a.displayName || a.task.slice(0, 20),
468
+ status: a.status,
469
+ color: TAB_COLORS[i % TAB_COLORS.length],
470
+ }));
471
+ }
472
+ // Switch views: clear screen, swap which messages are displayed
473
+ let viewSwitchCounter = 0;
474
+ function handleSelectAgent(agentId) {
475
+ if (agentId === selectedAgentId)
476
+ return;
477
+ selectedAgentId = agentId;
478
+ viewSwitchCounter++;
479
+ // Clear screen so Ink's <Static> re-renders with fresh items
480
+ if (appInstance)
481
+ appInstance.clear();
482
+ else
483
+ process.stdout.write("\x1b[2J\x1b[H");
484
+ update();
485
+ }
486
+ function handleCancelAgent() {
487
+ if (selectedAgentId && selectedAgentId !== "__main__" && spawner) {
488
+ const agent = spawner.getAgent(selectedAgentId);
489
+ if (agent && (agent.status === "running" || agent.status === "starting")) {
490
+ spawner.cancel(selectedAgentId);
491
+ const convo = getOrCreateConvo(selectedAgentId);
492
+ convo.messages.push({ id: nextId(), kind: "status", text: "Cancelled" });
493
+ update();
494
+ return;
495
+ }
496
+ }
497
+ handleCancelTurn();
498
+ }
499
+ // Wire spawner events — each agent's output goes to its OWN conversation
500
+ if (spawner) {
501
+ spawner.on("text_delta", (agentId, text) => {
502
+ const convo = getOrCreateConvo(agentId);
503
+ convo.streamingText += text;
504
+ // Only update if this agent is currently selected
505
+ if (selectedAgentId === agentId)
506
+ update();
507
+ });
508
+ spawner.on("text_block", (agentId, text) => {
509
+ const convo = getOrCreateConvo(agentId);
510
+ convo.streamingText += text;
511
+ if (selectedAgentId === agentId)
512
+ update();
513
+ });
514
+ spawner.on("tool_start", (agentId, toolName, input) => {
515
+ const convo = getOrCreateConvo(agentId);
516
+ convo.activeTool = { name: toolName, preview: formatToolInput(toolName, input) };
517
+ rebuildAgentTabs();
518
+ if (selectedAgentId === agentId)
519
+ update();
520
+ });
521
+ spawner.on("tool_end", (agentId, toolName, input, output, isError, durationMs) => {
522
+ const convo = getOrCreateConvo(agentId);
523
+ convo.activeTool = null;
524
+ const diffData = (toolName === "edit_file" || toolName === "write_file") ? decodeDiffPayload(output) : null;
525
+ const cleanOutput = diffData ? output.slice(0, output.indexOf(DIFF_MARKER)) : output;
526
+ const diffRendered = diffData ? renderInlineDiff(diffData.oldContent, diffData.newContent, diffData.filePath, theme.diff) : undefined;
527
+ convo.toolCalls.push({ name: toolName, input, output: cleanOutput, isError, durationMs, diffRendered });
528
+ rebuildAgentTabs();
529
+ if (selectedAgentId === agentId)
530
+ update();
531
+ });
532
+ spawner.on("done", (agentId, result) => {
533
+ const convo = getOrCreateConvo(agentId);
534
+ if (convo.streamingText || convo.toolCalls.length > 0) {
535
+ convo.messages.push({
536
+ id: nextId(),
537
+ kind: "assistant",
538
+ text: convo.streamingText || result.finalText,
539
+ toolCalls: convo.toolCalls.length > 0 ? [...convo.toolCalls] : undefined,
540
+ });
541
+ }
542
+ else if (result.finalText) {
543
+ convo.messages.push({ id: nextId(), kind: "assistant", text: result.finalText });
544
+ }
545
+ convo.streamingText = "";
546
+ convo.toolCalls = [];
547
+ convo.activeTool = null;
548
+ rebuildAgentTabs();
549
+ // Notify main stream that an agent completed
550
+ completedMessages.push({
551
+ id: nextId(),
552
+ kind: "status",
553
+ text: `\x1b[2m${spawner.getAgent(agentId)?.displayName || agentId} completed (${result.turns} turns, ${result.toolCalls} tools)\x1b[0m`,
554
+ });
555
+ update();
556
+ });
557
+ spawner.on("error", (agentId, error) => {
558
+ const convo = getOrCreateConvo(agentId);
559
+ convo.messages.push({ id: nextId(), kind: "status", text: `Error: ${error}` });
560
+ convo.streamingText = "";
561
+ convo.activeTool = null;
562
+ rebuildAgentTabs();
563
+ update();
564
+ });
565
+ spawner.on("idle", (agentId, reason) => {
566
+ const convo = getOrCreateConvo(agentId);
567
+ convo.messages.push({ id: nextId(), kind: "status", text: `idle (${reason})` });
568
+ rebuildAgentTabs();
569
+ update();
570
+ });
571
+ spawner.on("status", (agentId, message) => {
572
+ const convo = getOrCreateConvo(agentId);
573
+ convo.messages.push({ id: nextId(), kind: "status", text: message });
574
+ if (selectedAgentId === agentId)
575
+ update();
576
+ });
577
+ spawner.on("message", (from, to, content) => {
578
+ // Show DM notification in main stream
579
+ const preview = content.length > 80 ? content.slice(0, 80) + "..." : content;
580
+ completedMessages.push({
581
+ id: nextId(),
582
+ kind: "status",
583
+ text: `\x1b[2m${from} → ${to}: ${preview}\x1b[0m`,
584
+ });
585
+ update();
586
+ });
587
+ spawner.on("exit", () => {
588
+ rebuildAgentTabs();
589
+ update();
590
+ });
591
+ }
592
+ // Set terminal title
275
593
  const projectName = config.phrenCtx?.project ?? "phren";
276
594
  process.title = "phren";
277
595
  process.stdout.write(`\x1b]0;phren \xb7 ${projectName}\x07`); // set terminal window title
278
596
  // Initial render
279
- const app = render(_jsx(App, { state: getAppState(), completedMessages: [], streamingText: "", completedToolCalls: [], thinking: false, thinkStartTime: 0, thinkElapsed: null, steerQueue: [], running: false, showBanner: true, inputHistory: [], verbose: verbose, onSubmit: handleSubmit, onPermissionCycle: handlePermissionCycle, onCancelTurn: handleCancelTurn, onExit: handleExit }), { exitOnCtrlC: false });
597
+ const app = render(_jsx(App, { state: getAppState(), completedMessages: [], streamingText: "", completedToolCalls: [], activeTool: null, thinking: false, thinkStartTime: 0, thinkElapsed: null, steerQueue: [], running: false, showBanner: true, inputHistory: [], verbose: verbose, theme: theme, onSubmit: handleSubmit, onPermissionCycle: handlePermissionCycle, onCancelTurn: handleCancelTurn, onExit: handleExit, agents: undefined, selectedAgentId: undefined, onCancelAgent: handleCancelAgent, onSelectAgent: handleSelectAgent }), { exitOnCtrlC: false, incrementalRendering: true, maxFps: 30 });
280
598
  rerender = app.rerender;
599
+ appInstance = app;
600
+ terminalControl.enable(process.stdout);
601
+ enableMouse(process.stdout);
602
+ // Mouse event handling — raw stdin listener catches SGR mouse events that
603
+ // Ink doesn't parse, enabling click-to-focus on agent tabs.
604
+ mouseHandler = (data) => {
605
+ const str = data.toString();
606
+ const evt = parseMouseEvent(str);
607
+ if (!evt || evt.type !== "press" || evt.button !== "left")
608
+ return;
609
+ // Check if click is in the agent tab row (row above the fixed status bar)
610
+ const rows = process.stdout.rows || 24;
611
+ const tabRow = rows - 1;
612
+ if (evt.y === tabRow && agentTabs.length > 0) {
613
+ // Determine which tab was clicked based on x position.
614
+ // Tab layout mirrors what InputArea renders: "phren● name● ..."
615
+ let xPos = 2; // initial padding offset
616
+ // First slot is always the "phren" (main) tab
617
+ const mainTabWidth = "phren●".length + 2;
618
+ if (evt.x >= xPos && evt.x < xPos + mainTabWidth) {
619
+ handleSelectAgent(null);
620
+ return;
621
+ }
622
+ xPos += mainTabWidth;
623
+ for (const tab of agentTabs) {
624
+ const tabWidth = tab.name.length + 3; // "name● "
625
+ if (evt.x >= xPos && evt.x < xPos + tabWidth) {
626
+ handleSelectAgent(tab.id);
627
+ return;
628
+ }
629
+ xPos += tabWidth;
630
+ }
631
+ }
632
+ };
633
+ if (process.stdin.isTTY) {
634
+ process.stdin.on("data", mouseHandler);
635
+ }
281
636
  const done = new Promise((r) => { resolveSession = r; });
282
637
  app.waitUntilExit().then(() => {
283
- process.stdout.write("\x1b[?2004l"); // disable bracketed paste
638
+ disableMouse(process.stdout);
639
+ if (process.stdin.isTTY) {
640
+ process.stdin.off("data", mouseHandler);
641
+ }
642
+ terminalControl.disable(process.stdout);
284
643
  if (resolveSession)
285
644
  resolveSession(session);
286
645
  });
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Mouse support — SGR extended mode for terminal mouse events.
3
+ * Enables click detection for agent tab switching and hyperlink clicks.
4
+ */
5
+ /**
6
+ * Enable mouse tracking on the terminal.
7
+ * Uses SGR extended mode (\x1b[?1006h) for coordinates > 223.
8
+ * Also enables normal tracking (\x1b[?1000h) for basic button events.
9
+ */
10
+ export function enableMouse(stdout) {
11
+ if (!stdout.isTTY)
12
+ return;
13
+ stdout.write("\x1b[?1000h"); // Normal tracking (button press/release)
14
+ stdout.write("\x1b[?1006h"); // SGR extended mode
15
+ }
16
+ /** Disable mouse tracking and restore normal terminal behavior. */
17
+ export function disableMouse(stdout) {
18
+ if (!stdout.isTTY)
19
+ return;
20
+ stdout.write("\x1b[?1006l");
21
+ stdout.write("\x1b[?1000l");
22
+ }
23
+ /**
24
+ * Try to parse an SGR mouse event from raw input.
25
+ * SGR format: \x1b[<button;column;row(M|m)
26
+ * M = press, m = release
27
+ * Returns null if the input is not a mouse event.
28
+ */
29
+ export function parseMouseEvent(input) {
30
+ // SGR extended: \x1b[<Cb;Cx;CyM or \x1b[<Cb;Cx;Cym
31
+ const match = input.match(/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/);
32
+ if (!match)
33
+ return null;
34
+ const code = parseInt(match[1], 10);
35
+ const x = parseInt(match[2], 10);
36
+ const y = parseInt(match[3], 10);
37
+ const isRelease = match[4] === "m";
38
+ const shift = (code & 4) !== 0;
39
+ const alt = (code & 8) !== 0;
40
+ const ctrl = (code & 16) !== 0;
41
+ const baseCode = code & ~(4 | 8 | 16); // strip modifier bits
42
+ let button = "none";
43
+ let type = isRelease ? "release" : "press";
44
+ if (baseCode === 0)
45
+ button = "left";
46
+ else if (baseCode === 1)
47
+ button = "middle";
48
+ else if (baseCode === 2)
49
+ button = "right";
50
+ else if (baseCode === 64)
51
+ button = "scrollUp";
52
+ else if (baseCode === 65)
53
+ button = "scrollDown";
54
+ else if (baseCode === 32) {
55
+ button = "left";
56
+ type = "move";
57
+ }
58
+ else if (baseCode === 33) {
59
+ button = "middle";
60
+ type = "move";
61
+ }
62
+ else if (baseCode === 34) {
63
+ button = "right";
64
+ type = "move";
65
+ }
66
+ else if (baseCode === 35) {
67
+ button = "none";
68
+ type = "move";
69
+ }
70
+ return { type, button, x, y, shift, ctrl, alt };
71
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Terminal control — manages scroll regions and fixed status bar.
3
+ * Uses DECSTBM (Set Top and Bottom Margins) to create a scrollable area
4
+ * that excludes the bottom N lines, keeping the status bar pinned.
5
+ */
6
+ export class TerminalControl {
7
+ statusHeight = 1;
8
+ enabled = false;
9
+ resizeHandler = null;
10
+ /** Enable scroll regions. Call after Ink render() is set up. */
11
+ enable(stdout) {
12
+ if (!stdout.isTTY || this.enabled)
13
+ return;
14
+ this.enabled = true;
15
+ this.setScrollRegion(stdout);
16
+ this.resizeHandler = () => {
17
+ this.setScrollRegion(stdout);
18
+ this.renderStatusBar(stdout, this.lastContent);
19
+ };
20
+ stdout.on("resize", this.resizeHandler);
21
+ }
22
+ /** Disable scroll regions and restore full terminal. */
23
+ disable(stdout) {
24
+ if (!this.enabled)
25
+ return;
26
+ this.enabled = false;
27
+ // Reset scroll region to full screen
28
+ stdout.write("\x1b[r");
29
+ // Clear status bar line
30
+ const rows = stdout.rows || 24;
31
+ stdout.write(`\x1b[${rows};1H\x1b[2K`);
32
+ if (this.resizeHandler) {
33
+ stdout.off("resize", this.resizeHandler);
34
+ this.resizeHandler = null;
35
+ }
36
+ }
37
+ lastContent = "";
38
+ setScrollRegion(stdout) {
39
+ const rows = stdout.rows || 24;
40
+ // Set scrollable region to exclude bottom statusHeight lines
41
+ stdout.write(`\x1b[1;${rows - this.statusHeight}r`);
42
+ // Move cursor back to the scroll region (don't leave it in the status area)
43
+ stdout.write(`\x1b[${rows - this.statusHeight};1H`);
44
+ }
45
+ /** Render content in the fixed status bar area. */
46
+ renderStatusBar(stdout, content) {
47
+ if (!this.enabled)
48
+ return;
49
+ this.lastContent = content;
50
+ const rows = stdout.rows || 24;
51
+ const cols = stdout.columns || 80;
52
+ // Save cursor, move to status line, clear it, write content, restore cursor
53
+ stdout.write("\x1b[s"); // save cursor
54
+ stdout.write(`\x1b[${rows};1H`); // move to last row
55
+ stdout.write("\x1b[2K"); // clear line
56
+ stdout.write(content.slice(0, cols)); // write (truncate to width)
57
+ stdout.write("\x1b[u"); // restore cursor
58
+ }
59
+ get isEnabled() {
60
+ return this.enabled;
61
+ }
62
+ }