@phren/agent 0.3.20 → 0.3.21

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 (48) hide show
  1. package/dist/agent-loop/index.js +113 -19
  2. package/dist/agent-loop/stream.js +3 -1
  3. package/dist/attach-images.js +57 -0
  4. package/dist/commands/info.js +6 -2
  5. package/dist/commands/model.js +55 -13
  6. package/dist/commands/session.js +79 -18
  7. package/dist/commands.js +9 -2
  8. package/dist/config.js +45 -0
  9. package/dist/context/clear-tool-results.js +43 -0
  10. package/dist/context/compactor.js +8 -2
  11. package/dist/context/usage.js +26 -0
  12. package/dist/cost.js +10 -3
  13. package/dist/headless.js +41 -0
  14. package/dist/index.js +180 -56
  15. package/dist/mcp-client.js +38 -1
  16. package/dist/mcp-prompts.js +94 -0
  17. package/dist/multi/child-entry.js +3 -1
  18. package/dist/multi/spawner.js +27 -15
  19. package/dist/permissions/allowlist.js +19 -4
  20. package/dist/permissions/checker.js +37 -20
  21. package/dist/permissions/kernel-sandbox.js +32 -10
  22. package/dist/permissions/rules.js +173 -0
  23. package/dist/permissions/shell-classify.js +173 -0
  24. package/dist/plan.js +6 -2
  25. package/dist/repl.js +16 -1
  26. package/dist/session/persist.js +9 -4
  27. package/dist/settings.js +14 -0
  28. package/dist/structured-output.js +85 -0
  29. package/dist/system-prompt.js +117 -14
  30. package/dist/tools/apply-patch.js +15 -1
  31. package/dist/tools/edit-file.js +8 -1
  32. package/dist/tools/file-state.js +88 -0
  33. package/dist/tools/glob.js +53 -35
  34. package/dist/tools/grep.js +139 -53
  35. package/dist/tools/lint-test.js +24 -0
  36. package/dist/tools/read-file.js +2 -0
  37. package/dist/tools/registry.js +8 -1
  38. package/dist/tools/search-support.js +141 -0
  39. package/dist/tools/shell.js +3 -1
  40. package/dist/tools/spawn-agent.js +15 -3
  41. package/dist/tools/syntax-check.js +116 -0
  42. package/dist/tools/write-file.js +11 -3
  43. package/dist/tui/components/App.js +5 -4
  44. package/dist/tui/components/Banner.js +1 -1
  45. package/dist/tui/components/ListPicker.js +32 -0
  46. package/dist/tui/ink-entry.js +57 -16
  47. package/dist/user-hooks.js +26 -4
  48. package/package.json +3 -2
