@phren/agent 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/commands/info.js +1 -0
  2. package/dist/commands/model.js +5 -4
  3. package/dist/commands/session.js +24 -2
  4. package/dist/commands.js +36 -1
  5. package/dist/config.js +27 -11
  6. package/dist/cost.js +11 -74
  7. package/dist/index.js +92 -35
  8. package/dist/mcp-client.js +4 -2
  9. package/dist/memory/context.js +56 -24
  10. package/dist/memory/session.js +21 -88
  11. package/dist/models.js +390 -0
  12. package/dist/multi/agent-types.js +170 -0
  13. package/dist/multi/child-entry.js +248 -78
  14. package/dist/multi/coordinator.js +69 -1
  15. package/dist/multi/diff-renderer.js +193 -17
  16. package/dist/multi/markdown.js +49 -23
  17. package/dist/multi/model-picker.js +12 -21
  18. package/dist/multi/multi-events.js +17 -0
  19. package/dist/multi/multi-render.js +1 -0
  20. package/dist/multi/provider-manager.js +23 -13
  21. package/dist/multi/spawner.js +84 -7
  22. package/dist/multi/syntax-highlight.js +64 -48
  23. package/dist/multi/worktree.js +43 -0
  24. package/dist/package-metadata.js +11 -0
  25. package/dist/permissions/checker.js +21 -1
  26. package/dist/providers/codex-auth.js +48 -34
  27. package/dist/providers/codex.js +110 -40
  28. package/dist/providers/ollama.js +5 -4
  29. package/dist/providers/openrouter.js +12 -5
  30. package/dist/providers/resolve.js +50 -32
  31. package/dist/providers/types.js +0 -1
  32. package/dist/repl.js +19 -34
  33. package/dist/tools/grep.js +111 -23
  34. package/dist/tools/mcp-resources.js +32 -0
  35. package/dist/tools/registry.js +13 -2
  36. package/dist/tools/shell.js +101 -3
  37. package/dist/tools/skill.js +44 -0
  38. package/dist/tools/spawn-agent.js +158 -0
  39. package/dist/tui/ansi.js +15 -11
  40. package/dist/tui/components/App.js +180 -20
  41. package/dist/tui/components/Banner.js +7 -4
  42. package/dist/tui/components/InputArea.js +54 -12
  43. package/dist/tui/components/PhrenInput.js +329 -0
  44. package/dist/tui/components/StatusBar.js +3 -1
  45. package/dist/tui/components/SteerQueue.js +4 -2
  46. package/dist/tui/components/ThinkingIndicator.js +12 -11
  47. package/dist/tui/components/ToolCall.js +17 -11
  48. package/dist/tui/components/ToolSpinner.js +13 -0
  49. package/dist/tui/hooks/useKeyboardShortcuts.js +65 -24
  50. package/dist/tui/hooks/useSearch.js +47 -0
  51. package/dist/tui/hooks/useSlashCommands.js +16 -19
  52. package/dist/tui/ink-entry.js +317 -18
  53. package/dist/tui/mouse.js +71 -0
  54. package/dist/tui/terminal-control.js +62 -0
  55. package/dist/tui/themes.js +398 -0
  56. package/dist/tui/tool-render.js +12 -1
  57. package/dist/tui.js +2 -1
  58. package/package.json +1 -3
@@ -1,7 +1,7 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
3
  import { validatePath } from "../permissions/sandbox.js";
