@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
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
import { checkShellSafety } from "./shell-safety.js";
|
|
2
2
|
import { validatePath, checkSensitivePath } from "./sandbox.js";
|
|
3
3
|
import { isAllowed } from "./allowlist.js";
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
import { parsePatch, patchPaths } from "../tools/apply-patch.js";
|
|
5
|
+
/** Tools that are safe in all modes — read-only, no side effects. */
|
|
6
|
+
export const READ_ONLY_TOOLS = new Set([
|
|
7
|
+
"read_file",
|
|
8
|
+
"glob",
|
|
9
|
+
"grep",
|
|
10
|
+
"read_image",
|
|
11
|
+
"git_status",
|
|
12
|
+
"git_diff",
|
|
13
|
+
"task_output",
|
|
14
|
+
"list_mcp_resources",
|
|
15
|
+
"read_mcp_resource",
|
|
6
16
|
"phren_search",
|
|
7
17
|
"phren_get_tasks",
|
|
8
|
-
"spawn_agent",
|
|
9
|
-
"send_message_to_agent",
|
|
10
18
|
"list_agents",
|
|
11
19
|
]);
|
|
12
20
|
/** Tools that access file paths and need sensitive-path checks. */
|
|
@@ -14,14 +22,21 @@ const FILE_TOOLS = new Set([
|
|
|
14
22
|
"read_file",
|
|
15
23
|
"write_file",
|
|
16
24
|
"edit_file",
|
|
25
|
+
"multi_edit",
|
|
17
26
|
"glob",
|
|
18
27
|
"grep",
|
|
19
28
|
]);
|
|
20
29
|
/** Tools that auto-confirm mode allows without prompting. */
|
|
21
30
|
const AUTO_CONFIRM_TOOLS = new Set([
|
|
22
31
|
"edit_file",
|
|
32
|
+
"multi_edit",
|
|
33
|
+
"apply_patch",
|
|
23
34
|
"phren_add_finding",
|
|
24
35
|
"phren_complete_task",
|
|
36
|
+
// Spawning forks a child process running with auto-confirm permissions —
|
|
37
|
+
// suggest mode must ask first (these were unprompted in every mode before).
|
|
38
|
+
"spawn_agent",
|
|
39
|
+
"send_message_to_agent",
|
|
25
40
|
]);
|
|
26
41
|
/** Tools that are always denied regardless of mode. */
|
|
27
42
|
const DENY_LIST_TOOLS = new Set([
|
|
@@ -74,8 +89,28 @@ export function checkPermission(config, toolName, input) {
|
|
|
74
89
|
}
|
|
75
90
|
}
|
|
76
91
|
}
|
|
92
|
+
// apply_patch names its paths inside the patch text: check every one.
|
|
93
|
+
if (toolName === "apply_patch") {
|
|
94
|
+
let paths = [];
|
|
95
|
+
try {
|
|
96
|
+
paths = patchPaths(parsePatch(String(input.patch ?? "")));
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
// Unparseable: the tool itself reports the error without writing.
|
|
100
|
+
}
|
|
101
|
+
for (const p of paths) {
|
|
102
|
+
const sensitive = checkSensitivePath(p);
|
|
103
|
+
if (sensitive.sensitive) {
|
|
104
|
+
return { verdict: "deny", reason: `Sensitive path: ${sensitive.reason}` };
|
|
105
|
+
}
|
|
106
|
+
const pathResult = validatePath(p, config.projectRoot, config.allowedPaths);
|
|
107
|
+
if (!pathResult.ok) {
|
|
108
|
+
return { verdict: "ask", reason: `Path outside sandbox: ${pathResult.error}` };
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
77
112
|
// Always-safe tools pass in all modes
|
|
78
|
-
if (
|
|
113
|
+
if (READ_ONLY_TOOLS.has(toolName)) {
|
|
79
114
|
return { verdict: "allow", reason: "Read-only tool, always allowed." };
|
|
80
115
|
}
|
|
81
116
|
// Session allowlist — user previously approved this tool+pattern via (a)llow-tool or (s)ession-allow.
|
|
@@ -106,8 +141,8 @@ export function checkPermission(config, toolName, input) {
|
|
|
106
141
|
}
|
|
107
142
|
return { verdict: "ask", reason: `Auto-confirm mode requires confirmation for "${toolName}".` };
|
|
108
143
|
case "plan":
|
|
109
|
-
// Plan mode:
|
|
110
|
-
// can review the
|
|
144
|
+
// Plan mode: read-only tools are allowed; everything that mutates needs
|
|
145
|
+
// explicit approval so the user can review the plan before it executes.
|
|
111
146
|
return { verdict: "ask", reason: `Plan mode requires approval for "${toolName}".` };
|
|
112
147
|
case "full-auto":
|
|
113
148
|
// Full-auto: allow everything not denied or warned
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Kernel-level write fence for shell commands.
|
|
3
|
+
*
|
|
4
|
+
* Linux uses bubblewrap (`bwrap`): the whole filesystem is read-only except the
|
|
5
|
+
* workspace root, the allowed paths, and tmp. macOS uses `sandbox-exec` with a
|
|
6
|
+
* Seatbelt profile that allows reads and confines writes to the same roots.
|
|
7
|
+
* Either way the fence is enforced by the kernel, so it holds for every child
|
|
8
|
+
* process the command spawns, not just the ones the in-process checks can see.
|
|
9
|
+
* Writable roots derive from the SAME PermissionConfig fields as the in-process
|
|
10
|
+
* path sandbox, so the two layers cannot drift apart.
|
|
11
|
+
*
|
|
12
|
+
* Modes:
|
|
13
|
+
* off — never wrap.
|
|
14
|
+
* auto — wrap when a backend works; otherwise run unconfined with a
|
|
15
|
+
* one-time notice. On macOS the Seatbelt backend is opt-in via
|
|
16
|
+
* PHREN_AGENT_MACOS_SANDBOX=1 (sandbox-exec is deprecated and its
|
|
17
|
+
* profiles are easy to get subtly wrong); without it auto degrades
|
|
18
|
+
* visibly with the same notice as before.
|
|
19
|
+
* require — fail closed: no working backend ⇒ the command errors.
|
|
20
|
+
*/
|
|
21
|
+
import { execFileSync } from "child_process";
|
|
22
|
+
import * as fs from "fs";
|
|
23
|
+
import * as os from "os";
|
|
24
|
+
export class SandboxRequiredError extends Error {
|
|
25
|
+
constructor(reason) {
|
|
26
|
+
super(`--sandbox require: ${reason}`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export function parseSandboxMode(raw) {
|
|
30
|
+
if (raw === "off" || raw === "auto" || raw === "require")
|
|
31
|
+
return raw;
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
// ── Availability probe (functional, cached) ──────────────────────────────────
|
|
35
|
+
let probeResult = null;
|
|
36
|
+
let seatbeltProbeResult = null;
|
|
37
|
+
const noticesShown = new Set();
|
|
38
|
+
/** True when bwrap exists AND can actually confine (a real `bwrap ... true`). */
|
|
39
|
+
export function isBwrapAvailable() {
|
|
40
|
+
if (probeResult !== null)
|
|
41
|
+
return probeResult;
|
|
42
|
+
if (process.platform !== "linux") {
|
|
43
|
+
probeResult = false;
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
execFileSync("bwrap", ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--die-with-parent", "--", "true"], {
|
|
48
|
+
stdio: "ignore",
|
|
49
|
+
timeout: 5_000,
|
|
50
|
+
});
|
|
51
|
+
probeResult = true;
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
probeResult = false;
|
|
55
|
+
}
|
|
56
|
+
return probeResult;
|
|
57
|
+
}
|
|
58
|
+
export function isSeatbeltAvailable() {
|
|
59
|
+
if (!seatbeltEnabled())
|
|
60
|
+
return false;
|
|
61
|
+
if (seatbeltProbeResult !== null)
|
|
62
|
+
return seatbeltProbeResult;
|
|
63
|
+
try {
|
|
64
|
+
execFileSync("sandbox-exec", ["-p", "(version 1)(allow default)", "true"], {
|
|
65
|
+
stdio: "ignore",
|
|
66
|
+
timeout: 5_000,
|
|
67
|
+
});
|
|
68
|
+
seatbeltProbeResult = true;
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
seatbeltProbeResult = false;
|
|
72
|
+
}
|
|
73
|
+
return seatbeltProbeResult;
|
|
74
|
+
}
|
|
75
|
+
function seatbeltEnabled() {
|
|
76
|
+
return process.platform === "darwin" && process.env.PHREN_AGENT_MACOS_SANDBOX === "1";
|
|
77
|
+
}
|
|
78
|
+
export function isKernelSandboxAvailable() {
|
|
79
|
+
return isBwrapAvailable() || isSeatbeltAvailable();
|
|
80
|
+
}
|
|
81
|
+
/** Test hook: clear the cached probe + shown notices. */
|
|
82
|
+
export function _resetSandboxProbe() {
|
|
83
|
+
probeResult = null;
|
|
84
|
+
seatbeltProbeResult = null;
|
|
85
|
+
noticesShown.clear();
|
|
86
|
+
}
|
|
87
|
+
// ── Argv wrapping ────────────────────────────────────────────────────────────
|
|
88
|
+
function realpathOrNull(p) {
|
|
89
|
+
try {
|
|
90
|
+
return fs.realpathSync(p);
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/** Build the bwrap argv prefix for the given writable roots. */
|
|
97
|
+
export function buildBwrapArgv(argv, writableRoots) {
|
|
98
|
+
const wrapped = [
|
|
99
|
+
"bwrap",
|
|
100
|
+
"--ro-bind", "/", "/",
|
|
101
|
+
"--dev", "/dev",
|
|
102
|
+
"--proc", "/proc",
|
|
103
|
+
"--tmpfs", "/tmp",
|
|
104
|
+
];
|
|
105
|
+
const seen = new Set();
|
|
106
|
+
for (const root of writableRoots) {
|
|
107
|
+
const real = realpathOrNull(root);
|
|
108
|
+
if (!real || seen.has(real))
|
|
109
|
+
continue;
|
|
110
|
+
// Exactly /tmp is already the writable tmpfs. Paths UNDER /tmp still need
|
|
111
|
+
// a bind — the tmpfs would otherwise shadow their real contents.
|
|
112
|
+
if (real === "/tmp")
|
|
113
|
+
continue;
|
|
114
|
+
seen.add(real);
|
|
115
|
+
wrapped.push("--bind", real, real);
|
|
116
|
+
}
|
|
117
|
+
wrapped.push("--die-with-parent", "--");
|
|
118
|
+
return [...wrapped, ...argv];
|
|
119
|
+
}
|
|
120
|
+
function sbplQuote(value) {
|
|
121
|
+
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
122
|
+
}
|
|
123
|
+
export function buildSeatbeltProfile(writableRoots) {
|
|
124
|
+
const rules = [];
|
|
125
|
+
const seen = new Set();
|
|
126
|
+
for (const root of writableRoots) {
|
|
127
|
+
const real = realpathOrNull(root);
|
|
128
|
+
if (!real || seen.has(real))
|
|
129
|
+
continue;
|
|
130
|
+
seen.add(real);
|
|
131
|
+
rules.push(`(subpath ${sbplQuote(real)})`);
|
|
132
|
+
}
|
|
133
|
+
rules.push(`(literal "/dev/null")`);
|
|
134
|
+
rules.push(`(literal "/dev/stdout")`);
|
|
135
|
+
rules.push(`(literal "/dev/stderr")`);
|
|
136
|
+
rules.push(`(literal "/dev/tty")`);
|
|
137
|
+
rules.push(`(subpath "/dev/fd")`);
|
|
138
|
+
rules.push(`(subpath "/private/tmp")`);
|
|
139
|
+
rules.push(`(subpath "/private/var/tmp")`);
|
|
140
|
+
rules.push(`(subpath "/private/var/folders")`);
|
|
141
|
+
return [
|
|
142
|
+
"(version 1)",
|
|
143
|
+
"(allow default)",
|
|
144
|
+
"(deny file-write*)",
|
|
145
|
+
`(allow file-write* ${rules.join(" ")})`,
|
|
146
|
+
].join("\n");
|
|
147
|
+
}
|
|
148
|
+
export function buildSeatbeltArgv(argv, writableRoots) {
|
|
149
|
+
return ["sandbox-exec", "-p", buildSeatbeltProfile(writableRoots), ...argv];
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Decide how to run a shell argv under the given sandbox mode.
|
|
153
|
+
* Throws SandboxRequiredError only in `require` mode with no working backend.
|
|
154
|
+
*/
|
|
155
|
+
export function wrapWithSandbox(argv, opts) {
|
|
156
|
+
if (opts.mode === "off") {
|
|
157
|
+
return { argv, sandboxed: false };
|
|
158
|
+
}
|
|
159
|
+
const writable = [opts.workspaceRoot, os.tmpdir(), ...(opts.extraWritable ?? [])];
|
|
160
|
+
if (isBwrapAvailable()) {
|
|
161
|
+
return { argv: buildBwrapArgv(argv, writable), sandboxed: true };
|
|
162
|
+
}
|
|
163
|
+
if (isSeatbeltAvailable()) {
|
|
164
|
+
return { argv: buildSeatbeltArgv(argv, writable), sandboxed: true };
|
|
165
|
+
}
|
|
166
|
+
if (opts.mode === "require") {
|
|
167
|
+
throw new SandboxRequiredError(process.platform === "linux"
|
|
168
|
+
? "bwrap (bubblewrap) is not available or cannot confine on this system."
|
|
169
|
+
: process.platform === "darwin"
|
|
170
|
+
? "macOS Seatbelt (sandbox-exec) is not enabled; set PHREN_AGENT_MACOS_SANDBOX=1 to use it."
|
|
171
|
+
: `kernel sandboxing is not supported on ${process.platform} yet.`);
|
|
172
|
+
}
|
|
173
|
+
// auto: degrade with a one-time notice
|
|
174
|
+
const key = "sandbox-unavailable";
|
|
175
|
+
if (!noticesShown.has(key)) {
|
|
176
|
+
noticesShown.add(key);
|
|
177
|
+
const reason = process.platform === "linux"
|
|
178
|
+
? "bwrap not found — install bubblewrap to confine shell commands"
|
|
179
|
+
: process.platform === "darwin"
|
|
180
|
+
? "no kernel sandbox on darwin (set PHREN_AGENT_MACOS_SANDBOX=1 for the Seatbelt backend)"
|
|
181
|
+
: `no kernel sandbox on ${process.platform}`;
|
|
182
|
+
return { argv, sandboxed: false, notice: `[sandbox: running unconfined — ${reason}; --sandbox off silences this]` };
|
|
183
|
+
}
|
|
184
|
+
return { argv, sandboxed: false };
|
|
185
|
+
}
|
|
186
|
+
// ── Denial classification ────────────────────────────────────────────────────
|
|
187
|
+
const DENIAL_RE = /read-only file system|operation not permitted/i;
|
|
188
|
+
/**
|
|
189
|
+
* When a sandboxed command fails with a write-fence error, return an
|
|
190
|
+
* annotation explaining WHY so the model redirects instead of retrying.
|
|
191
|
+
*/
|
|
192
|
+
export function classifySandboxDenial(stderr, workspaceRoot) {
|
|
193
|
+
if (!DENIAL_RE.test(stderr))
|
|
194
|
+
return null;
|
|
195
|
+
return (`\n[sandbox] Write blocked: the filesystem is read-only outside ${workspaceRoot} under --sandbox. ` +
|
|
196
|
+
"Write inside the workspace, or the user can rerun with --sandbox off.");
|
|
197
|
+
}
|
|
@@ -60,7 +60,16 @@ function summarizeCall(toolName, input) {
|
|
|
60
60
|
}
|
|
61
61
|
case "edit_file": {
|
|
62
62
|
const p = input.path || "?";
|
|
63
|
-
return `Edit ${p}`;
|
|
63
|
+
return `Edit ${p}${input.replace_all === true ? " (all occurrences)" : ""}`;
|
|
64
|
+
}
|
|
65
|
+
case "multi_edit": {
|
|
66
|
+
const p = input.path || "?";
|
|
67
|
+
const n = Array.isArray(input.edits) ? input.edits.length : 0;
|
|
68
|
+
return `Edit ${p} (${n} edit${n === 1 ? "" : "s"})`;
|
|
69
|
+
}
|
|
70
|
+
case "apply_patch": {
|
|
71
|
+
const files = String(input.patch ?? "").match(/^\*\*\* (?:Add|Delete|Update) File: .+$/gm) ?? [];
|
|
72
|
+
return `Patch ${files.length} file${files.length === 1 ? "" : "s"}: ${files.map((f) => f.replace(/^\*\*\* (\w+) File: /, "$1 ")).join(", ")}`;
|
|
64
73
|
}
|
|
65
74
|
case "glob": {
|
|
66
75
|
const pattern = input.pattern || "?";
|
|
@@ -23,32 +23,55 @@ const SENSITIVE_PATTERNS = [
|
|
|
23
23
|
];
|
|
24
24
|
/** File extensions that are always sensitive. */
|
|
25
25
|
const SENSITIVE_EXTENSIONS = [".pem", ".p12", ".pfx", ".key", ".keystore", ".jks"];
|
|
26
|
+
/** Canonicalize even a not-yet-created file through its nearest existing
|
|
27
|
+
* ancestor. Broken/looping links and access errors cannot grant a boundary. */
|
|
28
|
+
function canonicalPath(filePath) {
|
|
29
|
+
let current = filePath;
|
|
30
|
+
const missing = [];
|
|
31
|
+
for (let depth = 0; depth < 256; depth++) {
|
|
32
|
+
try {
|
|
33
|
+
// The native implementation preserves kernel symlink/.. semantics.
|
|
34
|
+
return path.join(fs.realpathSync.native(current), ...missing.reverse());
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (error.code !== "ENOENT")
|
|
38
|
+
throw error;
|
|
39
|
+
// realpath also reports ENOENT for dangling symlinks. Unlike an absent
|
|
40
|
+
// filename, those must not fall back to a lexical path inside the root.
|
|
41
|
+
if (fs.lstatSync(current, { throwIfNoEntry: false }))
|
|
42
|
+
throw error;
|
|
43
|
+
const parent = path.dirname(current);
|
|
44
|
+
if (parent === current)
|
|
45
|
+
throw error;
|
|
46
|
+
missing.push(path.basename(current));
|
|
47
|
+
current = parent;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
throw new Error("Path exceeds the ancestor resolution limit.");
|
|
51
|
+
}
|
|
52
|
+
function expandHome(filePath) {
|
|
53
|
+
return filePath === "~" || filePath.startsWith("~/")
|
|
54
|
+
? path.join(os.homedir(), filePath.slice(1)) : filePath;
|
|
55
|
+
}
|
|
26
56
|
/**
|
|
27
57
|
* Resolve and validate a file path against the sandbox boundary.
|
|
28
58
|
*/
|
|
29
59
|
export function validatePath(filePath, projectRoot, allowedPaths) {
|
|
30
|
-
|
|
31
|
-
let resolved = filePath;
|
|
32
|
-
if (resolved.startsWith("~/") || resolved === "~") {
|
|
33
|
-
resolved = path.join(os.homedir(), resolved.slice(1));
|
|
34
|
-
}
|
|
35
|
-
// Resolve to absolute
|
|
36
|
-
if (!path.isAbsolute(resolved)) {
|
|
37
|
-
resolved = path.resolve(projectRoot, resolved);
|
|
38
|
-
}
|
|
39
|
-
// Normalize (remove .., trailing slashes, etc.)
|
|
40
|
-
resolved = path.normalize(resolved);
|
|
41
|
-
// Resolve symlinks if the path exists
|
|
60
|
+
let resolved, root, allowed;
|
|
42
61
|
try {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
62
|
+
const absoluteRoot = path.resolve(expandHome(projectRoot));
|
|
63
|
+
// Preserve .. until filesystem resolution: link/../file follows the
|
|
64
|
+
// link before traversing its parent, unlike path.resolve's lexical fold.
|
|
65
|
+
const requested = expandHome(filePath);
|
|
66
|
+
resolved = canonicalPath(path.isAbsolute(requested) ? requested : absoluteRoot + path.sep + requested);
|
|
67
|
+
root = canonicalPath(absoluteRoot);
|
|
68
|
+
allowed = allowedPaths.map(value => canonicalPath(path.resolve(absoluteRoot, expandHome(value))));
|
|
46
69
|
}
|
|
47
70
|
catch {
|
|
48
|
-
|
|
71
|
+
return { ok: false, error: `Path "${filePath}" could not be safely resolved.` };
|
|
49
72
|
}
|
|
50
73
|
// Check sandbox boundaries
|
|
51
|
-
if (!isPathInSandbox(resolved,
|
|
74
|
+
if (!isPathInSandbox(resolved, root, allowed)) {
|
|
52
75
|
return {
|
|
53
76
|
ok: false,
|
|
54
77
|
error: `Path "${resolved}" is outside project root "${projectRoot}" and not in allowed paths.`,
|
|
@@ -1,17 +1,58 @@
|
|
|
1
|
+
import { stripForeignReasoning } from "./history.js";
|
|
2
|
+
import { getModelMetadata } from "../models.js";
|
|
3
|
+
const PROVIDER_NAME = "anthropic";
|
|
4
|
+
/** Thinking budget per effort level; always clamped below max_tokens. */
|
|
5
|
+
const THINKING_BUDGETS = {
|
|
6
|
+
low: 2048,
|
|
7
|
+
medium: 8192,
|
|
8
|
+
high: 16384,
|
|
9
|
+
xhigh: 32768,
|
|
10
|
+
};
|
|
11
|
+
/** Anthropic rejects budget_tokens below this. */
|
|
12
|
+
const MIN_THINKING_BUDGET = 1024;
|
|
13
|
+
/**
|
|
14
|
+
* Models that use adaptive thinking + output_config.effort. On these,
|
|
15
|
+
* `thinking: {type: "enabled", budget_tokens}` is deprecated (4.6 family)
|
|
16
|
+
* or a hard 400 (4.7+/5 family) — never send a budget to them.
|
|
17
|
+
*/
|
|
18
|
+
const ADAPTIVE_THINKING_RE = /^claude-(?:(?:opus|sonnet)-4-[678]|opus-5|sonnet-5|fable-5|mythos-5)/;
|
|
19
|
+
/** xhigh effort arrived with 4.7; on the 4.6 family map it to "max". */
|
|
20
|
+
const EFFORT_NO_XHIGH_RE = /^claude-(?:opus|sonnet)-4-6/;
|
|
1
21
|
export class AnthropicProvider {
|
|
2
|
-
name =
|
|
22
|
+
name = PROVIDER_NAME;
|
|
3
23
|
contextWindow = 200_000;
|
|
4
24
|
maxOutputTokens;
|
|
5
25
|
apiKey;
|
|
6
26
|
model;
|
|
7
27
|
cacheEnabled;
|
|
8
|
-
|
|
28
|
+
reasoningEffort;
|
|
29
|
+
constructor(apiKey, model, maxOutputTokens, cacheEnabled = true, reasoningEffort) {
|
|
9
30
|
this.apiKey = apiKey;
|
|
10
|
-
this.model = model ?? "claude-sonnet-
|
|
31
|
+
this.model = model ?? "claude-sonnet-5";
|
|
11
32
|
this.maxOutputTokens = maxOutputTokens ?? 8192;
|
|
12
33
|
this.cacheEnabled = cacheEnabled;
|
|
34
|
+
this.reasoningEffort = reasoningEffort;
|
|
35
|
+
const metadata = getModelMetadata(PROVIDER_NAME, this.model);
|
|
36
|
+
if (metadata)
|
|
37
|
+
this.contextWindow = metadata.contextWindow;
|
|
13
38
|
}
|
|
14
|
-
|
|
39
|
+
/** True when the model takes adaptive thinking instead of budget_tokens. */
|
|
40
|
+
usesAdaptiveThinking() {
|
|
41
|
+
return ADAPTIVE_THINKING_RE.test(this.model);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Resolved thinking budget, or null when thinking stays off. The budget
|
|
45
|
+
* must fit under max_tokens (thinking counts against it), so it is clamped
|
|
46
|
+
* to half the output cap and dropped entirely if that leaves less than the
|
|
47
|
+
* API minimum.
|
|
48
|
+
*/
|
|
49
|
+
thinkingBudget() {
|
|
50
|
+
if (!this.reasoningEffort)
|
|
51
|
+
return null;
|
|
52
|
+
const budget = Math.min(THINKING_BUDGETS[this.reasoningEffort], Math.floor(this.maxOutputTokens / 2));
|
|
53
|
+
return budget >= MIN_THINKING_BUDGET ? budget : null;
|
|
54
|
+
}
|
|
55
|
+
async chat(system, messages, tools, signal) {
|
|
15
56
|
const body = this.buildRequestBody(system, messages, tools);
|
|
16
57
|
const res = await fetch("https://api.anthropic.com/v1/messages", {
|
|
17
58
|
method: "POST",
|
|
@@ -21,13 +62,14 @@ export class AnthropicProvider {
|
|
|
21
62
|
"anthropic-version": "2023-06-01",
|
|
22
63
|
},
|
|
23
64
|
body: JSON.stringify(body),
|
|
65
|
+
signal,
|
|
24
66
|
});
|
|
25
67
|
if (!res.ok) {
|
|
26
68
|
const text = await res.text();
|
|
27
69
|
throw new Error(`Anthropic API error ${res.status}: ${text}`);
|
|
28
70
|
}
|
|
29
71
|
const data = await res.json();
|
|
30
|
-
const content = data.content
|
|
72
|
+
const content = parseWireContent(data.content);
|
|
31
73
|
const stop_reason = data.stop_reason === "tool_use" ? "tool_use"
|
|
32
74
|
: data.stop_reason === "max_tokens" ? "max_tokens"
|
|
33
75
|
: "end_turn";
|
|
@@ -39,7 +81,7 @@ export class AnthropicProvider {
|
|
|
39
81
|
usage: usage ? { input_tokens: usage.input_tokens ?? 0, output_tokens: usage.output_tokens ?? 0 } : undefined,
|
|
40
82
|
};
|
|
41
83
|
}
|
|
42
|
-
async *chatStream(system, messages, tools) {
|
|
84
|
+
async *chatStream(system, messages, tools, signal) {
|
|
43
85
|
const body = this.buildRequestBody(system, messages, tools);
|
|
44
86
|
body.stream = true;
|
|
45
87
|
const res = await fetch("https://api.anthropic.com/v1/messages", {
|
|
@@ -50,6 +92,7 @@ export class AnthropicProvider {
|
|
|
50
92
|
"anthropic-version": "2023-06-01",
|
|
51
93
|
},
|
|
52
94
|
body: JSON.stringify(body),
|
|
95
|
+
signal,
|
|
53
96
|
});
|
|
54
97
|
if (!res.ok) {
|
|
55
98
|
const text = await res.text();
|
|
@@ -59,6 +102,9 @@ export class AnthropicProvider {
|
|
|
59
102
|
let usage;
|
|
60
103
|
// Map block index to tool ID for consistent ID across start/delta/end
|
|
61
104
|
const indexToToolId = new Map();
|
|
105
|
+
// Thinking blocks are index-tracked too: the signature arrives as a
|
|
106
|
+
// delta and must ride the reasoning_end at content_block_stop.
|
|
107
|
+
const thinkingByIndex = new Map();
|
|
62
108
|
for await (const event of parseSSE(res)) {
|
|
63
109
|
const type = event.event;
|
|
64
110
|
const data = event.data;
|
|
@@ -70,12 +116,31 @@ export class AnthropicProvider {
|
|
|
70
116
|
indexToToolId.set(index, id);
|
|
71
117
|
yield { type: "tool_use_start", id, name: block.name };
|
|
72
118
|
}
|
|
119
|
+
else if (block.type === "thinking") {
|
|
120
|
+
thinkingByIndex.set(data.index, {});
|
|
121
|
+
}
|
|
122
|
+
else if (block.type === "redacted_thinking") {
|
|
123
|
+
// Arrives complete: opaque payload, no deltas, no signature.
|
|
124
|
+
yield {
|
|
125
|
+
type: "reasoning_end",
|
|
126
|
+
redacted: true,
|
|
127
|
+
...(typeof block.data === "string" ? { data: block.data } : {}),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
73
130
|
}
|
|
74
131
|
else if (type === "content_block_delta") {
|
|
75
132
|
const delta = data.delta;
|
|
76
133
|
if (delta.type === "text_delta") {
|
|
77
134
|
yield { type: "text_delta", text: delta.text };
|
|
78
135
|
}
|
|
136
|
+
else if (delta.type === "thinking_delta") {
|
|
137
|
+
yield { type: "reasoning_delta", text: delta.thinking };
|
|
138
|
+
}
|
|
139
|
+
else if (delta.type === "signature_delta") {
|
|
140
|
+
const state = thinkingByIndex.get(data.index);
|
|
141
|
+
if (state)
|
|
142
|
+
state.signature = (state.signature ?? "") + delta.signature;
|
|
143
|
+
}
|
|
79
144
|
else if (delta.type === "input_json_delta") {
|
|
80
145
|
const index = data.index;
|
|
81
146
|
const id = indexToToolId.get(index) ?? String(index);
|
|
@@ -84,6 +149,14 @@ export class AnthropicProvider {
|
|
|
84
149
|
}
|
|
85
150
|
else if (type === "content_block_stop") {
|
|
86
151
|
const index = data.index;
|
|
152
|
+
if (thinkingByIndex.has(index)) {
|
|
153
|
+
const state = thinkingByIndex.get(index);
|
|
154
|
+
thinkingByIndex.delete(index);
|
|
155
|
+
yield {
|
|
156
|
+
type: "reasoning_end",
|
|
157
|
+
...(state.signature !== undefined ? { signature: state.signature } : {}),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
87
160
|
if (indexToToolId.has(index)) {
|
|
88
161
|
yield { type: "tool_use_end", id: indexToToolId.get(index) };
|
|
89
162
|
}
|
|
@@ -124,7 +197,10 @@ export class AnthropicProvider {
|
|
|
124
197
|
const systemValue = this.cacheEnabled
|
|
125
198
|
? [{ type: "text", text: system, ...cache }]
|
|
126
199
|
: system;
|
|
127
|
-
const mappedMessages = messages.map((m) => ({
|
|
200
|
+
const mappedMessages = stripForeignReasoning(messages, PROVIDER_NAME).map((m) => ({
|
|
201
|
+
role: m.role,
|
|
202
|
+
content: typeof m.content === "string" ? m.content : m.content.map(toWireBlock),
|
|
203
|
+
}));
|
|
128
204
|
// Mark the last 2 user messages with cache_control for recent-context caching
|
|
129
205
|
if (this.cacheEnabled) {
|
|
130
206
|
let marked = 0;
|
|
@@ -153,6 +229,23 @@ export class AnthropicProvider {
|
|
|
153
229
|
messages: mappedMessages,
|
|
154
230
|
max_tokens: this.maxOutputTokens,
|
|
155
231
|
};
|
|
232
|
+
if (this.usesAdaptiveThinking()) {
|
|
233
|
+
// Adaptive thinking: the model decides when/how much to think; effort
|
|
234
|
+
// controls depth. budget_tokens would 400 on 4.7+/5-family models.
|
|
235
|
+
if (this.reasoningEffort) {
|
|
236
|
+
body.thinking = { type: "adaptive" };
|
|
237
|
+
const effort = EFFORT_NO_XHIGH_RE.test(this.model) && this.reasoningEffort === "xhigh"
|
|
238
|
+
? "max"
|
|
239
|
+
: this.reasoningEffort;
|
|
240
|
+
body.output_config = { effort };
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
else {
|
|
244
|
+
const budget = this.thinkingBudget();
|
|
245
|
+
if (budget !== null) {
|
|
246
|
+
body.thinking = { type: "enabled", budget_tokens: budget };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
156
249
|
if (tools.length > 0) {
|
|
157
250
|
const mappedTools = tools.map((t) => ({
|
|
158
251
|
name: t.name,
|
|
@@ -168,6 +261,60 @@ export class AnthropicProvider {
|
|
|
168
261
|
return body;
|
|
169
262
|
}
|
|
170
263
|
}
|
|
264
|
+
/**
|
|
265
|
+
* Serialize one internal block into Anthropic wire format. Reasoning blocks
|
|
266
|
+
* become thinking/redacted_thinking (the API verifies the signature when the
|
|
267
|
+
* conversation continues into tool use); other blocks already match the wire
|
|
268
|
+
* shape, minus our internal-only fields.
|
|
269
|
+
*/
|
|
270
|
+
export function toWireBlock(block) {
|
|
271
|
+
if (block.type === "reasoning") {
|
|
272
|
+
if (block.redacted) {
|
|
273
|
+
return { type: "redacted_thinking", data: block.data ?? "" };
|
|
274
|
+
}
|
|
275
|
+
return {
|
|
276
|
+
type: "thinking",
|
|
277
|
+
thinking: block.text,
|
|
278
|
+
...(block.signature !== undefined ? { signature: block.signature } : {}),
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
return block;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Parse Anthropic wire content into internal blocks. Thinking blocks become
|
|
285
|
+
* tagged reasoning blocks; unknown wire types are dropped (they cannot be
|
|
286
|
+
* round-tripped and a blind cast previously let them pollute saved history).
|
|
287
|
+
*/
|
|
288
|
+
export function parseWireContent(raw) {
|
|
289
|
+
if (!Array.isArray(raw))
|
|
290
|
+
return [];
|
|
291
|
+
const content = [];
|
|
292
|
+
for (const item of raw) {
|
|
293
|
+
if (!item || typeof item !== "object")
|
|
294
|
+
continue;
|
|
295
|
+
if (item.type === "text" || item.type === "tool_use" || item.type === "tool_result") {
|
|
296
|
+
content.push(item);
|
|
297
|
+
}
|
|
298
|
+
else if (item.type === "thinking") {
|
|
299
|
+
content.push({
|
|
300
|
+
type: "reasoning",
|
|
301
|
+
text: typeof item.thinking === "string" ? item.thinking : "",
|
|
302
|
+
provider: PROVIDER_NAME,
|
|
303
|
+
...(typeof item.signature === "string" ? { signature: item.signature } : {}),
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
else if (item.type === "redacted_thinking") {
|
|
307
|
+
content.push({
|
|
308
|
+
type: "reasoning",
|
|
309
|
+
text: "",
|
|
310
|
+
provider: PROVIDER_NAME,
|
|
311
|
+
redacted: true,
|
|
312
|
+
...(typeof item.data === "string" ? { data: item.data } : {}),
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return content;
|
|
317
|
+
}
|
|
171
318
|
/** Log cache hit/creation stats to stderr (visible in verbose mode). */
|
|
172
319
|
function logCacheUsage(usage) {
|
|
173
320
|
if (!usage)
|
|
@@ -4,6 +4,9 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import * as crypto from "crypto";
|
|
6
6
|
import * as http from "http";
|
|
7
|
+
import * as fs from "fs";
|
|
8
|
+
import * as os from "os";
|
|
9
|
+
import * as path from "path";
|
|
7
10
|
import { authProfilesPath, getCodexAuthProfile, hasCodexAuthProfile, hasCodexCliAuth, removeCodexAuthProfile, upsertCodexAuthProfile, } from "@phren/cli/auth/profiles";
|
|
8
11
|
const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
9
12
|
const AUTH_URL = "https://auth.openai.com/oauth/authorize";
|
|
@@ -192,6 +195,31 @@ export async function getAccessToken() {
|
|
|
192
195
|
}
|
|
193
196
|
return { accessToken: profile.accessToken, accountId: profile.accountId };
|
|
194
197
|
}
|
|
198
|
+
/**
|
|
199
|
+
* The model the Codex CLI itself is configured to use (`model = "…"` in
|
|
200
|
+
* $CODEX_HOME/config.toml), else the first model in its cached catalogue.
|
|
201
|
+
* ChatGPT accounts reject model ids the account is not offered, so the
|
|
202
|
+
* built-in default goes stale; the CLI's own choice is known to work.
|
|
203
|
+
*/
|
|
204
|
+
export function codexConfiguredModel(codexHome = process.env.CODEX_HOME ?? path.join(os.homedir(), ".codex")) {
|
|
205
|
+
try {
|
|
206
|
+
const toml = fs.readFileSync(path.join(codexHome, "config.toml"), "utf8");
|
|
207
|
+
// Top-level key only: stop at the first [table] header.
|
|
208
|
+
const top = toml.split(/^\s*\[/m)[0];
|
|
209
|
+
const match = top.match(/^\s*model\s*=\s*"([^"]+)"/m);
|
|
210
|
+
if (match)
|
|
211
|
+
return match[1];
|
|
212
|
+
}
|
|
213
|
+
catch { /* no config */ }
|
|
214
|
+
try {
|
|
215
|
+
const cache = JSON.parse(fs.readFileSync(path.join(codexHome, "models_cache.json"), "utf8"));
|
|
216
|
+
const list = Array.isArray(cache) ? cache : cache.models;
|
|
217
|
+
const first = Array.isArray(list) ? list[0] : undefined;
|
|
218
|
+
return first?.slug ?? first?.id;
|
|
219
|
+
}
|
|
220
|
+
catch { /* no cache */ }
|
|
221
|
+
return undefined;
|
|
222
|
+
}
|
|
195
223
|
/** Check if user has a stored Codex token. */
|
|
196
224
|
export function hasCodexToken() {
|
|
197
225
|
return hasCodexAuthProfile({ allowCliImport: true });
|