@phren/agent 0.1.14 → 0.3.5

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 (112) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +86 -0
  3. package/dist/agent-loop/index.js +239 -65
  4. package/dist/agent-loop/stream.js +212 -29
  5. package/dist/agent-loop/types.js +15 -2
  6. package/dist/bin.js +0 -0
  7. package/dist/checkpoint.js +103 -22
  8. package/dist/commands/info.js +30 -15
  9. package/dist/commands/model.js +6 -2
  10. package/dist/commands/review.js +183 -0
  11. package/dist/commands/session.js +70 -7
  12. package/dist/commands.js +168 -12
  13. package/dist/config.js +87 -10
  14. package/dist/context/compactor.js +239 -0
  15. package/dist/context/pruner.js +39 -13
  16. package/dist/context/token-counter.js +33 -1
  17. package/dist/custom-commands.js +69 -0
  18. package/dist/guards/repeat-tool-reminder.js +75 -0
  19. package/dist/headless.js +115 -0
  20. package/dist/herdr-hooks.js +71 -0
  21. package/dist/index.js +351 -48
  22. package/dist/mcp-client.js +434 -73
  23. package/dist/mcp-oauth.js +121 -0
  24. package/dist/memory/anti-patterns.js +7 -3
  25. package/dist/memory/auto-capture.js +7 -3
  26. package/dist/memory/context.js +92 -73
  27. package/dist/memory/project-context.js +24 -5
  28. package/dist/memory/provenance.js +15 -0
  29. package/dist/memory/review-triage.js +166 -0
  30. package/dist/memory/session.js +36 -1
  31. package/dist/models.js +152 -19
  32. package/dist/multi/child-entry.js +65 -10
  33. package/dist/multi/diff-renderer.js +3 -3
  34. package/dist/multi/markdown.js +125 -27
  35. package/dist/multi/provider-manager.js +8 -0
  36. package/dist/multi/publish.js +72 -0
  37. package/dist/multi/spawner.js +45 -4
  38. package/dist/multi/syntax-highlight.js +25 -4
  39. package/dist/multi/types.js +1 -1
  40. package/dist/permissions/allowlist.js +86 -13
  41. package/dist/permissions/checker.js +42 -7
  42. package/dist/permissions/kernel-sandbox.js +197 -0
  43. package/dist/permissions/prompt.js +10 -1
  44. package/dist/permissions/sandbox.js +40 -17
  45. package/dist/providers/anthropic.js +154 -7
  46. package/dist/providers/codex-auth.js +28 -0
  47. package/dist/providers/codex.js +134 -23
  48. package/dist/providers/history.js +35 -0
  49. package/dist/providers/ollama.js +37 -6
  50. package/dist/providers/openai-compat.js +171 -74
  51. package/dist/providers/openrouter.js +47 -17
  52. package/dist/providers/replay.js +62 -0
  53. package/dist/providers/resolve.js +41 -7
  54. package/dist/providers/retry.js +38 -5
  55. package/dist/providers/types.js +9 -1
  56. package/dist/repl.js +47 -5
  57. package/dist/session/log.js +217 -0
  58. package/dist/session/persist.js +190 -0
  59. package/dist/settings.js +42 -26
  60. package/dist/system-prompt.js +18 -2
  61. package/dist/tools/apply-patch.js +355 -0
  62. package/dist/tools/edit-engine.js +287 -0
  63. package/dist/tools/edit-file.js +86 -27
  64. package/dist/tools/grep.js +25 -10
  65. package/dist/tools/lint-test.js +0 -22
  66. package/dist/tools/mcp-resources.js +51 -6
  67. package/dist/tools/phren-finding.js +12 -4
  68. package/dist/tools/phren-search.js +7 -2
  69. package/dist/tools/read-file.js +37 -9
  70. package/dist/tools/read-image.js +76 -0
  71. package/dist/tools/registry.js +27 -5
  72. package/dist/tools/shell.js +134 -71
  73. package/dist/tools/skill.js +20 -20
  74. package/dist/tools/spawn-agent.js +77 -13
  75. package/dist/tools/update-plan.js +48 -0
  76. package/dist/tools/web-fetch.js +110 -12
  77. package/dist/tools/web-search.js +4 -4
  78. package/dist/tui/components/App.js +98 -26
  79. package/dist/tui/components/ApprovalPanel.js +8 -0
  80. package/dist/tui/components/InputArea.js +5 -5
  81. package/dist/tui/components/ModelPicker.js +43 -0
  82. package/dist/tui/components/PhrenInput.js +10 -5
  83. package/dist/tui/components/PlanReview.js +7 -0
  84. package/dist/tui/components/ShortcutHelp.js +5 -0
  85. package/dist/tui/components/StatusBar.js +46 -20
  86. package/dist/tui/components/SteerQueue.js +1 -1
  87. package/dist/tui/components/ThinkingIndicator.js +6 -4
  88. package/dist/tui/components/ToolCall.js +10 -4
  89. package/dist/tui/components/ToolDetail.js +21 -0
  90. package/dist/tui/help.js +6 -0
  91. package/dist/tui/hooks/useKeyboardShortcuts.js +15 -1
  92. package/dist/tui/index.js +0 -1
  93. package/dist/tui/ink-entry.js +317 -33
  94. package/dist/tui/tool-render.js +1 -1
  95. package/dist/user-hooks.js +171 -0
  96. package/package.json +18 -12
  97. package/dist/multi/multi-commands.js +0 -170
  98. package/dist/multi/multi-events.js +0 -98
  99. package/dist/multi/multi-render.js +0 -147
  100. package/dist/multi/pane.js +0 -28
  101. package/dist/multi/tui-multi.js +0 -200
  102. package/dist/permissions/privacy.js +0 -248
  103. package/dist/tui/components/AgentMessage.js +0 -5
  104. package/dist/tui/components/ChatMessage.js +0 -23
  105. package/dist/tui/components/CodeBlock.js +0 -8
  106. package/dist/tui/components/Separator.js +0 -7
  107. package/dist/tui/components/StreamingText.js +0 -5
  108. package/dist/tui/components/UserMessage.js +0 -5
  109. package/dist/tui/menu-mode.js +0 -86
  110. package/dist/tui/mouse.js +0 -71
  111. package/dist/tui/terminal-control.js +0 -62
  112. package/dist/tui.js +0 -781
