@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.
- 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/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 +14 -8
- 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/edit-file.js
CHANGED
|
@@ -2,43 +2,102 @@ import * as fs from "fs";
|
|
|
2
2
|
import * as path from "path";
|
|
3
3
|
import { encodeDiffPayload } from "../multi/diff-renderer.js";
|
|
4
4
|
import { checkSensitivePath, validatePath } from "../permissions/sandbox.js";
|
|
5
|
+
import { applyEdits, snippetAround } from "./edit-engine.js";
|
|
6
|
+
/** Shared path checks and read for the edit tools. */
|
|
7
|
+
function openForEdit(filePath) {
|
|
8
|
+
if (typeof filePath !== "string" || filePath === "") {
|
|
9
|
+
return { ok: false, result: { output: "path is required.", is_error: true } };
|
|
10
|
+
}
|
|
11
|
+
const sensitive = checkSensitivePath(path.resolve(filePath));
|
|
12
|
+
if (sensitive.sensitive)
|
|
13
|
+
return { ok: false, result: { output: `Access denied: ${sensitive.reason}`, is_error: true } };
|
|
14
|
+
const sandboxResult = validatePath(filePath, process.cwd(), []);
|
|
15
|
+
if (!sandboxResult.ok)
|
|
16
|
+
return { ok: false, result: { output: `Path outside sandbox: ${sandboxResult.error}`, is_error: true } };
|
|
17
|
+
if (!fs.existsSync(filePath)) {
|
|
18
|
+
return { ok: false, result: { output: `File not found: ${filePath}. Use write_file to create a new file.`, is_error: true } };
|
|
19
|
+
}
|
|
20
|
+
if (fs.statSync(filePath).isDirectory()) {
|
|
21
|
+
return { ok: false, result: { output: `${filePath} is a directory, not a file.`, is_error: true } };
|
|
22
|
+
}
|
|
23
|
+
return { ok: true, filePath, content: fs.readFileSync(filePath, "utf-8") };
|
|
24
|
+
}
|
|
25
|
+
function runEdits(filePath, edits) {
|
|
26
|
+
const opened = openForEdit(filePath);
|
|
27
|
+
if (!opened.ok)
|
|
28
|
+
return opened.result;
|
|
29
|
+
const outcome = applyEdits(opened.content, edits);
|
|
30
|
+
if (!outcome.ok)
|
|
31
|
+
return { output: `${opened.filePath}: ${outcome.error}`, is_error: true };
|
|
32
|
+
fs.writeFileSync(opened.filePath, outcome.content);
|
|
33
|
+
const count = outcome.replacements === 1 ? "1 replacement" : `${outcome.replacements} replacements`;
|
|
34
|
+
const note = outcome.note ? ` (${outcome.note})` : "";
|
|
35
|
+
// The model sees a short numbered excerpt of the result; the diff payload
|
|
36
|
+
// after DIFF_MARKER is for the TUI and is stripped before the model sees it.
|
|
37
|
+
const snippet = snippetAround(outcome.content.replace(/\r\n/g, "\n"), outcome.firstLine, outcome.lastLine);
|
|
38
|
+
return {
|
|
39
|
+
output: `Edited ${opened.filePath}: ${count}${note}.\n${snippet}${encodeDiffPayload(opened.filePath, opened.content, outcome.content)}`,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
5
42
|
export const editFileTool = {
|
|
6
43
|
name: "edit_file",
|
|
7
|
-
description: "Edit a file by replacing an exact string
|
|
44
|
+
description: "Edit a file by replacing an exact string. Preferred over write_file for existing files. old_string must match the file " +
|
|
45
|
+
"exactly (copy it from read_file output without the line-number prefix) and must be unique unless replace_all is true; " +
|
|
46
|
+
"include a few surrounding lines to make it unique. On failure the error shows the closest matching lines.",
|
|
8
47
|
input_schema: {
|
|
9
48
|
type: "object",
|
|
10
49
|
properties: {
|
|
11
50
|
path: { type: "string", description: "File path to edit." },
|
|
12
|
-
old_string: { type: "string", description: "Exact
|
|
13
|
-
new_string: { type: "string", description: "Replacement
|
|
51
|
+
old_string: { type: "string", description: "Exact text to find." },
|
|
52
|
+
new_string: { type: "string", description: "Replacement text (must differ from old_string)." },
|
|
53
|
+
replace_all: { type: "boolean", description: "Replace every occurrence instead of requiring a unique match. Default false." },
|
|
14
54
|
},
|
|
15
55
|
required: ["path", "old_string", "new_string"],
|
|
16
56
|
},
|
|
17
57
|
async execute(input) {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
58
|
+
return runEdits(input.path, [{
|
|
59
|
+
old_string: input.old_string,
|
|
60
|
+
new_string: input.new_string,
|
|
61
|
+
replace_all: input.replace_all === true,
|
|
62
|
+
}]);
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
export const multiEditTool = {
|
|
66
|
+
name: "multi_edit",
|
|
67
|
+
description: "Apply several exact-string edits to one file in a single atomic call. Edits run in order, each against the result of " +
|
|
68
|
+
"the previous one; if any edit fails, nothing is written. Same matching rules as edit_file.",
|
|
69
|
+
input_schema: {
|
|
70
|
+
type: "object",
|
|
71
|
+
properties: {
|
|
72
|
+
path: { type: "string", description: "File path to edit." },
|
|
73
|
+
edits: {
|
|
74
|
+
type: "array",
|
|
75
|
+
description: "Edits to apply in order.",
|
|
76
|
+
items: {
|
|
77
|
+
type: "object",
|
|
78
|
+
properties: {
|
|
79
|
+
old_string: { type: "string" },
|
|
80
|
+
new_string: { type: "string" },
|
|
81
|
+
replace_all: { type: "boolean" },
|
|
82
|
+
},
|
|
83
|
+
required: ["old_string", "new_string"],
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
required: ["path", "edits"],
|
|
88
|
+
},
|
|
89
|
+
async execute(input) {
|
|
90
|
+
const edits = input.edits;
|
|
91
|
+
if (!Array.isArray(edits) || edits.length === 0) {
|
|
92
|
+
return { output: "edits must be a non-empty array of {old_string, new_string, replace_all?}.", is_error: true };
|
|
31
93
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
const newContent = oldContent.replace(oldStr, newStr);
|
|
41
|
-
fs.writeFileSync(filePath, newContent);
|
|
42
|
-
return { output: `Edited ${filePath}${encodeDiffPayload(filePath, oldContent, newContent)}` };
|
|
94
|
+
return runEdits(input.path, edits.map((e) => {
|
|
95
|
+
const edit = (e ?? {});
|
|
96
|
+
return {
|
|
97
|
+
old_string: edit.old_string,
|
|
98
|
+
new_string: edit.new_string,
|
|
99
|
+
replace_all: edit.replace_all === true,
|
|
100
|
+
};
|
|
101
|
+
}));
|
|
43
102
|
},
|
|
44
103
|
};
|
package/dist/tools/grep.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as fs from "fs";
|
|
2
2
|
import * as path from "path";
|
|
3
|
-
import { validatePath } from "../permissions/sandbox.js";
|
|
3
|
+
import { checkSensitivePath, validatePath } from "../permissions/sandbox.js";
|
|
4
4
|
function searchFile(filePath, regex, contextBefore, contextAfter) {
|
|
5
5
|
let content;
|
|
6
6
|
try {
|
|
@@ -33,8 +33,9 @@ function searchFileMultiline(filePath, regex) {
|
|
|
33
33
|
return [];
|
|
34
34
|
}
|
|
35
35
|
const matches = [];
|
|
36
|
-
|
|
37
|
-
|
|
36
|
+
// matchAll advances after empty matches (anchors/lookarounds), unlike exec.
|
|
37
|
+
// It also leaves the shared expression ready for the next file.
|
|
38
|
+
for (const match of content.matchAll(regex)) {
|
|
38
39
|
const beforeMatch = content.slice(0, match.index);
|
|
39
40
|
const lineNo = beforeMatch.split("\n").length;
|
|
40
41
|
matches.push({ line: lineNo, text: match[0].slice(0, 200) });
|
|
@@ -121,6 +122,9 @@ export const grepTool = {
|
|
|
121
122
|
if (!pathResult.ok) {
|
|
122
123
|
return { output: `Path outside sandbox: ${pathResult.error}`, is_error: true };
|
|
123
124
|
}
|
|
125
|
+
if (checkSensitivePath(path.resolve(searchPath)).sensitive || checkSensitivePath(pathResult.resolved).sensitive) {
|
|
126
|
+
return { output: "Access denied: sensitive path.", is_error: true };
|
|
127
|
+
}
|
|
124
128
|
let regex;
|
|
125
129
|
try {
|
|
126
130
|
const flags = (caseInsensitive ? "i" : "") + (multiline ? "gs" : "");
|
|
@@ -129,14 +133,14 @@ export const grepTool = {
|
|
|
129
133
|
catch {
|
|
130
134
|
return { output: `Invalid regex: ${pattern}`, is_error: true };
|
|
131
135
|
}
|
|
132
|
-
const stat = fs.statSync(
|
|
136
|
+
const stat = fs.statSync(pathResult.resolved, { throwIfNoEntry: false });
|
|
133
137
|
if (!stat)
|
|
134
138
|
return { output: `Path not found: ${searchPath}`, is_error: true };
|
|
135
139
|
// Single file
|
|
136
140
|
if (stat.isFile()) {
|
|
137
141
|
const results = multiline
|
|
138
|
-
? searchFileMultiline(
|
|
139
|
-
: searchFile(
|
|
142
|
+
? searchFileMultiline(pathResult.resolved, regex)
|
|
143
|
+
: searchFile(pathResult.resolved, regex, contextB, contextA);
|
|
140
144
|
if (outputMode === "files_with_matches")
|
|
141
145
|
return { output: results.length > 0 ? searchPath : "No matches." };
|
|
142
146
|
if (outputMode === "count")
|
|
@@ -161,17 +165,28 @@ export const grepTool = {
|
|
|
161
165
|
files.push(...filtered);
|
|
162
166
|
}
|
|
163
167
|
const output = [];
|
|
164
|
-
let
|
|
168
|
+
let _totalMatches = 0;
|
|
165
169
|
let skipped = 0;
|
|
166
170
|
for (const file of files) {
|
|
167
171
|
if (output.length >= headLimit + offset)
|
|
168
172
|
break;
|
|
173
|
+
const checked = validatePath(file, process.cwd(), []);
|
|
174
|
+
if (!checked.ok || checkSensitivePath(file).sensitive || checkSensitivePath(checked.resolved).sensitive)
|
|
175
|
+
continue;
|
|
176
|
+
// Ignore devices, pipes and directories, including symlinks to them.
|
|
177
|
+
try {
|
|
178
|
+
if (!fs.statSync(checked.resolved).isFile())
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
169
184
|
const results = multiline
|
|
170
|
-
? searchFileMultiline(
|
|
171
|
-
: searchFile(
|
|
185
|
+
? searchFileMultiline(checked.resolved, regex)
|
|
186
|
+
: searchFile(checked.resolved, regex, contextB, contextA);
|
|
172
187
|
if (results.length === 0)
|
|
173
188
|
continue;
|
|
174
|
-
|
|
189
|
+
_totalMatches++;
|
|
175
190
|
if (skipped < offset) {
|
|
176
191
|
skipped++;
|
|
177
192
|
continue;
|
package/dist/tools/lint-test.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import * as fs from "fs";
|
|
2
2
|
import * as path from "path";
|
|
3
|
-
import { execFileSync } from "child_process";
|
|
4
3
|
/** Detect test command from project config files. */
|
|
5
4
|
export function detectTestCommand(cwd) {
|
|
6
5
|
// package.json scripts.test
|
|
@@ -53,24 +52,3 @@ export function detectLintCommand(cwd) {
|
|
|
53
52
|
}
|
|
54
53
|
return null;
|
|
55
54
|
}
|
|
56
|
-
/** Run a command and return pass/fail + output. */
|
|
57
|
-
export function runPostEditCheck(command, cwd) {
|
|
58
|
-
try {
|
|
59
|
-
const output = execFileSync("bash", ["-c", command], {
|
|
60
|
-
cwd,
|
|
61
|
-
encoding: "utf-8",
|
|
62
|
-
timeout: 60_000,
|
|
63
|
-
maxBuffer: 200_000,
|
|
64
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
65
|
-
});
|
|
66
|
-
return { passed: true, output: output.trim() || "(passed)" };
|
|
67
|
-
}
|
|
68
|
-
catch (err) {
|
|
69
|
-
if (err && typeof err === "object" && "stdout" in err) {
|
|
70
|
-
const e = err;
|
|
71
|
-
const combined = [e.stdout, e.stderr].filter(Boolean).join("\n").trim();
|
|
72
|
-
return { passed: false, output: combined || "Check failed" };
|
|
73
|
-
}
|
|
74
|
-
return { passed: false, output: err instanceof Error ? err.message : String(err) };
|
|
75
|
-
}
|
|
76
|
-
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import { mcpRegistry } from "../mcp-client.js";
|
|
2
|
+
function errorMessage(err) {
|
|
3
|
+
return err instanceof Error ? err.message : String(err);
|
|
4
|
+
}
|
|
4
5
|
export const listMcpResourcesTool = {
|
|
5
6
|
name: "list_mcp_resources",
|
|
6
7
|
description: "List available resources from connected MCP servers. Resources are data endpoints that servers expose (database tables, config files, etc.).",
|
|
@@ -11,8 +12,30 @@ export const listMcpResourcesTool = {
|
|
|
11
12
|
},
|
|
12
13
|
},
|
|
13
14
|
async execute(input) {
|
|
14
|
-
|
|
15
|
-
|
|
15
|
+
const server = typeof input.server === "string" && input.server ? input.server : undefined;
|
|
16
|
+
const connected = mcpRegistry.listServers();
|
|
17
|
+
if (connected.length === 0) {
|
|
18
|
+
return { output: "No MCP servers connected. Connect one with --mcp-config or --mcp." };
|
|
19
|
+
}
|
|
20
|
+
try {
|
|
21
|
+
const resources = await mcpRegistry.listResources(server);
|
|
22
|
+
if (resources.length === 0) {
|
|
23
|
+
return {
|
|
24
|
+
output: server
|
|
25
|
+
? `MCP server "${server}" exposes no resources.`
|
|
26
|
+
: "Connected MCP servers expose no resources.",
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
const lines = resources.map((resource) => {
|
|
30
|
+
const heading = `${resource.server} ${resource.uri}${resource.name ? ` (${resource.name})` : ""}`;
|
|
31
|
+
const meta = [resource.mimeType, resource.description].filter(Boolean).join(" — ");
|
|
32
|
+
return meta ? `${heading}\n ${meta}` : heading;
|
|
33
|
+
});
|
|
34
|
+
return { output: `MCP resources (${resources.length}):\n${lines.join("\n")}` };
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
return { output: `Failed to list MCP resources: ${errorMessage(err)}`, is_error: true };
|
|
38
|
+
}
|
|
16
39
|
},
|
|
17
40
|
};
|
|
18
41
|
export const readMcpResourceTool = {
|
|
@@ -27,6 +50,28 @@ export const readMcpResourceTool = {
|
|
|
27
50
|
required: ["server", "uri"],
|
|
28
51
|
},
|
|
29
52
|
async execute(input) {
|
|
30
|
-
|
|
53
|
+
const server = typeof input.server === "string" ? input.server : "";
|
|
54
|
+
const uri = typeof input.uri === "string" ? input.uri : "";
|
|
55
|
+
if (!server)
|
|
56
|
+
return { output: "read_mcp_resource requires a server name.", is_error: true };
|
|
57
|
+
if (!uri)
|
|
58
|
+
return { output: "read_mcp_resource requires a resource uri.", is_error: true };
|
|
59
|
+
try {
|
|
60
|
+
const contents = await mcpRegistry.readResource(server, uri);
|
|
61
|
+
if (contents.length === 0)
|
|
62
|
+
return { output: `Resource ${uri} returned no contents.` };
|
|
63
|
+
const parts = contents.map((entry) => {
|
|
64
|
+
if (typeof entry.text === "string")
|
|
65
|
+
return entry.text;
|
|
66
|
+
if (entry.blob) {
|
|
67
|
+
return `[binary ${entry.mimeType ?? "application/octet-stream"}, ${entry.blob.length} base64 chars]`;
|
|
68
|
+
}
|
|
69
|
+
return JSON.stringify(entry);
|
|
70
|
+
});
|
|
71
|
+
return { output: parts.join("\n") };
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
return { output: `Failed to read MCP resource ${uri}: ${errorMessage(err)}`, is_error: true };
|
|
75
|
+
}
|
|
31
76
|
},
|
|
32
77
|
};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { addFindingToFile } from "@phren/cli/shared/content";
|
|
2
2
|
import { incrementSessionCounter } from "../memory/session.js";
|
|
3
|
+
import { agentProvenance } from "../memory/provenance.js";
|
|
3
4
|
export function createPhrenFindingTool(ctx, sessionId) {
|
|
4
5
|
return {
|
|
5
6
|
name: "phren_add_finding",
|
|
@@ -9,22 +10,29 @@ export function createPhrenFindingTool(ctx, sessionId) {
|
|
|
9
10
|
properties: {
|
|
10
11
|
finding: { type: "string", description: "The finding to save." },
|
|
11
12
|
project: { type: "string", description: "Project name. Default: detected project." },
|
|
13
|
+
file: { type: "string", description: "Source file the finding is about, for the citation." },
|
|
12
14
|
},
|
|
13
15
|
required: ["finding"],
|
|
14
16
|
},
|
|
15
17
|
async execute(input) {
|
|
16
18
|
const finding = input.finding;
|
|
17
19
|
const project = input.project || ctx.project;
|
|
20
|
+
const file = input.file || undefined;
|
|
18
21
|
if (!project)
|
|
19
22
|
return { output: "No project context. Specify a project name.", is_error: true };
|
|
20
23
|
try {
|
|
21
|
-
|
|
24
|
+
// addFindingToFile infers repo root + HEAD commit for the citation itself;
|
|
25
|
+
// we add the session provenance so the finding is traceable and age-able.
|
|
26
|
+
const result = addFindingToFile(ctx.phrenPath, project, finding, file ? { file } : undefined, {
|
|
27
|
+
provenance: agentProvenance(sessionId),
|
|
28
|
+
...(sessionId ? { sessionId } : {}),
|
|
29
|
+
});
|
|
22
30
|
if (result.ok) {
|
|
23
31
|
if (sessionId)
|
|
24
32
|
incrementSessionCounter(ctx.phrenPath, sessionId, "findingsAdded");
|
|
25
|
-
return { output: `Finding saved to ${project}.` };
|
|
33
|
+
return { output: result.data?.message ?? `Finding saved to ${project}.` };
|
|
26
34
|
}
|
|
27
|
-
return { output: result.
|
|
35
|
+
return { output: result.error ?? "Failed to save finding.", is_error: true };
|
|
28
36
|
}
|
|
29
37
|
catch (err) {
|
|
30
38
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { buildIndex } from "@phren/cli/shared";
|
|
2
|
-
import { searchKnowledgeRows, rankResults } from "@phren/cli/shared/retrieval";
|
|
2
|
+
import { searchKnowledgeRows, rankResults, isInjectableDocType } from "@phren/cli/shared/retrieval";
|
|
3
3
|
export function createPhrenSearchTool(ctx) {
|
|
4
4
|
return {
|
|
5
5
|
name: "phren_search",
|
|
@@ -29,9 +29,14 @@ export function createPhrenSearchTool(ctx) {
|
|
|
29
29
|
const ranked = rankResults(result.rows ?? [], query, null, project || null, ctx.phrenPath, db);
|
|
30
30
|
if (ranked.length === 0)
|
|
31
31
|
return { output: "No results found." };
|
|
32
|
+
// Explicit search may surface non-injectable doc types (notes, review-queue),
|
|
33
|
+
// but they get a visible tag so the model knows the content is unapproved /
|
|
34
|
+
// private scratch rather than vetted knowledge.
|
|
32
35
|
const lines = ranked.slice(0, limit).map((r, i) => {
|
|
33
36
|
const snippet = r.content?.slice(0, 300) ?? "";
|
|
34
|
-
|
|
37
|
+
const docType = r.type ?? "";
|
|
38
|
+
const tag = isInjectableDocType(docType) ? "" : ` [${docType} — unapproved, do not treat as truth]`;
|
|
39
|
+
return `${i + 1}. [${r.project}/${r.filename}]${tag} ${snippet}`;
|
|
35
40
|
});
|
|
36
41
|
return { output: lines.join("\n\n") };
|
|
37
42
|
}
|
package/dist/tools/read-file.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import * as fs from "fs";
|
|
2
2
|
import * as path from "path";
|
|
3
3
|
import { checkSensitivePath, validatePath } from "../permissions/sandbox.js";
|
|
4
|
+
/** Minified bundles and data files can have megabyte lines; cap each one. */
|
|
5
|
+
const MAX_LINE_CHARS = 2000;
|
|
4
6
|
export const readFileTool = {
|
|
5
7
|
name: "read_file",
|
|
6
8
|
description: "Read file contents with numbered lines. Always read a file before editing it. Use offset/limit for large files to avoid overwhelming context.",
|
|
@@ -30,15 +32,41 @@ export const readFileTool = {
|
|
|
30
32
|
}
|
|
31
33
|
if (!fs.existsSync(filePath))
|
|
32
34
|
return { output: `File not found: ${filePath}`, is_error: true };
|
|
33
|
-
|
|
34
|
-
|
|
35
|
+
if (fs.statSync(filePath).isDirectory()) {
|
|
36
|
+
return { output: `${filePath} is a directory. Use glob to list its files.`, is_error: true };
|
|
37
|
+
}
|
|
38
|
+
const buf = fs.readFileSync(filePath);
|
|
39
|
+
if (buf.subarray(0, 8192).includes(0)) {
|
|
40
|
+
return {
|
|
41
|
+
output: `${filePath} looks binary (${buf.length} bytes); not shown. Use read_image for images, or a shell tool such as xxd for other binaries.`,
|
|
42
|
+
is_error: true,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
const lines = buf.toString("utf-8").split("\n");
|
|
46
|
+
if (lines.length > 1 && lines[lines.length - 1] === "")
|
|
47
|
+
lines.pop();
|
|
48
|
+
if (offset > lines.length) {
|
|
49
|
+
return { output: `offset ${offset} is past the end of ${filePath} (${lines.length} lines).`, is_error: true };
|
|
50
|
+
}
|
|
35
51
|
const selected = lines.slice(offset - 1, offset - 1 + limit);
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
52
|
+
let clipped = 0;
|
|
53
|
+
const numbered = selected
|
|
54
|
+
.map((line, i) => {
|
|
55
|
+
const text = line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
56
|
+
if (text.length <= MAX_LINE_CHARS)
|
|
57
|
+
return `${offset + i}\t${text}`;
|
|
58
|
+
clipped++;
|
|
59
|
+
return `${offset + i}\t${text.slice(0, MAX_LINE_CHARS)}… [line truncated: ${text.length} chars]`;
|
|
60
|
+
})
|
|
61
|
+
.join("\n");
|
|
62
|
+
const end = offset + selected.length - 1;
|
|
63
|
+
const notes = [];
|
|
64
|
+
if (end < lines.length) {
|
|
65
|
+
notes.push(`${lines.length} total lines, showing ${offset}-${end}; continue with offset ${end + 1}`);
|
|
66
|
+
}
|
|
67
|
+
if (clipped > 0) {
|
|
68
|
+
notes.push(`${clipped} long line${clipped === 1 ? "" : "s"} truncated at ${MAX_LINE_CHARS} chars; use grep to see a specific line`);
|
|
69
|
+
}
|
|
70
|
+
return { output: notes.length > 0 ? `${numbered}\n\n(${notes.join("; ")})` : numbered };
|
|
43
71
|
},
|
|
44
72
|
};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import * as fs from "fs";
|
|
2
|
+
import * as path from "path";
|
|
3
|
+
import { modelSupportsVision } from "../models.js";
|
|
4
|
+
import { checkSensitivePath, validatePath } from "../permissions/sandbox.js";
|
|
5
|
+
/** Anthropic rejects images over 5MB; the other providers are in the same range. */
|
|
6
|
+
const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
7
|
+
const MEDIA_TYPES = {
|
|
8
|
+
".png": "image/png",
|
|
9
|
+
".jpg": "image/jpeg",
|
|
10
|
+
".jpeg": "image/jpeg",
|
|
11
|
+
".webp": "image/webp",
|
|
12
|
+
".gif": "image/gif",
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Read an image file into the conversation. Registered only for vision-capable
|
|
16
|
+
* models, and re-checked at execute time — registration-time gating is a
|
|
17
|
+
* schema decision, not enforcement.
|
|
18
|
+
*/
|
|
19
|
+
export function createReadImageTool(provider) {
|
|
20
|
+
return {
|
|
21
|
+
name: "read_image",
|
|
22
|
+
description: "Read an image file (png, jpeg, webp, gif) so you can see its contents. " +
|
|
23
|
+
"Use for screenshots, diagrams, and design assets. Maximum size 5MB.",
|
|
24
|
+
input_schema: {
|
|
25
|
+
type: "object",
|
|
26
|
+
properties: {
|
|
27
|
+
path: { type: "string", description: "Path to the image file" },
|
|
28
|
+
},
|
|
29
|
+
required: ["path"],
|
|
30
|
+
},
|
|
31
|
+
async execute(input) {
|
|
32
|
+
const filePath = String(input.path ?? "");
|
|
33
|
+
if (!filePath)
|
|
34
|
+
return { output: "Missing required parameter: path", is_error: true };
|
|
35
|
+
if (!modelSupportsVision(provider.name, provider.model ?? "")) {
|
|
36
|
+
return {
|
|
37
|
+
output: `The active model (${provider.model ?? provider.name}) does not accept image input.`,
|
|
38
|
+
is_error: true,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
const resolved = path.resolve(filePath);
|
|
42
|
+
const sensitive = checkSensitivePath(resolved);
|
|
43
|
+
if (sensitive.sensitive) {
|
|
44
|
+
return { output: `Access denied: ${sensitive.reason}`, is_error: true };
|
|
45
|
+
}
|
|
46
|
+
const sandboxResult = validatePath(filePath, process.cwd(), []);
|
|
47
|
+
if (!sandboxResult.ok) {
|
|
48
|
+
return { output: `Path outside sandbox: ${sandboxResult.error}`, is_error: true };
|
|
49
|
+
}
|
|
50
|
+
const mediaType = MEDIA_TYPES[path.extname(filePath).toLowerCase()];
|
|
51
|
+
if (!mediaType) {
|
|
52
|
+
return {
|
|
53
|
+
output: `Unsupported image type "${path.extname(filePath)}". Supported: png, jpeg, webp, gif.`,
|
|
54
|
+
is_error: true,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
let bytes;
|
|
58
|
+
try {
|
|
59
|
+
bytes = fs.readFileSync(filePath);
|
|
60
|
+
}
|
|
61
|
+
catch (err) {
|
|
62
|
+
return { output: `Cannot read ${filePath}: ${err instanceof Error ? err.message : String(err)}`, is_error: true };
|
|
63
|
+
}
|
|
64
|
+
if (bytes.length > MAX_IMAGE_BYTES) {
|
|
65
|
+
return {
|
|
66
|
+
output: `Image is ${(bytes.length / 1024 / 1024).toFixed(1)}MB (limit 5MB). Downscale it first, e.g. with sips/magick.`,
|
|
67
|
+
is_error: true,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
output: `Read ${path.basename(filePath)} (${mediaType}, ${(bytes.length / 1024).toFixed(0)}KB).`,
|
|
72
|
+
images: [{ media_type: mediaType, data: bytes.toString("base64") }],
|
|
73
|
+
};
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
package/dist/tools/registry.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { checkPermission } from "../permissions/checker.js";
|
|
2
2
|
import { askUser as defaultAskUser } from "../permissions/prompt.js";
|
|
3
|
+
import { runPreToolUseHooks, runPostToolUseHooks, } from "../user-hooks.js";
|
|
3
4
|
export class ToolRegistry {
|
|
4
5
|
tools = new Map();
|
|
5
6
|
/** Override the default permission prompt (e.g. for Ink TUI). */
|
|
@@ -9,9 +10,14 @@ export class ToolRegistry {
|
|
|
9
10
|
projectRoot: process.cwd(),
|
|
10
11
|
allowedPaths: [],
|
|
11
12
|
};
|
|
13
|
+
hookConfig = null;
|
|
14
|
+
hookExecutor;
|
|
12
15
|
register(tool) {
|
|
13
16
|
this.tools.set(tool.name, tool);
|
|
14
17
|
}
|
|
18
|
+
get(name) {
|
|
19
|
+
return this.tools.get(name);
|
|
20
|
+
}
|
|
15
21
|
remove(name) {
|
|
16
22
|
return this.tools.delete(name);
|
|
17
23
|
}
|
|
@@ -31,27 +37,43 @@ export class ToolRegistry {
|
|
|
31
37
|
input_schema: t.input_schema,
|
|
32
38
|
}));
|
|
33
39
|
}
|
|
34
|
-
async execute(name, input) {
|
|
40
|
+
async execute(name, input, signal) {
|
|
41
|
+
if (signal?.aborted)
|
|
42
|
+
return { output: "Cancelled by user.", is_error: true };
|
|
35
43
|
const tool = this.tools.get(name);
|
|
36
44
|
if (!tool)
|
|
37
45
|
return { output: `Unknown tool: ${name}`, is_error: true };
|
|
46
|
+
const hookOptions = { cwd: this.permissionConfig.projectRoot, executor: this.hookExecutor };
|
|
47
|
+
const pre = await runPreToolUseHooks(this.hookConfig, name, input, hookOptions);
|
|
48
|
+
if (pre.denied) {
|
|
49
|
+
return { output: pre.message, is_error: true, permissionDenied: true };
|
|
50
|
+
}
|
|
51
|
+
if (signal?.aborted)
|
|
52
|
+
return { output: "Cancelled by user.", is_error: true };
|
|
38
53
|
// Permission check — always enforced
|
|
39
54
|
const rule = checkPermission(this.permissionConfig, name, input);
|
|
40
55
|
if (rule.verdict === "deny") {
|
|
41
|
-
return { output: `Permission denied: ${rule.reason}`, is_error: true };
|
|
56
|
+
return { output: `Permission denied: ${rule.reason}`, is_error: true, permissionDenied: true };
|
|
42
57
|
}
|
|
43
58
|
if (rule.verdict === "ask") {
|
|
44
59
|
const allowed = await this.askUser(name, input, rule.reason);
|
|
45
60
|
if (!allowed) {
|
|
46
|
-
return { output: "User denied permission.", is_error: true };
|
|
61
|
+
return { output: "User denied permission.", is_error: true, permissionDenied: true };
|
|
47
62
|
}
|
|
48
63
|
}
|
|
64
|
+
// An approval may arrive after the turn was cancelled or this call timed out.
|
|
65
|
+
// Recheck here: tools such as synchronous file writes cannot observe abort later.
|
|
66
|
+
if (signal?.aborted)
|
|
67
|
+
return { output: "Cancelled by user.", is_error: true };
|
|
68
|
+
let result;
|
|
49
69
|
try {
|
|
50
|
-
|
|
70
|
+
result = await tool.execute(input, signal);
|
|
51
71
|
}
|
|
52
72
|
catch (err) {
|
|
53
73
|
const msg = err instanceof Error ? err.message : String(err);
|
|
54
|
-
|
|
74
|
+
result = { output: `Tool error: ${msg}`, is_error: true };
|
|
55
75
|
}
|
|
76
|
+
await runPostToolUseHooks(this.hookConfig, name, input, result.output, !!result.is_error, hookOptions);
|
|
77
|
+
return result;
|
|
56
78
|
}
|
|
57
79
|
}
|