@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
@@ -1,18 +1,131 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import { useState, useCallback } from "react";
3
- import { Static, Box, Text, useApp } from "ink";
2
+ import { useState, useCallback, useEffect } from "react";
3
+ import { Static, Box, Text, useApp, useInput } from "ink";
4
4
  import { Banner } from "./Banner.js";
5
5
  import { ToolCall } from "./ToolCall.js";
6
+ import { ToolSpinner } from "./ToolSpinner.js";
6
7
  import { ThinkingIndicator } from "./ThinkingIndicator.js";
7
8
  import { SteerQueue } from "./SteerQueue.js";
8
9
  import { InputArea, PermissionsLine } from "./InputArea.js";
9
10
  import { useKeyboardShortcuts } from "../hooks/useKeyboardShortcuts.js";
10
- export function App({ state, completedMessages, streamingText, completedToolCalls, thinking, thinkStartTime, thinkElapsed, steerQueue, running, showBanner, inputHistory, verbose, onSubmit, onPermissionCycle, onCancelTurn, onExit, }) {
11
+ import { renderMarkdown } from "../../multi/markdown.js";
12
+ import { useSearch, highlightMatches } from "../hooks/useSearch.js";
13
+ export function App({ state, completedMessages, streamingText, completedToolCalls, activeTool, thinking, thinkStartTime, thinkElapsed, steerQueue, running, showBanner, inputHistory, verbose, theme, onSubmit, onPermissionCycle, onCancelTurn, onExit, agents, selectedAgentId, onSelectAgent, onCancelAgent, }) {
11
14
  const { exit } = useApp();
12
15
  const [inputValue, setInputValue] = useState("");
13
16
  const [bashMode, setBashMode] = useState(false);
14
17
  const [historyIndex, setHistoryIndex] = useState(-1);
15
18
  const [ctrlCCount, setCtrlCCount] = useState(0);
19
+ const [tabFocused, setTabFocused] = useState(false);
20
+ const [highlightedTabIndex, setHighlightedTabIndex] = useState(0);
21
+ const [stashedInput, setStashedInput] = useState("");
22
+ const [historySearchMode, setHistorySearchMode] = useState(false);
23
+ const [historySearchQuery, setHistorySearchQuery] = useState("");
24
+ const [historySearchIndex, setHistorySearchIndex] = useState(0);
25
+ // ── Ctrl+F content search ────────────────────────────────────────────────
26
+ const search = useSearch();
27
+ // When the query changes, recompute total match count across all completed messages
28
+ useEffect(() => {
29
+ if (!search.state.active || !search.state.query) {
30
+ search.setMatchInfo(0, 0);
31
+ return;
32
+ }
33
+ let total = 0;
34
+ for (const msg of completedMessages) {
35
+ if (msg.kind === "user" || msg.kind === "status") {
36
+ const { count } = highlightMatches(msg.text, search.state.query);
37
+ total += count;
38
+ }
39
+ else if (msg.kind === "assistant") {
40
+ const { count } = highlightMatches(msg.text, search.state.query);
41
+ total += count;
42
+ }
43
+ }
44
+ search.setMatchInfo(total, 0);
45
+ // eslint-disable-next-line react-hooks/exhaustive-deps
46
+ }, [search.state.query, search.state.active, completedMessages]);
47
+ // Handle keypresses while search mode is active
48
+ useInput((input, key) => {
49
+ if (!search.state.active)
50
+ return;
51
+ // Escape: deactivate search
52
+ if (key.escape) {
53
+ search.deactivate();
54
+ return;
55
+ }
56
+ // Enter or n: next match
57
+ if (key.return || input === "n") {
58
+ search.nextMatch();
59
+ return;
60
+ }
61
+ // N (shift+n): previous match
62
+ if (input === "N") {
63
+ search.prevMatch();
64
+ return;
65
+ }
66
+ // Backspace: remove last char from query
67
+ if (key.backspace || key.delete) {
68
+ search.setQuery(search.state.query.slice(0, -1));
69
+ return;
70
+ }
71
+ // Skip ctrl/meta combinations
72
+ if (key.ctrl || key.meta)
73
+ return;
74
+ // Regular character: append to query
75
+ if (input.length > 0 && !key.upArrow && !key.downArrow && !key.leftArrow && !key.rightArrow && !key.tab) {
76
+ search.setQuery(search.state.query + input);
77
+ }
78
+ }, { isActive: search.state.active });
79
+ // History search: compute matches from current query
80
+ const historyMatches = historySearchMode
81
+ ? inputHistory.filter((h) => h.toLowerCase().includes(historySearchQuery.toLowerCase()))
82
+ : [];
83
+ const currentMatch = historyMatches.length > 0
84
+ ? historyMatches[historySearchIndex % historyMatches.length]
85
+ : null;
86
+ // Handle keypresses while in history search mode
87
+ useInput((input, key) => {
88
+ if (!historySearchMode)
89
+ return;
90
+ // Ctrl+R again: cycle to next match
91
+ if (key.ctrl && input === "r") {
92
+ if (historyMatches.length > 0) {
93
+ setHistorySearchIndex((i) => (i + 1) % historyMatches.length);
94
+ }
95
+ return;
96
+ }
97
+ // Enter: accept match
98
+ if (key.return) {
99
+ if (currentMatch) {
100
+ setInputValue(currentMatch);
101
+ }
102
+ setHistorySearchMode(false);
103
+ setHistorySearchQuery("");
104
+ setHistorySearchIndex(0);
105
+ return;
106
+ }
107
+ // Escape: cancel search
108
+ if (key.escape) {
109
+ setHistorySearchMode(false);
110
+ setHistorySearchQuery("");
111
+ setHistorySearchIndex(0);
112
+ return;
113
+ }
114
+ // Backspace: remove last char from query
115
+ if (key.backspace || key.delete) {
116
+ setHistorySearchQuery((q) => q.slice(0, -1));
117
+ setHistorySearchIndex(0);
118
+ return;
119
+ }
120
+ // Skip ctrl/meta combinations (except already handled)
121
+ if (key.ctrl || key.meta)
122
+ return;
123
+ // Regular character: append to query
124
+ if (input.length > 0 && !key.upArrow && !key.downArrow && !key.leftArrow && !key.rightArrow && !key.tab) {
125
+ setHistorySearchQuery((q) => q + input);
126
+ setHistorySearchIndex(0);
127
+ }
128
+ }, { isActive: historySearchMode });
16
129
  const handleSubmit = useCallback((value) => {
17
130
  setInputValue("");
18
131
  setHistoryIndex(-1);
@@ -26,6 +139,7 @@ export function App({ state, completedMessages, streamingText, completedToolCall
26
139
  onSubmit(bashMode ? `!${value}` : value);
27
140
  setBashMode(false);
28
141
  }, [bashMode, onSubmit]);
142
+ const isAnyModeActive = search.state.active || historySearchMode;
29
143
  useKeyboardShortcuts({
30
144
  isRunning: running,
31
145
  inputValue,
@@ -40,7 +154,53 @@ export function App({ state, completedMessages, streamingText, completedToolCall
40
154
  onExit: () => { onExit(); exit(); },
41
155
  onCyclePermissions: onPermissionCycle,
42
156
  onCancelTurn,
157
+ onEscCancelAgent: onCancelAgent,
158
+ onHistorySearch: () => {
159
+ setHistorySearchMode(true);
160
+ setHistorySearchQuery("");
161
+ setHistorySearchIndex(0);
162
+ },
163
+ onContentSearch: () => {
164
+ search.activate();
165
+ },
166
+ onOpenEditor: () => {
167
+ // Write input to temp file, open $EDITOR, read back
168
+ const tmpFile = `/tmp/phren-input-${Date.now()}.md`;
169
+ try {
170
+ const fs = require("fs");
171
+ const { execSync } = require("child_process");
172
+ fs.writeFileSync(tmpFile, inputValue);
173
+ const editor = process.env.VISUAL || process.env.EDITOR || "vi";
174
+ execSync(`${editor} ${tmpFile}`, { stdio: "inherit" });
175
+ const result = fs.readFileSync(tmpFile, "utf-8");
176
+ fs.unlinkSync(tmpFile);
177
+ setInputValue(result.replace(/\n$/, ""));
178
+ }
179
+ catch { /* editor cancelled or failed */ }
180
+ },
181
+ stashedInput,
182
+ onStash: (text) => { setStashedInput(text); },
183
+ onUnstash: () => { const s = stashedInput; setStashedInput(""); return s || null; },
184
+ tabFocused,
185
+ onEnterTabBar: agents && agents.length > 0 ? () => { setTabFocused(true); setHighlightedTabIndex(0); } : undefined,
186
+ onExitTabBar: () => { setTabFocused(false); },
187
+ onTabLeft: () => { setHighlightedTabIndex((p) => Math.max(0, p - 1)); },
188
+ onTabRight: () => { setHighlightedTabIndex((p) => Math.min((agents?.length ?? 1) - 1, p + 1)); },
189
+ onTabSelect: () => {
190
+ if (agents && agents[highlightedTabIndex]) {
191
+ const id = agents[highlightedTabIndex].id;
192
+ onSelectAgent?.(id === "__main__" ? null : id);
193
+ }
194
+ },
43
195
  });
196
+ // Helper: apply search highlighting to a text string (ANSI only works in
197
+ // non-Ink raw text mode). Since Ink's <Text> will escape ANSI we pass raw
198
+ // strings to renderMarkdown which outputs ANSI directly.
199
+ const applySearch = useCallback((text) => {
200
+ if (!search.state.active || !search.state.query)
201
+ return text;
202
+ return highlightMatches(text, search.state.query).highlighted;
203
+ }, [search.state.active, search.state.query]);
44
204
  // Build Static items — banner first, then completed messages
45
205
  const staticItems = [];
46
206
  if (showBanner) {
@@ -51,18 +211,29 @@ export function App({ state, completedMessages, streamingText, completedToolCall
51
211
  }
52
212
  return (_jsxs(_Fragment, { children: [_jsx(Static, { items: staticItems, children: (item) => {
53
213
  if (item.kind === "banner") {
54
- return (_jsx(Box, { flexDirection: "column", children: _jsx(Banner, { version: state.version }) }, "banner"));
214
+ return (_jsx(Box, { flexDirection: "column", children: _jsx(Banner, { version: state.version, theme: theme }) }, "banner"));
55
215
  }
56
216
  if (item.kind === "user") {
57
- return (_jsx(Box, { flexDirection: "column", children: _jsxs(Text, { bold: true, children: ["\u276f", " ", item.text] }) }, item.id));
217
+ return (_jsx(Box, { flexDirection: "column", children: _jsxs(Text, { bold: theme.user.bold ?? true, color: theme.user.color, children: [theme.user.label, " ", applySearch(item.text)] }) }, item.id));
58
218
  }
59
219
  if (item.kind === "assistant") {
60
220
  const aMsg = item;
61
- return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [aMsg.text ? (_jsxs(Box, { children: [_jsxs(Text, { color: "magenta", children: ["\u25c6", " "] }), _jsx(Text, { children: aMsg.text })] })) : null, aMsg.toolCalls?.map((tc, i) => (_jsx(ToolCall, { ...tc, verbose: verbose }, i)))] }, item.id));
221
+ const renderedText = aMsg.text
222
+ ? applySearch(renderMarkdown(aMsg.text, theme.markdown))
223
+ : "";
224
+ return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [aMsg.toolCalls?.map((tc, i) => (_jsx(ToolCall, { ...tc, verbose: verbose, theme: theme }, i))), renderedText ? (_jsxs(Box, { children: [_jsxs(Text, { color: theme.agent.color, wrap: "truncate", children: [theme.agent.label, " "] }), _jsx(Text, { wrap: "wrap", children: renderedText })] })) : null] }, item.id));
62
225
  }
63
226
  if (item.kind === "status") {
64
- return _jsx(Text, { dimColor: true, children: item.text }, item.id);
227
+ return _jsx(Text, { color: theme.system.color, dimColor: true, children: applySearch(item.text) }, item.id);
65
228
  }
66
229
  return null;
67
- } }), _jsxs(Box, { flexDirection: "column", children: [completedToolCalls.map((tc, i) => (_jsx(ToolCall, { ...tc, verbose: verbose }, `tc-${i}`))), streamingText !== "" && (_jsxs(Box, { children: [_jsxs(Text, { color: "magenta", children: ["\u25c6", " "] }), _jsx(Text, { children: streamingText })] })), thinking && _jsx(ThinkingIndicator, { startTime: thinkStartTime }), thinkElapsed !== null && (_jsxs(Text, { dimColor: true, children: [" ", "\u25c6", " thought for ", thinkElapsed, "s"] })), ctrlCCount > 0 && !running && (_jsxs(Text, { dimColor: true, children: [" ", "Press Ctrl+C again to exit."] })), _jsx(SteerQueue, { items: steerQueue }), _jsx(InputArea, { value: inputValue, onChange: setInputValue, onSubmit: handleSubmit, bashMode: bashMode, focus: true }), _jsx(PermissionsLine, { mode: state.permMode })] })] }));
230
+ } }), _jsxs(Box, { flexDirection: "column", children: [completedToolCalls.map((tc, i) => (_jsx(ToolCall, { ...tc, verbose: verbose, theme: theme }, `tc-${i}`))), activeTool && (_jsxs(Box, { paddingLeft: 2, children: [_jsx(ToolSpinner, { theme: theme }), _jsx(Text, { bold: true, color: theme.tool.name, children: activeTool.name }), activeTool.preview ? _jsxs(Text, { color: theme.tool.preview ?? theme.separator, children: [" ", activeTool.preview] }) : null] })), streamingText !== "" && (_jsxs(Box, { marginTop: 1, children: [_jsxs(Text, { color: theme.agent.color, wrap: "truncate", children: [theme.agent.label, " "] }), _jsx(Text, { wrap: "wrap", children: streamingText })] })), thinking && _jsx(Box, { marginTop: 1, children: _jsx(ThinkingIndicator, { startTime: thinkStartTime, theme: theme }) }), thinkElapsed !== null && (_jsxs(Text, { color: theme.dim, dimColor: true, children: [" ", "\u25c6", " thought for ", thinkElapsed, "s"] })), ctrlCCount > 0 && !running && (_jsxs(Text, { dimColor: true, children: [" ", "Press Ctrl+C again to exit."] })), _jsx(SteerQueue, { items: steerQueue, theme: theme }), search.state.active && (_jsxs(Box, { children: [_jsxs(Text, { color: theme.search?.prompt ?? "cyan", children: [" ", "find: ", search.state.query, _jsx(Text, { inverse: true, children: " " })] }), search.state.matchCount > 0
231
+ ? _jsxs(Text, { dimColor: true, color: theme.search?.match ?? undefined, children: [" (", search.state.currentMatch + 1, " of ", search.state.matchCount, ")"] })
232
+ : search.state.query.length > 0
233
+ ? _jsx(Text, { dimColor: true, color: theme.search?.noMatch ?? "red", children: " (no matches)" })
234
+ : _jsx(Text, { dimColor: true, children: " (type to search)" })] })), historySearchMode && (_jsxs(Box, { children: [_jsxs(Text, { color: theme.search?.prompt ?? "cyan", children: [" ", "search: ", historySearchQuery, _jsx(Text, { inverse: true, children: " " })] }), historyMatches.length > 0
235
+ ? _jsxs(Text, { dimColor: true, color: theme.search?.match ?? undefined, children: [" (match ", (historySearchIndex % historyMatches.length) + 1, " of ", historyMatches.length, ")"] })
236
+ : historySearchQuery.length > 0
237
+ ? _jsx(Text, { dimColor: true, color: theme.search?.noMatch ?? "red", children: " (no matches)" })
238
+ : _jsx(Text, { dimColor: true, children: " (type to search history)" })] })), historySearchMode && currentMatch && (_jsx(Box, { children: _jsxs(Text, { dimColor: true, children: [" ", "\u25b8", " ", currentMatch] }) })), _jsx(InputArea, { value: inputValue, onChange: setInputValue, onSubmit: handleSubmit, bashMode: bashMode, focus: !isAnyModeActive, separatorColor: theme.separator, theme: theme }), _jsx(PermissionsLine, { mode: state.permMode, theme: theme, agents: agents, selectedAgentId: selectedAgentId, highlightedTabId: agents?.[highlightedTabIndex]?.id ?? null, tabFocused: tabFocused })] })] }));
68
239
  }