@@ -0,0 +1,141 @@
1
+ import { spawn } from "child_process";
2
+ import * as fs from "fs";
3
+ import * as path from "path";
4
+ /** Longest line the search tools hand back; one minified file must not flood context. */
5
+ export const MAX_LINE_CHARS = 500;
6
+ export function capLine(text, max = MAX_LINE_CHARS) {
7
+ return text.length > max ? `${text.slice(0, max)} ...[${text.length - max} more chars]` : text;
8
+ }
9
+ let rgCache;
10
+ /**
11
+ * Absolute path of ripgrep, or null when it is not on PATH or
12
+ * `PHREN_AGENT_RIPGREP=off` forces the JS walker. The PATH scan runs once.
13
+ */
14
+ export function ripgrepPath() {
15
+ if (process.env.PHREN_AGENT_RIPGREP === "off")
16
+ return null;
17
+ if (rgCache !== undefined)
18
+ return rgCache;
19
+ rgCache = null;
20
+ const names = process.platform === "win32" ? ["rg.exe", "rg.cmd"] : ["rg"];
21
+ for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
22
+ if (!dir)
23
+ continue;
24
+ for (const name of names) {
25
+ const candidate = path.join(dir, name);
26
+ try {
27
+ if (fs.statSync(candidate).isFile()) {
28
+ fs.accessSync(candidate, fs.constants.X_OK);
29
+ return (rgCache = candidate);
30
+ }
31
+ }
32
+ catch { /* try the next one */ }
33
+ }
34
+ }
35
+ return rgCache;
36
+ }
37
+ /**
38
+ * Run ripgrep with an argument array (never a shell), feeding stdout to
39
+ * `onLine` one line at a time. `onLine` returns true to stop early.
40
+ * Rejects when ripgrep cannot start or the signal aborts.
41
+ */
42
+ export function runRipgrep(rg, args, cwd, onLine, signal) {
43
+ return new Promise((resolve, reject) => {
44
+ const child = spawn(rg, args, { cwd, stdio: ["ignore", "pipe", "pipe"], signal, windowsHide: true });
45
+ let buffer = "";
46
+ let stderr = "";
47
+ let stopped = false;
48
+ const feed = (line) => {
49
+ if (stopped || line === "")
50
+ return;
51
+ if (onLine(line)) {
52
+ stopped = true;
53
+ child.kill();
54
+ }
55
+ };
56
+ child.stdout.setEncoding("utf8");
57
+ child.stdout.on("data", (chunk) => {
58
+ buffer += chunk;
59
+ let nl;
60
+ while ((nl = buffer.indexOf("\n")) >= 0) {
61
+ feed(buffer.slice(0, nl));
62
+ buffer = buffer.slice(nl + 1);
63
+ }
64
+ });
65
+ child.stderr.setEncoding("utf8");
66
+ child.stderr.on("data", (chunk) => { if (stderr.length < 4000)
67
+ stderr += chunk; });
68
+ child.on("error", reject);
69
+ child.on("close", (code) => {
70
+ feed(buffer);
71
+ resolve({ code, stderr, stopped });
72
+ });
73
+ });
74
+ }
75
+ /** One simple .gitignore line as a matcher: directory names, prefixes and `*` / `?` globs. */
76
+ function ignoreMatcher(line) {
77
+ let p = line.trim();
78
+ if (!p || p.startsWith("#") || p.startsWith("!"))
79
+ return null;
80
+ p = p.replace(/\/+$/, "");
81
+ const anchored = p.includes("/");
82
+ p = p.replace(/^\/+/, "");
83
+ if (!p)
84
+ return null;
85
+ const re = new RegExp(`^${p.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "\0").replace(/\*/g, "[^/]*").replace(/\0/g, ".*").replace(/\?/g, "[^/]")}$`);
86
+ return anchored ? (rel) => re.test(rel) : (_rel, name) => re.test(name);
87
+ }
88
+ function readIgnore(root) {
89
+ let text;
90
+ try {
91
+ text = fs.readFileSync(path.join(root, ".gitignore"), "utf-8");
92
+ }
93
+ catch {
94
+ return [];
95
+ }
96
+ return text.split("\n").map(ignoreMatcher).filter((m) => m !== null);
97
+ }
98
+ /**
99
+ * Fallback tree walk for when ripgrep is missing. Skips `.git`, node_modules
100
+ * and what the root .gitignore names (simple patterns only); other dotdirs
101
+ * such as `.github` are searched. `accept` filters files before they count
102
+ * against `maxFiles`.
103
+ */
104
+ export function walkTree(root, maxFiles, accept = () => true) {
105
+ const ignores = readIgnore(root);
106
+ const files = [];
107
+ let truncated = false;
108
+ const visit = (dir, relDir) => {
109
+ if (truncated)
110
+ return;
111
+ let entries;
112
+ try {
113
+ entries = fs.readdirSync(dir, { withFileTypes: true });
114
+ }
115
+ catch {
116
+ return;
117
+ }
118
+ for (const entry of entries) {
119
+ if (truncated)
120
+ return;
121
+ if (entry.name === ".git" || entry.name === "node_modules")
122
+ continue;
123
+ const rel = relDir ? `${relDir}/${entry.name}` : entry.name;
124
+ if (ignores.some((m) => m(rel, entry.name)))
125
+ continue;
126
+ if (entry.isDirectory()) {
127
+ visit(path.join(dir, entry.name), rel);
128
+ continue;
129
+ }
130
+ if (!accept(rel))
131
+ continue;
132
+ if (files.length >= maxFiles) {
133
+ truncated = true;
134
+ return;
135
+ }
136
+ files.push(rel);
137
+ }
138
+ };
139
+ visit(root, "");
140
+ return { files, truncated };
141
+ }
@@ -3,7 +3,7 @@ import * as fs from "fs";
3
3
  import * as path from "path";
4
4
  import * as os from "os";
5
5
  import { checkShellSafety, scrubEnv } from "../permissions/shell-safety.js";
6
- import { wrapWithSandbox, classifySandboxDenial, SandboxRequiredError } from "../permissions/kernel-sandbox.js";
6
+ import { wrapWithSandbox, classifySandboxDenial, classifyNetworkDenial, SandboxRequiredError } from "../permissions/kernel-sandbox.js";
7
7
  /** A positive whole number from the environment, else the fallback. */
8
8
  function envPositiveInt(key, fallback) {
9
9
  const value = Number(process.env[key]);
@@ -305,6 +305,7 @@ export function createShellTool(getPermissions) {
305
305
  mode: perms?.sandboxMode ?? "off",
306
306
  workspaceRoot: perms?.projectRoot ?? process.cwd(),
307
307
  extraWritable: perms?.allowedPaths ?? [],
308
+ network: perms?.network !== "off",
308
309
  });
309
310
  }