package/dist/tui.js DELETED
@@ -1,781 +0,0 @@
1
- /**
2
- * Terminal UI for phren-agent — streaming chat with inline tool calls.
3
- * Dual-mode: Chat (LLM conversation) and Menu (navigable memory browser).
4
- * Tab toggles between modes. Raw stdin for steering support.
5
- */
6
- import * as readline from "node:readline";
7
- import { createSession, runTurn } from "./agent-loop.js";
8
- import { handleCommand } from "./commands.js";
9
- import { renderMarkdown } from "./multi/markdown.js";
10
- import { decodeDiffPayload, renderInlineDiff, DIFF_MARKER } from "./multi/diff-renderer.js";
11
- import * as os from "os";
12
- import * as fs from "node:fs";
13
- import * as path from "node:path";
14
- import { execSync } from "node:child_process";
15
- import { loadInputMode, saveInputMode, savePermissionMode } from "./settings.js";
16
- import { createRequire } from "node:module";
17
- import { ESC, s, cols, stripAnsi, PERMISSION_COLORS, PERMISSION_ICONS, PERMISSION_LABELS, nextPermissionMode, permTag, formatToolInput, renderToolCall, } from "./tui/index.js";
18
- import { enterMenuMode as enterMenu, exitMenuMode as exitMenu, handleMenuKeypress as handleMenuKey, } from "./tui/index.js";
19
- const _require = createRequire(import.meta.url);
20
- const AGENT_VERSION = _require("../package.json").version;
21
- // ── Status bar ───────────────────────────────────────────────────────────────
22
- function renderStatusBar(provider, project, turns, cost, permMode, agentCount) {
23
- const modeLabel = permMode ? PERMISSION_LABELS[permMode] : "";
24
- const agentTag = agentCount && agentCount > 0 ? ` A${agentCount}` : "";
25
- // Left: brand + provider (skip project if it matches "phren" to avoid "phren · codex · phren")
26
- const parts = [" ◆ phren", provider];
27
- if (project && project !== "phren")
28
- parts.push(project);
29
- const left = parts.join(" · ");
30
- // Right: mode + agents + cost + turns
31
- const rightParts = [];
32
- if (modeLabel)
33
- rightParts.push(modeLabel);
34
- if (agentTag)
35
- rightParts.push(agentTag.trim());
36
- if (cost)
37
- rightParts.push(cost);
38
- rightParts.push(`T${turns}`);
39
- const right = rightParts.join(" ") + " ";
40
- const w = cols();
41
- const pad = Math.max(0, w - left.length - right.length);
42
- return s.invert(left + " ".repeat(pad) + right);
43
- }
44
- // ── Main TUI ─────────────────────────────────────────────────────────────────
45
- export async function startTui(config, spawner) {
46
- const contextLimit = config.provider.contextWindow ?? 200_000;
47
- const session = createSession(contextLimit);
48
- const w = process.stdout;
49
- const isTTY = process.stdout.isTTY;
50
- const startTime = Date.now();
51
- let inputMode = loadInputMode();
52
- let pendingInput = null;
53
- const steerQueue = [];
54
- let running = false;
55
- let inputLine = "";
56
- let cursorPos = 0;
57
- let costStr = "";
58
- // ── Dual-mode state ─────────────────────────────────────────────────────
59
- let tuiMode = "chat";
60
- let menuState = {
61
- view: "Projects",
62
- project: config.phrenCtx?.project ?? undefined,
63
- cursor: 0,
64
- scroll: 0,
65
- };
66
- let menuListCount = 0;
67
- let menuFilterActive = false;
68
- let menuFilterBuf = "";
69
- let ctrlCCount = 0;
70
- // Input history
71
- const inputHistory = [];
72
- let historyIndex = -1;
73
- let savedInput = "";
74
- // ── Menu context bridge ─────────────────────────────────────────────────
75
- function getMenuCtx() {
76
- return {
77
- phrenCtx: config.phrenCtx ? {
78
- phrenPath: config.phrenCtx.phrenPath,
79
- profile: config.phrenCtx.profile,
80
- project: config.phrenCtx.project ?? undefined,
81
- } : undefined,
82
- w,
83
- menuState,
84
- menuListCount,
85
- menuFilterActive,
86
- menuFilterBuf,
87
- onExit: () => {
88
- tuiMode = "chat";
89
- statusBar();
90
- prompt();
91
- },
92
- onStateChange: (st, lc, fa, fb) => {
93
- menuState = st;
94
- menuListCount = lc;
95
- menuFilterActive = fa;
96
- menuFilterBuf = fb;
97
- },
98
- };
99
- }
100
- // Print status bar
101
- function statusBar() {
102
- // Intentionally empty — no top status bar. Info is in the bottom prompt area.
103
- }
104
- // Print prompt — inline input bar (written at current cursor position)
105
- let bashMode = false;
106
- // Track how many lines the bottom bar occupies so we can clear it on submit
107
- const PROMPT_LINES = 4; // separator, input, separator, permissions
108
- function prompt() {
109
- if (!isTTY)
110
- return;
111
- const mode = config.registry.permissionConfig.mode;
112
- const color = PERMISSION_COLORS[mode];
113
- const icon = PERMISSION_ICONS[mode];
114
- const c = cols();
115
- const sep = s.dim("─".repeat(c));
116
- const permLine = ` ${color(`${icon} ${PERMISSION_LABELS[mode]} permissions`)} ${s.dim("(shift+tab toggle · esc to interrupt)")}`;
117
- // Write inline — this naturally sits at the bottom
118
- w.write(`${sep}\n`);
119
- w.write(`${bashMode ? `${s.yellow("!")} ` : `${s.dim("▸")} `}`);
120
- w.write(`\n${sep}\n`);
121
- w.write(`${permLine}\n`);
122
- // Move cursor back up to the input line
123
- w.write(`${ESC}${PROMPT_LINES - 1}A`); // move up to input line
124
- w.write(`${ESC}${bashMode ? 3 : 4}G`); // move to column after prompt char
125
- }
126
- // Redraw the input line and position the terminal cursor at cursorPos
127
- function redrawInput() {
128
- w.write(`${ESC}2K\r`);
129
- w.write(`${bashMode ? `${s.yellow("!")} ` : `${s.dim("▸")} `}`);
130
- w.write(inputLine);
131
- // Move terminal cursor back from end to cursorPos
132
- const back = inputLine.length - cursorPos;
133
- if (back > 0)
134
- w.write(`${ESC}${back}D`);
135
- }
136
- // Periodic status bar refresh (every 30s) — keeps cost/turns current during long tool runs
137
- const statusRefreshTimer = isTTY
138
- ? setInterval(() => { if (tuiMode === "chat")
139
- statusBar(); }, 30_000)
140
- : null;
141
- if (statusRefreshTimer)
142
- statusRefreshTimer.unref(); // don't keep process alive
143
- // Terminal cleanup: restore state on exit
144
- function cleanupTerminal() {
145
- if (statusRefreshTimer)
146
- clearInterval(statusRefreshTimer);
147
- w.write("\x1b[?1049l"); // leave alt screen if active
148
- if (process.stdin.isTTY) {
149
- try {
150
- process.stdin.setRawMode(false);
151
- }
152
- catch { }
153
- }
154
- }
155
- process.on("exit", cleanupTerminal);
156
- // Terminal resize: do nothing — scrollback text reflows naturally.
157
- // The Ink TUI handles resize via React re-render. Legacy TUI just lets it be.
158
- // Setup: clear screen, status bar at top, content area clean
159
- if (isTTY) {
160
- w.write(`${ESC}2J${ESC}H`); // clear entire screen + home
161
- statusBar();
162
- w.write(`${ESC}2;1H`); // move below status bar
163
- // Startup banner
164
- const project = config.phrenCtx?.project;
165
- const cwd = process.cwd().replace(os.homedir(), "~");
166
- const permMode = config.registry.permissionConfig.mode;
167
- let artLines = [];
168
- try {
169
- const { PHREN_ART } = await import("@phren/cli/phren-art");
170
- artLines = PHREN_ART.filter((l) => l.trim());
171
- }
172
- catch { /* art not available */ }
173
- const info = [
174
- `${s.brand("◆ phren agent")} ${s.dim(`v${AGENT_VERSION}`)}`,
175
- `${s.dim(config.provider.name)}${project ? s.dim(` · ${project}`) : ""}`,
176
- `${s.dim(cwd)}`,
177
- ``,
178
- `${permTag(permMode)} ${s.dim("permissions (shift+tab toggle · esc to interrupt)")}`,
179
- ``,
180
- `${s.dim("Tab")} memory ${s.dim("Shift+Tab")} perms ${s.dim("/help")} cmds ${s.dim("Ctrl+D")} exit`,
181
- ];
182
- if (artLines.length > 0) {
183
- const maxArtWidth = 26;
184
- for (let i = 0; i < Math.max(artLines.length, info.length); i++) {
185
- const artPart = i < artLines.length ? artLines[i] : "";
186
- const infoPart = i < info.length ? info[i] : "";
187
- const artPadded = artPart + " ".repeat(Math.max(0, maxArtWidth - stripAnsi(artPart).length));
188
- w.write(`${artPadded}${infoPart}\n`);
189
- }
190
- }
191
- else {
192
- w.write(`\n ${info[0]}\n ${info[1]} ${info[2]}\n ${info[4]}\n\n ${info[6]}\n\n`);
193
- }
194
- w.write("\n");
195
- }
196
- // Raw stdin for steering
197
- if (process.stdin.isTTY) {
198
- readline.emitKeypressEvents(process.stdin);
199
- process.stdin.setRawMode(true);
200
- }
201
- let resolve = null;
202
- const done = new Promise((r) => { resolve = r; });
203
- // ── Keypress router ────────────────────────────────────────────────────
204
- process.stdin.on("keypress", (_ch, key) => {
205
- if (!key)
206
- return;
207
- // Ctrl+D — clean exit
208
- if (key.ctrl && key.name === "d") {
209
- if (tuiMode === "menu")
210
- w.write("\x1b[?1049l");
211
- cleanupTerminal();
212
- w.write(`\n${s.dim(`${session.turns} turns, ${session.toolCalls} tool calls.`)}\n`);
213
- resolve(session);
214
- return;
215
- }
216
- // Shift+Tab — cycle permission mode (works in chat mode, not during filter)
217
- if (key.shift && key.name === "tab" && !menuFilterActive && tuiMode === "chat") {
218
- const next = nextPermissionMode(config.registry.permissionConfig.mode);
219
- config.registry.setPermissions({ ...config.registry.permissionConfig, mode: next });
220
- savePermissionMode(next);
221
- // Redraw the entire prompt bar in-place (permissions line changed)
222
- w.write(`\r${ESC}J`); // clear from cursor to end of screen
223
- prompt();
224
- w.write(inputLine);
225
- const back = inputLine.length - cursorPos;
226
- if (back > 0)
227
- w.write(`${ESC}${back}D`);
228
- return;
229
- }
230
- // Tab — completion or toggle mode
231
- if (key.name === "tab" && !key.shift && !menuFilterActive) {
232
- // Slash command completion in chat mode
233
- if (tuiMode === "chat" && inputLine.startsWith("/")) {
234
- const SLASH_COMMANDS = [
235
- "/help", "/model", "/provider", "/turns", "/clear", "/cost",
236
- "/plan", "/undo", "/history", "/compact", "/context", "/mode",
237
- "/spawn", "/agents", "/diff", "/git", "/files", "/cwd",
238
- "/preset", "/exit",
239
- ];
240
- const matches = SLASH_COMMANDS.filter((c) => c.startsWith(inputLine));
241
- if (matches.length === 1) {
242
- inputLine = matches[0];
243
- cursorPos = inputLine.length;
244
- redrawInput();
245
- }
246
- else if (matches.length > 1) {
247
- // Show matches above prompt, then redraw
248
- w.write(`\r${ESC}J`); // clear from cursor to end of screen
249
- w.write(`\n${s.dim(" " + matches.join(" "))}\n`);
250
- prompt();
251
- w.write(inputLine);
252
- const back = inputLine.length - cursorPos;
253
- if (back > 0)
254
- w.write(`${ESC}${back}D`);
255
- }
256
- return;
257
- }
258
- // File path completion in bash mode
259
- if (tuiMode === "chat" && bashMode && inputLine.length > 0) {
260
- // Complete the last whitespace-delimited token as a path
261
- const lastSpace = inputLine.lastIndexOf(" ");
262
- const prefix = lastSpace === -1 ? "" : inputLine.slice(0, lastSpace + 1);
263
- const partial = lastSpace === -1 ? inputLine : inputLine.slice(lastSpace + 1);
264
- const expandedPartial = partial.replace(/^~/, os.homedir());
265
- const dir = path.dirname(expandedPartial);
266
- const base = path.basename(expandedPartial);
267
- try {
268
- const entries = fs.readdirSync(dir, { withFileTypes: true });
269
- const matches = entries.filter((e) => e.name.startsWith(base));
270
- if (matches.length === 1) {
271
- const completed = matches[0];
272
- const fullPath = partial.startsWith("~")
273
- ? "~/" + path.relative(os.homedir(), path.join(dir, completed.name))
274
- : path.join(dir, completed.name);
275
- inputLine = prefix + fullPath + (completed.isDirectory() ? "/" : "");
276
- cursorPos = inputLine.length;
277
- redrawInput();
278
- }
279
- else if (matches.length > 1) {
280
- const names = matches.map((e) => e.name + (e.isDirectory() ? "/" : ""));
281
- w.write(`\r${ESC}J`); // clear from cursor to end of screen
282
- w.write(`\n${s.dim(" " + names.join(" "))}\n`);
283
- // Find longest common prefix for partial completion
284
- let common = matches[0].name;
285
- for (const m of matches) {
286
- while (!m.name.startsWith(common))
287
- common = common.slice(0, -1);
288
- }
289
- if (common.length > base.length) {
290
- const fullPath = partial.startsWith("~")
291
- ? "~/" + path.relative(os.homedir(), path.join(dir, common))
292
- : path.join(dir, common);
293
- inputLine = prefix + fullPath;
294
- cursorPos = inputLine.length;
295
- }
296
- prompt();
297
- w.write(inputLine);
298
- const back = inputLine.length - cursorPos;
299
- if (back > 0)
300
- w.write(`${ESC}${back}D`);
301
- }
302
- }
303
- catch { /* dir doesn't exist or unreadable */ }
304
- return;
305
- }
306
- // Default: toggle menu mode
307
- if (tuiMode === "chat" && !running) {
308
- tuiMode = "menu";
309
- enterMenu(getMenuCtx());
310
- }
311
- else if (tuiMode === "menu") {
312
- exitMenu(getMenuCtx());
313
- }
314
- return;
315
- }
316
- // Route to mode-specific handler
317
- if (tuiMode === "menu") {
318
- handleMenuKey(key, getMenuCtx());
319
- return;
320
- }
321
- // ── Chat mode keys ──────────────────────────────────────────────────
322
- // Escape — exit bash mode, or clear input
323
- if (key.name === "escape") {
324
- if (bashMode) {
325
- bashMode = false;
326
- inputLine = "";
327
- cursorPos = 0;
328
- redrawInput();
329
- return;
330
- }
331
- if (inputLine) {
332
- inputLine = "";
333
- cursorPos = 0;
334
- redrawInput();
335
- return;
336
- }
337
- }
338
- // Ctrl+C — progressive: cancel → warn → quit
339
- if (key.ctrl && key.name === "c") {
340
- if (running) {
341
- // Cancel current agent turn
342
- pendingInput = null;
343
- w.write(s.yellow("\n [interrupted]\n"));
344
- ctrlCCount = 0;
345
- return;
346
- }
347
- if (bashMode) {
348
- bashMode = false;
349
- inputLine = "";
350
- cursorPos = 0;
351
- redrawInput();
352
- ctrlCCount = 0;
353
- return;
354
- }
355
- if (inputLine) {
356
- // Clear input
357
- inputLine = "";
358
- cursorPos = 0;
359
- redrawInput();
360
- ctrlCCount = 0;
361
- return;
362
- }
363
- // Nothing to cancel — progressive quit
364
- ctrlCCount++;
365
- if (ctrlCCount === 1) {
366
- // Clear current prompt, print warning, redraw prompt
367
- w.write(`\r${ESC}J`);
368
- w.write(s.dim("\n Press Ctrl+C again to exit.\n"));
369
- prompt();
370
- // Reset after 2 seconds
371
- setTimeout(() => { ctrlCCount = 0; }, 2000);
372
- }
373
- else {
374
- // Actually quit
375
- cleanupTerminal();
376
- w.write(s.dim("\nSession ended.\n"));
377
- resolve(session);
378
- }
379
- return;
380
- }
381
- // Enter — submit
382
- if (key.name === "return") {
383
- const line = inputLine.trim();
384
- cursorPos = 0;
385
- inputLine = "";
386
- if (!line) {
387
- redrawInput();
388
- return;
389
- }
390
- // Push to history
391
- if (inputHistory[inputHistory.length - 1] !== line) {
392
- inputHistory.push(line);
393
- }
394
- historyIndex = -1;
395
- // Bash mode: ! prefix runs shell directly
396
- if (line.startsWith("!") || bashMode) {
397
- const cmd = bashMode ? line : line.slice(1).trim();
398
- bashMode = false;
399
- if (cmd) {
400
- // Handle cd specially — change process cwd
401
- const cdMatch = cmd.match(/^cd\s+(.*)/);
402
- if (cdMatch) {
403
- try {
404
- const target = cdMatch[1].trim().replace(/^~/, os.homedir());
405
- const resolved = path.resolve(process.cwd(), target);
406
- process.chdir(resolved);
407
- w.write(s.dim(process.cwd()) + "\n");
408
- }
409
- catch (err) {
410
- w.write(s.red(err.message) + "\n");
411
- }
412
- }
413
- else {
414
- try {
415
- const output = execSync(cmd, { encoding: "utf-8", timeout: 30_000, cwd: process.cwd(), stdio: ["ignore", "pipe", "pipe"] });
416
- w.write(output);
417
- if (!output.endsWith("\n"))
418
- w.write("\n");
419
- }
420
- catch (err) {
421
- const e = err;
422
- w.write(s.red(e.stderr || e.message || "Command failed") + "\n");
423
- }
424
- }
425
- }
426
- prompt();
427
- return;
428
- }
429
- // Slash commands
430
- if (line === "/mode") {
431
- inputMode = inputMode === "steering" ? "queue" : "steering";
432
- saveInputMode(inputMode);
433
- w.write(s.yellow(` Input mode: ${inputMode}\n`));
434
- prompt();
435
- return;
436
- }
437
- const cmdResult = handleCommand(line, {
438
- session,
439
- contextLimit,
440
- undoStack: [],
441
- providerName: config.provider.name,
442
- currentModel: config.provider.model,
443
- currentReasoning: config.provider.reasoningEffort ?? null,
444
- provider: config.provider,
445
- systemPrompt: config.systemPrompt,
446
- spawner,
447
- sessionId: config.sessionId,
448
- startTime,
449
- phrenPath: config.phrenCtx?.phrenPath,
450
- phrenCtx: config.phrenCtx,
451
- onModelChange: async (result) => {
452
- // Live model switch — re-resolve provider with new model
453
- try {
454
- const { resolveProvider } = await import("./providers/resolve.js");
455
- const newProvider = resolveProvider(config.provider.name, result.model, undefined, result.reasoning ?? undefined);
456
- config.provider = newProvider;
457
- // Rebuild system prompt with new model info
458
- const { buildSystemPrompt } = await import("./system-prompt.js");
459
- config.systemPrompt = buildSystemPrompt(config.systemPrompt.split("\n## Last session")[0], // preserve context, strip old summary
460
- null, { name: newProvider.name, model: result.model });
461
- statusBar();
462
- }
463
- catch { /* keep current provider on error */ }
464
- },
465
- });
466
- if (cmdResult === true) {
467
- prompt();
468
- return;
469
- }
470
- if (typeof cmdResult === "object" && cmdResult instanceof Promise) {
471
- cmdResult.then(() => { prompt(); });
472
- return;
473
- }
474
- // If agent is running, add to steer queue
475
- if (running) {
476
- if (inputMode === "steering") {
477
- steerQueue.push(line);
478
- }
479
- else {
480
- pendingInput = line;
481
- }
482
- // Show queued input above the thinking line
483
- w.write(`${ESC}2K${s.dim(` ↳ ${inputMode === "steering" ? "steer" : "queued"}: ${line.slice(0, 60)}`)}\n`);
484
- return;
485
- }
486
- // Clear input line, echo user input above prompt, redraw prompt
487
- w.write(`\r${ESC}2K`); // clear input line
488
- // Scroll up: move to line above prompt area, write content, redraw prompt
489
- w.write(`${ESC}${PROMPT_LINES}A`); // move up past the prompt area
490
- w.write(`${s.bold("❯")} ${line}\n`);
491
- prompt(); // redraw prompt below
492
- runAgentTurn(line);
493
- return;
494
- }
495
- // Up arrow — previous history
496
- if (key.name === "up" && !running && tuiMode === "chat") {
497
- if (inputHistory.length === 0)
498
- return;
499
- if (historyIndex === -1) {
500
- savedInput = inputLine;
501
- historyIndex = inputHistory.length - 1;
502
- }
503
- else if (historyIndex > 0) {
504
- historyIndex--;
505
- }
506
- inputLine = inputHistory[historyIndex];
507
- cursorPos = inputLine.length;
508
- redrawInput();
509
- return;
510
- }
511
- // Down arrow — next history or restore saved
512
- if (key.name === "down" && !running && tuiMode === "chat") {
513
- if (historyIndex === -1)
514
- return;
515
- if (historyIndex < inputHistory.length - 1) {
516
- historyIndex++;
517
- inputLine = inputHistory[historyIndex];
518
- }
519
- else {
520
- historyIndex = -1;
521
- inputLine = savedInput;
522
- }
523
- cursorPos = inputLine.length;
524
- redrawInput();
525
- return;
526
- }
527
- // Ctrl+A — move cursor to start of line
528
- if (key.ctrl && key.name === "a") {
529
- cursorPos = 0;
530
- redrawInput();
531
- return;
532
- }
533
- // Ctrl+E — move cursor to end of line
534
- if (key.ctrl && key.name === "e") {
535
- cursorPos = inputLine.length;
536
- redrawInput();
537
- return;
538
- }
539
- // Ctrl+U — kill entire line
540
- if (key.ctrl && key.name === "u") {
541
- inputLine = "";
542
- cursorPos = 0;
543
- redrawInput();
544
- return;
545
- }
546
- // Ctrl+K — kill from cursor to end of line
547
- if (key.ctrl && key.name === "k") {
548
- inputLine = inputLine.slice(0, cursorPos);
549
- redrawInput();
550
- return;
551
- }
552
- // Left arrow — move cursor left one character
553
- if (key.name === "left" && !key.meta && !key.ctrl) {
554
- if (cursorPos > 0) {
555
- cursorPos--;
556
- w.write(`${ESC}D`);
557
- }
558
- return;
559
- }
560
- // Right arrow — move cursor right one character
561
- if (key.name === "right" && !key.meta && !key.ctrl) {
562
- if (cursorPos < inputLine.length) {
563
- cursorPos++;
564
- w.write(`${ESC}C`);
565
- }
566
- return;
567
- }
568
- // Alt+Left — move cursor left by one word
569
- if (key.name === "left" && (key.meta || key.ctrl)) {
570
- if (cursorPos > 0) {
571
- // Skip spaces, then skip non-spaces
572
- let p = cursorPos;
573
- while (p > 0 && inputLine[p - 1] === " ")
574
- p--;
575
- while (p > 0 && inputLine[p - 1] !== " ")
576
- p--;
577
- cursorPos = p;
578
- redrawInput();
579
- }
580
- return;
581
- }
582
- // Alt+Right — move cursor right by one word
583
- if (key.name === "right" && (key.meta || key.ctrl)) {
584
- if (cursorPos < inputLine.length) {
585
- let p = cursorPos;
586
- while (p < inputLine.length && inputLine[p] !== " ")
587
- p++;
588
- while (p < inputLine.length && inputLine[p] === " ")
589
- p++;
590
- cursorPos = p;
591
- redrawInput();
592
- }
593
- return;
594
- }
595
- // Word-delete: Alt+Backspace, Ctrl+Backspace, Ctrl+W
596
- if (((key.meta || key.ctrl) && key.name === "backspace") ||
597
- (key.ctrl && key.name === "w")) {
598
- if (cursorPos > 0) {
599
- // Find word boundary before cursor
600
- let p = cursorPos;
601
- while (p > 0 && inputLine[p - 1] === " ")
602
- p--;
603
- while (p > 0 && inputLine[p - 1] !== " ")
604
- p--;
605
- inputLine = inputLine.slice(0, p) + inputLine.slice(cursorPos);
606
- cursorPos = p;
607
- redrawInput();
608
- }
609
- return;
610
- }
611
- // Backspace — delete character before cursor
612
- if (key.name === "backspace") {
613
- if (cursorPos > 0) {
614
- inputLine = inputLine.slice(0, cursorPos - 1) + inputLine.slice(cursorPos);
615
- cursorPos--;
616
- redrawInput();
617
- }
618
- return;
619
- }
620
- // Delete — delete character at cursor
621
- if (key.name === "delete") {
622
- if (cursorPos < inputLine.length) {
623
- inputLine = inputLine.slice(0, cursorPos) + inputLine.slice(cursorPos + 1);
624
- redrawInput();
625
- }
626
- return;
627
- }
628
- // Regular character — insert at cursor position
629
- if (key.sequence && !key.ctrl && !key.meta) {
630
- // ! at start of empty input toggles bash mode
631
- if (key.sequence === "!" && inputLine === "" && !bashMode) {
632
- bashMode = true;
633
- redrawInput();
634
- return;
635
- }
636
- inputLine = inputLine.slice(0, cursorPos) + key.sequence + inputLine.slice(cursorPos);
637
- cursorPos += key.sequence.length;
638
- redrawInput();
639
- }
640
- });
641
- // TUI hooks — render streaming text with markdown, compact tool output
642
- let textBuffer = "";
643
- let firstDelta = true;
644
- let activeThinkTimer = null;
645
- function flushTextBuffer() {
646
- if (!textBuffer)
647
- return;
648
- w.write(renderMarkdown(textBuffer));
649
- textBuffer = "";
650
- }
651
- const tuiHooks = {
652
- onTextDelta: (text) => {
653
- if (firstDelta) {
654
- if (activeThinkTimer) {
655
- clearInterval(activeThinkTimer);
656
- activeThinkTimer = null;
657
- }
658
- w.write(`${ESC}2K\r`);
659
- w.write(`\n${s.brand("◆")} `); // blank line + diamond prefix for phren's response
660
- firstDelta = false;
661
- }
662
- w.write(text);
663
- },
664
- onTextDone: () => {
665
- flushTextBuffer();
666
- },
667
- onTextBlock: (text) => {
668
- if (activeThinkTimer) {
669
- clearInterval(activeThinkTimer);
670
- activeThinkTimer = null;
671
- }
672
- if (firstDelta) {
673
- w.write(`${ESC}2K\r`);
674
- w.write(`\n${s.brand("◆")} `); // diamond prefix + blank line before response
675
- firstDelta = false;
676
- }
677
- w.write(text);
678
- if (!text.endsWith("\n"))
679
- w.write("\n");
680
- },
681
- onToolStart: (name, input, count) => {
682
- // Kill the thinking animation if it's still running (tools can fire before any text delta)
683
- if (activeThinkTimer) {
684
- clearInterval(activeThinkTimer);
685
- activeThinkTimer = null;
686
- }
687
- if (firstDelta) {
688
- w.write(`${ESC}2K\r`); // clear thinking line
689
- firstDelta = false;
690
- }
691
- flushTextBuffer();
692
- const preview = formatToolInput(name, input);
693
- const countLabel = count > 1 ? s.dim(` (${count} tools)`) : "";
694
- w.write(`${ESC}2K ${s.dim("◌")} ${s.gray(name)} ${s.dim(preview)}${countLabel}\r`);
695
- },
696
- onToolEnd: (name, input, output, isError, dur) => {
697
- w.write(`${ESC}2K\r`);
698
- const diffData = (name === "edit_file" || name === "write_file") ? decodeDiffPayload(output) : null;
699
- const cleanOutput = diffData ? output.slice(0, output.indexOf(DIFF_MARKER)) : output;
700
- w.write(renderToolCall(name, input, cleanOutput, isError, dur) + "\n");
701
- if (diffData) {
702
- w.write(renderInlineDiff(diffData.oldContent, diffData.newContent, diffData.filePath) + "\n");
703
- }
704
- },
705
- onStatus: (msg) => w.write(s.dim(msg)),
706
- getSteeringInput: () => {
707
- // Drain steer queue first (newest steering inputs)
708
- if (steerQueue.length > 0 && inputMode === "steering") {
709
- const steer = steerQueue.shift();
710
- w.write(s.yellow(` ↳ steering: ${steer}\n`));
711
- return steer;
712
- }
713
- if (pendingInput && inputMode === "steering") {
714
- const steer = pendingInput;
715
- pendingInput = null;
716
- w.write(s.yellow(` ↳ steering: ${steer}\n`));
717
- return steer;
718
- }
719
- return null;
720
- },
721
- };
722
- async function runAgentTurn(userInput) {
723
- running = true;
724
- firstDelta = true;
725
- const thinkStart = Date.now();
726
- // Phren thinking — subtle purple/cyan breath with rotating verbs
727
- const THINK_VERBS = ["thinking", "reasoning", "recalling", "connecting", "processing"];
728
- let thinkFrame = 0;
729
- activeThinkTimer = setInterval(() => {
730
- const elapsed = (Date.now() - thinkStart) / 1000;
731
- const verb = THINK_VERBS[Math.floor(elapsed / 6) % THINK_VERBS.length];
732
- const t = (Math.sin(thinkFrame * 0.08) + 1) / 2;
733
- const r = Math.round(155 * (1 - t) + 40 * t);
734
- const g = Math.round(140 * (1 - t) + 211 * t);
735
- const b = Math.round(250 * (1 - t) + 242 * t);
736
- const color = `${ESC}38;2;${r};${g};${b}m`;
737
- w.write(`${ESC}2K${color}◆ ${verb}${ESC}0m ${s.dim(`${elapsed.toFixed(1)}s`)}\r`);
738
- thinkFrame++;
739
- }, 50);
740
- try {
741
- await runTurn(userInput, session, config, tuiHooks);
742
- if (activeThinkTimer) {
743
- clearInterval(activeThinkTimer);
744
- activeThinkTimer = null;
745
- }
746
- const elapsed = ((Date.now() - thinkStart) / 1000).toFixed(1);
747
- const DONE_VERBS = ["◆ recalled", "◆ processed", "◆ connected", "◆ resolved"];
748
- const doneVerb = DONE_VERBS[session.turns % DONE_VERBS.length];
749
- w.write(`${ESC}2K${s.dim(`${doneVerb} in ${elapsed}s`)}\n\n`);
750
- statusBar();
751
- }
752
- catch (err) {
753
- if (activeThinkTimer) {
754
- clearInterval(activeThinkTimer);
755
- activeThinkTimer = null;
756
- }
757
- const msg = err instanceof Error ? err.message : String(err);
758
- w.write(`${ESC}2K\r`);
759
- w.write(s.red(` Error: ${msg}\n`));
760
- }
761
- running = false;
762
- // Process queued input — steer queue first, then pending
763
- if (steerQueue.length > 0) {
764
- const queued = steerQueue.shift();
765
- w.write(`${s.bold("❯")} ${queued}\n`);
766
- runAgentTurn(queued);
767
- }
768
- else if (pendingInput) {
769
- const queued = pendingInput;
770
- pendingInput = null;
771
- w.write(`${s.bold("❯")} ${queued}\n`);
772
- runAgentTurn(queued);
773
- }
774
- else {
775
- prompt();
776
- }
777
- }
778
- // Initial prompt
779
- prompt();
780
- return done;
781
- }