@@ -21,14 +21,17 @@ function getArtLines() {
21
21
  function stripAnsi(t) {
22
22
  return t.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "");
23
23
  }
24
- export function Banner({ version }) {
24
+ export function Banner({ version, theme }) {
25
25
  const cwd = process.cwd().replace(os.homedir(), "~");
26
26
  const artLines = getArtLines();
27
27
  const maxArtWidth = 26;
28
+ const logoColor = theme?.banner.logo ?? "magenta";
29
+ const versionColor = theme?.banner.version ?? "gray";
30
+ const cwdColor = theme?.banner.cwd ?? "cyan";
28
31
  const infoLines = [
29
- { key: "title", node: _jsx(Text, { bold: true, color: "magenta", children: "◆ phren" }) },
30
- { key: "version", node: _jsx(Text, { dimColor: true, children: " v" + version }) },
31
- { key: "cwd", node: _jsx(Text, { dimColor: true, children: cwd }) },
32
+ { key: "title", node: _jsx(Text, { bold: true, color: logoColor, children: "◆ phren" }) },
33
+ { key: "version", node: _jsx(Text, { color: versionColor, dimColor: true, children: " v" + version }) },
34
+ { key: "cwd", node: _jsx(Text, { color: cwdColor, dimColor: true, children: cwd }) },
32
35
  ];
33
36
  if (artLines.length > 0) {
34
37
  const rowCount = Math.max(artLines.length, infoLines.length);
@@ -1,23 +1,65 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Box, Text, useStdout } from "ink";
3
- import TextInput from "ink-text-input";
3
+ import { PhrenInput } from "./PhrenInput.js";
4
4
  import { PERMISSION_LABELS, PERMISSION_ICONS } from "../ansi.js";
5
- export function InputArea({ value, onChange, onSubmit, bashMode, focus }) {
5
+ export function InputArea({ value, onChange, onSubmit, bashMode, focus, separatorColor, theme }) {
6
6
  const { stdout } = useStdout();
7
7
  const columns = stdout?.columns || 80;
8
8
  const sep = "\u2500".repeat(columns);
9
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { dimColor: true, children: sep }), _jsxs(Box, { children: [bashMode
10
- ? _jsx(Text, { color: "yellow", children: "! " })
11
- : _jsxs(Text, { dimColor: true, children: ["\u25b8", " "] }), _jsx(TextInput, { value: value, onChange: onChange, onSubmit: onSubmit, focus: focus, showCursor: true })] }), _jsx(Text, { dimColor: true, children: sep })] }));
9
+ const sepColor = theme?.input.separator ?? separatorColor ?? "gray";
10
+ const promptColor = theme?.input.prompt ?? undefined;
11
+ const bashPromptColor = theme?.input.bashPrompt ?? "yellow";
12
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: sepColor, dimColor: true, children: sep }), _jsxs(Box, { children: [bashMode
13
+ ? _jsx(Text, { color: bashPromptColor, children: "! " })
14
+ : _jsxs(Text, { color: promptColor, dimColor: true, children: ["\u25b8", " "] }), _jsx(PhrenInput, { value: value, onChange: onChange, onSubmit: onSubmit, focus: focus })] }), _jsx(Text, { color: sepColor, dimColor: true, children: sep })] }));
12
15
  }