310
311
  catch (err) {
@@ -359,6 +360,7 @@ export function createShellTool(getPermissions) {
359
360
  // of retrying (classify combined output — commands often 2>&1)
360
361
  const denial = decision.sandboxed
361
362
  ? classifySandboxDenial(combined, perms?.projectRoot ?? process.cwd())
363
+ ?? (perms?.network === "off" ? classifyNetworkDenial(combined) : null)
362
364
  : null;
363
365
  const status = result.code !== null ? `Exit code ${result.code}` : `Killed by ${result.signal ?? "signal"}`;
364
366
  return { output: `${noticePrefix}${status}\n${combined}${denial ?? ""}`, is_error: true };
@@ -73,6 +73,20 @@ export function createListAgentsTool(spawner) {
73
73
  };
74
74
  }
75
75
  const VALID_PERMISSION_MODES = ["suggest", "auto-confirm", "plan", "full-auto"];
76
+ /** How much a mode lets run without asking. */
77
+ const MODE_RANK = { plan: 0, suggest: 0, "auto-confirm": 1, "full-auto": 2 };
78
+ /**
79
+ * A child runs with the mode the model asked for, but never more than the
80
+ * parent's: a suggest or auto-confirm session must not start a full-auto
81
+ * child that runs what the parent would have asked about.
82
+ */
83
+ export function clampChildMode(requested, parent) {
84
+ if (!requested)
85
+ return parent;
86
+ if (!parent)
87
+ return MODE_RANK[requested] > MODE_RANK.suggest ? "suggest" : requested;
88
+ return MODE_RANK[requested] > MODE_RANK[parent] ? parent : requested;
89
+ }
76
90
  export function createSpawnAgentTool(spawner, getPermissions) {
77
91
  return {
78
92
  name: "spawn_agent",
@@ -144,9 +158,7 @@ export function createSpawnAgentTool(spawner, getPermissions) {
144
158
  : task || `You are agent "${name}". Work on any tasks assigned to you.`;
145
159
  const perms = getPermissions?.();
146
160
  const requestedPermissions = input.permissions;
147
- const permissions = requestedPermissions && VALID_PERMISSION_MODES.includes(requestedPermissions)
148
- ? requestedPermissions
149
- : perms?.mode;
161
+ const permissions = clampChildMode(requestedPermissions && VALID_PERMISSION_MODES.includes(requestedPermissions) ? requestedPermissions : undefined, perms?.mode);
150
162
  const isolation = input.isolation === "worktree" ? "worktree" : undefined;
151
163
  const agentId = spawner.spawn({
152
164
  task: agentTask,
@@ -0,0 +1,116 @@
1
+ /**
2
+ * A syntax check after each edit, so a dropped brace or a broken indent shows
3
+ * up in the edit's own result instead of three tool calls later in a test run.
4
+ * OpenCode feeds LSP diagnostics back the same way; this is the cheap part of
5
+ * that: parse errors only, no type checking, nothing that needs a server.
6
+ *
7
+ * - TypeScript and JavaScript: Node's own TypeScript parser
8
+ * (`module.stripTypeScriptTypes`, Node 22.13 and later), in-process. Syntax
9
+ * it parses but won't strip (enums, namespaces) counts as fine; JSX files
10
+ * are skipped, since the parser doesn't take JSX.
11
+ * - Python: `python3` parses it with `ast` (no .pyc is written).
12
+ * - JSON: JSON.parse, skipped for files with comments (tsconfig and friends).
13
+ *
14
+ * Anything else, a missing parser, or a parser that fails is silent. Errors the
15
+ * file already had before the edit are not blamed on it.
16
+ */
17
+ import { execFileSync } from "child_process";
18
+ import * as nodeModule from "module";
19
+ import * as path from "path";
20
+ const MAX_ERRORS = 5;
21
+ const SCRIPT_EXTENSIONS = new Set([".ts", ".mts", ".cts", ".js", ".mjs", ".cjs"]);
22
+ function scriptErrors(content) {
23
+ const strip = nodeModule.stripTypeScriptTypes;
24
+ if (typeof strip !== "function")
25
+ return null;
26
+ // JSX in a .js file: the parser would call it an error.
27
+ if (/<\/[A-Za-z]|\/>/.test(content))
28
+ return null;
29
+ // The first call prints an ExperimentalWarning; keep it out of the TUI.
30
+ const emitWarning = process.emitWarning;
31
+ process.emitWarning = (() => { });
32
+ try {
33
+ strip(content);
34
+ return [];
35
+ }
36
+ catch (err) {
37
+ const code = err.code;
38
+ if (code !== "ERR_INVALID_TYPESCRIPT_SYNTAX")
39
+ return null;
40
+ return [{ message: err instanceof Error ? err.message.split("\n")[0] : String(err) }];
41
+ }
42
+ finally {
43
+ process.emitWarning = emitWarning;
44
+ }
45
+ }
46
+ function pythonErrors(content) {
47
+ const script = [
48
+ "import ast, json, sys",
49
+ "try:",
50
+ " ast.parse(sys.stdin.read())",
51
+ " print('[]')",
52
+ "except SyntaxError as e:",
53
+ " print(json.dumps([{'line': e.lineno or 1, 'column': e.offset or 1, 'message': e.msg}]))",
54
+ ].join("\n");
55
+ try {
56
+ const out = execFileSync("python3", ["-c", script], { input: content, encoding: "utf-8", timeout: 5_000, stdio: ["pipe", "pipe", "ignore"] });
57
+ return JSON.parse(out);
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ }
63
+ function jsonErrors(content) {
64
+ try {
65
+ JSON.parse(content);
66
+ return [];
67
+ }
68
+ catch (err) {
69
+ // JSONC (tsconfig.json, .vscode settings) is not JSON; don't flag it.
70
+ if (/\/\/|\/\*/.test(content))
71
+ return null;
72
+ const message = err instanceof Error ? err.message : String(err);
73
+ const pos = Number(/position (\d+)/.exec(message)?.[1] ?? "0");
74
+ const before = content.slice(0, pos).split("\n");
75
+ return [{ line: before.length, column: before[before.length - 1].length + 1, message }];
76
+ }
77
+ }
78
+ function errorsFor(filePath, content) {
79
+ const ext = path.extname(filePath).toLowerCase();
80
+ if (SCRIPT_EXTENSIONS.has(ext))
81
+ return scriptErrors(content);
82
+ if (ext === ".py")
83
+ return pythonErrors(content);
84
+ if (ext === ".json")
85
+ return jsonErrors(content);
86
+ return null;
87
+ }
88
+ /**
89
+ * A note for the edit result when the edit left the file with syntax errors,
90
+ * or null. `before` is the content the edit started from (null for a new file).
91
+ */
92
+ export function syntaxCheckNote(filePath, before, after) {
93
+ if (process.env.PHREN_AGENT_SYNTAX_CHECK === "off")
94
+ return null;
95
+ let errors;
96
+ try {
97
+ errors = errorsFor(filePath, after);
98
+ }
99
+ catch {
100
+ return null;
101
+ }
102
+ if (!errors || errors.length === 0)
103
+ return null;
104
+ let preexisting = false;
105
+ if (before !== null) {
106
+ try {
107
+ preexisting = (errorsFor(filePath, before)?.length ?? 0) >= errors.length;
108
+ }
109
+ catch { /* treat as clean before */ }
110
+ }
111
+ if (preexisting)
112
+ return null;
113
+ const shown = errors.slice(0, MAX_ERRORS).map((e) => ` ${filePath}${e.line ? `:${e.line}:${e.column ?? 1}` : ""} ${e.message}`);
114
+ const more = errors.length > MAX_ERRORS ? `\n … ${errors.length - MAX_ERRORS} more` : "";
115
+ return `Syntax check: the file no longer parses.\n${shown.join("\n")}${more}`;
116
+ }
@@ -2,9 +2,11 @@ import * as fs from "fs";
2
2
  import * as path from "path";
3
3
  import { encodeDiffPayload } from "../multi/diff-renderer.js";
4
4
  import { checkSensitivePath, validatePath } from "../permissions/sandbox.js";
5
+ import { recordFileState, staleFileError } from "./file-state.js";
6
+ import { syntaxCheckNote } from "./syntax-check.js";
5
7
  export const writeFileTool = {
6
8
  name: "write_file",
7
- description: "Write content to a file, creating parent directories as needed. Use for new files only — prefer edit_file for modifying existing files. Overwrites existing content entirely.",
9
+ description: "Write content to a file, creating parent directories as needed. Use for new files only — prefer edit_file for modifying existing files. Overwrites existing content entirely; an existing file must be read first.",
8
10
  input_schema: {
9
11
  type: "object",
10
12
  properties: {
@@ -27,10 +29,16 @@ export const writeFileTool = {
27
29
  if (!sandboxResult.ok) {
28
30
  return { output: `Path outside sandbox: ${sandboxResult.error}`, is_error: true };
29
31
  }
30
- const oldContent = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf-8") : "";
32
+ const stale = staleFileError(filePath, { requireRead: true });
33
+ if (stale)
34
+ return { output: stale, is_error: true };
35
+ const existed = fs.existsSync(filePath);
36
+ const oldContent = existed ? fs.readFileSync(filePath, "utf-8") : "";
31
37
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
32
38
  fs.writeFileSync(filePath, content);
33
- const msg = `Wrote ${content.length} bytes to ${filePath}`;
39
+ recordFileState(filePath);
40
+ const syntax = syntaxCheckNote(filePath, existed ? oldContent : null, content);
41
+ const msg = `Wrote ${content.length} bytes to ${filePath}${syntax ? `\n\n${syntax}` : ""}`;
34
42
  if (oldContent) {
35
43
  return { output: msg + encodeDiffPayload(filePath, oldContent, content) };
36
44
  }
@@ -12,6 +12,7 @@ import { ApprovalPanel } from "./ApprovalPanel.js";
12
12
  import { Banner } from "./Banner.js";
13
13
  import { InputArea, PermissionsLine } from "./InputArea.js";
14
14
  import { ModelPicker } from "./ModelPicker.js";
15
+ import { ListPicker } from "./ListPicker.js";
15
16
  import { PlanReview } from "./PlanReview.js";
16
17
  import { ShortcutHelp } from "./ShortcutHelp.js";
17
18
  import { StatusBar } from "./StatusBar.js";
@@ -20,7 +21,7 @@ import { ThinkingIndicator } from "./ThinkingIndicator.js";
20
21
  import { ToolCall } from "./ToolCall.js";
21
22
  import { ToolDetail } from "./ToolDetail.js";
22
23
  import { ToolSpinner } from "./ToolSpinner.js";
23
- export function App({ state, completedMessages, streamingText, reasoningText, completedToolCalls, activeTool, thinking, thinkStartTime, thinkElapsed, steerQueue, running, showBanner, inputHistory, verbose, theme, onSubmit, onPermissionCycle, onCancelTurn, onExit, onExpandTool, agents, selectedAgentId, onSelectAgent, onCancelAgent, approval, modelPicker, onModelPickerMove, onModelPickerReasoning, onModelPickerSelect, onModelPickerCancel, onInspectTool, toolDetail, onToolDetailMove, onToolDetailClose, planReview, }) {
24
+ export function App({ state, completedMessages, streamingText, reasoningText, completedToolCalls, activeTool, thinking, thinkStartTime, thinkElapsed, steerQueue, running, showBanner, inputHistory, verbose, theme, onSubmit, onPermissionCycle, onCancelTurn, onExit, onExpandTool, agents, selectedAgentId, onSelectAgent, onCancelAgent, approval, modelPicker, onModelPickerMove, onModelPickerReasoning, onModelPickerSelect, onModelPickerCancel, listPicker, onListPickerMove, onListPickerSelect, onListPickerCancel, onInspectTool, toolDetail, onToolDetailMove, onToolDetailClose, planReview, }) {
24
25
  const { exit } = useApp();
25
26
  const { stdin } = useStdin();
26
27
  const [inputValue, setInputValue] = useState("");
@@ -176,7 +177,7 @@ export function App({ state, completedMessages, streamingText, reasoningText, co
176
177
  setBashMode(false);
177
178
  }, [bashMode, onSubmit]);
178
179
  const isAnyModeActive = search.state.active || historySearchMode;
179
- const helpEnabled = !isAnyModeActive && !modelPicker && !toolDetail && !approval;
180
+ const helpEnabled = !isAnyModeActive && !modelPicker && !listPicker && !toolDetail && !approval;
180
181
  useEffect(() => {
181
182
  if (!helpEnabled)
182
183
  return;
@@ -274,7 +275,7 @@ export function App({ state, completedMessages, streamingText, reasoningText, co
274
275
  onSelectAgent?.(nextId === "__main__" ? null : nextId);
275
276
  } : undefined,
276
277
  onToggleTaskList: () => setShowTaskList(v => !v),
277
- enabled: !isAnyModeActive && !showHelp && !modelPicker && !toolDetail,
278
+ enabled: !isAnyModeActive && !showHelp && !modelPicker && !listPicker && !toolDetail,
278
279
  completionOpen: completions.length > 0,
279
280
  completionCount: completions.length,
280
281
  onCompletionMove: (delta) => setCompletionIndex((i) => (i + delta + completions.length) % completions.length),
@@ -321,5 +322,5 @@ export function App({ state, completedMessages, streamingText, reasoningText, co
321
322
  ? _jsxs(Text, { dimColor: true, color: theme.search?.match ?? undefined, children: [" (match ", (historySearchIndex % historyMatches.length) + 1, " of ", historyMatches.length, ")"] })
322
323
  : historySearchQuery.length > 0
323
324
  ? _jsx(Text, { dimColor: true, color: theme.search?.noMatch ?? "red", children: " (no matches)" })
324
- : _jsx(Text, { dimColor: true, children: " (type to search history)" })] })), historySearchMode && currentMatch && (_jsx(Box, { children: _jsxs(Text, { dimColor: true, children: [" ", "\u25b8", " ", currentMatch] }) })), showHelp ? _jsx(ShortcutHelp, { theme: theme }) : null, planReview !== null && planReview !== undefined ? _jsx(PlanReview, { text: planReview, theme: theme }) : null, toolDetail ? (_jsx(ToolDetail, { detail: toolDetail, theme: theme, onMove: onToolDetailMove ?? (() => { }), onClose: onToolDetailClose ?? (() => { }) })) : null, modelPicker ? (_jsx(ModelPicker, { state: modelPicker, theme: theme, onMove: onModelPickerMove ?? (() => { }), onReasoning: onModelPickerReasoning ?? (() => { }), onSelect: onModelPickerSelect ?? (() => { }), onCancel: onModelPickerCancel ?? (() => { }) })) : null, completions.length > 0 && (_jsx(Box, { flexDirection: "column", paddingLeft: 2, children: completions.map((candidate, i) => (_jsxs(Text, { color: i === completionIndex ? theme.statusBar.accent : undefined, dimColor: i !== completionIndex, children: [i === completionIndex ? "\u25b8 " : " ", candidate] }, candidate))) })), approval ? _jsx(ApprovalPanel, { info: approval, theme: theme }) : null, _jsx(StatusBar, { provider: state.provider, model: state.model, project: state.project, turns: state.turns, cost: state.cost, contextTokens: state.contextTokens, contextLimit: state.contextWindow, reasoningEffort: state.reasoningEffort, theme: theme }), _jsx(InputArea, { value: inputValue, onChange: setInputValue, onSubmit: handleSubmit, bashMode: bashMode, focus: !isAnyModeActive && !showHelp && !modelPicker && !toolDetail, completionOpen: completions.length > 0, separatorColor: theme.separator, theme: theme }), _jsx(PermissionsLine, { mode: state.permMode, theme: theme, running: running, agents: agents, selectedAgentId: selectedAgentId, highlightedTabId: agents?.[highlightedTabIndex]?.id ?? null, tabFocused: tabFocused })] })] }));
325
+ : _jsx(Text, { dimColor: true, children: " (type to search history)" })] })), historySearchMode && currentMatch && (_jsx(Box, { children: _jsxs(Text, { dimColor: true, children: [" ", "\u25b8", " ", currentMatch] }) })), showHelp ? _jsx(ShortcutHelp, { theme: theme }) : null, planReview !== null && planReview !== undefined ? _jsx(PlanReview, { text: planReview, theme: theme }) : null, toolDetail ? (_jsx(ToolDetail, { detail: toolDetail, theme: theme, onMove: onToolDetailMove ?? (() => { }), onClose: onToolDetailClose ?? (() => { }) })) : null, modelPicker ? (_jsx(ModelPicker, { state: modelPicker, theme: theme, onMove: onModelPickerMove ?? (() => { }), onReasoning: onModelPickerReasoning ?? (() => { }), onSelect: onModelPickerSelect ?? (() => { }), onCancel: onModelPickerCancel ?? (() => { }) })) : null, listPicker ? (_jsx(ListPicker, { state: listPicker, theme: theme, onMove: onListPickerMove ?? (() => { }), onSelect: onListPickerSelect ?? (() => { }), onCancel: onListPickerCancel ?? (() => { }) })) : null, completions.length > 0 && (_jsx(Box, { flexDirection: "column", paddingLeft: 2, children: completions.map((candidate, i) => (_jsxs(Text, { color: i === completionIndex ? theme.statusBar.accent : undefined, dimColor: i !== completionIndex, children: [i === completionIndex ? "\u25b8 " : " ", candidate] }, candidate))) })), approval ? _jsx(ApprovalPanel, { info: approval, theme: theme }) : null, _jsx(StatusBar, { provider: state.provider, model: state.model, project: state.project, turns: state.turns, cost: state.cost, contextTokens: state.contextTokens, contextLimit: state.contextWindow, reasoningEffort: state.reasoningEffort, theme: theme }), _jsx(InputArea, { value: inputValue, onChange: setInputValue, onSubmit: handleSubmit, bashMode: bashMode, focus: !isAnyModeActive && !showHelp && !modelPicker && !listPicker && !toolDetail, completionOpen: completions.length > 0, separatorColor: theme.separator, theme: theme }), _jsx(PermissionsLine, { mode: state.permMode, theme: theme, running: running, agents: agents, selectedAgentId: selectedAgentId, highlightedTabId: agents?.[highlightedTabIndex]?.id ?? null, tabFocused: tabFocused })] })] }));
325
326
  }
