@phren/agent 0.3.19 → 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 (67) hide show
  1. package/dist/agent-loop/index.js +185 -47
  2. package/dist/agent-loop/stream.js +74 -66
  3. package/dist/agent-loop/types.js +2 -3
  4. package/dist/attach-images.js +57 -0
  5. package/dist/bin.js +7 -2
  6. package/dist/commands/info.js +7 -3
  7. package/dist/commands/model.js +55 -13
  8. package/dist/commands/session.js +79 -18
  9. package/dist/commands.js +24 -3
  10. package/dist/config.js +89 -10
  11. package/dist/context/clear-tool-results.js +43 -0
  12. package/dist/context/compactor.js +13 -3
  13. package/dist/context/pruner.js +29 -11
  14. package/dist/context/usage.js +26 -0
  15. package/dist/cost.js +68 -10
  16. package/dist/headless.js +47 -1
  17. package/dist/index.js +335 -127
  18. package/dist/mcp-client.js +38 -1
  19. package/dist/mcp-prompts.js +94 -0
  20. package/dist/memory/chat.js +70 -0
  21. package/dist/memory/context.js +1 -1
  22. package/dist/model-overrides.js +17 -0
  23. package/dist/models-list.js +73 -0
  24. package/dist/models.js +42 -15
  25. package/dist/multi/child-entry.js +18 -28
  26. package/dist/multi/ipc-hooks.js +34 -0
  27. package/dist/multi/spawner.js +49 -3
  28. package/dist/permissions/allowlist.js +19 -4
  29. package/dist/permissions/checker.js +37 -20
  30. package/dist/permissions/kernel-sandbox.js +32 -10
  31. package/dist/permissions/rules.js +173 -0
  32. package/dist/permissions/shell-classify.js +173 -0
  33. package/dist/plan.js +6 -2
  34. package/dist/providers/anthropic.js +119 -75
  35. package/dist/providers/codex.js +10 -9
  36. package/dist/providers/ollama.js +5 -2
  37. package/dist/providers/openai-compat.js +219 -92
  38. package/dist/providers/openrouter.js +12 -7
  39. package/dist/providers/resolve.js +47 -1
  40. package/dist/providers/retry.js +20 -7
  41. package/dist/providers/types.js +31 -0
  42. package/dist/repl.js +17 -1
  43. package/dist/session/persist.js +9 -4
  44. package/dist/session/preview.js +99 -0
  45. package/dist/settings.js +14 -0
  46. package/dist/structured-output.js +85 -0
  47. package/dist/system-prompt.js +117 -14
  48. package/dist/tools/apply-patch.js +15 -1
  49. package/dist/tools/edit-file.js +8 -1
  50. package/dist/tools/file-state.js +88 -0
  51. package/dist/tools/glob.js +53 -35
  52. package/dist/tools/grep.js +139 -53
  53. package/dist/tools/lint-test.js +24 -0
  54. package/dist/tools/read-file.js +2 -0
  55. package/dist/tools/registry.js +8 -1
  56. package/dist/tools/search-support.js +141 -0
  57. package/dist/tools/shell.js +266 -41
  58. package/dist/tools/spawn-agent.js +15 -3
  59. package/dist/tools/syntax-check.js +116 -0
  60. package/dist/tools/write-file.js +11 -3
  61. package/dist/tui/components/App.js +5 -4
  62. package/dist/tui/components/Banner.js +1 -1
  63. package/dist/tui/components/ListPicker.js +32 -0
  64. package/dist/tui/ink-entry.js +79 -15
  65. package/dist/user-hooks.js +26 -4
  66. package/package.json +3 -2
  67. package/dist/memory/context-flush.js +0 -24
@@ -1,14 +1,37 @@
1
- import { execFile, spawn } from "child_process";
2
- import { promisify } from "util";
1
+ import { spawn } from "child_process";
3
2
  import * as fs from "fs";
4
3
  import * as path from "path";
5
4
  import * as os from "os";
6
5
  import { checkShellSafety, scrubEnv } from "../permissions/shell-safety.js";
