@phren/agent 0.1.7 → 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.
- package/dist/commands/info.js +2 -0
- package/dist/commands/model.js +5 -4
- package/dist/commands/session.js +24 -2
- package/dist/commands.js +36 -1
- package/dist/config.js +27 -11
- package/dist/cost.js +11 -74
- package/dist/index.js +93 -35
- package/dist/mcp-client.js +4 -2
- package/dist/memory/context.js +56 -24
- package/dist/memory/session.js +21 -88
- package/dist/models.js +390 -0
- package/dist/multi/agent-types.js +170 -0
- package/dist/multi/child-entry.js +248 -78
- package/dist/multi/coordinator.js +69 -1
- package/dist/multi/diff-renderer.js +193 -17
- package/dist/multi/markdown.js +49 -23
- package/dist/multi/model-picker.js +12 -21
- package/dist/multi/multi-events.js +17 -0
- package/dist/multi/multi-render.js +1 -0
- package/dist/multi/provider-manager.js +23 -13
- package/dist/multi/spawner.js +84 -7
- package/dist/multi/syntax-highlight.js +64 -48
- package/dist/multi/worktree.js +43 -0
- package/dist/package-metadata.js +11 -0
- package/dist/permissions/checker.js +21 -1
- package/dist/providers/codex-auth.js +48 -34
- package/dist/providers/codex.js +110 -40
- package/dist/providers/ollama.js +5 -4
- package/dist/providers/openrouter.js +12 -5
- package/dist/providers/resolve.js +50 -32
- package/dist/providers/types.js +0 -1
- package/dist/repl.js +19 -34
- package/dist/tools/grep.js +111 -23
- package/dist/tools/mcp-resources.js +32 -0
- package/dist/tools/registry.js +13 -2
- package/dist/tools/shell.js +101 -3
- package/dist/tools/skill.js +44 -0
- package/dist/tools/spawn-agent.js +158 -0
- package/dist/tui/ansi.js +15 -11
- package/dist/tui/components/App.js +179 -8
- package/dist/tui/components/Banner.js +7 -4
- package/dist/tui/components/CodeBlock.js +8 -0
- package/dist/tui/components/InputArea.js +54 -12
- package/dist/tui/components/PhrenInput.js +329 -0
- package/dist/tui/components/StatusBar.js +3 -1
- package/dist/tui/components/SteerQueue.js +4 -2
- package/dist/tui/components/ThinkingIndicator.js +7 -5
- package/dist/tui/components/ToolCall.js +17 -7
- package/dist/tui/components/ToolSpinner.js +13 -0
- package/dist/tui/hooks/useKeyboardShortcuts.js +70 -8
- package/dist/tui/hooks/useSearch.js +47 -0
- package/dist/tui/hooks/useSlashCommands.js +16 -19
- package/dist/tui/ink-entry.js +383 -11
- package/dist/tui/mouse.js +71 -0
- package/dist/tui/terminal-control.js +62 -0
- package/dist/tui/themes.js +398 -0
- package/dist/tui/tool-render.js +12 -1
- package/dist/tui.js +2 -1
- package/package.json +2 -4
package/dist/tui/ink-entry.js
CHANGED
|
@@ -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) {
|
|
@@ -21,7 +25,38 @@ export async function startInkTui(config, spawner) {
|
|
|
21
25
|
const steerQueueBuf = [];
|
|
22
26
|
const inputHistory = [];
|
|
23
27
|
let running = false;
|
|
28
|
+
let verbose = false;
|
|
29
|
+
let theme = getTheme();
|
|
24
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
|
+
};
|
|
25
60
|
// Mutable render state — updated then pushed to React via rerender()
|
|
26
61
|
const completedMessages = [];
|
|
27
62
|
let streamingText = "";
|
|
@@ -29,6 +64,7 @@ export async function startInkTui(config, spawner) {
|
|
|
29
64
|
let thinkStartTime = 0;
|
|
30
65
|
let thinkElapsed = null;
|
|
31
66
|
let currentToolCalls = [];
|
|
67
|
+
let activeTool = null;
|
|
32
68
|
function nextId() {
|
|
33
69
|
return `msg-${++msgCounter}`;
|
|
34
70
|
}
|
|
@@ -43,12 +79,49 @@ export async function startInkTui(config, spawner) {
|
|
|
43
79
|
version: AGENT_VERSION,
|
|
44
80
|
};
|
|
45
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
|
+
}
|
|
46
93
|
// Re-render the Ink app with current state
|
|
47
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
|
+
}
|
|
48
108
|
function update() {
|
|
49
109
|
if (!rerender)
|
|
50
110
|
return;
|
|
51
|
-
|
|
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();
|
|
52
125
|
}
|
|
53
126
|
function handlePermissionCycle() {
|
|
54
127
|
const next = nextPermissionMode(config.registry.permissionConfig.mode);
|
|
@@ -58,6 +131,11 @@ export async function startInkTui(config, spawner) {
|
|
|
58
131
|
}
|
|
59
132
|
let resolveSession = null;
|
|
60
133
|
function handleExit() {
|
|
134
|
+
disableMouse(process.stdout);
|
|
135
|
+
if (process.stdin.isTTY) {
|
|
136
|
+
process.stdin.off("data", mouseHandler);
|
|
137
|
+
}
|
|
138
|
+
terminalControl.disable(process.stdout);
|
|
61
139
|
if (resolveSession)
|
|
62
140
|
resolveSession(session);
|
|
63
141
|
}
|
|
@@ -75,6 +153,7 @@ export async function startInkTui(config, spawner) {
|
|
|
75
153
|
undoStack: [],
|
|
76
154
|
providerName: config.provider.name,
|
|
77
155
|
currentModel: config.provider.model,
|
|
156
|
+
currentReasoning: config.provider.reasoningEffort ?? null,
|
|
78
157
|
provider: config.provider,
|
|
79
158
|
systemPrompt: config.systemPrompt,
|
|
80
159
|
spawner,
|
|
@@ -85,7 +164,7 @@ export async function startInkTui(config, spawner) {
|
|
|
85
164
|
onModelChange: async (result) => {
|
|
86
165
|
try {
|
|
87
166
|
const { resolveProvider } = await import("../providers/resolve.js");
|
|
88
|
-
const newProvider = resolveProvider(config.provider.name, result.model);
|
|
167
|
+
const newProvider = resolveProvider(config.provider.name, result.model, undefined, result.reasoning ?? undefined);
|
|
89
168
|
config.provider = newProvider;
|
|
90
169
|
const { buildSystemPrompt } = await import("../system-prompt.js");
|
|
91
170
|
config.systemPrompt = buildSystemPrompt(config.systemPrompt.split("\n## Last session")[0], null, { name: newProvider.name, model: result.model });
|
|
@@ -102,6 +181,31 @@ export async function startInkTui(config, spawner) {
|
|
|
102
181
|
const line = input.trim();
|
|
103
182
|
if (!line)
|
|
104
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
|
+
}
|
|
105
209
|
// Track input history (skip duplicates of the last entry)
|
|
106
210
|
if (inputHistory.length === 0 || inputHistory[inputHistory.length - 1] !== line) {
|
|
107
211
|
inputHistory.push(line);
|
|
@@ -146,6 +250,63 @@ export async function startInkTui(config, spawner) {
|
|
|
146
250
|
update();
|
|
147
251
|
return;
|
|
148
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
|
+
}
|
|
285
|
+
if (line === "/verbose") {
|
|
286
|
+
verbose = !verbose;
|
|
287
|
+
completedMessages.push({ id: nextId(), kind: "status", text: `Verbose: ${verbose ? "on" : "off"}` });
|
|
288
|
+
update();
|
|
289
|
+
return;
|
|
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
|
+
}
|
|
149
310
|
// Slash commands — capture stderr output and display as status message
|
|
150
311
|
if (line.startsWith("/")) {
|
|
151
312
|
if (slashCommands.tryHandleCommand(line)) {
|
|
@@ -164,7 +325,21 @@ export async function startInkTui(config, spawner) {
|
|
|
164
325
|
update();
|
|
165
326
|
return;
|
|
166
327
|
}
|
|
167
|
-
//
|
|
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
|
|
168
343
|
completedMessages.push({ id: nextId(), kind: "user", text: line });
|
|
169
344
|
update();
|
|
170
345
|
runAgentTurn(line);
|
|
@@ -174,7 +349,7 @@ export async function startInkTui(config, spawner) {
|
|
|
174
349
|
onTextDelta: (text) => {
|
|
175
350
|
thinking = false;
|
|
176
351
|
streamingText += text;
|
|
177
|
-
|
|
352
|
+
scheduleUpdate();
|
|
178
353
|
},
|
|
179
354
|
onTextDone: () => {
|
|
180
355
|
// streaming complete — finalized in runAgentTurn
|
|
@@ -182,16 +357,19 @@ export async function startInkTui(config, spawner) {
|
|
|
182
357
|
onTextBlock: (text) => {
|
|
183
358
|
thinking = false;
|
|
184
359
|
streamingText += text;
|
|
185
|
-
|
|
360
|
+
scheduleUpdate();
|
|
186
361
|
},
|
|
187
|
-
onToolStart: (
|
|
362
|
+
onToolStart: (name, input, _count) => {
|
|
188
363
|
thinking = false;
|
|
364
|
+
activeTool = { name, preview: formatToolInput(name, input) };
|
|
189
365
|
update();
|
|
190
366
|
},
|
|
191
367
|
onToolEnd: (name, input, output, isError, dur) => {
|
|
368
|
+
activeTool = null;
|
|
192
369
|
const diffData = (name === "edit_file" || name === "write_file") ? decodeDiffPayload(output) : null;
|
|
193
370
|
const cleanOutput = diffData ? output.slice(0, output.indexOf(DIFF_MARKER)) : output;
|
|
194
|
-
|
|
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 });
|
|
195
373
|
update();
|
|
196
374
|
},
|
|
197
375
|
getSteeringInput: () => {
|
|
@@ -216,6 +394,7 @@ export async function startInkTui(config, spawner) {
|
|
|
216
394
|
thinkElapsed = null;
|
|
217
395
|
streamingText = "";
|
|
218
396
|
currentToolCalls = [];
|
|
397
|
+
activeTool = null;
|
|
219
398
|
update();
|
|
220
399
|
try {
|
|
221
400
|
await runTurn(userInput, session, config, tuiHooks);
|
|
@@ -238,8 +417,10 @@ export async function startInkTui(config, spawner) {
|
|
|
238
417
|
}
|
|
239
418
|
streamingText = "";
|
|
240
419
|
currentToolCalls = [];
|
|
420
|
+
activeTool = null;
|
|
241
421
|
running = false;
|
|
242
422
|
thinkElapsed = elapsed;
|
|
423
|
+
process.stdout.write("\x07"); // terminal bell on completion
|
|
243
424
|
update();
|
|
244
425
|
// Clear elapsed indicator after a brief display
|
|
245
426
|
setTimeout(() => {
|
|
@@ -261,13 +442,204 @@ export async function startInkTui(config, spawner) {
|
|
|
261
442
|
runAgentTurn(queued);
|
|
262
443
|
}
|
|
263
444
|
}
|
|
264
|
-
//
|
|
265
|
-
|
|
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
|
|
593
|
+
const projectName = config.phrenCtx?.project ?? "phren";
|
|
594
|
+
process.title = "phren";
|
|
595
|
+
process.stdout.write(`\x1b]0;phren \xb7 ${projectName}\x07`); // set terminal window title
|
|
266
596
|
// Initial render
|
|
267
|
-
const app = render(_jsx(App, { state: getAppState(), completedMessages: [], streamingText: "", completedToolCalls: [], thinking: false, thinkStartTime: 0, thinkElapsed: null, steerQueue: [], running: false, showBanner: true, inputHistory: [], 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 });
|
|
268
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
|
+
}
|
|
269
636
|
const done = new Promise((r) => { resolveSession = r; });
|
|
270
637
|
app.waitUntilExit().then(() => {
|
|
638
|
+
disableMouse(process.stdout);
|
|
639
|
+
if (process.stdin.isTTY) {
|
|
640
|
+
process.stdin.off("data", mouseHandler);
|
|
641
|
+
}
|
|
642
|
+
terminalControl.disable(process.stdout);
|
|
271
643
|
if (resolveSession)
|
|
272
644
|
resolveSession(session);
|
|
273
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
|
+
}
|