@@ -21,5 +21,5 @@ export function Banner({ state, theme }) {
21
21
  if (state.reasoningEffort)
22
22
  modelParts.push(state.reasoningEffort);
23
23
  const modelLine = modelParts.join(" · ");
24
- return (_jsxs(Box, { flexDirection: "column", paddingLeft: 2, children: [_jsxs(Box, { flexDirection: "row", children: [_jsx(Text, { bold: true, color: logoColor, children: "◆ phren" }), _jsx(Text, { color: versionColor, dimColor: true, children: " v" + state.version })] }), modelLine ? (_jsx(Text, { color: versionColor, dimColor: true, children: modelLine })) : null, _jsx(Text, { color: cwdColor, dimColor: true, children: cwd }), _jsx(Text, { children: "" })] }));
24
+ return (_jsxs(Box, { flexDirection: "column", paddingLeft: 2, children: [_jsxs(Box, { flexDirection: "row", children: [_jsx(Text, { bold: true, color: logoColor, children: "◆ phren" }), _jsx(Text, { color: versionColor, dimColor: true, children: " v" + state.version })] }), modelLine ? (_jsx(Text, { color: versionColor, dimColor: true, children: modelLine })) : null, state.chat ? null : _jsx(Text, { color: cwdColor, dimColor: true, children: cwd }), _jsx(Text, { children: "" })] }));
25
25
  }
