@phren/agent 0.1.15 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +86 -0
  2. package/dist/agent-loop/index.js +239 -65
  3. package/dist/agent-loop/stream.js +212 -29
  4. package/dist/agent-loop/types.js +15 -2
  5. package/dist/checkpoint.js +103 -22
  6. package/dist/commands/info.js +30 -15
  7. package/dist/commands/model.js +6 -2
  8. package/dist/commands/review.js +183 -0
  9. package/dist/commands/session.js +70 -7
  10. package/dist/commands.js +168 -12
  11. package/dist/config.js +87 -10
  12. package/dist/context/compactor.js +239 -0
  13. package/dist/context/pruner.js +39 -13
  14. package/dist/context/token-counter.js +33 -1
  15. package/dist/custom-commands.js +69 -0
  16. package/dist/guards/repeat-tool-reminder.js +75 -0
  17. package/dist/headless.js +115 -0
  18. package/dist/herdr-hooks.js +71 -0
  19. package/dist/index.js +351 -48
  20. package/dist/mcp-client.js +434 -73
  21. package/dist/mcp-oauth.js +121 -0
  22. package/dist/memory/anti-patterns.js +7 -3
  23. package/dist/memory/auto-capture.js +7 -3
  24. package/dist/memory/context.js +92 -73
  25. package/dist/memory/project-context.js +24 -5
  26. package/dist/memory/provenance.js +15 -0
  27. package/dist/memory/review-triage.js +166 -0
  28. package/dist/memory/session.js +36 -1
  29. package/dist/models.js +152 -19
  30. package/dist/multi/child-entry.js +65 -10
  31. package/dist/multi/diff-renderer.js +3 -3
  32. package/dist/multi/markdown.js +125 -27
  33. package/dist/multi/provider-manager.js +8 -0
  34. package/dist/multi/publish.js +72 -0
  35. package/dist/multi/spawner.js +45 -4
  36. package/dist/multi/syntax-highlight.js +25 -4
  37. package/dist/multi/types.js +1 -1
  38. package/dist/permissions/allowlist.js +86 -13
  39. package/dist/permissions/checker.js +42 -7
  40. package/dist/permissions/kernel-sandbox.js +197 -0
  41. package/dist/permissions/prompt.js +10 -1
  42. package/dist/permissions/sandbox.js +40 -17
  43. package/dist/providers/anthropic.js +154 -7
  44. package/dist/providers/codex-auth.js +28 -0
  45. package/dist/providers/codex.js +134 -23
  46. package/dist/providers/history.js +35 -0
  47. package/dist/providers/ollama.js +37 -6
  48. package/dist/providers/openai-compat.js +171 -74
  49. package/dist/providers/openrouter.js +47 -17
  50. package/dist/providers/replay.js +62 -0
  51. package/dist/providers/resolve.js +41 -7
  52. package/dist/providers/retry.js +38 -5
  53. package/dist/providers/types.js +9 -1
  54. package/dist/repl.js +47 -5
  55. package/dist/session/log.js +217 -0
  56. package/dist/session/persist.js +190 -0
  57. package/dist/settings.js +42 -26
  58. package/dist/system-prompt.js +18 -2
  59. package/dist/tools/apply-patch.js +355 -0
  60. package/dist/tools/edit-engine.js +287 -0
  61. package/dist/tools/edit-file.js +86 -27
  62. package/dist/tools/grep.js +25 -10
  63. package/dist/tools/lint-test.js +0 -22
  64. package/dist/tools/mcp-resources.js +51 -6
  65. package/dist/tools/phren-finding.js +12 -4
  66. package/dist/tools/phren-search.js +7 -2
  67. package/dist/tools/read-file.js +37 -9
  68. package/dist/tools/read-image.js +76 -0
  69. package/dist/tools/registry.js +27 -5
  70. package/dist/tools/shell.js +134 -71
  71. package/dist/tools/skill.js +20 -20
  72. package/dist/tools/spawn-agent.js +77 -13
  73. package/dist/tools/update-plan.js +48 -0
  74. package/dist/tools/web-fetch.js +110 -12
  75. package/dist/tools/web-search.js +4 -4
  76. package/dist/tui/components/App.js +98 -26
  77. package/dist/tui/components/ApprovalPanel.js +8 -0
  78. package/dist/tui/components/InputArea.js +5 -5
  79. package/dist/tui/components/ModelPicker.js +43 -0
  80. package/dist/tui/components/PhrenInput.js +10 -5
  81. package/dist/tui/components/PlanReview.js +7 -0
  82. package/dist/tui/components/ShortcutHelp.js +5 -0
  83. package/dist/tui/components/StatusBar.js +46 -20
  84. package/dist/tui/components/SteerQueue.js +1 -1
  85. package/dist/tui/components/ThinkingIndicator.js +6 -4
  86. package/dist/tui/components/ToolCall.js +10 -4
  87. package/dist/tui/components/ToolDetail.js +21 -0
  88. package/dist/tui/help.js +6 -0
  89. package/dist/tui/hooks/useKeyboardShortcuts.js +15 -1
  90. package/dist/tui/index.js +0 -1
  91. package/dist/tui/ink-entry.js +317 -33
  92. package/dist/tui/tool-render.js +1 -1
  93. package/dist/user-hooks.js +171 -0
  94. package/package.json +14 -8
  95. package/dist/multi/multi-commands.js +0 -170
  96. package/dist/multi/multi-events.js +0 -98
  97. package/dist/multi/multi-render.js +0 -147
  98. package/dist/multi/pane.js +0 -28
  99. package/dist/multi/tui-multi.js +0 -200
  100. package/dist/permissions/privacy.js +0 -248
  101. package/dist/tui/components/AgentMessage.js +0 -5
  102. package/dist/tui/components/ChatMessage.js +0 -23
  103. package/dist/tui/components/CodeBlock.js +0 -8
  104. package/dist/tui/components/Separator.js +0 -7
  105. package/dist/tui/components/StreamingText.js +0 -5
  106. package/dist/tui/components/UserMessage.js +0 -5
  107. package/dist/tui/menu-mode.js +0 -86
  108. package/dist/tui/mouse.js +0 -71
  109. package/dist/tui/terminal-control.js +0 -62
  110. package/dist/tui.js +0 -781