4
- function searchFile(filePath, regex, context) {
4
+ function searchFile(filePath, regex, contextBefore, contextAfter) {
5
5
  let content;
6
6
  try {
7
7
  content = fs.readFileSync(filePath, "utf-8");
@@ -10,19 +10,36 @@ function searchFile(filePath, regex, context) {
10
10
  return [];
11
11
  }
12
12
  const lines = content.split("\n");
13
- const results = [];
13
+ const matches = [];
14
14
  for (let i = 0; i < lines.length; i++) {
15
15
  if (regex.test(lines[i])) {
16
- const start = Math.max(0, i - context);
17
- const end = Math.min(lines.length - 1, i + context);
16
+ const start = Math.max(0, i - contextBefore);
17
+ const end = Math.min(lines.length - 1, i + contextAfter);
18
18
  for (let j = start; j <= end; j++) {
19
- results.push(`${j + 1}\t${lines[j]}`);
19
+ matches.push({ line: j + 1, text: lines[j] });
20
20
  }
21
21
  if (end < lines.length - 1)
22
- results.push("--");
22
+ matches.push({ line: -1, text: "--" });
23
23
  }
24
24
  }
25
- return results;
25
+ return matches;
26
+ }
27
+ function searchFileMultiline(filePath, regex) {
28
+ let content;
29
+ try {
30
+ content = fs.readFileSync(filePath, "utf-8");
31
+ }
32
+ catch {
33
+ return [];
34
+ }
35
+ const matches = [];
36
+ let match;
37
+ while ((match = regex.exec(content)) !== null) {
38
+ const beforeMatch = content.slice(0, match.index);
39
+ const lineNo = beforeMatch.split("\n").length;
40
+ matches.push({ line: lineNo, text: match[0].slice(0, 200) });
41
+ }
42
+ return matches;
26
43
  }
27
44
  function walkDir(dir, results, maxFiles) {
28
45
  if (results.length >= maxFiles)
@@ -46,32 +63,68 @@ function walkDir(dir, results, maxFiles) {
46
63
  results.push(full);
47
64
  }
48
65
  }
66
+ const FILE_TYPE_EXTENSIONS = {
67
+ js: [".js", ".jsx", ".mjs", ".cjs"],
68
+ ts: [".ts", ".tsx", ".mts", ".cts"],
69
+ py: [".py", ".pyw"],
70
+ rust: [".rs"],
71
+ go: [".go"],
72
+ java: [".java"],
73
+ rb: [".rb"],
74
+ css: [".css", ".scss", ".sass", ".less"],
75
+ html: [".html", ".htm"],
76
+ json: [".json"],
77
+ yaml: [".yaml", ".yml"],
78
+ md: [".md", ".mdx"],
79
+ sh: [".sh", ".bash", ".zsh"],
80
+ sql: [".sql"],
81
+ };
49
82
  export const grepTool = {
50
83
  name: "grep",
51
- description: "Search file contents by regex pattern. Use to find function definitions, imports, error messages, or any text across the codebase. Returns matching lines with surrounding context. Use glob param to limit to specific file types.",
84
+ description: "Search file contents by regex. Supports output modes (content, files_with_matches, count), context lines, multiline matching, file type filtering, and result pagination.",
52
85
  input_schema: {
53
86
  type: "object",
54
87
  properties: {
55
88
  pattern: { type: "string", description: "Regex pattern to search for." },
56
89
  path: { type: "string", description: "File or directory to search. Default: cwd." },
57
- context: { type: "number", description: "Lines of context around matches. Default: 2." },
58
- glob: { type: "string", description: "File glob filter (e.g. '*.ts'). Default: all files." },
90
+ context: { type: "number", description: "Lines of context around matches (-C). Default: 2." },
91
+ "-A": { type: "number", description: "Lines to show after each match." },
92
+ "-B": { type: "number", description: "Lines to show before each match." },
93
+ glob: { type: "string", description: "File glob filter (e.g. '*.ts')." },
94
+ type: { type: "string", description: "File type filter (e.g. 'js', 'py', 'ts', 'rust', 'go')." },
95
+ output_mode: {
96
+ type: "string",
97
+ enum: ["content", "files_with_matches", "count"],
98
+ description: "Output mode. 'content' shows lines, 'files_with_matches' shows paths only, 'count' shows match counts. Default: content.",
99
+ },
100
+ multiline: { type: "boolean", description: "Enable multiline matching (pattern can span lines). Default: false." },
101
+ head_limit: { type: "number", description: "Max results to return. Default: 100." },
102
+ offset: { type: "number", description: "Skip first N results before applying head_limit." },
103
+ "-i": { type: "boolean", description: "Case insensitive search. Default: true." },
59
104
  },
60
105
  required: ["pattern"],
61
106
  },
62
107
  async execute(input) {
63
108
  const pattern = input.pattern;
64
109
  const searchPath = input.path || process.cwd();
65
- const context = input.context ?? 2;
110
+ const contextC = input.context ?? input["-C"] ?? 2;
111
+ const contextA = input["-A"] ?? contextC;
112
+ const contextB = input["-B"] ?? contextC;
66
113
  const fileGlob = input.glob;
67
- // Defense-in-depth: validate search path against sandbox
114
+ const fileType = input.type;
115
+ const outputMode = input.output_mode || "content";
116
+ const multiline = input.multiline;
117
+ const headLimit = input.head_limit ?? 100;
118
+ const offset = input.offset ?? 0;
119
+ const caseInsensitive = input["-i"] ?? true;
68
120
  const pathResult = validatePath(searchPath, process.cwd(), []);
69
121
  if (!pathResult.ok) {
70
122
  return { output: `Path outside sandbox: ${pathResult.error}`, is_error: true };
71
123
  }
72
124
  let regex;
73
125
  try {
74
- regex = new RegExp(pattern, "i");
126
+ const flags = (caseInsensitive ? "i" : "") + (multiline ? "gs" : "");
127
+ regex = new RegExp(pattern, flags || "i");
75
128
  }
76
129
  catch {
77
130
  return { output: `Invalid regex: ${pattern}`, is_error: true };
@@ -79,12 +132,28 @@ export const grepTool = {
79
132
  const stat = fs.statSync(searchPath, { throwIfNoEntry: false });
80
133
  if (!stat)
81
134
  return { output: `Path not found: ${searchPath}`, is_error: true };
135
+ // Single file
82
136
  if (stat.isFile()) {
83
- const results = searchFile(searchPath, regex, context);
84
- return { output: results.length > 0 ? `${searchPath}:\n${results.join("\n")}` : "No matches." };
137
+ const results = multiline
138
+ ? searchFileMultiline(searchPath, regex)
139
+ : searchFile(searchPath, regex, contextB, contextA);
140
+ if (outputMode === "files_with_matches")
141
+ return { output: results.length > 0 ? searchPath : "No matches." };
142
+ if (outputMode === "count")
143
+ return { output: `${results.filter((r) => r.line > 0).length}` };
144
+ return { output: results.length > 0 ? `${searchPath}:\n${results.map((r) => r.line > 0 ? `${r.line}\t${r.text}` : r.text).join("\n")}` : "No matches." };
85
145
  }
146
+ // Directory search
86
147
  const files = [];
87
148
  walkDir(searchPath, files, 5000);
149
+ // File type filter
150
+ if (fileType) {
151
+ const exts = FILE_TYPE_EXTENSIONS[fileType] ?? [`.${fileType}`];
152
+ const filtered = files.filter((f) => exts.some((ext) => f.endsWith(ext)));
153
+ files.length = 0;
154
+ files.push(...filtered);
155
+ }
156
+ // Glob filter
88
157
  if (fileGlob) {
89
158
  const globRegex = new RegExp(fileGlob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*"));
90
159
  const filtered = files.filter((f) => globRegex.test(path.basename(f)));
@@ -92,17 +161,36 @@ export const grepTool = {
92
161
  files.push(...filtered);
93
162
  }
94
163
  const output = [];
95
- let matchCount = 0;
164
+ let totalMatches = 0;
165
+ let skipped = 0;
96
166
  for (const file of files) {
97
- if (matchCount > 100)
167
+ if (output.length >= headLimit + offset)
98
168
  break;
99
- const results = searchFile(file, regex, context);
100
- if (results.length > 0) {
101
- const rel = path.relative(searchPath, file);
102
- output.push(`${rel}:\n${results.join("\n")}`);
103
- matchCount++;
169
+ const results = multiline
170
+ ? searchFileMultiline(file, regex)
171
+ : searchFile(file, regex, contextB, contextA);
172
+ if (results.length === 0)
173
+ continue;
174
+ totalMatches++;
175
+ if (skipped < offset) {
176
+ skipped++;
177
+ continue;
178
+ }
179
+ if (output.length >= headLimit)
180
+ break;
181
+ const rel = path.relative(searchPath, file);
182
+ if (outputMode === "files_with_matches") {
183
+ output.push(rel);
184
+ }
185
+ else if (outputMode === "count") {
186
+ output.push(`${rel}: ${results.filter((r) => r.line > 0).length}`);
187
+ }
188
+ else {
189
+ output.push(`${rel}:\n${results.map((r) => r.line > 0 ? `${r.line}\t${r.text}` : r.text).join("\n")}`);
104
190
  }
105
191
  }
106
- return { output: output.length > 0 ? output.join("\n\n") : "No matches." };
192
+ if (output.length === 0)
193
+ return { output: "No matches." };
194
+ return { output: output.join(outputMode === "content" ? "\n\n" : "\n") };
107
195
  },
108
196
  };
@@ -0,0 +1,32 @@
1
+ // These tools work with the MCP client connection stored in the agent
2
+ // For now, create stub tools that explain MCP resources aren't connected yet
3
+ // The actual implementation depends on how mcp-client.ts stores connections
4
+ export const listMcpResourcesTool = {
5
+ name: "list_mcp_resources",
6
+ description: "List available resources from connected MCP servers. Resources are data endpoints that servers expose (database tables, config files, etc.).",
7
+ input_schema: {
8
+ type: "object",
9
+ properties: {
10
+ server: { type: "string", description: "Optional: filter by server name." },
11
+ },
12
+ },
13
+ async execute(input) {
14
+ // TODO: Wire to actual MCP client connections
15
+ return { output: "No MCP resource connections available. Connect MCP servers with --mcp-config to use resources." };
16
+ },
17
+ };
18
+ export const readMcpResourceTool = {
19
+ name: "read_mcp_resource",
20
+ description: "Read a specific resource from an MCP server by URI.",
21
+ input_schema: {
22
+ type: "object",
23
+ properties: {
24
+ server: { type: "string", description: "MCP server name." },
25
+ uri: { type: "string", description: "Resource URI to read." },
26
+ },
27
+ required: ["server", "uri"],
28
+ },
29
+ async execute(input) {
30
+ return { output: "No MCP resource connections available. Connect MCP servers with --mcp-config to use resources." };
31
+ },
32
+ };
@@ -1,7 +1,9 @@
1
1
  import { checkPermission } from "../permissions/checker.js";
2
- import { askUser } from "../permissions/prompt.js";
2
+ import { askUser as defaultAskUser } from "../permissions/prompt.js";
3
3
  export class ToolRegistry {
4
4
  tools = new Map();
5
+ /** Override the default permission prompt (e.g. for Ink TUI). */
6
+ askUser = defaultAskUser;
5
7
  permissionConfig = {
6
8
  mode: "suggest",
7
9
  projectRoot: process.cwd(),
@@ -10,6 +12,15 @@ export class ToolRegistry {
10
12
  register(tool) {
11
13
  this.tools.set(tool.name, tool);
12
14
  }
15
+ remove(name) {
16
+ return this.tools.delete(name);
17
+ }
18
+ has(name) {
19
+ return this.tools.has(name);
20
+ }
21
+ toolNames() {
22
+ return [...this.tools.keys()];
23
+ }
13
24
  setPermissions(config) {
14
25
  this.permissionConfig = config;
15
26
  }
@@ -30,7 +41,7 @@ export class ToolRegistry {
30
41
  return { output: `Permission denied: ${rule.reason}`, is_error: true };
31
42
  }
32
43
  if (rule.verdict === "ask") {
33
- const allowed = await askUser(name, input, rule.reason);
44
+ const allowed = await this.askUser(name, input, rule.reason);
34
45
  if (!allowed) {
35
46
  return { output: "User denied permission.", is_error: true };
36
47
  }
@@ -1,17 +1,25 @@
1
- import { execFileSync } from "child_process";
1
+ import { execFileSync, spawn } from "child_process";
2
+ import * as fs from "fs";
3
+ import * as path from "path";
4
+ import * as os from "os";
2
5
  import { checkShellSafety, scrubEnv } from "../permissions/shell-safety.js";
3
6
  const DEFAULT_TIMEOUT_MS = 30_000;
4
7
  const MAX_TIMEOUT_MS = 120_000;
5
8
  const MAX_OUTPUT_BYTES = 100_000;
9
+ // Background task tracking
10
+ const backgroundTasks = new Map();
11
+ let nextBgId = 1;
6
12
  export const shellTool = {
7
13
  name: "shell",
8
- description: "Run a shell command and return stdout + stderr. Uses bash on Unix, cmd.exe on Windows. Use for: running tests, linters, build commands, git operations, and exploring the environment. Prefer specific tools (read_file, glob, grep) over shell equivalents when available.",
14
+ 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.",
9
15
  input_schema: {
10
16
  type: "object",
11
17
  properties: {
12
18
  command: { type: "string", description: "Shell command to execute." },
19
+ description: { type: "string", description: "Human-readable description of what this command does (shown to user)." },
13
20
  cwd: { type: "string", description: "Working directory. Defaults to process cwd." },
14
21
  timeout: { type: "number", description: "Timeout in ms. Default: 30000, max: 120000." },
22
+ run_in_background: { type: "boolean", description: "If true, run in background and return a task_id. Use task_output to get results later." },
15
23
  },
16
24
  required: ["command"],
17
25
  },
@@ -19,7 +27,8 @@ export const shellTool = {
19
27
  const command = input.command;
20
28
  const cwd = input.cwd || process.cwd();
21
29
  const timeout = Math.min(MAX_TIMEOUT_MS, input.timeout || DEFAULT_TIMEOUT_MS);
22
- // Block dangerous commands immediately
30
+ const description = input.description;
31
+ const runInBackground = input.run_in_background;
23
32
  const safety = checkShellSafety(command);
24
33
  if (!safety.safe && safety.severity === "block") {
25
34
  return { output: `Blocked: ${safety.reason}`, is_error: true };
@@ -27,6 +36,29 @@ export const shellTool = {
27
36
  const isWindows = process.platform === "win32";
28
37
  const shell = isWindows ? "cmd" : "bash";
29
38
  const shellArgs = isWindows ? ["/c", command] : ["-c", command];
39
+ // Background execution
40
+ if (runInBackground) {
41
+ const taskId = `bg-${nextBgId++}`;
42
+ const outputFile = path.join(os.tmpdir(), `phren-bg-${taskId}.log`);
43
+ const fd = fs.openSync(outputFile, "w");
44
+ const child = spawn(shell, shellArgs, {
45
+ cwd,
46
+ stdio: ["ignore", fd, fd],
47
+ env: scrubEnv(),
48
+ detached: true,
49
+ });
50
+ const task = { pid: child.pid, outputFile, done: false, exitCode: null };
51
+ backgroundTasks.set(taskId, task);
52
+ child.on("exit", (code) => {
53
+ task.done = true;
54
+ task.exitCode = code;
55
+ fs.closeSync(fd);
56
+ });
57
+ child.unref();
58
+ const desc = description ? ` (${description})` : "";
59
+ return { output: `Background task ${taskId} started${desc}. PID: ${child.pid}. Use task_output to get results.` };
60
+ }
61
+ // Foreground execution
30
62
  try {
31
63
  const output = execFileSync(shell, shellArgs, {
32
64
  cwd,
@@ -49,3 +81,69 @@ export const shellTool = {
49
81
  }
50
82
  },
51
83
  };
84
+ // Task output and stop tools
85
+ export const taskOutputTool = {
86
+ name: "task_output",
87
+ description: "Get output from a background shell task. Set block=true to wait for completion.",
88
+ input_schema: {
89
+ type: "object",
90
+ properties: {
91
+ task_id: { type: "string", description: "Background task ID (e.g. 'bg-1')." },
92
+ block: { type: "boolean", description: "If true, wait for the task to complete before returning. Default: false." },
93
+ timeout: { type: "number", description: "Max ms to wait when blocking. Default: 60000." },
94
+ },
95
+ required: ["task_id"],
96
+ },
97
+ async execute(input) {
98
+ const taskId = input.task_id;
99
+ const block = input.block;
100
+ const timeout = input.timeout || 60_000;
101
+ const task = backgroundTasks.get(taskId);
102
+ if (!task) {
103
+ const available = [...backgroundTasks.keys()].join(", ") || "none";
104
+ return { output: `Task "${taskId}" not found. Available: ${available}`, is_error: true };
105
+ }
106
+ if (block && !task.done) {
107
+ const start = Date.now();
108
+ while (!task.done && Date.now() - start < timeout) {
109
+ await new Promise((r) => setTimeout(r, 200));
110
+ }
111
+ }
112
+ const status = task.done ? `completed (exit ${task.exitCode})` : "running";
113
+ let output = "";
114
+ try {
115
+ output = fs.readFileSync(task.outputFile, "utf-8");
116
+ }
117
+ catch { /* no output yet */ }
118
+ if (output.length > MAX_OUTPUT_BYTES) {
119
+ output = output.slice(-MAX_OUTPUT_BYTES) + "\n... (truncated, showing last 100KB)";
120
+ }
121
+ return { output: `[${status}]\n${output.trim() || "(no output yet)"}` };
122
+ },
123
+ };
124
+ export const taskStopTool = {
125
+ name: "task_stop",
126
+ description: "Stop a background shell task.",
127
+ input_schema: {
128
+ type: "object",
129
+ properties: {
130
+ task_id: { type: "string", description: "Background task ID to stop." },
131
+ },
132
+ required: ["task_id"],
133
+ },
134
+ async execute(input) {
135
+ const taskId = input.task_id;
136
+ const task = backgroundTasks.get(taskId);
137
+ if (!task)
138
+ return { output: `Task "${taskId}" not found.`, is_error: true };
139
+ if (task.done)
140
+ return { output: `Task "${taskId}" already finished.` };
141
+ try {
142
+ process.kill(task.pid, "SIGTERM");
143
+ }
144
+ catch { /* already dead */ }
145
+ task.done = true;
146
+ task.exitCode = -1;
147
+ return { output: `Task "${taskId}" stopped.` };
148
+ },
149
+ };
@@ -0,0 +1,44 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ export function createSkillTool(phrenCtx) {
4
+ return {
5
+ name: "run_skill",
6
+ description: "Execute a phren skill by name. Skills are prompt templates stored in ~/.phren/skills/. Returns the skill content which you should follow as instructions.",
7
+ input_schema: {
8
+ type: "object",
9
+ properties: {
10
+ name: { type: "string", description: "Skill name (e.g. 'commit', 'review-pr', 'consolidate')" },
11
+ args: { type: "string", description: "Optional arguments to pass to the skill" },
12
+ },
13
+ required: ["name"],
14
+ },
15
+ async execute(input) {
16
+ const name = input.name;
17
+ const args = input.args || "";
18
+ if (!phrenCtx) {
19
+ return { output: "No phren context available.", is_error: true };
20
+ }
21
+ // Look for skill in global and project locations
22
+ const locations = [
23
+ path.join(phrenCtx.phrenPath, "skills", `${name}.md`),
24
+ path.join(phrenCtx.phrenPath, "skills", name, "index.md"),
25
+ ];
26
+ // Also check project-specific skills (higher priority)
27
+ if (phrenCtx.project) {
28
+ locations.unshift(path.join(phrenCtx.phrenPath, phrenCtx.project, "skills", `${name}.md`));
29
+ }
30
+ for (const loc of locations) {
31
+ try {
32
+ const content = fs.readFileSync(loc, "utf-8");
33
+ // Strip YAML frontmatter
34
+ const stripped = content.replace(/^---\n[\s\S]*?\n---\n/, "");
35
+ return { output: `[Skill: ${name}${args ? ` ${args}` : ""}]\n\n${stripped}` };
36
+ }
37
+ catch {
38
+ continue;
39
+ }
40
+ }
41
+ return { output: `Skill "${name}" not found. Check ~/.phren/skills/ for available skills.`, is_error: true };
42
+ },
43
+ };
44
+ }
@@ -0,0 +1,158 @@
1
+ export function createSendMessageTool(spawner) {
2
+ return {
3
+ name: "send_message_to_agent",
4
+ description: `Send a message to an existing spawned agent. Use this to give instructions to idle agents, ask them questions, or assign new tasks. The agent will process the message and respond.`,
5
+ input_schema: {
6
+ type: "object",
7
+ properties: {
8
+ agent_id: {
9
+ type: "string",
10
+ description: "The agent ID to send the message to (e.g. 'agent-1')",
11
+ },
12
+ message: {
13
+ type: "string",
14
+ description: "The message to send to the agent",
15
+ },
16
+ },
17
+ required: ["agent_id", "message"],
18
+ },
19
+ async execute(input) {
20
+ const agentId = input.agent_id;
21
+ const message = input.message;
22
+ if (!agentId || !message) {
23
+ return { output: "Both agent_id and message are required.", is_error: true };
24
+ }
25
+ const agent = spawner.getAgent(agentId);
26
+ if (!agent) {
27
+ // Try to find by display name
28
+ const allAgents = spawner.listAgents();
29
+ const byName = allAgents.find((a) => a.displayName === agentId || a.id === agentId);
30
+ if (!byName) {
31
+ const available = allAgents.map((a) => `${a.id} (${a.displayName || a.task.slice(0, 30)})`).join(", ");
32
+ return { output: `Agent "${agentId}" not found. Available: ${available || "none"}`, is_error: true };
33
+ }
34
+ // Use the found agent
35
+ if (byName.status === "idle") {
36
+ spawner.wakeAgent(byName.id, { message, from: "orchestrator" });
37
+ return { output: `Sent message to ${byName.displayName || byName.id} (woke from idle): "${message}"` };
38
+ }
39
+ spawner.sendToAgent(byName.id, message, "orchestrator");
40
+ return { output: `Sent message to ${byName.displayName || byName.id}: "${message}"` };
41
+ }
42
+ if (agent.status === "idle") {
43
+ spawner.wakeAgent(agentId, { message, from: "orchestrator" });
44
+ return { output: `Sent message to ${agent.displayName || agentId} (woke from idle): "${message}"` };
45
+ }
46
+ if (agent.status === "done" || agent.status === "error" || agent.status === "cancelled") {
47
+ return { output: `Agent "${agentId}" is ${agent.status} and cannot receive messages.`, is_error: true };
48
+ }
49
+ spawner.sendToAgent(agentId, message, "orchestrator");
50
+ return { output: `Sent message to ${agent.displayName || agentId}: "${message}"` };
51
+ },
52
+ };
53
+ }
54
+ export function createListAgentsTool(spawner) {
55
+ return {
56
+ name: "list_agents",
57
+ description: `List all spawned agents and their current status (running, idle, done, error).`,
58
+ input_schema: { type: "object", properties: {} },
59
+ async execute() {
60
+ const agents = spawner.listAgents();
61
+ if (agents.length === 0) {
62
+ return { output: "No agents spawned." };
63
+ }
64
+ const lines = agents.map((a) => {
65
+ const name = a.displayName || a.id;
66
+ const elapsed = a.finishedAt
67
+ ? `${((a.finishedAt - a.startedAt) / 1000).toFixed(1)}s`
68
+ : `${((Date.now() - a.startedAt) / 1000).toFixed(0)}s`;
69
+ return `${a.id} [${a.status}] "${name}" — ${elapsed} — ${a.task.slice(0, 60)}`;
70
+ });
71
+ return { output: lines.join("\n") };
72
+ },
73
+ };
74
+ }
75
+ export function createSpawnAgentTool(spawner) {
76
+ return {
77
+ name: "spawn_agent",
78
+ description: `Spawn a child agent. Two modes:
79
+
80
+ **Subagent** (background=false, default): Runs the task and waits for the result. Output appears inline in your conversation. Use for quick parallel work like "search 3 files", "run tests", "check dependencies". The tool call blocks until the agent finishes and returns its response.
81
+
82
+ **TeamAgent** (background=true or idle=true): Spawns a persistent agent with its own conversation. Shows up in the tab bar. The user can switch to its chat and talk to it directly. Use when the user says "spawn a team", "create agents on idle", "spin up workers".`,
83
+ input_schema: {
84
+ type: "object",
85
+ properties: {
86
+ name: {
87
+ type: "string",
88
+ description: "Short descriptive name for the agent (e.g. 'fixer', 'explorer', 'tester')",
89
+ },
90
+ task: {
91
+ type: "string",
92
+ description: "The task for the agent to work on.",
93
+ },
94
+ background: {
95
+ type: "boolean",
96
+ description: "If true, creates a TeamAgent (persistent, own chat, shows in tab bar). If false (default), creates a subagent that runs inline and returns the result.",
97
+ },
98
+ idle: {
99
+ type: "boolean",
100
+ description: "If true, spawn as TeamAgent on idle (no task yet, waits for instructions). Implies background=true.",
101
+ },
102
+ },
103
+ required: ["name"],
104
+ },
105
+ async execute(input) {
106
+ const name = input.name;
107
+ const task = input.task || "";
108
+ const idle = input.idle;
109
+ const background = input.background || idle;
110
+ if (!name) {
111
+ return { output: "Agent name is required.", is_error: true };
112
+ }
113
+ const agentTask = idle
114
+ ? `You are agent "${name}". You have been spawned on idle. Wait for instructions.`
115
+ : task || `You are agent "${name}". Work on any tasks assigned to you.`;
116
+ const agentId = spawner.spawn({
117
+ task: agentTask,
118
+ displayName: name,
119
+ cwd: process.cwd(),
120
+ verbose: false,
121
+ });
122
+ // TeamAgent (background): return immediately, agent lives in tab bar
123
+ if (background) {
124
+ const status = idle ? "idle (waiting for instructions)" : "running in background";
125
+ return {
126
+ output: `Spawned TeamAgent "${name}" (${agentId}) — ${status}${task ? `: ${task}` : ""}`,
127
+ };
128
+ }
129
+ // Subagent (foreground): wait for completion, return result inline
130
+ return new Promise((resolve) => {
131
+ const onDone = (doneId, result) => {
132
+ if (doneId !== agentId)
133
+ return;
134
+ spawner.removeListener("done", onDone);
135
+ spawner.removeListener("error", onError);
136
+ resolve({
137
+ output: result.finalText || `Agent "${name}" completed (${result.turns} turns, ${result.toolCalls} tool calls)`,
138
+ });
139
+ };
140
+ const onError = (errId, error) => {
141
+ if (errId !== agentId)
142
+ return;
143
+ spawner.removeListener("done", onDone);
144
+ spawner.removeListener("error", onError);
145
+ resolve({ output: `Agent "${name}" failed: ${error}`, is_error: true });
146
+ };
147
+ spawner.on("done", onDone);
148
+ spawner.on("error", onError);
149
+ // Timeout after 5 minutes
150
+ setTimeout(() => {
151
+ spawner.removeListener("done", onDone);
152
+ spawner.removeListener("error", onError);
153
+ resolve({ output: `Agent "${name}" timed out after 5 minutes`, is_error: true });
154
+ }, 300_000);
155
+ });
156
+ },
157
+ };
158
+ }
package/dist/tui/ansi.js CHANGED
@@ -23,26 +23,30 @@ export function stripAnsi(t) {
23
23
  return t.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "");
24
24
  }
25
25
  // ── Permission mode helpers ─────────────────────────────────────────────────
26
- export const PERMISSION_MODES = ["suggest", "auto-confirm", "full-auto"];
26
+ // Cycle: ask → auto edits → plan → autopilot (matches Claude Code pattern)
27
+ export const PERMISSION_MODES = ["suggest", "auto-confirm", "plan", "full-auto"];
27
28
  export function nextPermissionMode(current) {
28
29
  const idx = PERMISSION_MODES.indexOf(current);
29
30
  return PERMISSION_MODES[(idx + 1) % PERMISSION_MODES.length];
30
31
  }
31
32
  export const PERMISSION_LABELS = {
32
- "suggest": "suggest",
33
- "auto-confirm": "auto",
34
- "full-auto": "full-auto",
33
+ "suggest": "",
34
+ "auto-confirm": "auto edits",
35
+ "plan": "plan",
36
+ "full-auto": "autopilot",
35
37
  };
36
38
  export const PERMISSION_ICONS = {
37
- "suggest": "○",
38
- "auto-confirm": "◐",
39
- "full-auto": "●",
39
+ "suggest": "",
40
+ "auto-confirm": "\u25d0", // ◐
41
+ "plan": "\u25d1", // ◑
42
+ "full-auto": "\u25cf", // ●
40
43
  };
41
44
  export const PERMISSION_COLORS = {
42
- "suggest": s.cyan,
43
- "auto-confirm": s.green,
44
- "full-auto": s.yellow,
45
+ "suggest": (t) => t, // invisible / no color
46
+ "auto-confirm": s.yellow, // orange-ish (ANSI yellow)
47
+ "plan": s.magenta, // purple
48
+ "full-auto": s.green, // green
45
49
  };
46
50
  export function permTag(mode) {
47
- return PERMISSION_COLORS[mode](`${PERMISSION_ICONS[mode]} ${mode}`);
51
+ return PERMISSION_COLORS[mode](`${PERMISSION_ICONS[mode]} ${PERMISSION_LABELS[mode]}`);
48
52
  }