@@ -0,0 +1,32 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Text, useInput } from "ink";
3
+ /** Rows shown at once; the window follows the cursor. */
4
+ const VISIBLE = 10;
5
+ export function ListPicker({ state, theme, onMove, onSelect, onCancel }) {
6
+ useInput((_input, key) => {
7
+ if (key.escape) {
8
+ onCancel();
9
+ return;
10
+ }
11
+ if (key.return) {
12
+ onSelect();
13
+ return;
14
+ }
15
+ if (key.upArrow) {
16
+ onMove(-1);
17
+ return;
18
+ }
19
+ if (key.downArrow) {
20
+ onMove(1);
21
+ return;
22
+ }
23
+ });
24
+ const accent = theme?.statusBar.accent ?? "cyan";
25
+ const start = Math.max(0, Math.min(state.cursor - Math.floor(VISIBLE / 2), state.items.length - VISIBLE));
26
+ const shown = state.items.slice(start, start + VISIBLE);
27
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: accent, paddingX: 1, marginTop: 1, children: [_jsxs(Box, { children: [_jsxs(Text, { bold: true, children: [state.title, " "] }), _jsx(Text, { dimColor: true, children: "↑↓ navigate · enter select · esc cancel" })] }), shown.map((item, offset) => {
28
+ const i = start + offset;
29
+ const selected = i === state.cursor;
30
+ return (_jsxs(Text, { color: selected ? accent : undefined, dimColor: !selected, wrap: "truncate-end", children: [selected ? "▸ " : " ", item.label, item.detail ? _jsxs(Text, { dimColor: true, children: [" ", item.detail] }) : null] }, i));
31
+ }), state.items.length > VISIBLE ? _jsx(Text, { dimColor: true, children: ` ${state.cursor + 1} of ${state.items.length}` }) : null] }));
32
+ }
@@ -4,6 +4,7 @@ import { createSession, runTurn } from "../agent-loop.js";
4
4
  import { emitHerdrHook, setHerdrHookSession } from "../herdr-hooks.js";