7
- import { wrapWithSandbox, classifySandboxDenial, SandboxRequiredError } from "../permissions/kernel-sandbox.js";
8
- const execFileAsync = promisify(execFile);
9
- const DEFAULT_TIMEOUT_MS = 30_000;
10
- const MAX_TIMEOUT_MS = 120_000;
6
+ import { wrapWithSandbox, classifySandboxDenial, classifyNetworkDenial, SandboxRequiredError } from "../permissions/kernel-sandbox.js";
7
+ /** A positive whole number from the environment, else the fallback. */
8
+ function envPositiveInt(key, fallback) {
9
+ const value = Number(process.env[key]);
10
+ return Number.isInteger(value) && value > 0 ? value : fallback;
11
+ }
12
+ /**
13
+ * Foreground limits. A real test suite or build often needs minutes, and
14
+ * weaker models handle background polling badly, so the cap is 10 minutes
15
+ * (as in Claude Code). Override with PHREN_AGENT_SHELL_TIMEOUT_MS (default)
16
+ * and PHREN_AGENT_SHELL_MAX_TIMEOUT_MS (cap).
17
+ */
18
+ function shellTimeouts() {
19
+ const maxMs = envPositiveInt("PHREN_AGENT_SHELL_MAX_TIMEOUT_MS", 600_000);
20
+ return { defaultMs: Math.min(maxMs, envPositiveInt("PHREN_AGENT_SHELL_TIMEOUT_MS", 120_000)), maxMs };
21
+ }
22
+ /** Background task_output reads are capped at this many trailing characters. */
11
23
  const MAX_OUTPUT_BYTES = 100_000;
24
+ /**
25
+ * Foreground output kept for the model: the head (what ran) and the tail
26
+ * (test summaries, stack traces). Anything between is dropped with a marker
27
+ * and the full output is kept in a log file the model can read.
28
+ */
29
+ export const OUTPUT_HEAD_CHARS = 8_000;
30
+ export const OUTPUT_TAIL_CHARS = 24_000;
31
+ /** Stop writing the full-output file past this, so a runaway command can't fill the disk. */
32
+ const MAX_SPILL_BYTES = 50_000_000;
33
+ /** All full-output files of one agent process together stop growing past this (PHREN_AGENT_SHELL_SPILL_TOTAL_BYTES). */
34
+ const sessionSpillLimit = () => envPositiveInt("PHREN_AGENT_SHELL_SPILL_TOTAL_BYTES", 200_000_000);
12
35
  // Background task tracking
13
36
  const backgroundTasks = new Map();
