@phren/agent 0.1.14 → 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.
- package/LICENSE +21 -0
- package/README.md +86 -0
- package/dist/agent-loop/index.js +239 -65
- package/dist/agent-loop/stream.js +212 -29
- package/dist/agent-loop/types.js +15 -2
- package/dist/bin.js +0 -0
- package/dist/checkpoint.js +103 -22
- package/dist/commands/info.js +30 -15
- package/dist/commands/model.js +6 -2
- package/dist/commands/review.js +183 -0
- package/dist/commands/session.js +70 -7
- package/dist/commands.js +168 -12
- package/dist/config.js +87 -10
- package/dist/context/compactor.js +239 -0
- package/dist/context/pruner.js +39 -13
- package/dist/context/token-counter.js +33 -1
- package/dist/custom-commands.js +69 -0
- package/dist/guards/repeat-tool-reminder.js +75 -0
- package/dist/headless.js +115 -0
- package/dist/herdr-hooks.js +71 -0
- package/dist/index.js +351 -48
- package/dist/mcp-client.js +434 -73
- package/dist/mcp-oauth.js +121 -0
- package/dist/memory/anti-patterns.js +7 -3
- package/dist/memory/auto-capture.js +7 -3
- package/dist/memory/context.js +92 -73
- package/dist/memory/project-context.js +24 -5
- package/dist/memory/provenance.js +15 -0
- package/dist/memory/review-triage.js +166 -0
- package/dist/memory/session.js +36 -1
- package/dist/models.js +152 -19
- package/dist/multi/child-entry.js +65 -10
- package/dist/multi/diff-renderer.js +3 -3
- package/dist/multi/markdown.js +125 -27
- package/dist/multi/provider-manager.js +8 -0
- package/dist/multi/publish.js +72 -0
- package/dist/multi/spawner.js +45 -4
- package/dist/multi/syntax-highlight.js +25 -4
- package/dist/multi/types.js +1 -1
- package/dist/permissions/allowlist.js +86 -13
- package/dist/permissions/checker.js +42 -7
- package/dist/permissions/kernel-sandbox.js +197 -0
- package/dist/permissions/prompt.js +10 -1
- package/dist/permissions/sandbox.js +40 -17
- package/dist/providers/anthropic.js +154 -7
- package/dist/providers/codex-auth.js +28 -0
- package/dist/providers/codex.js +134 -23
- package/dist/providers/history.js +35 -0
- package/dist/providers/ollama.js +37 -6
- package/dist/providers/openai-compat.js +171 -74
- package/dist/providers/openrouter.js +47 -17
- package/dist/providers/replay.js +62 -0
- package/dist/providers/resolve.js +41 -7
- package/dist/providers/retry.js +38 -5
- package/dist/providers/types.js +9 -1
- package/dist/repl.js +47 -5
- package/dist/session/log.js +217 -0
- package/dist/session/persist.js +190 -0
- package/dist/settings.js +42 -26
- package/dist/system-prompt.js +18 -2
- package/dist/tools/apply-patch.js +355 -0
- package/dist/tools/edit-engine.js +287 -0
- package/dist/tools/edit-file.js +86 -27
- package/dist/tools/grep.js +25 -10
- package/dist/tools/lint-test.js +0 -22
- package/dist/tools/mcp-resources.js +51 -6
- package/dist/tools/phren-finding.js +12 -4
- package/dist/tools/phren-search.js +7 -2
- package/dist/tools/read-file.js +37 -9
- package/dist/tools/read-image.js +76 -0
- package/dist/tools/registry.js +27 -5
- package/dist/tools/shell.js +134 -71
- package/dist/tools/skill.js +20 -20
- package/dist/tools/spawn-agent.js +77 -13
- package/dist/tools/update-plan.js +48 -0
- package/dist/tools/web-fetch.js +110 -12
- package/dist/tools/web-search.js +4 -4
- package/dist/tui/components/App.js +98 -26
- package/dist/tui/components/ApprovalPanel.js +8 -0
- package/dist/tui/components/InputArea.js +5 -5
- package/dist/tui/components/ModelPicker.js +43 -0
- package/dist/tui/components/PhrenInput.js +10 -5
- package/dist/tui/components/PlanReview.js +7 -0
- package/dist/tui/components/ShortcutHelp.js +5 -0
- package/dist/tui/components/StatusBar.js +46 -20
- package/dist/tui/components/SteerQueue.js +1 -1
- package/dist/tui/components/ThinkingIndicator.js +6 -4
- package/dist/tui/components/ToolCall.js +10 -4
- package/dist/tui/components/ToolDetail.js +21 -0
- package/dist/tui/help.js +6 -0
- package/dist/tui/hooks/useKeyboardShortcuts.js +15 -1
- package/dist/tui/index.js +0 -1
- package/dist/tui/ink-entry.js +317 -33
- package/dist/tui/tool-render.js +1 -1
- package/dist/user-hooks.js +171 -0
- package/package.json +18 -12
- package/dist/multi/multi-commands.js +0 -170
- package/dist/multi/multi-events.js +0 -98
- package/dist/multi/multi-render.js +0 -147
- package/dist/multi/pane.js +0 -28
- package/dist/multi/tui-multi.js +0 -200
- package/dist/permissions/privacy.js +0 -248
- package/dist/tui/components/AgentMessage.js +0 -5
- package/dist/tui/components/ChatMessage.js +0 -23
- package/dist/tui/components/CodeBlock.js +0 -8
- package/dist/tui/components/Separator.js +0 -7
- package/dist/tui/components/StreamingText.js +0 -5
- package/dist/tui/components/UserMessage.js +0 -5
- package/dist/tui/menu-mode.js +0 -86
- package/dist/tui/mouse.js +0 -71
- package/dist/tui/terminal-control.js +0 -62
- package/dist/tui.js +0 -781
package/dist/tools/shell.js
CHANGED
|
@@ -1,86 +1,149 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { execFile, spawn } from "child_process";
|
|
2
|
+
import { promisify } from "util";
|
|
2
3
|
import * as fs from "fs";
|
|
3
4
|
import * as path from "path";
|
|
4
5
|
import * as os from "os";
|
|
5
6
|
import { checkShellSafety, scrubEnv } from "../permissions/shell-safety.js";
|
|
7
|
+
import { wrapWithSandbox, classifySandboxDenial, SandboxRequiredError } from "../permissions/kernel-sandbox.js";
|
|
8
|
+
const execFileAsync = promisify(execFile);
|
|
6
9
|
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
7
10
|
const MAX_TIMEOUT_MS = 120_000;
|
|
8
11
|
const MAX_OUTPUT_BYTES = 100_000;
|
|
9
12
|
// Background task tracking
|
|
10
13
|
const backgroundTasks = new Map();
|
|
14
|
+
/**
|
|
15
|
+
* Background task logs live in a private directory, not loose in os.tmpdir().
|
|
16
|
+
*
|
|
17
|
+
* On Linux /tmp is world-writable (mode 1777) and the task ids are sequential,
|
|
18
|
+
* so `phren-bg-bg-1.log` was a name any other local account could predict and
|
|
19
|
+
* pre-create as a symlink to a file this user can write — `openSync(…, "w")`
|
|
20
|
+
* follows it, which turns a background shell command into an arbitrary-file
|
|
21
|
+
* overwrite running as us. mkdtemp gives a 0700 directory with a random name,
|
|
22
|
+
* and the "wx" flag refuses to open a path that already exists.
|
|
23
|
+
*/
|
|
24
|
+
let backgroundLogRoot;
|
|
25
|
+
function backgroundLogDir() {
|
|
26
|
+
if (!backgroundLogRoot || !fs.existsSync(backgroundLogRoot)) {
|
|
27
|
+
backgroundLogRoot = fs.mkdtempSync(path.join(os.tmpdir(), "phren-bg-"));
|
|
28
|
+
}
|
|
29
|
+
return backgroundLogRoot;
|
|
30
|
+
}
|
|
11
31
|
let nextBgId = 1;
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
32
|
+
/**
|
|
33
|
+
* Shell tool factory. `getPermissions` is read per call so /permissions and
|
|
34
|
+
* /sandbox changes apply live; the kernel write fence derives its writable
|
|
35
|
+
* roots from the SAME config as the in-process path sandbox.
|
|
36
|
+
*/
|
|
37
|
+
export function createShellTool(getPermissions) {
|
|
38
|
+
return {
|
|
39
|
+
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,
|
|
43
|
+
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
|
+
input_schema: {
|
|
45
|
+
type: "object",
|
|
46
|
+
properties: {
|
|
47
|
+
command: { type: "string", description: "Shell command to execute." },
|
|
48
|
+
description: { type: "string", description: "Human-readable description of what this command does (shown to user)." },
|
|
49
|
+
cwd: { type: "string", description: "Working directory. Defaults to process cwd." },
|
|
50
|
+
timeout: { type: "number", description: "Timeout in ms. Default: 30000, max: 120000." },
|
|
51
|
+
run_in_background: { type: "boolean", description: "If true, run in background and return a task_id. Use task_output to get results later." },
|
|
52
|
+
},
|
|
53
|
+
required: ["command"],
|
|
23
54
|
},
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
if (!safety.safe && safety.severity === "block") {
|
|
34
|
-
return { output: `Blocked: ${safety.reason}`, is_error: true };
|
|
35
|
-
}
|
|
36
|
-
const isWindows = process.platform === "win32";
|
|
37
|
-
const shell = isWindows ? "cmd" : "bash";
|
|
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
|
|
62
|
-
try {
|
|
63
|
-
const output = execFileSync(shell, shellArgs, {
|
|
64
|
-
cwd,
|
|
65
|
-
encoding: "utf-8",
|
|
66
|
-
timeout,
|
|
67
|
-
maxBuffer: MAX_OUTPUT_BYTES,
|
|
68
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
69
|
-
env: scrubEnv(),
|
|
70
|
-
});
|
|
71
|
-
return { output: output.trim() || "(no output)" };
|
|
72
|
-
}
|
|
73
|
-
catch (err) {
|
|
74
|
-
if (err && typeof err === "object" && "stdout" in err) {
|
|
75
|
-
const e = err;
|
|
76
|
-
const combined = [e.stdout, e.stderr].filter(Boolean).join("\n").trim();
|
|
77
|
-
return { output: `Exit code ${e.status ?? 1}\n${combined}`, is_error: true };
|
|
55
|
+
async execute(input, signal) {
|
|
56
|
+
const command = input.command;
|
|
57
|
+
const cwd = input.cwd || process.cwd();
|
|
58
|
+
const timeout = Math.min(MAX_TIMEOUT_MS, input.timeout || DEFAULT_TIMEOUT_MS);
|
|
59
|
+
const description = input.description;
|
|
60
|
+
const runInBackground = input.run_in_background;
|
|
61
|
+
const safety = checkShellSafety(command);
|
|
62
|
+
if (!safety.safe && safety.severity === "block") {
|
|
63
|
+
return { output: `Blocked: ${safety.reason}`, is_error: true, permissionDenied: true };
|
|
78
64
|
}
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
65
|
+
const isWindows = process.platform === "win32";
|
|
66
|
+
const shell = isWindows ? "cmd" : "bash";
|
|
67
|
+
const shellArgs = isWindows ? ["/c", command] : ["-c", command];
|
|
68
|
+
// Kernel write fence — one decision feeds both spawn paths.
|
|
69
|
+
const perms = getPermissions?.();
|
|
70
|
+
let decision;
|
|
71
|
+
try {
|
|
72
|
+
decision = wrapWithSandbox([shell, ...shellArgs], {
|
|
73
|
+
mode: perms?.sandboxMode ?? "off",
|
|
74
|
+
workspaceRoot: perms?.projectRoot ?? process.cwd(),
|
|
75
|
+
extraWritable: perms?.allowedPaths ?? [],
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
if (err instanceof SandboxRequiredError) {
|
|
80
|
+
return { output: err.message, is_error: true, permissionDenied: true };
|
|
81
|
+
}
|
|
82
|
+
throw err;
|
|
83
|
+
}
|
|
84
|
+
const noticePrefix = decision.notice ? `${decision.notice}\n` : "";
|
|
85
|
+
const [exe, ...exeArgs] = decision.argv;
|
|
86
|
+
// Background execution
|
|
87
|
+
if (runInBackground) {
|
|
88
|
+
const taskId = `bg-${nextBgId++}`;
|
|
89
|
+
const outputFile = path.join(backgroundLogDir(), `${taskId}.log`);
|
|
90
|
+
const fd = fs.openSync(outputFile, "wx");
|
|
91
|
+
const child = spawn(exe, exeArgs, {
|
|
92
|
+
cwd,
|
|
93
|
+
stdio: ["ignore", fd, fd],
|
|
94
|
+
env: scrubEnv(),
|
|
95
|
+
detached: true,
|
|
96
|
+
});
|
|
97
|
+
const task = { pid: child.pid, outputFile, done: false, exitCode: null };
|
|
98
|
+
backgroundTasks.set(taskId, task);
|
|
99
|
+
child.on("exit", (code) => {
|
|
100
|
+
task.done = true;
|
|
101
|
+
task.exitCode = code;
|
|
102
|
+
fs.closeSync(fd);
|
|
103
|
+
});
|
|
104
|
+
child.unref();
|
|
105
|
+
const desc = description ? ` (${description})` : "";
|
|
106
|
+
const confined = decision.sandboxed ? " [sandboxed]" : "";
|
|
107
|
+
return { output: `${noticePrefix}Background task ${taskId} started${desc}${confined}. PID: ${child.pid}. Use task_output to get results.` };
|
|
108
|
+
}
|
|
109
|
+
// 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)") };
|
|
124
|
+
}
|
|
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 };
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/** Back-compat singleton: no permission source, so the sandbox stays off. */
|
|
146
|
+
export const shellTool = createShellTool();
|
|
84
147
|
// Task output and stop tools
|
|
85
148
|
export const taskOutputTool = {
|
|
86
149
|
name: "task_output",
|
package/dist/tools/skill.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { findSkill } from "@phren/cli/skill/registry";
|
|
1
2
|
import * as fs from "fs";
|
|
2
|
-
import * as path from "path";
|
|
3
3
|
export function createSkillTool(phrenCtx) {
|
|
4
4
|
return {
|
|
5
5
|
name: "run_skill",
|
|
6
|
-
description: "Execute a phren skill by name. Skills are prompt templates stored in
|
|
6
|
+
description: "Execute a phren skill by name. Skills are prompt templates stored in the phren store (global/skills/ and per-project skills/). Returns the skill content which you should follow as instructions.",
|
|
7
7
|
input_schema: {
|
|
8
8
|
type: "object",
|
|
9
9
|
properties: {
|
|
@@ -18,27 +18,27 @@ export function createSkillTool(phrenCtx) {
|
|
|
18
18
|
if (!phrenCtx) {
|
|
19
19
|
return { output: "No phren context available.", is_error: true };
|
|
20
20
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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}` };
|
|
21
|
+
try {
|
|
22
|
+
// The CLI's registry resolves precedence (project over global), folder
|
|
23
|
+
// vs flat layout, and enable state — the same view `phren skills` shows.
|
|
24
|
+
const result = findSkill(phrenCtx.phrenPath, phrenCtx.profile, phrenCtx.project ?? undefined, name);
|
|
25
|
+
if (!result) {
|
|
26
|
+
return { output: `Skill "${name}" not found. Use the skills listed in the system prompt, or check \`phren skills\`.`, is_error: true };
|
|
27
|
+
}
|
|
28
|
+
if ("error" in result) {
|
|
29
|
+
return { output: result.error, is_error: true };
|
|
36
30
|
}
|
|
37
|
-
|
|
38
|
-
|
|
31
|
+
if (!result.enabled) {
|
|
32
|
+
return { output: `Skill "${result.name}" exists but is disabled for this scope.`, is_error: true };
|
|
39
33
|
}
|
|
34
|
+
const content = fs.readFileSync(result.path, "utf-8");
|
|
35
|
+
const stripped = content.replace(/^---\n[\s\S]*?\n---\n/, "");
|
|
36
|
+
return { output: `[Skill: ${result.name}${args ? ` ${args}` : ""}]\n\n${stripped}` };
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
40
|
+
return { output: `Failed to load skill "${name}": ${msg}`, is_error: true };
|
|
40
41
|
}
|
|
41
|
-
return { output: `Skill "${name}" not found. Check ~/.phren/skills/ for available skills.`, is_error: true };
|
|
42
42
|
},
|
|
43
43
|
};
|
|
44
44
|
}
|
|
@@ -72,9 +72,13 @@ export function createListAgentsTool(spawner) {
|
|
|
72
72
|
},
|
|
73
73
|
};
|
|
74
74
|
}
|
|
75
|
-
|
|
75
|
+
const VALID_PERMISSION_MODES = ["suggest", "auto-confirm", "plan", "full-auto"];
|
|
76
|
+
export function createSpawnAgentTool(spawner, getPermissions) {
|
|
76
77
|
return {
|
|
77
78
|
name: "spawn_agent",
|
|
79
|
+
// The foreground subagent wait is 300s; without a wider scheduler budget
|
|
80
|
+
// the default 120s race always won while the child kept running.
|
|
81
|
+
timeoutMs: 330_000,
|
|
78
82
|
description: `Spawn a child agent. Two modes:
|
|
79
83
|
|
|
80
84
|
**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.
|
|
@@ -99,10 +103,32 @@ export function createSpawnAgentTool(spawner) {
|
|
|
99
103
|
type: "boolean",
|
|
100
104
|
description: "If true, spawn as TeamAgent on idle (no task yet, waits for instructions). Implies background=true.",
|
|
101
105
|
},
|
|
106
|
+
isolation: {
|
|
107
|
+
type: "string",
|
|
108
|
+
enum: ["worktree"],
|
|
109
|
+
description: "Set to 'worktree' to run the child in its own git worktree, isolated from your working tree.",
|
|
110
|
+
},
|
|
111
|
+
agent_type: {
|
|
112
|
+
type: "string",
|
|
113
|
+
description: "Agent type name (e.g. 'explore', 'plan', 'general') to restrict the child's tools and prompt.",
|
|
114
|
+
},
|
|
115
|
+
provider: {
|
|
116
|
+
type: "string",
|
|
117
|
+
description: "Override the child's provider (openrouter, anthropic, openai, openai-codex, ollama).",
|
|
118
|
+
},
|
|
119
|
+
model: {
|
|
120
|
+
type: "string",
|
|
121
|
+
description: "Override the child's model.",
|
|
122
|
+
},
|
|
123
|
+
permissions: {
|
|
124
|
+
type: "string",
|
|
125
|
+
enum: ["suggest", "auto-confirm", "plan", "full-auto"],
|
|
126
|
+
description: "Permission mode for the child. Defaults to the parent's current mode.",
|
|
127
|
+
},
|
|
102
128
|
},
|
|
103
129
|
required: ["name"],
|
|
104
130
|
},
|
|
105
|
-
async execute(input) {
|
|
131
|
+
async execute(input, signal) {
|
|
106
132
|
const name = input.name;
|
|
107
133
|
const task = input.task || "";
|
|
108
134
|
const idle = input.idle;
|
|
@@ -110,14 +136,30 @@ export function createSpawnAgentTool(spawner) {
|
|
|
110
136
|
if (!name) {
|
|
111
137
|
return { output: "Agent name is required.", is_error: true };
|
|
112
138
|
}
|
|
139
|
+
if (!spawner.canSpawn()) {
|
|
140
|
+
return { output: "Maximum subagent depth reached — this agent cannot spawn more children.", is_error: true };
|
|
141
|
+
}
|
|
113
142
|
const agentTask = idle
|
|
114
143
|
? `You are agent "${name}". You have been spawned on idle. Wait for instructions.`
|
|
115
144
|
: task || `You are agent "${name}". Work on any tasks assigned to you.`;
|
|
145
|
+
const perms = getPermissions?.();
|
|
146
|
+
const requestedPermissions = input.permissions;
|
|
147
|
+
const permissions = requestedPermissions && VALID_PERMISSION_MODES.includes(requestedPermissions)
|
|
148
|
+
? requestedPermissions
|
|
149
|
+
: perms?.mode;
|
|
150
|
+
const isolation = input.isolation === "worktree" ? "worktree" : undefined;
|
|
116
151
|
const agentId = spawner.spawn({
|
|
117
152
|
task: agentTask,
|
|
118
153
|
displayName: name,
|
|
119
|
-
cwd: process.cwd(),
|
|
154
|
+
cwd: perms?.projectRoot ?? process.cwd(),
|
|
120
155
|
verbose: false,
|
|
156
|
+
isolation,
|
|
157
|
+
agentType: input.agent_type,
|
|
158
|
+
provider: input.provider,
|
|
159
|
+
model: input.model,
|
|
160
|
+
permissions,
|
|
161
|
+
sandboxMode: perms?.sandboxMode,
|
|
162
|
+
allowedPaths: perms?.allowedPaths,
|
|
121
163
|
});
|
|
122
164
|
// TeamAgent (background): return immediately, agent lives in tab bar
|
|
123
165
|
if (background) {
|
|
@@ -128,29 +170,51 @@ export function createSpawnAgentTool(spawner) {
|
|
|
128
170
|
}
|
|
129
171
|
// Subagent (foreground): wait for completion, return result inline
|
|
130
172
|
return new Promise((resolve) => {
|
|
173
|
+
let settled = false;
|
|
174
|
+
let timer;
|
|
175
|
+
const cleanup = () => {
|
|
176
|
+
if (timer)
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
spawner.removeListener("done", onDone);
|
|
179
|
+
spawner.removeListener("error", onError);
|
|
180
|
+
signal?.removeEventListener("abort", onAbort);
|
|
181
|
+
};
|
|
182
|
+
const finish = (result) => {
|
|
183
|
+
if (settled)
|
|
184
|
+
return;
|
|
185
|
+
settled = true;
|
|
186
|
+
cleanup();
|
|
187
|
+
resolve(result);
|
|
188
|
+
};
|
|
131
189
|
const onDone = (doneId, result) => {
|
|
132
190
|
if (doneId !== agentId)
|
|
133
191
|
return;
|
|
134
|
-
|
|
135
|
-
spawner.removeListener("error", onError);
|
|
136
|
-
resolve({
|
|
192
|
+
finish({
|
|
137
193
|
output: result.finalText || `Agent "${name}" completed (${result.turns} turns, ${result.toolCalls} tool calls)`,
|
|
138
194
|
});
|
|
139
195
|
};
|
|
140
196
|
const onError = (errId, error) => {
|
|
141
197
|
if (errId !== agentId)
|
|
142
198
|
return;
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
199
|
+
finish({ output: `Agent "${name}" failed: ${error}`, is_error: true });
|
|
200
|
+
};
|
|
201
|
+
const onAbort = () => {
|
|
202
|
+
spawner.cancel(agentId);
|
|
203
|
+
finish({ output: `Agent "${name}" cancelled.`, is_error: true });
|
|
146
204
|
};
|
|
147
205
|
spawner.on("done", onDone);
|
|
148
206
|
spawner.on("error", onError);
|
|
207
|
+
if (signal) {
|
|
208
|
+
if (signal.aborted) {
|
|
209
|
+
onAbort();
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
213
|
+
}
|
|
149
214
|
// Timeout after 5 minutes
|
|
150
|
-
setTimeout(() => {
|
|
151
|
-
spawner.
|
|
152
|
-
|
|
153
|
-
resolve({ output: `Agent "${name}" timed out after 5 minutes`, is_error: true });
|
|
215
|
+
timer = setTimeout(() => {
|
|
216
|
+
spawner.cancel(agentId);
|
|
217
|
+
finish({ output: `Agent "${name}" timed out after 5 minutes`, is_error: true });
|
|
154
218
|
}, 300_000);
|
|
155
219
|
});
|
|
156
220
|
},
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
let currentPlan = [];
|
|
2
|
+
export function getPlan() {
|
|
3
|
+
return currentPlan;
|
|
4
|
+
}
|
|
5
|
+
export function clearPlan() {
|
|
6
|
+
currentPlan = [];
|
|
7
|
+
}
|
|
8
|
+
const STATUSES = ["pending", "in_progress", "completed"];
|
|
9
|
+
export const updatePlanTool = {
|
|
10
|
+
name: "update_plan",
|
|
11
|
+
description: "Create or replace the task plan for the current work. Pass the complete ordered list every time; keep at most one item in_progress. Use it for multi-step tasks so progress is visible.",
|
|
12
|
+
input_schema: {
|
|
13
|
+
type: "object",
|
|
14
|
+
properties: {
|
|
15
|
+
plan: {
|
|
16
|
+
type: "array",
|
|
17
|
+
description: "The complete plan, in order.",
|
|
18
|
+
items: {
|
|
19
|
+
type: "object",
|
|
20
|
+
properties: {
|
|
21
|
+
content: { type: "string", description: "Short imperative description of the step." },
|
|
22
|
+
status: { type: "string", enum: STATUSES },
|
|
23
|
+
},
|
|
24
|
+
required: ["content", "status"],
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
required: ["plan"],
|
|
29
|
+
},
|
|
30
|
+
async execute(input) {
|
|
31
|
+
const raw = Array.isArray(input.plan) ? input.plan : [];
|
|
32
|
+
const plan = raw
|
|
33
|
+
.slice(0, 50)
|
|
34
|
+
.map((item) => {
|
|
35
|
+
const entry = (item ?? {});
|
|
36
|
+
const content = String(entry.content ?? "").slice(0, 500);
|
|
37
|
+
const status = STATUSES.includes(String(entry.status)) ? String(entry.status) : "pending";
|
|
38
|
+
return { content, status };
|
|
39
|
+
})
|
|
40
|
+
.filter((item) => item.content);
|
|
41
|
+
currentPlan = plan;
|
|
42
|
+
if (plan.length === 0)
|
|
43
|
+
return { output: "Plan cleared." };
|
|
44
|
+
const done = plan.filter((item) => item.status === "completed").length;
|
|
45
|
+
const active = plan.find((item) => item.status === "in_progress");
|
|
46
|
+
return { output: `Plan updated: ${done}/${plan.length} done${active ? `, now: ${active.content}` : ""}.` };
|
|
47
|
+
},
|
|
48
|
+
};
|
package/dist/tools/web-fetch.js
CHANGED
|
@@ -1,3 +1,77 @@
|
|
|
1
|
+
import * as dns from "node:dns/promises";
|
|
2
|
+
import * as net from "node:net";
|
|
3
|
+
/**
|
|
4
|
+
* SSRF guard: block URLs that resolve to private, loopback, or link-local
|
|
5
|
+
* addresses so an injected "fetch this URL" can't reach cloud metadata
|
|
6
|
+
* endpoints or internal services. PHREN_AGENT_ALLOW_PRIVATE_FETCH=1 disables
|
|
7
|
+
* (for users whose docs genuinely live on their LAN).
|
|
8
|
+
*/
|
|
9
|
+
export function isPrivateAddress(ip) {
|
|
10
|
+
if (net.isIPv6(ip)) {
|
|
11
|
+
const lower = ip.toLowerCase();
|
|
12
|
+
// Normalize the unambiguous cases: loopback, link-local, unique-local, v4-mapped
|
|
13
|
+
if (lower === "::1" || lower === "::")
|
|
14
|
+
return true;
|
|
15
|
+
if (lower.startsWith("fe80:") || lower.startsWith("fc") || lower.startsWith("fd"))
|
|
16
|
+
return true;
|
|
17
|
+
const v4 = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
|
|
18
|
+
if (v4)
|
|
19
|
+
return isPrivateAddress(v4[1]);
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
const parts = ip.split(".").map(Number);
|
|
23
|
+
if (parts.length !== 4 || parts.some((p) => !Number.isInteger(p) || p < 0 || p > 255)) {
|
|
24
|
+
return true; // unparseable — fail closed
|
|
25
|
+
}
|
|
26
|
+
const [a, b] = parts;
|
|
27
|
+
if (a === 10 || a === 127 || a === 0)
|
|
28
|
+
return true; // private, loopback, "this"
|
|
29
|
+
if (a === 172 && b >= 16 && b <= 31)
|
|
30
|
+
return true; // 172.16/12
|
|
31
|
+
if (a === 192 && b === 168)
|
|
32
|
+
return true; // 192.168/16
|
|
33
|
+
if (a === 169 && b === 254)
|
|
34
|
+
return true; // link-local (cloud metadata!)
|
|
35
|
+
if (a === 100 && b >= 64 && b <= 127)
|
|
36
|
+
return true; // CGNAT 100.64/10
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
/** Returns a rejection reason, or null when the URL is safe to fetch. */
|
|
40
|
+
export async function checkUrlSafety(rawUrl) {
|
|
41
|
+
if (process.env.PHREN_AGENT_ALLOW_PRIVATE_FETCH === "1")
|
|
42
|
+
return null;
|
|
43
|
+
let parsed;
|
|
44
|
+
try {
|
|
45
|
+
parsed = new URL(rawUrl);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return `Invalid URL: ${rawUrl}`;
|
|
49
|
+
}
|
|
50
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
51
|
+
return `Only http/https URLs are allowed (got ${parsed.protocol})`;
|
|
52
|
+
}
|
|
53
|
+
const host = parsed.hostname.replace(/^\[|\]$/g, "");
|
|
54
|
+
if (net.isIP(host)) {
|
|
55
|
+
return isPrivateAddress(host)
|
|
56
|
+
? `Blocked: ${host} is a private/loopback/link-local address (SSRF guard; PHREN_AGENT_ALLOW_PRIVATE_FETCH=1 to override)`
|
|
57
|
+
: null;
|
|
58
|
+
}
|
|
59
|
+
if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) {
|
|
60
|
+
return `Blocked: ${host} is a local hostname (SSRF guard; PHREN_AGENT_ALLOW_PRIVATE_FETCH=1 to override)`;
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
const results = await dns.lookup(host, { all: true });
|
|
64
|
+
for (const { address } of results) {
|
|
65
|
+
if (isPrivateAddress(address)) {
|
|
66
|
+
return `Blocked: ${host} resolves to private address ${address} (SSRF guard; PHREN_AGENT_ALLOW_PRIVATE_FETCH=1 to override)`;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return `Could not resolve host: ${host}`;
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
1
75
|
export function createWebFetchTool() {
|
|
2
76
|
return {
|
|
3
77
|
name: "web_fetch",
|
|
@@ -10,26 +84,38 @@ export function createWebFetchTool() {
|
|
|
10
84
|
},
|
|
11
85
|
required: ["url"],
|
|
12
86
|
},
|
|
13
|
-
async execute(input) {
|
|
87
|
+
async execute(input, signal) {
|
|
14
88
|
const url = input.url;
|
|
15
89
|
const maxLen = input.max_length || 50_000;
|
|
90
|
+
const unsafe = await checkUrlSafety(url);
|
|
91
|
+
if (unsafe)
|
|
92
|
+
return { output: unsafe, is_error: true };
|
|
16
93
|
try {
|
|
17
94
|
const res = await fetch(url, {
|
|
18
95
|
headers: { "User-Agent": "phren-agent/0.1" },
|
|
19
|
-
signal: AbortSignal.timeout(15_000),
|
|
96
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15_000)]) : AbortSignal.timeout(15_000),
|
|
97
|
+
redirect: "manual",
|
|
20
98
|
});
|
|
99
|
+
// Follow redirects manually so each hop goes through the SSRF guard.
|
|
100
|
+
if (res.status >= 300 && res.status < 400) {
|
|
101
|
+
const location = res.headers.get("location");
|
|
102
|
+
if (!location)
|
|
103
|
+
return { output: `HTTP ${res.status} with no Location header`, is_error: true };
|
|
104
|
+
const next = new URL(location, url).toString();
|
|
105
|
+
const nextUnsafe = await checkUrlSafety(next);
|
|
106
|
+
if (nextUnsafe)
|
|
107
|
+
return { output: `Redirect to unsafe target: ${nextUnsafe}`, is_error: true };
|
|
108
|
+
const res2 = await fetch(next, {
|
|
109
|
+
headers: { "User-Agent": "phren-agent/0.1" },
|
|
110
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15_000)]) : AbortSignal.timeout(15_000),
|
|
111
|
+
});
|
|
112
|
+
if (!res2.ok)
|
|
113
|
+
return { output: `HTTP ${res2.status}: ${res2.statusText}`, is_error: true };
|
|
114
|
+
return { output: cleanHtml(await res2.text(), maxLen) };
|
|
115
|
+
}
|
|
21
116
|
if (!res.ok)
|
|
22
117
|
return { output: `HTTP ${res.status}: ${res.statusText}`, is_error: true };
|
|
23
|
-
|
|
24
|
-
// Strip HTML tags for readability
|
|
25
|
-
text = text.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "");
|
|
26
|
-
text = text.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "");
|
|
27
|
-
text = text.replace(/<[^>]+>/g, " ");
|
|
28
|
-
text = text.replace(/\s{2,}/g, " ").trim();
|
|
29
|
-
if (text.length > maxLen) {
|
|
30
|
-
text = text.slice(0, maxLen) + `\n\n[truncated at ${maxLen} chars]`;
|
|
31
|
-
}
|
|
32
|
-
return { output: text };
|
|
118
|
+
return { output: cleanHtml(await res.text(), maxLen) };
|
|
33
119
|
}
|
|
34
120
|
catch (err) {
|
|
35
121
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -38,3 +124,15 @@ export function createWebFetchTool() {
|
|
|
38
124
|
},
|
|
39
125
|
};
|
|
40
126
|
}
|
|
127
|
+
function cleanHtml(raw, maxLen) {
|
|
128
|
+
let text = raw;
|
|
129
|
+
// Strip HTML tags for readability
|
|
130
|
+
text = text.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "");
|
|
131
|
+
text = text.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "");
|
|
132
|
+
text = text.replace(/<[^>]+>/g, " ");
|
|
133
|
+
text = text.replace(/\s{2,}/g, " ").trim();
|
|
134
|
+
if (text.length > maxLen) {
|
|
135
|
+
text = text.slice(0, maxLen) + `\n\n[truncated at ${maxLen} chars]`;
|
|
136
|
+
}
|
|
137
|
+
return text;
|
|
138
|
+
}
|
package/dist/tools/web-search.js
CHANGED
|
@@ -18,11 +18,11 @@ export function createWebSearchTool() {
|
|
|
18
18
|
},
|
|
19
19
|
required: ["query"],
|
|
20
20
|
},
|
|
21
|
-
async execute(input) {
|
|
21
|
+
async execute(input, signal) {
|
|
22
22
|
const query = input.query;
|
|
23
23
|
const limit = Math.min(input.limit || 5, 10);
|
|
24
24
|
try {
|
|
25
|
-
const results = await searchDuckDuckGo(query, limit);
|
|
25
|
+
const results = await searchDuckDuckGo(query, limit, signal);
|
|
26
26
|
if (results.length === 0) {
|
|
27
27
|
return { output: "No search results found." };
|
|
28
28
|
}
|
|
@@ -36,7 +36,7 @@ export function createWebSearchTool() {
|
|
|
36
36
|
},
|
|
37
37
|
};
|
|
38
38
|
}
|
|
39
|
-
async function searchDuckDuckGo(query, limit) {
|
|
39
|
+
async function searchDuckDuckGo(query, limit, signal) {
|
|
40
40
|
const encoded = encodeURIComponent(query);
|
|
41
41
|
const url = `https://html.duckduckgo.com/html/?q=${encoded}`;
|
|
42
42
|
const res = await fetch(url, {
|
|
@@ -44,7 +44,7 @@ async function searchDuckDuckGo(query, limit) {
|
|
|
44
44
|
"User-Agent": "phren-agent/0.1 (search tool)",
|
|
45
45
|
"Accept": "text/html",
|
|
46
46
|
},
|
|
47
|
-
signal: AbortSignal.timeout(10_000),
|
|
47
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(10_000)]) : AbortSignal.timeout(10_000),
|
|
48
48
|
});
|
|
49
49
|
if (!res.ok) {
|
|
50
50
|
throw new Error(`Search returned HTTP ${res.status}`);
|