5
5
  import { useSlashCommands } from "./hooks/useSlashCommands.js";
6
6
  import { resolveSkillGesture, resolveCustomCommand } from "../commands.js";
7
+ import { isMcpPromptCommand, resolveMcpPromptCommand } from "../mcp-prompts.js";
7
8
  import { decodeDiffPayload, DIFF_MARKER, renderInlineDiff } from "../multi/diff-renderer.js";
8
9
  import { formatToolInput } from "./tool-render.js";
9
10
  import * as os from "os";
@@ -11,7 +12,7 @@ import * as fs from "node:fs";
11
12
  import { execSync } from "node:child_process";
12
13
  import * as path from "node:path";
13
14
  import { loadInputMode, saveInputMode, savePermissionMode, loadTheme, saveTheme, loadInputHistory, saveInputHistory } from "../settings.js";
14
- import { estimateMessageTokens } from "../context/token-counter.js";
15
+ import { contextTokens } from "../context/usage.js";
15
16
  import { READ_ONLY_TOOLS } from "../permissions/checker.js";
16
17
  import { nextPermissionMode } from "./ansi.js";
17
18
  import { App } from "./components/App.js";
@@ -162,6 +163,8 @@ export async function startInkTui(config, spawner) {
162
163
  let activeTool = null;
163
164
  let modelPicker = null;
164
165
  let modelPickerResolve = null;
166
+ let listPicker = null;
167
+ let listPickerResolve = null;
165
168
  const toolHistory = [];
166
169
  let toolDetailIndex = null;
167
170
  let planReview = null;
@@ -188,13 +191,18 @@ export async function startInkTui(config, spawner) {
188
191
  contextWindow: contextLimit,
189
192
  contextTokens: currentContextTokens(),
190
193
  reasoningEffort: config.provider.reasoningEffort,
194
+ chat: config.mode === "chat",
191
195
  };
192
196
  }