@@ -9,27 +9,44 @@ const RESET = `${ESC}0m`;
9
9
  const BOLD = `${ESC}1m`;
10
10
  const DIM = `${ESC}2m`;
11
11
  const ITALIC = `${ESC}3m`;
12
+ const STRIKE = `${ESC}9m`;
12
13
  const CYAN = `${ESC}36m`;
13
14
  const YELLOW = `${ESC}33m`;
14
- const GREEN = `${ESC}32m`;
15
- const MAGENTA = `${ESC}35m`;
15
+ const _GREEN = `${ESC}32m`;
16
+ const _MAGENTA = `${ESC}35m`;
16
17
  const INVERSE = `${ESC}7m`;
17
- const MAX_WIDTH = Math.min(process.stdout.columns || 80, 120);
18
+ const MAX_WIDTH_CAP = 120;
18
19
  /** Render basic markdown to ANSI-colored terminal text. */
19
- export function renderMarkdown(text, colors) {
20
+ export function renderMarkdown(text, colors, width) {
20
21
  const h = colors?.heading ?? BOLD + YELLOW;
21
22
  const bd = colors?.bold ?? BOLD;
22
23
  const it = colors?.italic ?? ITALIC;
23
24
  const cd = colors?.code ?? CYAN + INVERSE;
24
25
  const cbb = colors?.codeBlockBorder ?? DIM;
26
+ const cbl = colors?.codeBlockLabel ?? DIM + YELLOW;
25
27
  const lnk = colors?.link ?? `${ESC}4m${CYAN}`;
26
28
  const rst = colors?.reset ?? RESET;
29
+ const maxWidth = width ?? Math.min(process.stdout.columns || 80, MAX_WIDTH_CAP);
30
+ const syn = colors?.syntax;
31
+ const syntaxColors = syn ? {
32
+ keyword: syn.keyword ?? cd,
33
+ string: syn.string ?? cd,
34
+ number: syn.number ?? cd,
35
+ comment: syn.comment ?? cbb,
36
+ type: syn.type ?? cd,
37
+ variable: syn.variable ?? cd,
38
+ operator: syn.operator ?? cd,
39
+ function: syn.function ?? cd,
40
+ punctuation: syn.punctuation ?? cd,
41
+ reset: syn.reset ?? rst,
42
+ } : undefined;
27
43
  const lines = text.split("\n");
28
44
  const out = [];
29
45
  let inCodeBlock = false;
30
46
  let codeLang = "";
31
47
  let codeBuffer = [];
32
- for (const line of lines) {
48
+ for (let i = 0; i < lines.length; i++) {
49
+ const line = lines[i];
33
50
  // Code block fences
34
51
  if (line.trimStart().startsWith("```")) {
35
52
  if (!inCodeBlock) {
@@ -37,21 +54,12 @@ export function renderMarkdown(text, colors) {
37
54
  codeLang = line.trimStart().slice(3).trim();
38
55
  codeBuffer = [];
39
56
  const label = codeLang ? ` ${codeLang}` : "";
40
- out.push(`${cbb} ┌──${label}${"─".repeat(Math.max(0, MAX_WIDTH - 6 - label.length))}${rst}`);
57
+ const fill = Math.max(0, maxWidth - 5 - label.length);
58
+ out.push(`${cbb} ┌──${rst}${cbl}${label}${rst}${cbb}${"─".repeat(fill)}${rst}`);
41
59
  }
42
60
  else {
43
61
  // Flush code buffer through syntax highlighter
44
62
  const lang = codeLang ? detectLanguage(codeLang) : "generic";
45
- const syntaxColors = colors ? {
46
- keyword: colors.code,
47
- string: colors.code,
48
- number: colors.code,
49
- comment: colors.codeBlockBorder,
50
- type: colors.code,
51
- variable: colors.code,
52
- operator: colors.code,
53
- reset: colors.reset,
54
- } : undefined;
55
63
  const highlighted = highlightCode(codeBuffer.join("\n"), lang, syntaxColors);
56
64
  for (const hl of highlighted.split("\n")) {
57
65
  out.push(`${cbb} │ ${rst}${hl}`);
@@ -59,12 +67,16 @@ export function renderMarkdown(text, colors) {
59
67
  inCodeBlock = false;
60
68
  codeLang = "";
61
69
  codeBuffer = [];
62
- out.push(`${cbb} └${"─".repeat(MAX_WIDTH - 3)}${rst}`);
70
+ out.push(`${cbb} └${"─".repeat(Math.max(0, maxWidth - 3))}${rst}`);
63
71
  }
64
72
  continue;
65
73
  }
66
74
  if (inCodeBlock) {
67
- codeBuffer.push(line.slice(0, MAX_WIDTH - 4));
75
+ codeBuffer.push(line.slice(0, Math.max(0, maxWidth - 4)));
76
+ continue;
77
+ }
78
+ if (/^\s{0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/.test(line)) {
79
+ out.push(`${cbb}${"─".repeat(maxWidth)}${rst}`);
68
80
  continue;
69
81
  }
70
82
  // Headers
@@ -83,22 +95,44 @@ export function renderMarkdown(text, colors) {
83
95
  out.push(`${h}${h1[1]}${rst}`);
84
96
  continue;
85
97
  }
98
+ const quote = line.match(/^(\s*)>\s?(.*)$/);
99
+ if (quote) {
100
+ const content = renderInline(quote[2], bd, it, cd, rst, lnk);
101
+ out.push(`${quote[1]}${cbb}│ ${rst}${DIM}${content}${rst}`);
102
+ continue;
103
+ }
104
+ if (i + 1 < lines.length && isTableRow(line) && isSeparatorRow(lines[i + 1])) {
105
+ const table = renderTable(lines, i, { bd, it, cd, rst, lnk, cbb });
106
+ out.push(...table.rendered);
107
+ i = table.next - 1;
108
+ continue;
109
+ }
110
+ const task = line.match(/^(\s*)[*+-]\s+\[([ xX])\]\s+(.*)$/);
111
+ if (task) {
112
+ const depth = indentDepth(task[1]);
113
+ const blt = colors?.bullet ?? DIM + BOLD;
114
+ const box = task[2].toLowerCase() === "x" ? "☑" : "☐";
115
+ const content = renderInline(task[3], bd, it, cd, rst, lnk);
116
+ out.push(`${" ".repeat(depth + 1)}${blt}${box}${rst} ${content}`);
117
+ continue;
118
+ }
86
119
  // Bullet lists (-, *, +)
87
120
  const bullet = line.match(/^(\s*)[*+-]\s+(.+)/);
88
121
  if (bullet) {
89
- const indent = bullet[1];
90
- const content = renderInline(bullet[2], bd, it, cd, rst, lnk);
122
+ const depth = indentDepth(bullet[1]);
123
+ const marks = ["·", "◦", "▪", "‣"];
124
+ const mark = marks[depth % marks.length];
91
125
  const blt = colors?.bullet ?? DIM + BOLD;
92
- out.push(`${indent} ${blt}·${rst} ${content}`);
126
+ const content = renderInline(bullet[2], bd, it, cd, rst, lnk);
127
+ out.push(`${" ".repeat(depth + 1)}${blt}${mark}${rst} ${content}`);
93
128
  continue;
94
129
  }
95
130
  // Numbered lists
96
- const numbered = line.match(/^(\s*)\d+[.)]\s+(.+)/);
131
+ const numbered = line.match(/^(\s*)(\d+[.)])\s+(.+)/);
97
132
  if (numbered) {
98
- const indent = numbered[1];
99
- const num = line.match(/^(\s*)(\d+[.)])/);
100
- const content = renderInline(numbered[2], bd, it, cd, rst, lnk);
101
- out.push(`${indent} ${DIM}${num[2]}${rst} ${content}`);
133
+ const depth = indentDepth(numbered[1]);
134
+ const content = renderInline(numbered[3], bd, it, cd, rst, lnk);
135
+ out.push(`${" ".repeat(depth + 1)}${DIM}${numbered[2]}${rst} ${content}`);
102
136
  continue;
103
137
  }
104
138
  // Regular line — apply inline formatting
@@ -106,6 +140,69 @@ export function renderMarkdown(text, colors) {
106
140
  }
107
141
  return out.join("\n");
108
142
  }
143
+ function indentDepth(indent) {
144
+ return Math.floor(indent.replace(/\t/g, " ").length / 2);
145
+ }
146
+ function isTableRow(line) {
147
+ return line.includes("|");
148
+ }
149
+ function splitTableRow(line) {
150
+ let s = line.trim();
151
+ if (s.startsWith("|"))
152
+ s = s.slice(1);
153
+ if (s.endsWith("|"))
154
+ s = s.slice(0, -1);
155
+ return s.split("|").map((cell) => cell.trim());
156
+ }
157
+ function isSeparatorRow(line) {
158
+ if (!line.includes("|") || !line.includes("-"))
159
+ return false;
160
+ const cells = splitTableRow(line);
161
+ return cells.length > 0 && cells.every((cell) => /^:?-+:?$/.test(cell));
162
+ }
163
+ function renderTable(lines, start, ctx) {
164
+ const { bd, it, cd, rst, lnk, cbb } = ctx;
165
+ try {
166
+ const header = splitTableRow(lines[start]);
167
+ const aligns = splitTableRow(lines[start + 1]).map((cell) => {
168
+ const left = cell.startsWith(":");
169
+ const right = cell.endsWith(":");
170
+ return left && right ? "center" : right ? "right" : "left";
171
+ });
172
+ const rows = [];
173
+ let j = start + 2;
174
+ while (j < lines.length && isTableRow(lines[j]) && !isSeparatorRow(lines[j])) {
175
+ const cells = splitTableRow(lines[j]);
176
+ rows.push(header.map((_, c) => cells[c] ?? ""));
177
+ j++;
178
+ }
179
+ const cols = header.length;
180
+ const widths = header.map((cell, c) => Math.max(cell.length, ...rows.map((row) => row[c]?.length ?? 0)));
181
+ const pad = (text, width, align) => {
182
+ const padding = Math.max(0, width - text.length);
183
+ if (align === "right")
184
+ return " ".repeat(padding) + text;
185
+ if (align === "center") {
186
+ const left = Math.floor(padding / 2);
187
+ return " ".repeat(left) + text + " ".repeat(padding - left);
188
+ }
189
+ return text + " ".repeat(padding);
190
+ };
191
+ const renderRow = (cells, isHeader) => {
192
+ const parts = cells.slice(0, cols).map((cell, c) => {
193
+ const aligned = pad(cell, widths[c], aligns[c] ?? "left");
194
+ return isHeader ? `${bd}${aligned}${rst}` : renderInline(aligned, bd, it, cd, rst, lnk);
195
+ });
196
+ return `${cbb}│${rst} ${parts.join(` ${cbb}│${rst} `)} ${cbb}│${rst}`;
197
+ };
198
+ const separator = `${cbb}├${widths.map((w) => "─".repeat(w + 2)).join("┼")}┤${rst}`;
199
+ const rendered = [renderRow(header, true), separator, ...rows.map((row) => renderRow(row, false))];
200
+ return { rendered, next: j };
201
+ }
202
+ catch {
203
+ return { rendered: [renderInline(lines[start], bd, it, cd, rst, lnk)], next: start + 1 };
204
+ }
205
+ }
109
206
  /** Wrap text in an OSC 8 hyperlink escape sequence. */
110
207
  function osc8Link(url, text, linkStyle, reset) {
111
208
  return `\x1b]8;;${url}\x07${linkStyle}${text}${reset}\x1b]8;;\x07`;
@@ -114,11 +211,12 @@ function osc8Link(url, text, linkStyle, reset) {
114
211
  function renderInline(text, bold = BOLD, italic = ITALIC, code = CYAN + INVERSE, reset = RESET, link = `${ESC}4m${CYAN}`) {
115
212
  let result = text;
116
213
  // Inline code (must go first to avoid bold/italic inside code)
117
- result = result.replace(/`([^`]+)`/g, `${code} $1 ${reset}`);
214
+ result = result.replace(/`([^`]+)`/g, `${code}$1${reset}`);
118
215
  // Markdown links [text](url) — render as OSC 8 hyperlinks
119
216
  result = result.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_match, linkText, url) => {
120
217
  return osc8Link(url, linkText, link, reset);
121
218
  });
219
+ result = result.replace(/~~(.+?)~~/g, `${STRIKE}$1${reset}`);
122
220
  // Bold+italic (***text*** or ___text___)
123
221
  result = result.replace(/\*\*\*(.+?)\*\*\*/g, `${bold}${italic}$1${reset}`);
124
222
  result = result.replace(/___(.+?)___/g, `${bold}${italic}$1${reset}`);
@@ -48,6 +48,14 @@ export function getProviderStatuses() {
48
48
  authSource: auth.get("openai-codex")?.source ?? "none",
49
49
  models: getBuiltinModels("openai-codex").map((model) => model.id),
50
50
  },
51
+ {
52
+ name: "deepseek",
53
+ configured: !!process.env.DEEPSEEK_API_KEY,
54
+ authMethod: "api-key",
55
+ authSource: process.env.DEEPSEEK_API_KEY ? "env" : "none",
56
+ keyEnvVar: "DEEPSEEK_API_KEY",
57
+ models: getBuiltinModels("deepseek").map((model) => model.id),
58
+ },
51
59
  {
52
60
  name: "ollama",
53
61
  configured: (process.env.PHREN_OLLAMA_URL ?? "").toLowerCase() !== "off",
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Publish this process's agents so phren can see them.
3
+ *
4
+ * The phren shell runs in a different process, so the spawner writes its live
5
+ * agents to `<store>/.runtime/agents/<pid>.json` and removes the file on exit.
6
+ * phren's agents overlay reads that directory, which is what lets a graph open
7
+ * in one terminal show the agents this process is running in another.
8
+ *
9
+ * Entirely best-effort: publishing is a courtesy to another tool, and must
10
+ * never interfere with running agents.
11
+ */
12
+ import * as fs from "fs";
13
+ import * as path from "path";
14
+ /** phren's vocabulary, which is narrower than the spawner's. */
15
+ function toPhrenStatus(status) {
16
+ switch (status) {
17
+ case "running":
18
+ case "starting":
19
+ return "working";
20
+ case "idle":
21
+ return "idle";
22
+ case "error":
23
+ return "error";
24
+ default:
25
+ return "done";
26
+ }
27
+ }
28
+ /** No-op publisher, for when there is no phren store to publish into. */
29
+ const INERT = { publish: () => { }, stop: () => { } };
30
+ export function createAgentPublisher(phrenPath, pid = process.pid) {
31
+ if (!phrenPath)
32
+ return INERT;
33
+ const dir = path.join(phrenPath, ".runtime", "agents");
34
+ const file = path.join(dir, `${pid}.json`);
35
+ let stopped = false;
36
+ const remove = () => {
37
+ try {
38
+ fs.rmSync(file, { force: true });
39
+ }
40
+ catch { /* best effort */ }
41
+ };
42
+ const publisher = {
43
+ publish(agents) {
44
+ if (stopped)
45
+ return;
46
+ try {
47
+ fs.mkdirSync(dir, { recursive: true });
48
+ const records = agents.map((agent) => ({
49
+ id: `${pid}:${agent.id}`,
50
+ label: agent.displayName || agent.task.slice(0, 60),
51
+ cwd: agent.cwd ?? process.cwd(),
52
+ status: toPhrenStatus(agent.status),
53
+ kind: "phren-agent",
54
+ }));
55
+ const tmp = `${file}.tmp`;
56
+ fs.writeFileSync(tmp, JSON.stringify(records));
57
+ fs.renameSync(tmp, file);
58
+ }
59
+ catch { /* best effort: never break an agent to publish it */ }
60
+ },
61
+ stop() {
62
+ stopped = true;
63
+ remove();
64
+ },
65
+ };
66
+ // Deliberately no process-level exit hook. Registering one per publisher put
67
+ // filesystem work on the exit path, which is enough to stop a process
68
+ // finishing when the path is unwritable, and it is redundant besides: the
69
+ // caller removes the file in a finally, and a crash is already covered by the
70
+ // reader treating anything untouched for a few minutes as gone.
71
+ return publisher;
72
+ }
@@ -12,7 +12,8 @@ import { fork } from "node:child_process";
12
12
  import { fileURLToPath } from "node:url";
13
13
  import { dirname, join } from "node:path";
14
14
  import { EventEmitter } from "node:events";
15
- import { createWorktree, hasWorktreeChanges, removeWorktree } from "./worktree.js";
15
+ import { MAX_SPAWN_DEPTH } from "./types.js";
16
+ import { createWorktree, hasWorktreeChanges, removeWorktree, } from "./worktree.js";
16
17
  const __filename = fileURLToPath(import.meta.url);
17
18
  const __dirname = dirname(__filename);
18
19
  /** Resolved path to the child-entry module. */
@@ -28,6 +29,7 @@ const ENV_FORWARD_KEYS = [
28
29
  "PHREN_PATH",
29
30
  "PHREN_PROFILE",
30
31
  "PHREN_DEBUG",
32
+ "PHREN_AGENT_MACOS_SANDBOX",
31
33
  "HOME",
32
34
  "USERPROFILE",
33
35
  "PATH",
@@ -37,9 +39,30 @@ export class AgentSpawner extends EventEmitter {
37
39
  agents = new Map();
38
40
  processes = new Map();
39
41
  nextId = 1;
42
+ costTracker;
43
+ depth;
44
+ maxDepth;
45
+ getPermissionDefaults;
46
+ constructor(opts = {}) {
47
+ super();
48
+ this.costTracker = opts.costTracker ?? null;
49
+ this.depth = opts.depth ?? 0;
50
+ this.maxDepth = opts.maxDepth ?? MAX_SPAWN_DEPTH;
51
+ this.getPermissionDefaults = opts.getPermissionDefaults;
52
+ }
53
+ canSpawn() {
54
+ return this.depth < this.maxDepth;
55
+ }
56
+ setCostTracker(tracker) {
57
+ this.costTracker = tracker;
58
+ }
40
59
  /** Spawn a new child agent. Returns the agent ID. */
41
60
  spawn(opts) {
61
+ if (!this.canSpawn()) {
62
+ throw new Error(`Maximum subagent depth (${this.maxDepth}) reached`);
63
+ }
42
64
  const agentId = `agent-${this.nextId++}`;
65
+ const defaults = this.getPermissionDefaults?.();
43
66
  // Build forwarded env
44
67
  const childEnv = {};
45
68
  for (const key of ENV_FORWARD_KEYS) {
@@ -52,21 +75,25 @@ export class AgentSpawner extends EventEmitter {
52
75
  type: "spawn",
53
76
  agentId,
54
77
  task: opts.task,
55
- cwd: opts.cwd ?? process.cwd(),
78
+ cwd: opts.cwd ?? defaults?.projectRoot ?? process.cwd(),
56
79
  provider: opts.provider,
57
80
  model: opts.model,
58
81
  project: opts.project,
59
- permissions: opts.permissions ?? "auto-confirm",
82
+ permissions: opts.permissions ?? defaults?.mode ?? "auto-confirm",
60
83
  maxTurns: opts.maxTurns ?? 50,
61
84
  budget: opts.budget ?? null,
62
85
  plan: opts.plan ?? false,
63
86
  verbose: opts.verbose ?? false,
64
87
  env: childEnv,
65
88
  agentType: opts.agentType,
89
+ depth: this.depth + 1,
90
+ sandboxMode: opts.sandboxMode ?? defaults?.sandboxMode,
91
+ allowedPaths: opts.allowedPaths ?? defaults?.allowedPaths ?? [],
66
92
  };
67
93
  const entry = {
68
94
  id: agentId,
69
95
  task: opts.task,
96
+ cwd: payload.cwd,
70
97
  displayName: opts.displayName,
71
98
  status: "starting",
72
99
  startedAt: Date.now(),
@@ -76,7 +103,7 @@ export class AgentSpawner extends EventEmitter {
76
103
  const child = fork(CHILD_ENTRY, [], {
77
104
  stdio: ["pipe", "pipe", "pipe", "ipc"],
78
105
  env: { ...childEnv, FORCE_COLOR: "0" },
79
- cwd: opts.cwd ?? process.cwd(),
106
+ cwd: payload.cwd,
80
107
  });
81
108
  this.processes.set(agentId, child);
82
109
  entry.pid = child.pid;
@@ -160,6 +187,7 @@ export class AgentSpawner extends EventEmitter {
160
187
  // Don't mark as "done" status — child stays alive and will go idle
161
188
  agent.result = msg.result;
162
189
  }
190
+ this.aggregateChildCost(msg.result);
163
191
  this.emit("done", msg.agentId, msg.result);
164
192
  break;
165
193
  case "error":
@@ -183,6 +211,19 @@ export class AgentSpawner extends EventEmitter {
183
211
  break;
184
212
  }
185
213
  }
214
+ aggregateChildCost(result) {
215
+ const tracker = this.costTracker;
216
+ if (!tracker)
217
+ return;
218
+ const inputTokens = result.inputTokens ?? 0;
219
+ const outputTokens = result.outputTokens ?? 0;
220
+ const costUsd = result.costUsd ?? 0;
221
+ if (inputTokens === 0 && outputTokens === 0 && costUsd === 0)
222
+ return;
223
+ tracker.totalInputTokens += inputTokens;
224
+ tracker.totalOutputTokens += outputTokens;
225
+ tracker.totalCost += costUsd;
226
+ }
186
227
  /** Route a direct message from one agent to another. */
187
228
  routeDirectMessage(from, to, content) {
188
229
  this.emit("message", from, to, content);
@@ -31,11 +31,18 @@ export function detectLanguage(filename) {
31
31
  function colorize(line, rules, resetSeq = RESET) {
32
32
  // We process rules sequentially; each rule operates on uncolored segments only.
33
33
  // Segments already colored are wrapped in \x1b and end with RESET.
34
+ const tokens = [];
34
35
  let result = line;
35
36
  for (const [re, color] of rules) {
36
- result = result.replace(re, (match) => `${color}${match}${resetSeq}`);
37
+ result = result.replace(re, (match) => {
38
+ const token = `\uE000${String.fromCharCode(0xE100 + tokens.length)}\uE001`;
39
+ tokens.push(`${color}${match}${resetSeq}`);
40
+ return token;
41
+ });
37
42
  }
38
- return result;
43
+ return result.replace(/\uE000([\uE100-\uF8FF])\uE001/g, (_match, ch) => {
44
+ return tokens[ch.charCodeAt(0) - 0xE100] ?? "";
45
+ });
39
46
  }
40
47
  // ── TypeScript / JavaScript ─────────────────────────────────────────
41
48
  const TS_KEYWORDS = /\b(const|let|var|function|return|if|else|for|while|do|switch|case|break|continue|new|typeof|instanceof|void|delete|throw|try|catch|finally|import|export|from|default|class|extends|implements|async|await|yield|type|interface|enum|namespace|declare|readonly|abstract|static|get|set|of|in|as|is)\b/g;
@@ -60,9 +67,13 @@ function highlightTSCode(line, colors) {
60
67
  return colorize(line, [
61
68
  [/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/g, colors?.string ?? GREEN], // strings
62
69
  [/\b\d+(\.\d+)?\b/g, colors?.number ?? YELLOW], // numbers
63
- [TS_KEYWORDS, colors?.keyword ?? MAGENTA], // keywords
70
+ [/(?<=\bfunction\s+)[A-Za-z_$][\w$]*/g, colors?.function ?? colors?.type ?? CYAN],
71
+ [/(?<=\.)[A-Za-z_$][\w$]*(?=\s*\()/g, colors?.function ?? colors?.type ?? CYAN],
64
72
  [/(?<=[:]\s*)\b[A-Z]\w*/g, colors?.type ?? CYAN], // types after :
65
73
  [/(?<=\bas\s+)\b[A-Z]\w*/g, colors?.type ?? CYAN], // types after as
74
+ [TS_KEYWORDS, colors?.keyword ?? MAGENTA], // keywords
75
+ [/[{}()[\]]/g, colors?.punctuation ?? colors?.type ?? CYAN],
76
+ [/[+\-*/%=<>!&|^~?]+/g, colors?.operator ?? CYAN],
66
77
  ], rst);
67
78
  }
68
79
  // ── Python ──────────────────────────────────────────────────────────
@@ -88,7 +99,11 @@ function highlightPYCode(line, colors) {
88
99
  return colorize(line, [
89
100
  [/""".*?"""|'''.*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, colors?.string ?? GREEN], // strings
90
101
  [/\b\d+(\.\d+)?\b/g, colors?.number ?? YELLOW], // numbers
102
+ [/(?<=\bdef\s+)[A-Za-z_]\w*/g, colors?.function ?? colors?.type ?? CYAN],
103
+ [/(?<=\.)[A-Za-z_]\w*(?=\s*\()/g, colors?.function ?? colors?.type ?? CYAN],
91
104
  [PY_KEYWORDS, colors?.keyword ?? MAGENTA], // keywords
105
+ [/[{}()[\]]/g, colors?.punctuation ?? colors?.type ?? CYAN],
106
+ [/[+\-*/%=<>!&|^~@]+/g, colors?.operator ?? CYAN],
92
107
  ], rst);
93
108
  }
94
109
  // ── Bash / Shell ────────────────────────────────────────────────────
@@ -112,7 +127,9 @@ function highlightBashCode(line, colors) {
112
127
  [/\$\{?\w+\}?/g, colors?.variable ?? CYAN], // variables
113
128
  [/\b\d+\b/g, colors?.number ?? YELLOW], // numbers
114
129
  [BASH_KEYWORDS, colors?.keyword ?? MAGENTA], // keywords
115
- [/(?<=\|\s*)\w+/g, BOLD], // commands after pipe
130
+ [/(?<=\|\s*)\w+/g, colors?.function ?? BOLD], // commands after pipe
131
+ [/[{}()[\]]/g, colors?.punctuation ?? colors?.type ?? CYAN],
132
+ [/[|&<>]+/g, colors?.operator ?? CYAN],
116
133
  ], rst);
117
134
  }
118
135
  // ── JSON ────────────────────────────────────────────────────────────
@@ -123,6 +140,7 @@ const jsonHighlight = (line, colors) => {
123
140
  [/:\s*"[^"]*"/g, colors?.string ?? GREEN], // string values
124
141
  [/\b\d+(\.\d+)?([eE][+-]?\d+)?\b/g, colors?.number ?? YELLOW], // numbers
125
142
  [/\b(true|false|null)\b/g, colors?.keyword ?? MAGENTA], // literals
143
+ [/[{}[\],:]/g, colors?.punctuation ?? colors?.type ?? CYAN],
126
144
  ], rst);
127
145
  };
128
146
  // ── CSS / SCSS ──────────────────────────────────────────────────────
@@ -155,6 +173,9 @@ const genericHighlight = (line, colors) => {
155
173
  [/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, colors?.string ?? GREEN], // strings
156
174
  [/\/\/.*$|#.*$/g, colors?.comment ?? GRAY], // comments
157
175
  [/\b\d+(\.\d+)?\b/g, colors?.number ?? YELLOW], // numbers
176
+ [/(?<=\.)[A-Za-z_$][\w$]*(?=\s*\()/g, colors?.function ?? colors?.type ?? CYAN],
177
+ [/[{}()[\]]/g, colors?.punctuation ?? colors?.type ?? CYAN],
178
+ [/[+\-*/%=<>!&|^~?]+/g, colors?.operator ?? CYAN],
158
179
  ], rst);
159
180
  };
160
181
  // ── Dispatcher ──────────────────────────────────────────────────────
@@ -4,4 +4,4 @@
4
4
  * All messages flow over Node's built-in IPC channel (process.send / process.on("message")).
5
5
  * Each message has a `type` discriminant for exhaustive switching.
6
6
  */
7
- export {};
7
+ export const MAX_SPAWN_DEPTH = 2;
@@ -5,7 +5,13 @@
5
5
  * in the permission prompt. Checked before mode-based rules so approved tools
6
6
  * skip the interactive prompt for the rest of the session.
7
7
  */
8
+ import * as fs from "fs";
9
+ import * as os from "os";
10
+ import * as path from "path";
11
+ export const PERSISTED_ALLOWLIST_FILE = path.join(os.homedir(), ".phren-agent", "permissions.json");
8
12
  const sessionAllowlist = [];
13
+ const persistentAllowlist = [];
14
+ let persistentProjectRoot = null;
9
15
  /**
10
16
  * Extract a matchable pattern from tool input.
11
17
  * - File tools: the path argument
@@ -23,31 +29,98 @@ export function extractPattern(toolName, input) {
23
29
  return filePath;
24
30
  return "*";
25
31
  }
32
+ function matches(entry, toolName, pattern) {
33
+ if (entry.toolName !== toolName)
34
+ return false;
35
+ if (entry.pattern === "*")
36
+ return true;
37
+ // For file paths: exact match or child path (boundary-aware to prevent prefix collisions)
38
+ if (pattern === entry.pattern || pattern.startsWith(entry.pattern.endsWith("/") ? entry.pattern : entry.pattern + "/"))
39
+ return true;
40
+ // For shell commands: match the binary name
41
+ return entry.pattern === pattern;
42
+ }
26
43
  /** Check if a tool call is in the session allowlist. */
27
44
  export function isAllowed(toolName, input) {
28
- if (sessionAllowlist.length === 0)
45
+ if (sessionAllowlist.length === 0 && persistentAllowlist.length === 0)
29
46
  return false;
30
47
  const pattern = extractPattern(toolName, input);
31
- return sessionAllowlist.some((entry) => {
32
- if (entry.toolName !== toolName)
33
- return false;
34
- if (entry.pattern === "*")
35
- return true;
36
- // For file paths: exact match or child path (boundary-aware to prevent prefix collisions)
37
- if (pattern === entry.pattern || pattern.startsWith(entry.pattern.endsWith("/") ? entry.pattern : entry.pattern + "/"))
38
- return true;
39
- // For shell commands: match the binary name
40
- return entry.pattern === pattern;
41
- });
48
+ return (sessionAllowlist.some((entry) => matches(entry, toolName, pattern)) ||
49
+ persistentAllowlist.some((entry) => matches(entry, toolName, pattern)));
50
+ }
51
+ function readPersisted() {
52
+ try {
53
+ const raw = JSON.parse(fs.readFileSync(PERSISTED_ALLOWLIST_FILE, "utf-8"));
54
+ if (!raw || typeof raw !== "object")
55
+ throw new Error("not an object");
56
+ return {
57
+ version: 1,
58
+ global: Array.isArray(raw.global) ? raw.global.filter(isEntry) : [],
59
+ projects: raw.projects && typeof raw.projects === "object" ? raw.projects : {},
60
+ };
61
+ }
62
+ catch {
63
+ return { version: 1, global: [], projects: {} };
64
+ }
65
+ }
66
+ function isEntry(value) {
67
+ if (!value || typeof value !== "object")
68
+ return false;
69
+ const entry = value;
70
+ return typeof entry.toolName === "string" && typeof entry.pattern === "string";
71
+ }
72
+ function writePersisted(data) {
73
+ try {
74
+ fs.mkdirSync(path.dirname(PERSISTED_ALLOWLIST_FILE), { recursive: true });
75
+ fs.writeFileSync(PERSISTED_ALLOWLIST_FILE, JSON.stringify(data, null, 2) + "\n");
76
+ }
77
+ catch { /* best effort */ }
78
+ }
79
+ export function loadPersistentAllowlist(projectRoot) {
80
+ const data = readPersisted();
81
+ persistentProjectRoot = projectRoot ?? null;
82
+ persistentAllowlist.length = 0;
83
+ for (const entry of data.global) {
84
+ persistentAllowlist.push({ ...entry, scope: "global" });
85
+ }
86
+ if (projectRoot) {
87
+ const projectEntries = data.projects[projectRoot];
88
+ if (Array.isArray(projectEntries)) {
89
+ for (const entry of projectEntries) {
90
+ persistentAllowlist.push({ ...entry, scope: "project" });
91
+ }
92
+ }
93
+ }
94
+ }
95
+ function persistEntry(entry, scope, projectRoot) {
96
+ const data = readPersisted();
97
+ const list = scope === "global"
98
+ ? data.global
99
+ : (data.projects[projectRoot ?? process.cwd()] ??= []);
100
+ if (!list.some((e) => e.toolName === entry.toolName && e.pattern === entry.pattern)) {
101
+ list.push({ toolName: entry.toolName, pattern: entry.pattern });
102
+ }
103
+ writePersisted(data);
42
104
  }
43
105
  /** Add a tool+pattern to the session allowlist. */
44
- export function addAllow(toolName, input, scope) {
106
+ export function addAllow(toolName, input, scope, projectRoot) {
45
107
  if (scope === "once")
46
108
  return; // "once" approvals don't persist
47
109
  // For shell commands, never allow "*" — always scope to the binary name
48
110
  const pattern = scope === "tool" && toolName !== "shell"
49
111
  ? "*"
50
112
  : extractPattern(toolName, input);
113
+ if (scope === "project" || scope === "global") {
114
+ const entry = { toolName, pattern, scope };
115
+ persistEntry(entry, scope, projectRoot);
116
+ const root = projectRoot ?? process.cwd();
117
+ if (scope === "project" && persistentProjectRoot !== root)
118
+ return;
119
+ if (!persistentAllowlist.some((e) => e.toolName === toolName && e.pattern === pattern && e.scope === scope)) {
120
+ persistentAllowlist.push(entry);
121
+ }
122
+ return;
123
+ }
51
124
  // Avoid duplicates
52
125
  const exists = sessionAllowlist.some((e) => e.toolName === toolName && e.pattern === pattern);
53
126
  if (!exists) {