14
37
  /**
@@ -29,6 +52,214 @@ function backgroundLogDir() {
29
52
  return backgroundLogRoot;
30
53
  }
31
54
  let nextBgId = 1;
55
+ let nextSpillId = 1;
56
+ /** Full-output files written by this process; removed when it exits. */
57
+ const spillFiles = new Set();
58
+ let sessionSpilled = 0;
59
+ /**
60
+ * Process groups of foreground commands still running. Each one is detached
61
+ * into its own group (so a timeout kills what it spawned), which also means
62
+ * Ctrl+C, a closed terminal or the agent exiting no longer reach it; the
63
+ * exit and signal handlers below kill them instead.
64
+ */
65
+ const foregroundGroups = new Set();
66
+ let exitHandlersInstalled = false;
67
+ /** Kill every running foreground command's process group. Synchronous, so it can run in an exit handler. */
68
+ export function killForegroundCommands() {
69
+ for (const pgid of foregroundGroups) {
70
+ try {
71
+ process.kill(-pgid, "SIGKILL");
72
+ }
73
+ catch { /* already gone */ }
74
+ }
75
+ foregroundGroups.clear();
76
+ }
77
+ /** Remove this process's full-output files. */
78
+ export function removeSpillFiles() {
79
+ for (const file of spillFiles) {
80
+ try {
81
+ fs.rmSync(file, { force: true });
82
+ }
83
+ catch { /* best effort */ }
84
+ }
85
+ spillFiles.clear();
86
+ // Background logs may still be in use; the directory goes only when empty.
87
+ if (backgroundLogRoot) {
88
+ try {
89
+ fs.rmdirSync(backgroundLogRoot);
90
+ backgroundLogRoot = undefined;
91
+ }
92
+ catch { /* not empty */ }
93
+ }
94
+ }
95
+ function onProcessExit() {
96
+ killForegroundCommands();
97
+ removeSpillFiles();
98
+ }
99
+ /**
100
+ * Covers every way the agent ends: process.exit from the one-shot, REPL,
101
+ * TUI and subagent paths (a subagent exits when its parent's IPC channel
102
+ * closes) runs the exit handler; SIGINT, SIGTERM and SIGHUP kill the groups
103
+ * first and, when nothing else handles the signal, re-raise it so the
104
+ * default exit still happens.
105
+ */
106
+ function installExitHandlers() {
107
+ if (exitHandlersInstalled)
108
+ return;
109
+ exitHandlersInstalled = true;
110
+ process.on("exit", onProcessExit);
111
+ for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) {
112
+ const onSignal = () => {
113
+ killForegroundCommands();
114
+ if (process.listenerCount(sig) === 1) {
115
+ process.removeListener(sig, onSignal);
116
+ process.kill(process.pid, sig);
117
+ }
118
+ };
119
+ process.on(sig, onSignal);
120
+ }
121
+ }
122
+ /** Interleaved stdout/stderr, keeping only the head and tail in memory. */
123
+ class OutputCapture {
124
+ head = "";
125
+ tail = "";
126
+ total = 0;
127
+ spillFd = null;
128
+ spillPath = null;
129
+ spilled = 0;
130
+ push(chunk) {
131
+ const full = this.total <= OUTPUT_HEAD_CHARS + OUTPUT_TAIL_CHARS;
132
+ this.total += chunk.length;
133
+ if (full && this.total <= OUTPUT_HEAD_CHARS + OUTPUT_TAIL_CHARS) {
134
+ // Still small enough to hold whole: everything lives in head.
135
+ this.head += chunk;
136
+ return;
137
+ }
138
+ if (full) {
139
+ // Crossing the limit: start the full-output file with what we have.
140
+ const all = this.head + chunk;
141
+ this.openSpill(all.slice(0, all.length - chunk.length));
142
+ this.head = all.slice(0, OUTPUT_HEAD_CHARS);
143
+ this.tail = all.slice(OUTPUT_HEAD_CHARS).slice(-OUTPUT_TAIL_CHARS);
144
+ }
145
+ else {
146
+ this.tail = (this.tail + chunk).slice(-OUTPUT_TAIL_CHARS);
147
+ }
148
+ this.writeSpill(chunk);
149
+ }
150
+ openSpill(initial) {
151
+ if (sessionSpilled >= sessionSpillLimit())
152
+ return;
153
+ try {
154
+ this.spillPath = path.join(backgroundLogDir(), `shell-${nextSpillId++}.log`);
155
+ this.spillFd = fs.openSync(this.spillPath, "wx");
156
+ spillFiles.add(this.spillPath);
157
+ installExitHandlers();
158
+ this.writeSpill(initial);
159
+ }
160
+ catch {
161
+ this.spillFd = null;
162
+ this.spillPath = null;
163
+ }
164
+ }
165
+ get capped() {
166
+ return this.spilled >= MAX_SPILL_BYTES || sessionSpilled >= sessionSpillLimit();
167
+ }
168
+ writeSpill(text) {
169
+ if (this.spillFd === null || this.capped)
170
+ return;
171
+ try {
172
+ const written = fs.writeSync(this.spillFd, text);
173
+ this.spilled += written;
174
+ sessionSpilled += written;
175
+ }
176
+ catch { /* best effort */ }
177
+ }
178
+ /** The model-visible text: whole when small, else head + marker + tail. */
179
+ finish() {
180
+ if (this.spillFd !== null) {
181
+ try {
182
+ fs.closeSync(this.spillFd);
183
+ }
184
+ catch { /* already closed */ }
185
+ this.spillFd = null;
186
+ }
187
+ if (this.total <= OUTPUT_HEAD_CHARS + OUTPUT_TAIL_CHARS)
188
+ return this.head.trim();
189
+ const omitted = this.total - this.head.length - this.tail.length;
190
+ const where = this.spillPath
191
+ ? ` Full output (${this.total} chars${this.capped ? `, file capped at ${this.spilled} bytes` : ""}) is in ${this.spillPath}; read or grep it for the middle.`
192
+ : sessionSpilled >= sessionSpillLimit()
193
+ ? " Full output was not saved: this session's output files reached their size cap; rerun with less output (e.g. pipe through grep or tail)."
194
+ : "";
195
+ return `${this.head}\n\n... [${omitted} chars of output omitted.${where}] ...\n\n${this.tail}`.trim();
196
+ }
197
+ }
198
+ /**
199
+ * Run a command to completion without a size limit: output streams into an
200
+ * OutputCapture, so a verbose command is never killed for printing too much
201
+ * and its real exit code is reported. On POSIX the command gets its own
202
+ * process group so a timeout or cancel also kills what it spawned.
203
+ */
204
+ function runForeground(exe, args, opts) {
205
+ return new Promise((resolve) => {
206
+ const capture = new OutputCapture();
207
+ const posix = process.platform !== "win32";
208
+ let timedOut = false;
209
+ let aborted = false;
210
+ let settled = false;
211
+ let child;
212
+ try {
213
+ child = spawn(exe, args, {
214
+ cwd: opts.cwd,
215
+ env: scrubEnv(),
216
+ stdio: ["ignore", "pipe", "pipe"],
217
+ detached: posix,
218
+ });
219
+ }
220
+ catch (err) {
221
+ resolve({ code: null, signal: null, output: "", timedOut, aborted, error: err instanceof Error ? err : new Error(String(err)) });
222
+ return;
223
+ }
224
+ const pgid = posix ? child.pid : undefined;
225
+ if (pgid) {
226
+ foregroundGroups.add(pgid);
227
+ installExitHandlers();
228
+ }
229
+ const kill = () => {
230
+ try {
231
+ if (pgid)
232
+ process.kill(-pgid, "SIGKILL");
233
+ else
234
+ child.kill("SIGKILL");
235
+ }
236
+ catch { /* already gone */ }
237
+ };
238
+ const timer = setTimeout(() => { timedOut = true; kill(); }, opts.timeout);
239
+ const onAbort = () => { aborted = true; kill(); };
240
+ if (opts.signal?.aborted)
241
+ onAbort();
242
+ else
243
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
244
+ child.stdout?.setEncoding("utf-8");
245
+ child.stderr?.setEncoding("utf-8");
246
+ child.stdout?.on("data", (chunk) => capture.push(chunk));
247
+ child.stderr?.on("data", (chunk) => capture.push(chunk));
248
+ const done = (result) => {
249
+ if (settled)
250
+ return;
251
+ settled = true;
252
+ if (pgid)
253
+ foregroundGroups.delete(pgid);
254
+ clearTimeout(timer);
255
+ opts.signal?.removeEventListener("abort", onAbort);
256
+ resolve({ ...result, output: capture.finish(), timedOut, aborted });
257
+ };
258
+ child.on("error", (err) => done({ code: null, signal: null, error: err }));
259
+ // "close" fires after stdio drains, so the tail is complete.
260
+ child.on("close", (code, signal) => done({ code, signal }));
261
+ });
262
+ }
32
263
  /**
33
264
  * Shell tool factory. `getPermissions` is read per call so /permissions and
34
265
  * /sandbox changes apply live; the kernel write fence derives its writable
@@ -37,9 +268,9 @@ let nextBgId = 1;
37
268
  export function createShellTool(getPermissions) {
38
269
  return {
39
270
  name: "shell",
40
- // Internal budget maxes at 120s; give the scheduler a little headroom so
41
- // the tool's own richer timeout message wins the race.
42
- timeoutMs: MAX_TIMEOUT_MS + 5_000,
271
+ // Give the scheduler a little headroom over the internal cap so the
272
+ // tool's own richer timeout message wins the race.
273
+ timeoutMs: shellTimeouts().maxMs + 5_000,
43
274
  description: "Run a shell command and return stdout + stderr. Use run_in_background for long-running commands (builds, test suites, dev servers). Use description to explain what the command does.",
44
275
  input_schema: {
45
276
  type: "object",
@@ -47,7 +278,7 @@ export function createShellTool(getPermissions) {
47
278
  command: { type: "string", description: "Shell command to execute." },
48
279
  description: { type: "string", description: "Human-readable description of what this command does (shown to user)." },
49
280
  cwd: { type: "string", description: "Working directory. Defaults to process cwd." },
50
- timeout: { type: "number", description: "Timeout in ms. Default: 30000, max: 120000." },
281
+ timeout: { type: "number", description: `Timeout in ms. Default: ${shellTimeouts().defaultMs}, max: ${shellTimeouts().maxMs}.` },
51
282
  run_in_background: { type: "boolean", description: "If true, run in background and return a task_id. Use task_output to get results later." },
52
283
  },
53
284
  required: ["command"],
@@ -55,7 +286,8 @@ export function createShellTool(getPermissions) {
55
286
  async execute(input, signal) {
56
287
  const command = input.command;
57
288
  const cwd = input.cwd || process.cwd();
58
- const timeout = Math.min(MAX_TIMEOUT_MS, input.timeout || DEFAULT_TIMEOUT_MS);
289
+ const limits = shellTimeouts();
290
+ const timeout = Math.min(limits.maxMs, input.timeout || limits.defaultMs);
59
291
  const description = input.description;
60
292
  const runInBackground = input.run_in_background;
61
293
  const safety = checkShellSafety(command);
@@ -73,6 +305,7 @@ export function createShellTool(getPermissions) {
73
305
  mode: perms?.sandboxMode ?? "off",
74
306
  workspaceRoot: perms?.projectRoot ?? process.cwd(),
75
307
  extraWritable: perms?.allowedPaths ?? [],
308
+ network: perms?.network !== "off",
76
309
  });
77
310
  }
78
311
  catch (err) {
@@ -107,38 +340,30 @@ export function createShellTool(getPermissions) {
107
340
  return { output: `${noticePrefix}Background task ${taskId} started${desc}${confined}. PID: ${child.pid}. Use task_output to get results.` };
108
341
  }
109
342
  // Foreground execution — async so concurrent tool batches actually run
110
- // concurrently (execFileSync blocked the event loop, making batch
111
- // concurrency fictional and timeouts unenforceable mid-call) and so the
112
- // scheduler's abort signal can kill a hung command.
113
- try {
114
- const { stdout, stderr } = await execFileAsync(exe, exeArgs, {
115
- cwd,
116
- encoding: "utf-8",
117
- timeout,
118
- maxBuffer: MAX_OUTPUT_BYTES,
119
- env: scrubEnv(),
120
- ...(signal ? { signal } : {}),
121
- });
122
- const combined = [stdout, stderr].filter(Boolean).join("\n").trim();
123
- return { output: noticePrefix + (combined || "(no output)") };
343
+ // concurrently and the scheduler's abort signal can kill a hung command.
344
+ const result = await runForeground(exe, exeArgs, { cwd, timeout, signal });
345
+ if (result.error)
346
+ return { output: noticePrefix + result.error.message, is_error: true };
347
+ const combined = result.output;
348
+ if (result.aborted) {
349
+ return { output: `${noticePrefix}Command was cancelled\n${combined}`.trim(), is_error: true };
124
350
  }
125
- catch (err) {
126
- if (err && typeof err === "object" && ("stdout" in err || "stderr" in err)) {
127
- const e = err;
128
- const combined = [e.stdout, e.stderr].filter(Boolean).join("\n").trim();
129
- if (e.killed || e.signal === "SIGTERM") {
130
- return { output: `${noticePrefix}Command timed out or was cancelled after ${timeout}ms\n${combined}`, is_error: true };
131
- }
132
- // Explain kernel write-fence denials so the model redirects instead
133
- // of retrying (classify combined output — commands often 2>&1)
134
- const denial = decision.sandboxed
135
- ? classifySandboxDenial(combined, perms?.projectRoot ?? process.cwd())
136
- : null;
137
- return { output: `${noticePrefix}Exit code ${typeof e.code === "number" ? e.code : 1}\n${combined}${denial ?? ""}`, is_error: true };
138
- }
139
- const msg = err instanceof Error ? err.message : String(err);
140
- return { output: msg, is_error: true };
351
+ if (result.timedOut) {
352
+ return {
353
+ output: `${noticePrefix}Command timed out after ${timeout}ms (pass a larger timeout, up to ${limits.maxMs}ms, or use run_in_background)\n${combined}`.trim(),
354
+ is_error: true,
355
+ };
141
356
  }
357
+ if (result.code === 0)
358
+ return { output: noticePrefix + (combined || "(no output)") };
359
+ // Explain kernel write-fence denials so the model redirects instead
360
+ // of retrying (classify combined output — commands often 2>&1)
361
+ const denial = decision.sandboxed
362
+ ? classifySandboxDenial(combined, perms?.projectRoot ?? process.cwd())
363
+ ?? (perms?.network === "off" ? classifyNetworkDenial(combined) : null)
364
+ : null;
365
+ const status = result.code !== null ? `Exit code ${result.code}` : `Killed by ${result.signal ?? "signal"}`;
366
+ return { output: `${noticePrefix}${status}\n${combined}${denial ?? ""}`, is_error: true };
142
367
  },
143
368
  };
144
369
  }
@@ -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
+ }