193
- let contextMemo = { count: -1, tokens: 0 };
197
+ let contextMemo = { count: -1, logLength: -1, tokens: 0 };
194
198
  function currentContextTokens() {
195
199
  const count = session.messages.length;
196
- if (contextMemo.count !== count) {
197
- contextMemo = { count, tokens: estimateMessageTokens(session.messages) };
200
+ if (contextMemo.count !== count || contextMemo.logLength !== session.log.length) {
201
+ contextMemo = {
202
+ count,
203
+ logLength: session.log.length,
204
+ tokens: contextTokens(config.systemPrompt, session.messages, session.log, session.reportedContext),
205
+ };
198
206
  }
199
207
  return contextMemo.tokens;
200
208
  }
@@ -227,7 +235,27 @@ export async function startInkTui(config, spawner) {
227
235
  const displayActiveTool = agentConvo ? agentConvo.activeTool : activeTool;
228
236
  const displayThinking = agentConvo ? false : thinking;
229
237
  const displayRunning = agentConvo ? (spawner?.getAgent(selectedAgentId)?.status === "running" || false) : running;
230
- rerender(_jsx(App, { state: getAppState(), completedMessages: displayMessages, streamingText: displayStreaming, reasoningText: agentConvo ? "" : reasoningText, 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), approval: approvalInfo, modelPicker: modelPicker, onModelPickerMove: moveModelPicker, onModelPickerReasoning: adjustModelReasoning, onModelPickerSelect: selectModelPicker, onModelPickerCancel: () => closeModelPicker(null), onInspectTool: openToolDetail, toolDetail: toolDetailIndex !== null ? { call: toolHistory[toolDetailIndex], index: toolDetailIndex, total: toolHistory.length } : null, onToolDetailMove: moveToolDetail, onToolDetailClose: closeToolDetail, planReview: planReview }));
238
+ rerender(_jsx(App, { state: getAppState(), completedMessages: displayMessages, streamingText: displayStreaming, reasoningText: agentConvo ? "" : reasoningText, 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), approval: approvalInfo, modelPicker: modelPicker, listPicker: listPicker, onListPickerMove: (delta) => {
239
+ if (!listPicker)
240
+ return;
241
+ const count = listPicker.items.length;
242
+ listPicker = { ...listPicker, cursor: (listPicker.cursor + delta + count) % count };
243
+ update();
244
+ }, onListPickerSelect: () => closeListPicker(listPicker?.cursor ?? null), onListPickerCancel: () => closeListPicker(null), onModelPickerMove: moveModelPicker, onModelPickerReasoning: adjustModelReasoning, onModelPickerSelect: selectModelPicker, onModelPickerCancel: () => closeModelPicker(null), onInspectTool: openToolDetail, toolDetail: toolDetailIndex !== null ? { call: toolHistory[toolDetailIndex], index: toolDetailIndex, total: toolHistory.length } : null, onToolDetailMove: moveToolDetail, onToolDetailClose: closeToolDetail, planReview: planReview }));
245
+ }
246
+ function openListPicker(title, items) {
247
+ if (items.length === 0)
248
+ return Promise.resolve(null);
249
+ listPicker = { title, items, cursor: 0 };
250
+ update();
251
+ return new Promise((resolve) => { listPickerResolve = resolve; });
252
+ }
253
+ function closeListPicker(index) {
254
+ listPicker = null;
255
+ const resolve = listPickerResolve;
256
+ listPickerResolve = null;
257
+ update();
258
+ resolve?.(index);
231
259
  }
232
260
  function openModelPicker() {
233
261
  const providerName = config.provider.name;
@@ -368,19 +396,21 @@ export async function startInkTui(config, spawner) {
368
396
  }
369
397
  },
370
398
  onModelChange: async (result) => {
371
- try {
372
- const { resolveProvider } = await import("../providers/resolve.js");
373
- const newProvider = resolveProvider(config.provider.name, result.model, undefined, result.reasoning ?? undefined);
374
- config.provider = newProvider;
375
- const { buildSystemPrompt } = await import("../system-prompt.js");
376
- config.systemPrompt = config.rebuildSystemPrompt
377
- ? config.rebuildSystemPrompt({ name: newProvider.name, model: result.model })
378
- : buildSystemPrompt(config.systemPrompt.split("\n## Last session")[0], null, { name: newProvider.name, model: result.model });
379
- update();
380
- }
381
- catch { /* keep current provider */ }
399
+ // A failure (no key for that provider, an unknown name) is reported
400
+ // by the command; the current provider stays.
401
+ const { resolveProvider } = await import("../providers/resolve.js");
402
+ const newProvider = resolveProvider(result.provider ?? config.provider.name, result.model || undefined, undefined, result.reasoning ?? undefined);
403
+ config.provider = newProvider;
404
+ config.costTracker?.reprice(newProvider.model ?? newProvider.name, newProvider.name, newProvider.baseUrl);
405
+ const { buildSystemPrompt } = await import("../system-prompt.js");
406
+ config.systemPrompt = config.rebuildSystemPrompt
407
+ ? config.rebuildSystemPrompt({ name: newProvider.name, model: newProvider.model })
408
+ : buildSystemPrompt(config.systemPrompt.split("\n## Last session")[0], null, { name: newProvider.name, model: newProvider.model });
409
+ update();
410
+ return newProvider;
382
411
  },