13
- const PERM_COLOR_MAP = {
14
- "suggest": "cyan",
15
- "auto-confirm": "green",
16
- "full-auto": "yellow",
16
+ const STATUS_ICON = {
17
+ running: "\u25cf", // ●
18
+ idle: "\u25cb", // ○
19
+ done: "\u2713", // ✓
20
+ error: "\u2717", // ✗
21
+ starting: "\u25cc", // ◌
22
+ cancelled: "\u2500", // ─
17
23
  };
18
- export function PermissionsLine({ mode }) {
24
+ export function PermissionsLine({ mode, theme, agents, selectedAgentId, highlightedTabId, tabFocused }) {
19
25
  const icon = PERMISSION_ICONS[mode];
20
26
  const label = PERMISSION_LABELS[mode];
21
- const color = PERM_COLOR_MAP[mode];
22
- return (_jsxs(Text, { children: [" ", _jsxs(Text, { color: color, children: [icon, " ", label, " permissions"] }), " ", _jsxs(Text, { dimColor: true, children: ["(shift+tab toggle ", "\u00b7", " esc to interrupt)"] })] }));
27
+ const permColors = theme?.permission;
28
+ const color = mode === "suggest"
29
+ ? (permColors?.suggest ?? "")
30
+ : mode === "auto-confirm"
31
+ ? (permColors?.auto ?? "yellow")
32
+ : mode === "plan"
33
+ ? (permColors?.plan ?? "magenta")
34
+ : (permColors?.fullAuto ?? "green");
35
+ const showPerm = mode !== "suggest";
36
+ const hasAgents = agents && agents.length > 0;
37
+ // Agent tab status → theme color
38
+ const tabColors = theme?.agentTab;
39
+ function agentTabColor(agent) {
40
+ if (tabColors) {
41
+ if (agent.status === "running")
42
+ return tabColors.running;
43
+ if (agent.status === "idle")
44
+ return tabColors.idle;
45
+ if (agent.status === "done")
46
+ return tabColors.done;
47
+ if (agent.status === "error")
48
+ return tabColors.error;
49
+ }
50
+ return agent.color;
51
+ }
52
+ return (_jsxs(Box, { children: [showPerm ? (_jsxs(Text, { children: [" ", _jsxs(Text, { color: color, children: [icon, " ", label] })] })) : (_jsx(Text, { children: " " })), hasAgents ? (_jsxs(Text, { children: [" ", agents.map((agent, i) => {
53
+ const isActive = agent.id === selectedAgentId;
54
+ const isHighlighted = tabFocused && agent.id === highlightedTabId;
55
+ const statusIcon = STATUS_ICON[agent.status];
56
+ const resolvedColor = agentTabColor(agent);
57
+ return (_jsxs(Text, { children: [i > 0 ? " " : "", isHighlighted
58
+ ? _jsx(Text, { bold: true, inverse: true, color: resolvedColor, children: ` ${statusIcon} ${agent.name} ` })
59
+ : isActive
60
+ ? _jsxs(Text, { bold: true, underline: true, color: resolvedColor, children: [statusIcon, " ", agent.name] })
61
+ : _jsxs(Text, { color: resolvedColor, dimColor: agent.status === "idle" || agent.status === "done", children: [statusIcon, " ", agent.name] })] }, agent.id));
62
+ }), tabFocused
63
+ ? _jsx(Text, { dimColor: true, children: " \u2190\u2192 enter \u2191 back" })
64
+ : _jsx(Text, { dimColor: true, children: " \u2193" })] })) : null] }));
23
65
  }
@@ -0,0 +1,329 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useState, useEffect } from "react";
3
+ import { Box, Text, useInput } from "ink";
4
+ import * as fs from "fs";
5
+ import * as nodePath from "path";
6
+ import * as os from "os";
7
+ /** Map a flat cursor offset to { line, col } within a multi-line string. */
8
+ function offsetToPos(text, offset) {
9
+ let line = 0;
10
+ let col = 0;
11
+ for (let i = 0; i < offset && i < text.length; i++) {
12
+ if (text[i] === "\n") {
13
+ line++;
14
+ col = 0;
15
+ }
16
+ else {
17
+ col++;
18
+ }
19
+ }
20
+ return { line, col };
21
+ }
22
+ /** Map { line, col } back to a flat cursor offset. */
23
+ function posToOffset(lines, line, col) {
24
+ let offset = 0;
25
+ for (let i = 0; i < line && i < lines.length; i++) {
26
+ offset += lines[i].length + 1; // +1 for the \n
27
+ }
28
+ const targetLine = lines[line] ?? "";
29
+ return offset + Math.min(col, targetLine.length);
30
+ }
31
+ /**
32
+ * Custom controlled text input with full cursor and multi-line support.
33
+ * Replaces ink-text-input to enable cursor positioning, word jump,
34
+ * kill-line, Shift+Enter multi-line, and other readline-style keybindings.
35
+ */
36
+ export function PhrenInput({ value, onChange, onSubmit, placeholder, focus = true }) {
37
+ const [cursor, setCursor] = useState(value.length);
38
+ // Keep cursor within bounds when value changes externally
39
+ useEffect(() => {
40
+ setCursor((c) => Math.min(c, value.length));
41
+ }, [value]);
42
+ const lines = value.split("\n");
43
+ const isMultiLine = lines.length > 1;
44
+ useInput((input, key) => {
45
+ // Bracketed paste: strip \x1b[200~ (start) and \x1b[201~ (end) markers.
46
+ // If markers are present, insert the cleaned text at cursor as a single paste.
47
+ const PASTE_START = "\x1b[200~";
48
+ const PASTE_END = "\x1b[201~";
49
+ if (input.includes(PASTE_START) || input.includes(PASTE_END)) {
50
+ const cleaned = input
51
+ .replaceAll(PASTE_START, "")
52
+ .replaceAll(PASTE_END, "")
53
+ .replace(/\r\n?/g, "\n"); // normalize line endings
54
+ if (cleaned.length > 0) {
55
+ const next = value.slice(0, cursor) + cleaned + value.slice(cursor);
56
+ onChange(next);
57
+ setCursor(cursor + cleaned.length);
58
+ }
59
+ return;
60
+ }
61
+ // Heuristic paste detection for terminals without bracketed paste
62
+ if (input.length > 10 && !input.startsWith("\x1b")) {
63
+ const normalized = input.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
64
+ const before = value.slice(0, cursor);
65
+ const after = value.slice(cursor);
66
+ const newValue = before + normalized + after;
67
+ const newCursor = cursor + normalized.length;
68
+ onChange(newValue);
69
+ setCursor(newCursor);
70
+ return;
71
+ }
72
+ // Shift+Enter — insert newline (multi-line input)
73
+ if (key.return && key.shift) {
74
+ const next = value.slice(0, cursor) + "\n" + value.slice(cursor);
75
+ onChange(next);
76
+ setCursor(cursor + 1);
77
+ return;
78
+ }
79
+ // Plain Enter — submit
80
+ if (key.return) {
81
+ onSubmit(value);
82
+ setCursor(0);
83
+ return;
84
+ }
85
+ // Up arrow — in multi-line: move cursor up; single-line: pass through
86
+ if (key.upArrow && isMultiLine) {
87
+ const { line, col } = offsetToPos(value, cursor);
88
+ if (line > 0) {
89
+ setCursor(posToOffset(lines, line - 1, col));
90
+ }
91
+ return;
92
+ }
93
+ // Down arrow — in multi-line: move cursor down; single-line: pass through
94
+ if (key.downArrow && isMultiLine) {
95
+ const { line, col } = offsetToPos(value, cursor);
96
+ if (line < lines.length - 1) {
97
+ setCursor(posToOffset(lines, line + 1, col));
98
+ }
99
+ return;
100
+ }
101
+ // Left arrow / Ctrl+B — move cursor left
102
+ if (key.leftArrow || (key.ctrl && input === "b")) {
103
+ if (key.meta) {
104
+ // Alt+Left / Alt+B — word jump left
105
+ setCursor((c) => wordBoundaryLeft(value, c));
106
+ }
107
+ else {
108
+ setCursor((c) => Math.max(0, c - 1));
109
+ }
110
+ return;
111
+ }
112
+ // Right arrow / Ctrl+F — move cursor right
113
+ if (key.rightArrow || (key.ctrl && input === "f")) {
114
+ if (key.meta) {
115
+ // Alt+Right / Alt+F — word jump right
116
+ setCursor((c) => wordBoundaryRight(value, c));
117
+ }
118
+ else {
119
+ setCursor((c) => Math.min(value.length, c + 1));
120
+ }
121
+ return;
122
+ }
123
+ // Alt+B — word jump left (standalone, not combined with arrow)
124
+ if (key.meta && input === "b") {
125
+ setCursor((c) => wordBoundaryLeft(value, c));
126
+ return;
127
+ }
128
+ // Alt+F — word jump right (standalone)
129
+ if (key.meta && input === "f") {
130
+ setCursor((c) => wordBoundaryRight(value, c));
131
+ return;
132
+ }
133
+ // Home / Ctrl+A — beginning of current line
134
+ if (key.ctrl && input === "a") {
135
+ const { line } = offsetToPos(value, cursor);
136
+ setCursor(posToOffset(lines, line, 0));
137
+ return;
138
+ }
139
+ // End / Ctrl+E — end of current line
140
+ if (key.ctrl && input === "e") {
141
+ const { line } = offsetToPos(value, cursor);
142
+ setCursor(posToOffset(lines, line, lines[line].length));
143
+ return;
144
+ }
145
+ // Backspace — delete character before cursor
146
+ if (key.backspace || key.delete) {
147
+ if (cursor > 0) {
148
+ const next = value.slice(0, cursor - 1) + value.slice(cursor);
149
+ onChange(next);
150
+ setCursor(cursor - 1);
151
+ }
152
+ return;
153
+ }
154
+ // Ctrl+W — delete word before cursor
155
+ if (key.ctrl && input === "w") {
156
+ const boundary = wordBoundaryLeft(value, cursor);
157
+ onChange(value.slice(0, boundary) + value.slice(cursor));
158
+ setCursor(boundary);
159
+ return;
160
+ }
161
+ // Ctrl+U — kill to beginning of current line
162
+ if (key.ctrl && input === "u") {
163
+ const { line } = offsetToPos(value, cursor);
164
+ const lineStart = posToOffset(lines, line, 0);
165
+ onChange(value.slice(0, lineStart) + value.slice(cursor));
166
+ setCursor(lineStart);
167
+ return;
168
+ }
169
+ // Ctrl+K — kill to end of current line
170
+ if (key.ctrl && input === "k") {
171
+ const { line } = offsetToPos(value, cursor);
172
+ const lineEnd = posToOffset(lines, line, lines[line].length);
173
+ onChange(value.slice(0, cursor) + value.slice(lineEnd));
174
+ return;
175
+ }
176
+ // Tab — file path completion (slash commands handled by shortcuts hook)
177
+ if (key.tab && !key.shift) {
178
+ if (!value.startsWith("/")) {
179
+ const result = completeFilePath(value, cursor);
180
+ if (result) {
181
+ onChange(result.value);
182
+ setCursor(result.cursor);
183
+ }
184
+ }
185
+ return;
186
+ }
187
+ // Escape, arrows already handled — skip control sequences
188
+ if (key.escape || key.upArrow || key.downArrow) {
189
+ return;
190
+ }
191
+ // Skip remaining ctrl sequences we don't handle
192
+ if (key.ctrl || key.meta) {
193
+ return;
194
+ }
195
+ // Regular character input
196
+ if (input.length > 0) {
197
+ const next = value.slice(0, cursor) + input + value.slice(cursor);
198
+ onChange(next);
199
+ setCursor(cursor + input.length);
200
+ }
201
+ }, { isActive: focus });
202
+ // Render: empty with placeholder
203
+ if (value.length === 0 && placeholder) {
204
+ return (_jsxs(Text, { children: [_jsx(Text, { inverse: true, children: " " }), _jsx(Text, { dimColor: true, children: placeholder })] }));
205
+ }
206
+ // Single-line render (fast path)
207
+ if (!isMultiLine) {
208
+ const before = value.slice(0, cursor);
209
+ const cursorChar = cursor < value.length ? value[cursor] : " ";
210
+ const after = cursor < value.length ? value.slice(cursor + 1) : "";
211
+ return (_jsxs(Text, { children: [before, _jsx(Text, { inverse: true, children: cursorChar }), after] }));
212
+ }
213
+ // Multi-line render: each line separately, cursor inverse on correct position
214
+ let charsSeen = 0;
215
+ return (_jsx(Box, { flexDirection: "column", children: lines.map((line, lineIdx) => {
216
+ const lineStart = charsSeen;
217
+ const lineEnd = lineStart + line.length;
218
+ // Advance past this line's content + its \n separator (except last line)
219
+ charsSeen = lineEnd + (lineIdx < lines.length - 1 ? 1 : 0);
220
+ const cursorInLine = cursor >= lineStart && cursor <= lineEnd;
221
+ if (!cursorInLine) {
222
+ return _jsx(Text, { children: line || " " }, lineIdx);
223
+ }
224
+ const localCursor = cursor - lineStart;
225
+ const before = line.slice(0, localCursor);
226
+ const cursorChar = localCursor < line.length ? line[localCursor] : " ";
227
+ const after = localCursor < line.length ? line.slice(localCursor + 1) : "";
228
+ return (_jsxs(Text, { children: [before, _jsx(Text, { inverse: true, children: cursorChar }), after] }, lineIdx));
229
+ }) }));
230
+ }
231
+ /** Find the start of the word to the left of pos (stops at newlines). */
232
+ function wordBoundaryLeft(text, pos) {
233
+ if (pos <= 0)
234
+ return 0;
235
+ let i = pos - 1;
236
+ // Skip whitespace but not newlines
237
+ while (i > 0 && text[i] !== "\n" && /\s/.test(text[i]))
238
+ i--;
239
+ // Skip word characters
240
+ while (i > 0 && text[i - 1] !== "\n" && /\S/.test(text[i - 1]))
241
+ i--;
242
+ return i;
243
+ }
244
+ /** Find the end of the word to the right of pos (stops at newlines). */
245
+ function wordBoundaryRight(text, pos) {
246
+ const len = text.length;
247
+ if (pos >= len)
248
+ return len;
249
+ let i = pos;
250
+ // Skip word characters
251
+ while (i < len && text[i] !== "\n" && /\S/.test(text[i]))
252
+ i++;
253
+ // Skip whitespace but not newlines
254
+ while (i < len && text[i] !== "\n" && /\s/.test(text[i]))
255
+ i++;
256
+ return i;
257
+ }
258
+ /** Expand ~ to home directory. */
259
+ function expandHome(p) {
260
+ if (p === "~" || p.startsWith("~/")) {
261
+ return os.homedir() + p.slice(1);
262
+ }
263
+ return p;
264
+ }
265
+ /**
266
+ * File path tab completion.
267
+ * Extracts the last whitespace-delimited token before the cursor,
268
+ * checks if it looks like a path, and completes it from the filesystem.
269
+ * Returns null if no completion applies.
270
+ */
271
+ function completeFilePath(value, cursor) {
272
+ // Extract the text before cursor and find the last token
273
+ const before = value.slice(0, cursor);
274
+ const tokenMatch = before.match(/(\S+)$/);
275
+ if (!tokenMatch)
276
+ return null;
277
+ const token = tokenMatch[1];
278
+ const tokenStart = cursor - token.length;
279
+ // Only complete tokens that look like paths
280
+ if (!/[/.~]/.test(token))
281
+ return null;
282
+ const expanded = expandHome(token);
283
+ const resolved = nodePath.resolve(expanded);
284
+ const dir = expanded.endsWith("/") ? resolved : nodePath.dirname(resolved);
285
+ const partial = expanded.endsWith("/") ? "" : nodePath.basename(resolved);
286
+ let entries;
287
+ try {
288
+ entries = fs.readdirSync(dir);
289
+ }
290
+ catch {
291
+ return null;
292
+ }
293
+ const matches = entries.filter((e) => e.startsWith(partial));
294
+ if (matches.length === 0)
295
+ return null;
296
+ let completion;
297
+ if (matches.length === 1) {
298
+ completion = matches[0];
299
+ // Append / for directories
300
+ try {
301
+ const stat = fs.statSync(nodePath.join(dir, completion));
302
+ if (stat.isDirectory())
303
+ completion += "/";
304
+ }
305
+ catch { /* leave as is */ }
306
+ }
307
+ else {
308
+ // Find longest common prefix among matches
309
+ let prefix = matches[0];
310
+ for (let i = 1; i < matches.length; i++) {
311
+ const m = matches[i];
312
+ let j = 0;
313
+ while (j < prefix.length && j < m.length && prefix[j] === m[j])
314
+ j++;
315
+ prefix = prefix.slice(0, j);
316
+ }
317
+ if (prefix.length <= partial.length)
318
+ return null; // no progress
319
+ completion = prefix;
320
+ }
321
+ // Build the completed token: keep the original prefix up to partial, append completion
322
+ const suffix = completion.slice(partial.length);
323
+ if (suffix.length === 0)
324
+ return null;
325
+ const after = value.slice(cursor);
326
+ const newValue = before + suffix + after;
327
+ const newCursor = cursor + suffix.length;
328
+ return { value: newValue, cursor: newCursor };
329
+ }