383
412
  pickModel: openModelPicker,
413
+ pickFromList: openListPicker,
384
414
  promote: config.promote,
385
415
  },
386
416
  onOutput: (text) => {
@@ -553,6 +583,17 @@ export async function startInkTui(config, spawner) {
553
583
  update();
554
584
  return;
555
585
  }
586
+ // An MCP prompt: fetch it from its server, then send what it says.
587
+ if (isMcpPromptCommand(line)) {
588
+ const command = line.split(/\s+/)[0];
589
+ completedMessages.push({ id: nextId(), kind: "status", text: `↳ fetching MCP prompt ${command}` });
590
+ update();
591
+ resolveMcpPromptCommand(line).then((task) => handleSubmit(task.startsWith("/") ? ` ${task}` : task), (err) => {
592
+ completedMessages.push({ id: nextId(), kind: "status", text: err instanceof Error ? err.message : String(err) });
593
+ update();
594
+ });
595
+ return;
596
+ }
556
597
  // Slash commands — capture stderr output and display as status message
557
598
  if (line.startsWith("/")) {
558
599
  // /skill-name gesture: rewrite into a run_skill task and fall through
@@ -7,7 +7,11 @@ export const HOOK_EVENT_NAMES = [
7
7
  "PostToolUse",
8
8
  "UserPromptSubmit",
9
9
  "Stop",
10
+ "SessionStart",
11
+ "PreCompact",
10
12
  ];
13
+ /** Exit code that blocks, as in Claude Code. */
14
+ export const BLOCKING_EXIT_CODE = 2;
11
15
  const DEFAULT_TIMEOUT_MS = 10_000;
12
16
  const MAX_OUTPUT_CHARS = 16_384;
13
17
  function isHookCommand(value) {
@@ -144,10 +148,15 @@ export async function runPreToolUseHooks(config, toolName, input, options = {})
144
148
  }
145
149
  return { denied: false, message: "" };
146
150
  }
151
+ /**
152
+ * PostToolUse hooks run after the tool; one that exits 2 sends its stderr back
153
+ * to the model with the tool's result (a formatter or linter complaining).
154
+ * Returns that feedback, or "".
155
+ */
147
156
  export async function runPostToolUseHooks(config, toolName, input, output, isError, options = {}) {
148
157
  const hooks = (config?.PostToolUse ?? []).filter((hook) => matchesTool(hook.matcher, toolName));
149
158
  if (hooks.length === 0)
150
- return;
159
+ return "";
151
160
  const payload = {
152
161
  hook_event_name: "PostToolUse",
153
162
  tool_name: toolName,
@@ -156,16 +165,29 @@ export async function runPostToolUseHooks(config, toolName, input, output, isErr
156
165
  is_error: isError,
157
166
  cwd: options.cwd ?? process.cwd(),
158
167
  };
168
+ const feedback = [];
159
169
  for (const hook of hooks) {
160
- await runHook(hook, payload, options);
170
+ const result = await runHook(hook, payload, options);
171
+ if (result.exitCode === BLOCKING_EXIT_CODE && result.stderr.trim())
172
+ feedback.push(result.stderr.trim());
161
173
  }
174
+ return feedback.join("\n");
162
175
  }
163
176
  export async function runLifecycleHooks(config, event, payload = {}, options = {}) {
164
177
  const hooks = config?.[event] ?? [];
178
+ const outcome = { blocked: false, reason: "", context: "" };
165
179
  if (hooks.length === 0)
166
- return;
180
+ return outcome;
167
181
  const body = { hook_event_name: event, ...payload, cwd: options.cwd ?? process.cwd() };
182
+ const context = [];
168
183
  for (const hook of hooks) {
169
- await runHook(hook, body, options);
184
+ const result = await runHook(hook, body, options);
185
+ if (result.exitCode === BLOCKING_EXIT_CODE) {
186
+ return { blocked: true, reason: result.stderr.trim() || `Blocked by ${event} hook: ${hook.command}`, context: context.join("\n") };
187
+ }
188
+ if (result.exitCode === 0 && result.stdout.trim())
189
+ context.push(result.stdout.trim());
170
190
  }
191
+ outcome.context = context.join("\n");
192
+ return outcome;
171
193
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/agent",
3
- "version": "0.3.20",
3
+ "version": "0.3.21",
4
4
  "description": "phren's coding agent: starts every session knowing your project's memory, tasks and decisions",
5
5
  "type": "module",
6
6
  "bin": {
@@ -15,9 +15,10 @@
15
15
  ],
16
16
  "dependencies": {
17
17
  "@modelcontextprotocol/sdk": "^1.30.1",
18
+ "ajv": "^8.20.0",
18
19
  "ink": "^7.1.1",
19
20
  "react": "^19.3.0",
20
- "@phren/cli": "0.3.20"
21
+ "@phren/cli": "0.3.21"
21
22
  },
22
23
  "engines": {
23
24
  "node": ">=20.0.0"