@phren/agent 0.3.19 → 0.3.21
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/dist/agent-loop/index.js +185 -47
- package/dist/agent-loop/stream.js +74 -66
- package/dist/agent-loop/types.js +2 -3
- package/dist/attach-images.js +57 -0
- package/dist/bin.js +7 -2
- package/dist/commands/info.js +7 -3
- package/dist/commands/model.js +55 -13
- package/dist/commands/session.js +79 -18
- package/dist/commands.js +24 -3
- package/dist/config.js +89 -10
- package/dist/context/clear-tool-results.js +43 -0
- package/dist/context/compactor.js +13 -3
- package/dist/context/pruner.js +29 -11
- package/dist/context/usage.js +26 -0
- package/dist/cost.js +68 -10
- package/dist/headless.js +47 -1
- package/dist/index.js +335 -127
- package/dist/mcp-client.js +38 -1
- package/dist/mcp-prompts.js +94 -0
- package/dist/memory/chat.js +70 -0
- package/dist/memory/context.js +1 -1
- package/dist/model-overrides.js +17 -0
- package/dist/models-list.js +73 -0
- package/dist/models.js +42 -15
- package/dist/multi/child-entry.js +18 -28
- package/dist/multi/ipc-hooks.js +34 -0
- package/dist/multi/spawner.js +49 -3
- package/dist/permissions/allowlist.js +19 -4
- package/dist/permissions/checker.js +37 -20
- package/dist/permissions/kernel-sandbox.js +32 -10
- package/dist/permissions/rules.js +173 -0
- package/dist/permissions/shell-classify.js +173 -0
- package/dist/plan.js +6 -2
- package/dist/providers/anthropic.js +119 -75
- package/dist/providers/codex.js +10 -9
- package/dist/providers/ollama.js +5 -2
- package/dist/providers/openai-compat.js +219 -92
- package/dist/providers/openrouter.js +12 -7
- package/dist/providers/resolve.js +47 -1
- package/dist/providers/retry.js +20 -7
- package/dist/providers/types.js +31 -0
- package/dist/repl.js +17 -1
- package/dist/session/persist.js +9 -4
- package/dist/session/preview.js +99 -0
- package/dist/settings.js +14 -0
- package/dist/structured-output.js +85 -0
- package/dist/system-prompt.js +117 -14
- package/dist/tools/apply-patch.js +15 -1
- package/dist/tools/edit-file.js +8 -1
- package/dist/tools/file-state.js +88 -0
- package/dist/tools/glob.js +53 -35
- package/dist/tools/grep.js +139 -53
- package/dist/tools/lint-test.js +24 -0
- package/dist/tools/read-file.js +2 -0
- package/dist/tools/registry.js +8 -1
- package/dist/tools/search-support.js +141 -0
- package/dist/tools/shell.js +266 -41
- package/dist/tools/spawn-agent.js +15 -3
- package/dist/tools/syntax-check.js +116 -0
- package/dist/tools/write-file.js +11 -3
- package/dist/tui/components/App.js +5 -4
- package/dist/tui/components/Banner.js +1 -1
- package/dist/tui/components/ListPicker.js +32 -0
- package/dist/tui/ink-entry.js +79 -15
- package/dist/user-hooks.js +26 -4
- package/package.json +3 -2
- package/dist/memory/context-flush.js +0 -24
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Images in a prompt: a path to a png, jpeg, webp or gif in the message
|
|
3
|
+
* (typed, or dropped onto the terminal, which pastes the path, quoted or with
|
|
4
|
+
* escaped spaces) is attached to the message as the image itself, on a model
|
|
5
|
+
* that can see. Terminals don't pass clipboard image data to a program, so a
|
|
6
|
+
* dropped or typed path is how an image gets in, as in Claude Code.
|
|
7
|
+
*/
|
|
8
|
+
import * as fs from "fs";
|
|
9
|
+
import * as path from "path";
|
|
10
|
+
/** Anthropic rejects images over 5MB; the other providers are in the same range. */
|
|
11
|
+
const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
12
|
+
const MAX_IMAGES = 5;
|
|
13
|
+
const MEDIA_TYPES = {
|
|
14
|
+
".png": "image/png",
|
|
15
|
+
".jpg": "image/jpeg",
|
|
16
|
+
".jpeg": "image/jpeg",
|
|
17
|
+
".webp": "image/webp",
|
|
18
|
+
".gif": "image/gif",
|
|
19
|
+
};
|
|
20
|
+
/** Candidate paths: quoted, backslash-escaped spaces, or plain, with an image extension. */
|
|
21
|
+
const PATH_RE = /'([^']+\.(?:png|jpe?g|webp|gif))'|"([^"]+\.(?:png|jpe?g|webp|gif))"|((?:[^\s'"\\]|\\ )+\.(?:png|jpe?g|webp|gif))/gi;
|
|
22
|
+
/** The message with any image paths in it attached as images. */
|
|
23
|
+
export function attachImages(text, cwd) {
|
|
24
|
+
const attached = [];
|
|
25
|
+
const skipped = [];
|
|
26
|
+
const images = [];
|
|
27
|
+
for (const match of text.matchAll(PATH_RE)) {
|
|
28
|
+
const raw = (match[1] ?? match[2] ?? match[3]).replace(/\\ /g, " ");
|
|
29
|
+
const file = path.resolve(cwd, raw.replace(/^~(?=\/)/, process.env.HOME ?? "~"));
|
|
30
|
+
if (attached.includes(file))
|
|
31
|
+
continue;
|
|
32
|
+
let size;
|
|
33
|
+
try {
|
|
34
|
+
const stat = fs.statSync(file);
|
|
35
|
+
if (!stat.isFile())
|
|
36
|
+
continue;
|
|
37
|
+
size = stat.size;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
continue; // not a file here: just text
|
|
41
|
+
}
|
|
42
|
+
if (images.length >= MAX_IMAGES) {
|
|
43
|
+
skipped.push(`${raw} (more than ${MAX_IMAGES} images)`);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (size > MAX_IMAGE_BYTES) {
|
|
47
|
+
skipped.push(`${raw} (over 5MB)`);
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
images.push({
|
|
51
|
+
type: "image",
|
|
52
|
+
source: { type: "base64", media_type: MEDIA_TYPES[path.extname(file).toLowerCase()], data: fs.readFileSync(file).toString("base64") },
|
|
53
|
+
});
|
|
54
|
+
attached.push(file);
|
|
55
|
+
}
|
|
56
|
+
return images.length === 0 ? { content: text, attached, skipped } : { content: [{ type: "text", text }, ...images], attached, skipped };
|
|
57
|
+
}
|
package/dist/bin.js
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
const argv = process.argv.slice(2);
|
|
3
|
+
// `phren-agent models [--json]` lists the model catalog without loading the agent.
|
|
4
|
+
if (argv[0] === "models")
|
|
5
|
+
(await import("./models-list.js")).printModels(argv.slice(1));
|
|
6
|
+
else
|
|
7
|
+
(await import("./index.js")).runAgentCli(argv);
|
|
8
|
+
export {};
|
package/dist/commands/info.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { estimateMessageTokens } from "../context/token-counter.js";
|
|
2
|
+
import { contextTokens } from "../context/usage.js";
|
|
2
3
|
import { execSync } from "node:child_process";
|
|
3
4
|
const DIM = "\x1b[2m";
|
|
4
5
|
const _BOLD = "\x1b[1m";
|
|
@@ -13,7 +14,10 @@ export function helpCommand(_parts, _ctx) {
|
|
|
13
14
|
/model Interactive model + reasoning picker
|
|
14
15
|
/model add <id> Add a custom model
|
|
15
16
|
/model remove <id> Remove a custom model
|
|
17
|
+
/model <id> Switch to that model on the current provider
|
|
16
18
|
/provider Show configured providers + auth status
|
|
19
|
+
/provider <name> [model] Switch provider (and model) mid-session
|
|
20
|
+
/reasoning [level] Show or set the reasoning effort (none, low, medium, high, xhigh)
|
|
17
21
|
/turns Show turn and tool call counts
|
|
18
22
|
/clear Clear conversation history and terminal screen
|
|
19
23
|
/cwd Show current working directory
|
|
@@ -22,7 +26,7 @@ export function helpCommand(_parts, _ctx) {
|
|
|
22
26
|
/plan Show conversation plan (tool calls so far)
|
|
23
27
|
/undo Undo last user message and response
|
|
24
28
|
/history [n|full] Show last N messages (default 10) with rich formatting
|
|
25
|
-
/compact
|
|
29
|
+
/compact [focus] Compact conversation (LLM checkpoint + knowledge promotion), keeping the focus
|
|
26
30
|
/review Triage the phren review queue (go = manual, auto = model-assisted)
|
|
27
31
|
/context Show context window usage and provider info
|
|
28
32
|
/mode Toggle input mode (steering ↔ queue)
|
|
@@ -94,7 +98,7 @@ export function costCommand(_parts, ctx) {
|
|
|
94
98
|
const ct = ctx.costTracker;
|
|
95
99
|
if (ct) {
|
|
96
100
|
const cost = ct.metered ? `$${ct.totalCost.toFixed(4)}` : "included";
|
|
97
|
-
process.stderr.write(`${DIM}Tokens — input: ${ct.totalInputTokens} output: ${ct.totalOutputTokens} est. cost: ${cost}${RESET}\n`);
|
|
101
|
+
process.stderr.write(`${DIM}Tokens — input: ${ct.totalInputTokens} cached: ${ct.totalCacheReadTokens} output: ${ct.totalOutputTokens} est. cost: ${cost}${RESET}\n`);
|
|
98
102
|
}
|
|
99
103
|
else {
|
|
100
104
|
process.stderr.write(`${DIM}Cost tracking not available.${RESET}\n`);
|
|
@@ -144,7 +148,7 @@ export function undoCommand(_parts, ctx) {
|
|
|
144
148
|
return true;
|
|
145
149
|
}
|
|
146
150
|
export function contextCommand(_parts, ctx) {
|
|
147
|
-
const ctxTokens =
|
|
151
|
+
const ctxTokens = contextTokens(ctx.systemPrompt ?? "", ctx.session.messages, ctx.session.log, ctx.session.reportedContext);
|
|
148
152
|
const ctxPct = ctx.contextLimit > 0 ? (ctxTokens / ctx.contextLimit) * 100 : 0;
|
|
149
153
|
const ctxPctStr = ctxPct.toFixed(1);
|
|
150
154
|
const ctxWindowK = ctx.contextLimit >= 1000 ? `${(ctx.contextLimit / 1000).toFixed(0)}k` : String(ctx.contextLimit);
|
package/dist/commands/model.js
CHANGED
|
@@ -4,6 +4,7 @@ import { formatProviderList, formatModelAddHelp, addCustomModel, removeCustomMod
|
|
|
4
4
|
import { normalizeReasoningEffort } from "../models.js";
|
|
5
5
|
const DIM = "\x1b[2m";
|
|
6
6
|
const GREEN = "\x1b[32m";
|
|
7
|
+
const RED = "\x1b[31m";
|
|
7
8
|
const RESET = "\x1b[0m";
|
|
8
9
|
export function modelCommand(parts, ctx) {
|
|
9
10
|
const sub = parts[1]?.toLowerCase();
|
|
@@ -46,31 +47,72 @@ export function modelCommand(parts, ctx) {
|
|
|
46
47
|
process.stderr.write(ok ? `${GREEN}-> Removed ${modelId}${RESET}\n` : `${DIM}Model "${modelId}" not found in custom models.${RESET}\n`);
|
|
47
48
|
return true;
|
|
48
49
|
}
|
|
50
|
+
// /model <id>: that model on the current provider, keeping the effort.
|
|
51
|
+
if (parts[1] && sub !== "add" && sub !== "remove" && sub !== "rm") {
|
|
52
|
+
return switchModel(ctx, { model: parts[1], reasoning: ctx.currentReasoning ?? null });
|
|
53
|
+
}
|
|
49
54
|
// /model (no sub) -- interactive picker
|
|
50
55
|
if (!ctx.providerName) {
|
|
51
56
|
process.stderr.write(`${DIM}Provider not configured. Start with --provider to set one.${RESET}\n`);
|
|
52
57
|
return true;
|
|
53
58
|
}
|
|
54
|
-
const applyResult = (result) =>
|
|
55
|
-
if (result && ctx.onModelChange) {
|
|
56
|
-
ctx.onModelChange(result);
|
|
57
|
-
const reasoningLabel = result.reasoning ? ` (reasoning: ${result.reasoning})` : "";
|
|
58
|
-
process.stderr.write(`${GREEN}-> ${result.model}${reasoningLabel}${RESET}\n`);
|
|
59
|
-
}
|
|
60
|
-
else if (result) {
|
|
61
|
-
process.stderr.write(`${DIM}Model selected: ${result.model} -- restart to apply.${RESET}\n`);
|
|
62
|
-
}
|
|
63
|
-
};
|
|
59
|
+
const applyResult = (result) => (result ? switchModel(ctx, result) : true);
|
|
64
60
|
if (ctx.pickModel) {
|
|
65
|
-
return ctx.pickModel().then(
|
|
61
|
+
return ctx.pickModel().then(applyResult);
|
|
66
62
|
}
|
|
67
63
|
showModelPicker(ctx.providerName, ctx.currentModel, ctx.currentReasoning, process.stdout).then(applyResult);
|
|
68
64
|
return true;
|
|
69
65
|
}
|
|
70
|
-
|
|
71
|
-
|
|
66
|
+
/**
|
|
67
|
+
* Apply a model, provider or effort change through the host and keep the
|
|
68
|
+
* command context in step with it, so the next /model or /reasoning starts
|
|
69
|
+
* from what is running now.
|
|
70
|
+
*/
|
|
71
|
+
export async function switchModel(ctx, result) {
|
|
72
|
+
if (!ctx.onModelChange) {
|
|
73
|
+
process.stderr.write(`${DIM}Model selected: ${result.model || "(default)"} -- restart to apply.${RESET}\n`);
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
const provider = await ctx.onModelChange(result);
|
|
78
|
+
if (provider) {
|
|
79
|
+
ctx.provider = provider;
|
|
80
|
+
ctx.providerName = provider.name;
|
|
81
|
+
ctx.currentModel = provider.model;
|
|
82
|
+
ctx.currentReasoning = provider.reasoningEffort ?? null;
|
|
83
|
+
}
|
|
84
|
+
const name = provider ? `${provider.name}/${provider.model ?? "default"}` : result.model;
|
|
85
|
+
const effort = provider?.reasoningEffort ?? result.reasoning;
|
|
86
|
+
process.stderr.write(`${GREEN}-> ${name}${effort ? ` (reasoning: ${effort})` : ""}${RESET}\n`);
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
process.stderr.write(`${RED}Could not switch: ${err instanceof Error ? err.message : String(err)}${RESET}\n`);
|
|
90
|
+
}
|
|
72
91
|
return true;
|
|
73
92
|
}
|
|
93
|
+
/** /reasoning [level]: show the effort, or set it on the current model. */
|
|
94
|
+
export function reasoningCommand(parts, ctx) {
|
|
95
|
+
const arg = parts[1];
|
|
96
|
+
if (!arg) {
|
|
97
|
+
process.stderr.write(`${DIM}Reasoning: ${ctx.currentReasoning ?? "model default"}. Set it with /reasoning none|low|medium|high|xhigh.${RESET}\n`);
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
const level = normalizeReasoningEffort(arg);
|
|
101
|
+
if (!level) {
|
|
102
|
+
process.stderr.write(`${RED}Unknown reasoning level "${arg}". Use none, low, medium, high or xhigh.${RESET}\n`);
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
return switchModel(ctx, { model: ctx.currentModel ?? "", reasoning: level });
|
|
106
|
+
}
|
|
107
|
+
/** /provider lists providers; /provider <name> [model] switches to one mid-session. */
|
|
108
|
+
export function providerCommand(parts, ctx) {
|
|
109
|
+
if (!parts[1]) {
|
|
110
|
+
process.stderr.write(formatProviderList());
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
// Another provider's effort scale may differ: start from its default.
|
|
114
|
+
return switchModel(ctx, { provider: parts[1], model: parts[2] ?? "", reasoning: null });
|
|
115
|
+
}
|
|
74
116
|
export function presetCommand(parts, _ctx) {
|
|
75
117
|
const sub = parts[1]?.toLowerCase();
|
|
76
118
|
if (!sub || sub === "list") {
|
package/dist/commands/session.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { toolResultText } from "../providers/types.js";
|
|
2
|
-
import { seedFromMessages } from "../session/log.js";
|
|
2
|
+
import { SessionLog, seedFromMessages } from "../session/log.js";
|
|
3
|
+
import { listEventLogs, loadEventLog } from "../session/persist.js";
|
|
4
|
+
import { agentUserDir } from "../config.js";
|
|
3
5
|
import { estimateMessageTokens } from "../context/token-counter.js";
|
|
4
6
|
import { planPrune } from "../context/pruner.js";
|
|
5
7
|
import { compactWithLlm } from "../context/compactor.js";
|
|
@@ -144,7 +146,8 @@ export function historyCommand(parts, ctx) {
|
|
|
144
146
|
process.stderr.write(`${DIM}-- end --${RESET}\n`);
|
|
145
147
|
return true;
|
|
146
148
|
}
|
|
147
|
-
export async function compactCommand(
|
|
149
|
+
export async function compactCommand(parts, ctx) {
|
|
150
|
+
const focus = parts.slice(1).join(" ");
|
|
148
151
|
const beforeCount = ctx.session.messages.length;
|
|
149
152
|
const beforeTokens = estimateMessageTokens(ctx.session.messages);
|
|
150
153
|
// LLM checkpoint when a provider is wired up; regex fallback otherwise.
|
|
@@ -158,6 +161,8 @@ export async function compactCommand(_parts, ctx) {
|
|
|
158
161
|
pruneConfig: { contextLimit: ctx.contextLimit, keepRecentTurns: 4 },
|
|
159
162
|
// Manual /compact should always try the LLM, even for small ranges.
|
|
160
163
|
config: { minPrunedTokens: 0 },
|
|
164
|
+
tools: ctx.registry?.getDefinitions?.(),
|
|
165
|
+
focus,
|
|
161
166
|
});
|
|
162
167
|
if (result) {
|
|
163
168
|
ctx.session.log.replaceMessageRange(result.plan.startIndex, result.plan.endIndex, result.plan.summaryMessage);
|
|
@@ -216,30 +221,86 @@ export function diffCommand(parts, _ctx) {
|
|
|
216
221
|
}
|
|
217
222
|
return true;
|
|
218
223
|
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
224
|
+
/** Sessions /resume can offer: this store's, or ~/.phren-agent's for this directory without one. */
|
|
225
|
+
function resumableSessions(ctx) {
|
|
226
|
+
const current = ctx.session.log.header.sessionId;
|
|
227
|
+
const listed = ctx.phrenPath
|
|
228
|
+
? listEventLogs(ctx.phrenPath, { project: ctx.phrenCtx?.project ?? undefined, limit: 30 })
|
|
229
|
+
: listEventLogs(agentUserDir(), { cwd: process.cwd(), limit: 30 });
|
|
230
|
+
return listed.filter((s) => s.sessionId !== current);
|
|
231
|
+
}
|
|
232
|
+
function sessionLabel(s) {
|
|
233
|
+
const when = new Date(s.mtimeMs).toISOString().replace("T", " ").slice(0, 16);
|
|
234
|
+
return { label: s.title || "(no prompt)", detail: `${when} \u00b7 ${s.messages} msgs \u00b7 ${s.sessionId.slice(0, 8)}` };
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* /resume picks an earlier session and loads its conversation into this
|
|
238
|
+
* fresh one: from a picker in the terminal UI, by number or id prefix
|
|
239
|
+
* (`/resume 2`, `/resume 3fa9`), or from a printed list elsewhere.
|
|
240
|
+
*/
|
|
241
|
+
export async function resumeCommand(parts, ctx) {
|
|
242
|
+
if (ctx.session.messages.length > 0) {
|
|
243
|
+
process.stderr.write(`${DIM}Session already has history; /resume only works on a fresh session.${RESET}\n`);
|
|
244
|
+
return true;
|
|
245
|
+
}
|
|
246
|
+
const sessions = resumableSessions(ctx);
|
|
247
|
+
const arg = parts[1];
|
|
248
|
+
let chosen;
|
|
249
|
+
if (arg) {
|
|
250
|
+
const index = Number(arg);
|
|
251
|
+
chosen = Number.isInteger(index) && index >= 1 && index <= sessions.length
|
|
252
|
+
? sessions[index - 1]
|
|
253
|
+
: sessions.find((s) => s.sessionId.startsWith(arg));
|
|
254
|
+
if (!chosen) {
|
|
255
|
+
process.stderr.write(`${RED}No session "${arg}". /resume lists them.${RESET}\n`);
|
|
256
|
+
return true;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
else if (sessions.length === 0) {
|
|
260
|
+
return resumeLegacySnapshot(ctx);
|
|
261
|
+
}
|
|
262
|
+
else if (ctx.pickFromList) {
|
|
263
|
+
const picked = await ctx.pickFromList("Resume a session", sessions.map(sessionLabel));
|
|
264
|
+
if (picked === null)
|
|
265
|
+
return true;
|
|
266
|
+
chosen = sessions[picked];
|
|
267
|
+
}
|
|
268
|
+
else {
|
|
269
|
+
const lines = sessions.slice(0, 15).map((s, i) => {
|
|
270
|
+
const { label, detail } = sessionLabel(s);
|
|
271
|
+
return ` ${String(i + 1).padStart(2)}. ${label.slice(0, 60)} ${detail}`;
|
|
272
|
+
});
|
|
273
|
+
process.stderr.write(`${DIM}Recent sessions (newest first):\n${lines.join("\n")}\n /resume <n> or /resume <id> to load one${RESET}\n`);
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
let messages;
|
|
277
|
+
try {
|
|
278
|
+
const { header, events } = loadEventLog(chosen.file);
|
|
279
|
+
messages = SessionLog.restore(header, events, () => { }).getMessages();
|
|
280
|
+
}
|
|
281
|
+
catch (err) {
|
|
282
|
+
process.stderr.write(`${RED}Cannot read that session: ${err instanceof Error ? err.message : String(err)}${RESET}\n`);
|
|
222
283
|
return true;
|
|
223
284
|
}
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
285
|
+
seedFromMessages(ctx.session.log, messages);
|
|
286
|
+
process.stderr.write(`${GREEN}-> Resumed ${messages.length} messages from session ${chosen.sessionId.slice(0, 8)}: ${chosen.title}${RESET}\n`);
|
|
287
|
+
process.stderr.write(`${DIM} Use /history to review. The model sees the whole conversation on your next message.${RESET}\n`);
|
|
288
|
+
return true;
|
|
289
|
+
}
|
|
290
|
+
/** Before event logs: the v1 snapshot saved at the end of the last session. */
|
|
291
|
+
function resumeLegacySnapshot(ctx) {
|
|
292
|
+
if (!ctx.phrenPath) {
|
|
227
293
|
process.stderr.write(`${DIM}No previous session to resume.${RESET}\n`);
|
|
228
294
|
return true;
|
|
229
295
|
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
process.stderr.write(`${DIM}Session already has history; /resume only works on a fresh session.${RESET}\n`);
|
|
296
|
+
const snapshot = loadLastSessionSnapshot(ctx.phrenPath, ctx.phrenCtx?.project ?? undefined);
|
|
297
|
+
if (!snapshot || snapshot.messages.length === 0) {
|
|
298
|
+
process.stderr.write(`${DIM}No previous session to resume.${RESET}\n`);
|
|
234
299
|
return true;
|
|
235
300
|
}
|
|
236
301
|
seedFromMessages(ctx.session.log, snapshot.messages);
|
|
237
|
-
process.stderr.write(`${GREEN}-> Resumed ${
|
|
238
|
-
|
|
239
|
-
process.stderr.write(`${DIM} Project: ${snapshot.project}${RESET}\n`);
|
|
240
|
-
}
|
|
241
|
-
process.stderr.write(`${DIM} Saved: ${snapshot.savedAt}${RESET}\n`);
|
|
242
|
-
process.stderr.write(`${DIM} Use /history to review. The LLM will see the full prior conversation on your next message.${RESET}\n`);
|
|
302
|
+
process.stderr.write(`${GREEN}-> Resumed ${snapshot.messages.length} messages from session ${snapshot.sessionId}${RESET}\n`);
|
|
303
|
+
process.stderr.write(`${DIM} Saved: ${snapshot.savedAt}. Use /history to review.${RESET}\n`);
|
|
243
304
|
return true;
|
|
244
305
|
}
|
|
245
306
|
export function rewindCommand(parts, _ctx) {
|
package/dist/commands.js
CHANGED
|
@@ -4,7 +4,7 @@ import { sessionCommand, historyCommand, compactCommand, diffCommand, gitCommand
|
|
|
4
4
|
import { memCommand, askCommand } from "./commands/memory.js";
|
|
5
5
|
import { reviewCommand } from "./commands/review.js";
|
|
6
6
|
import { findSkill, getScopedSkills } from "@phren/cli/skill/registry";
|
|
7
|
-
import { modelCommand, providerCommand, presetCommand } from "./commands/model.js";
|
|
7
|
+
import { modelCommand, providerCommand, presetCommand, reasoningCommand } from "./commands/model.js";
|
|
8
8
|
import { configCommand } from "./commands/config.js";
|
|
9
9
|
import { loadInputMode, saveInputMode, savePermissionMode } from "./settings.js";
|
|
10
10
|
import { addAllow } from "./permissions/allowlist.js";
|
|
@@ -20,10 +20,10 @@ export function createCommandContext(session, contextLimit) {
|
|
|
20
20
|
}
|
|
21
21
|
const BUILTIN_COMMAND_NAMES = [
|
|
22
22
|
"/help", "/turns", "/clear", "/cwd", "/files", "/cost", "/plan", "/undo",
|
|
23
|
-
"/context", "/model", "/provider", "/preset", "/session", "/history",
|
|
23
|
+
"/context", "/model", "/provider", "/reasoning", "/preset", "/session", "/history",
|
|
24
24
|
"/compact", "/diff", "/git", "/mem", "/ask", "/resume", "/review", "/config", "/spawn", "/agents",
|
|
25
25
|
"/allow",
|
|
26
|
-
"/mode", "/permissions", "/verbose", "/theme", "/agent", "/rewind", "/fork",
|
|
26
|
+
"/mode", "/permissions", "/verbose", "/theme", "/agent", "/rewind", "/fork", "/promote",
|
|
27
27
|
"/exit", "/quit", "/q",
|
|
28
28
|
];
|
|
29
29
|
/**
|
|
@@ -38,6 +38,12 @@ export function setCustomCommands(commands) {
|
|
|
38
38
|
COMMAND_NAMES.length = 0;
|
|
39
39
|
COMMAND_NAMES.push(...BUILTIN_COMMAND_NAMES, ...customCommands.map((command) => `/${command.name}`));
|
|
40
40
|
}
|
|
41
|
+
/** Extra command names for completion (MCP prompts, found after servers connect). */
|
|
42
|
+
export function addCommandNames(names) {
|
|
43
|
+
for (const name of names)
|
|
44
|
+
if (!COMMAND_NAMES.includes(name))
|
|
45
|
+
COMMAND_NAMES.push(name);
|
|
46
|
+
}
|
|
41
47
|
export function loadAndRegisterCustomCommands(cwd = process.cwd()) {
|
|
42
48
|
const commands = loadCustomCommands(cwd);
|
|
43
49
|
setCustomCommands(commands);
|
|
@@ -122,6 +128,7 @@ export function handleCommand(input, ctx) {
|
|
|
122
128
|
case "/context": return contextCommand(parts, ctx);
|
|
123
129
|
case "/model": return modelCommand(parts, ctx);
|
|
124
130
|
case "/provider": return providerCommand(parts, ctx);
|
|
131
|
+
case "/reasoning": return reasoningCommand(parts, ctx);
|
|
125
132
|
case "/preset": return presetCommand(parts, ctx);
|
|
126
133
|
case "/session": return sessionCommand(parts, ctx);
|
|
127
134
|
case "/history": return historyCommand(parts, ctx);
|
|
@@ -134,6 +141,20 @@ export function handleCommand(input, ctx) {
|
|
|
134
141
|
case "/review": return reviewCommand(parts, ctx);
|
|
135
142
|
case "/config": return configCommand(parts, ctx);
|
|
136
143
|
case "/rewind": return rewindCommand(parts, ctx);
|
|
144
|
+
case "/promote": {
|
|
145
|
+
const promote = ctx.promote;
|
|
146
|
+
if (!promote) {
|
|
147
|
+
process.stderr.write(`${DIM}Already an agent session: /promote turns a quick chat (--mode chat) into one.${RESET}\n`);
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
return promote().then((message) => {
|
|
151
|
+
process.stderr.write(`\x1b[32m${message}${RESET}\n`);
|
|
152
|
+
return true;
|
|
153
|
+
}, (err) => {
|
|
154
|
+
process.stderr.write(`\x1b[31mPromote failed: ${err instanceof Error ? err.message : String(err)}${RESET}\n`);
|
|
155
|
+
return true;
|
|
156
|
+
});
|
|
157
|
+
}
|
|
137
158
|
case "/fork": {
|
|
138
159
|
const result = ctx.forkSession?.();
|
|
139
160
|
if (!result) {
|
package/dist/config.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import * as os from "node:os";
|
|
2
2
|
import * as path from "node:path";
|
|
3
|
+
import { parseRuleList } from "./permissions/rules.js";
|
|
4
|
+
import { normalizeReasoningEffort } from "./models.js";
|
|
3
5
|
import { loadPermissionMode } from "./settings.js";
|
|
4
6
|
export const AGENT_CONFIG_DIR = ".phren-agent";
|
|
5
7
|
export function agentConfigDir(base) {
|
|
@@ -18,17 +20,26 @@ Options:
|
|
|
18
20
|
openai-compat, ollama
|
|
19
21
|
--base-url <url> Endpoint for openai-compat (or to override deepseek's)
|
|
20
22
|
--model <model> Override LLM model
|
|
21
|
-
--reasoning <level> Reasoning effort: low, medium, high, xhigh
|
|
23
|
+
--reasoning <level> Reasoning effort: none, low, medium, high, xhigh (max)
|
|
22
24
|
--project <name> Force phren project context
|
|
23
25
|
--max-turns <n> Max tool-use turns (default: 50)
|
|
24
26
|
--max-output <n> Max output tokens per response (default: auto per model)
|
|
27
|
+
--context-window <n> Context window in tokens, overriding the model catalog
|
|
28
|
+
--price-in <usd> Input price per 1M tokens, overriding the catalog
|
|
29
|
+
--price-out <usd> Output price per 1M tokens
|
|
30
|
+
--price-cache <usd> Cache-hit input price per 1M tokens
|
|
25
31
|
--budget <dollars> Max spend in USD (aborts when exceeded)
|
|
26
32
|
--plan Plan mode: show plan before executing tools
|
|
33
|
+
--mode <mode> agent (default) or chat: quick chat with no tools and read-only
|
|
34
|
+
phren memory up front; /promote continues it as an agent
|
|
27
35
|
--no-subagents Disable spawn_agent/send_message/list_agents in one-shot mode
|
|
28
36
|
--no-llm-compact Use regex prune summaries instead of LLM compaction
|
|
29
37
|
--sandbox <mode> Kernel write-fence for shell (bwrap): off, auto (default), require
|
|
38
|
+
--no-network Run shell commands without network (bwrap or Seatbelt; fails closed)
|
|
30
39
|
--permissions <mode> Permission mode: suggest (default), auto-confirm, full-auto
|
|
31
40
|
--yolo Full-auto permissions — no confirmations (alias for --permissions full-auto)
|
|
41
|
+
--allowedTools <rules> Allow these without asking, comma-separated: read_file, shell(npm test), edit_file(src/**)
|
|
42
|
+
--disallowedTools <rules> Deny these in every mode, same syntax
|
|
32
43
|
--interactive, -i Interactive REPL mode (multi-turn conversation)
|
|
33
44
|
--resume, -c Resume the newest session's conversation (task optional)
|
|
34
45
|
--session <id> Resume a specific session by id or unique id prefix
|
|
@@ -36,10 +47,18 @@ Options:
|
|
|
36
47
|
-p, --print Headless: no prompts (tool approvals are denied), clean stdout
|
|
37
48
|
--output-format <f> With -p: text (final message), json (one result object),
|
|
38
49
|
stream-json (NDJSON events + result). Implies -p
|
|
50
|
+
--json-schema <s> With -p: end with a JSON value matching this schema (inline JSON or a
|
|
51
|
+
file), in the result's structured_output; implies -p
|
|
52
|
+
--input-format <f> With -p: text (the task, default) or stream-json (user
|
|
53
|
+
messages as JSON lines on stdin, one turn each, same session;
|
|
54
|
+
needs --output-format stream-json)
|
|
39
55
|
--lint-cmd <cmd> Override auto-detected lint command
|
|
40
56
|
--test-cmd <cmd> Override auto-detected test command
|
|
57
|
+
--typecheck-cmd <cmd> Override the auto-detected type check run after edits
|
|
41
58
|
--mcp <command> Connect to an MCP server via stdio (repeatable)
|
|
42
59
|
--mcp-config <path> Load MCP server config from JSON file
|
|
60
|
+
--trust-project-mcp Load this project's .mcp.json and .phren-agent/mcp.json (remembered)
|
|
61
|
+
--strict-mcp-config Use only --mcp-config and --mcp servers, no default config files
|
|
43
62
|
--team <name> Start in team mode with named team coordination
|
|
44
63
|
--multi Start in multi-agent TUI mode
|
|
45
64
|
--dry-run Show system prompt and exit
|
|
@@ -65,8 +84,14 @@ Environment:
|
|
|
65
84
|
PHREN_AGENT_PROVIDER Force provider via env
|
|
66
85
|
PHREN_AGENT_MODEL Override model via env
|
|
67
86
|
PHREN_AGENT_REASONING Override reasoning effort via env
|
|
68
|
-
PHREN_AGENT_BASE_URL Endpoint for openai-compat
|
|
87
|
+
PHREN_AGENT_BASE_URL Endpoint for openai-compat (and for deepseek with
|
|
88
|
+
PHREN_AGENT_PROVIDER=deepseek)
|
|
69
89
|
PHREN_AGENT_API_KEY Key for openai-compat
|
|
90
|
+
PHREN_AGENT_CONTEXT_WINDOW, PHREN_AGENT_PRICE_IN, PHREN_AGENT_PRICE_OUT,
|
|
91
|
+
PHREN_AGENT_PRICE_CACHE Same as the flags, for every model (the flags apply
|
|
92
|
+
only to the model they were given with, and win)
|
|
93
|
+
OpenCode Go (base URL https://opencode.ai/zen/go/v1) is a subscription, so
|
|
94
|
+
its usage shows as included rather than priced.
|
|
70
95
|
|
|
71
96
|
Examples:
|
|
72
97
|
phren-agent "fix the login bug"
|
|
@@ -79,6 +104,8 @@ export function parseArgs(argv) {
|
|
|
79
104
|
task: "",
|
|
80
105
|
permissions: "suggest",
|
|
81
106
|
permissionsExplicit: false,
|
|
107
|
+
allowedTools: [],
|
|
108
|
+
disallowedTools: [],
|
|
82
109
|
maxTurns: 50,
|
|
83
110
|
budget: null,
|
|
84
111
|
plan: false,
|
|
@@ -89,11 +116,13 @@ export function parseArgs(argv) {
|
|
|
89
116
|
listSessions: false,
|
|
90
117
|
print: false,
|
|
91
118
|
outputFormat: "text",
|
|
119
|
+
inputFormat: "text",
|
|
92
120
|
noSubagents: false,
|
|
93
121
|
noLlmCompact: false,
|
|
94
122
|
sandbox: "auto",
|
|
95
123
|
mcp: [],
|
|
96
124
|
multi: false,
|
|
125
|
+
mode: "agent",
|
|
97
126
|
help: false,
|
|
98
127
|
version: false,
|
|
99
128
|
};
|
|
@@ -122,6 +151,9 @@ export function parseArgs(argv) {
|
|
|
122
151
|
else if (arg === "--no-llm-compact") {
|
|
123
152
|
args.noLlmCompact = true;
|
|
124
153
|
}
|
|
154
|
+
else if (arg === "--no-network") {
|
|
155
|
+
args.noNetwork = true;
|
|
156
|
+
}
|
|
125
157
|
else if (arg === "--sandbox" && argv[i + 1]) {
|
|
126
158
|
const mode = argv[++i];
|
|
127
159
|
if (mode === "off" || mode === "auto" || mode === "require") {
|
|
@@ -131,6 +163,12 @@ export function parseArgs(argv) {
|
|
|
131
163
|
else if (arg === "--plan") {
|
|
132
164
|
args.plan = true;
|
|
133
165
|
}
|
|
166
|
+
else if (arg === "--mode" && argv[i + 1]) {
|
|
167
|
+
const mode = argv[++i];
|
|
168
|
+
if (mode !== "agent" && mode !== "chat")
|
|
169
|
+
throw new Error(`Unknown --mode "${mode}". Use agent or chat.`);
|
|
170
|
+
args.mode = mode;
|
|
171
|
+
}
|
|
134
172
|
else if (arg === "--resume" || arg === "--continue" || arg === "-c") {
|
|
135
173
|
args.resume = true;
|
|
136
174
|
}
|
|
@@ -144,6 +182,18 @@ export function parseArgs(argv) {
|
|
|
144
182
|
else if (arg === "--print" || arg === "-p") {
|
|
145
183
|
args.print = true;
|
|
146
184
|
}
|
|
185
|
+
else if (arg === "--json-schema" && argv[i + 1]) {
|
|
186
|
+
args.jsonSchema = argv[++i];
|
|
187
|
+
args.print = true;
|
|
188
|
+
}
|
|
189
|
+
else if (arg === "--input-format" && argv[i + 1]) {
|
|
190
|
+
const format = argv[++i];
|
|
191
|
+
if (format !== "text" && format !== "stream-json")
|
|
192
|
+
throw new Error(`Unknown --input-format "${format}". Use text or stream-json.`);
|
|
193
|
+
args.inputFormat = format;
|
|
194
|
+
if (format === "stream-json")
|
|
195
|
+
args.print = true;
|
|
196
|
+
}
|
|
147
197
|
else if (arg === "--output-format" && argv[i + 1]) {
|
|
148
198
|
const format = argv[++i];
|
|
149
199
|
if (format === "text" || format === "json" || format === "stream-json") {
|
|
@@ -163,12 +213,21 @@ export function parseArgs(argv) {
|
|
|
163
213
|
else if (arg === "--test-cmd" && argv[i + 1]) {
|
|
164
214
|
args.testCmd = argv[++i];
|
|
165
215
|
}
|
|
216
|
+
else if (arg === "--typecheck-cmd" && argv[i + 1]) {
|
|
217
|
+
args.typecheckCmd = argv[++i];
|
|
218
|
+
}
|
|
166
219
|
else if (arg === "--mcp" && argv[i + 1]) {
|
|
167
220
|
args.mcp.push(argv[++i]);
|
|
168
221
|
}
|
|
169
222
|
else if (arg === "--mcp-config" && argv[i + 1]) {
|
|
170
223
|
args.mcpConfig = argv[++i];
|
|
171
224
|
}
|
|
225
|
+
else if (arg === "--trust-project-mcp") {
|
|
226
|
+
args.trustProjectMcp = true;
|
|
227
|
+
}
|
|
228
|
+
else if (arg === "--strict-mcp-config") {
|
|
229
|
+
args.strictMcpConfig = true;
|
|
230
|
+
}
|
|
172
231
|
else if (arg === "--team" && argv[i + 1]) {
|
|
173
232
|
args.team = argv[++i];
|
|
174
233
|
}
|
|
@@ -182,10 +241,7 @@ export function parseArgs(argv) {
|
|
|
182
241
|
args.model = argv[++i];
|
|
183
242
|
}
|
|
184
243
|
else if (arg === "--reasoning" && argv[i + 1]) {
|
|
185
|
-
|
|
186
|
-
if (value === "low" || value === "medium" || value === "high" || value === "xhigh" || value === "max") {
|
|
187
|
-
args.reasoning = value === "max" ? "xhigh" : value;
|
|
188
|
-
}
|
|
244
|
+
args.reasoning = normalizeReasoningEffort(argv[++i]) ?? args.reasoning;
|
|
189
245
|
}
|
|
190
246
|
else if (arg === "--project" && argv[i + 1]) {
|
|
191
247
|
args.project = argv[++i];
|
|
@@ -196,9 +252,27 @@ export function parseArgs(argv) {
|
|
|
196
252
|
else if (arg === "--max-output" && argv[i + 1]) {
|
|
197
253
|
args.maxOutput = parseInt(argv[++i], 10) || undefined;
|
|
198
254
|
}
|
|
255
|
+
else if (arg === "--context-window" && argv[i + 1]) {
|
|
256
|
+
args.contextWindow = parsePositive(argv[++i], arg, true);
|
|
257
|
+
}
|
|
258
|
+
else if (arg === "--price-in" && argv[i + 1]) {
|
|
259
|
+
args.priceIn = parsePositive(argv[++i], arg);
|
|
260
|
+
}
|
|
261
|
+
else if (arg === "--price-out" && argv[i + 1]) {
|
|
262
|
+
args.priceOut = parsePositive(argv[++i], arg);
|
|
263
|
+
}
|
|
264
|
+
else if (arg === "--price-cache" && argv[i + 1]) {
|
|
265
|
+
args.priceCache = parsePositive(argv[++i], arg);
|
|
266
|
+
}
|
|
199
267
|
else if (arg === "--budget" && argv[i + 1]) {
|
|
200
268
|
args.budget = parseFloat(argv[++i]) || null;
|
|
201
269
|
}
|
|
270
|
+
else if ((arg === "--allowedTools" || arg === "--allowed-tools") && argv[i + 1]) {
|
|
271
|
+
args.allowedTools.push(...parseRuleList(argv[++i]));
|
|
272
|
+
}
|
|
273
|
+
else if ((arg === "--disallowedTools" || arg === "--disallowed-tools") && argv[i + 1]) {
|
|
274
|
+
args.disallowedTools.push(...parseRuleList(argv[++i]));
|
|
275
|
+
}
|
|
202
276
|
else if (arg === "--yolo") {
|
|
203
277
|
args.permissions = "full-auto";
|
|
204
278
|
args.permissionsExplicit = true;
|
|
@@ -221,13 +295,18 @@ export function parseArgs(argv) {
|
|
|
221
295
|
args.model = process.env.PHREN_AGENT_MODEL;
|
|
222
296
|
}
|
|
223
297
|
if (!args.reasoning && process.env.PHREN_AGENT_REASONING) {
|
|
224
|
-
|
|
225
|
-
if (value === "low" || value === "medium" || value === "high" || value === "xhigh" || value === "max") {
|
|
226
|
-
args.reasoning = value === "max" ? "xhigh" : value;
|
|
227
|
-
}
|
|
298
|
+
args.reasoning = normalizeReasoningEffort(process.env.PHREN_AGENT_REASONING);
|
|
228
299
|
}
|
|
229
300
|
return args;
|
|
230
301
|
}
|
|
302
|
+
/** A non-negative number (prices) or positive integer (token counts); throws on junk. */
|
|
303
|
+
function parsePositive(raw, flag, integer = false) {
|
|
304
|
+
const value = Number(raw.replace(/_/g, ""));
|
|
305
|
+
const ok = integer ? Number.isInteger(value) && value > 0 : Number.isFinite(value) && value >= 0;
|
|
306
|
+
if (!ok)
|
|
307
|
+
throw new Error(`${flag} needs ${integer ? "a positive whole number" : "a number"}, got "${raw}".`);
|
|
308
|
+
return value;
|
|
309
|
+
}
|
|
231
310
|
export function resolveStartupPermissions(args) {
|
|
232
311
|
if (args.permissionsExplicit)
|
|
233
312
|
return;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { toolResultText } from "../providers/types.js";
|
|
2
|
+
export const DEFAULT_CLEAR = { keepRecent: 8, minChars: 2_000 };
|
|
3
|
+
const CLEARED_PREFIX = "[Earlier output cleared to save context";
|
|
4
|
+
/** Plan which old tool results to clear. Returns [] when there is nothing worth clearing. */
|
|
5
|
+
export function planToolResultClearing(messages, config = {}) {
|
|
6
|
+
const { keepRecent, minChars } = { ...DEFAULT_CLEAR, ...config };
|
|
7
|
+
const names = new Map();
|
|
8
|
+
const results = [];
|
|
9
|
+
messages.forEach((msg, index) => {
|
|
10
|
+
if (typeof msg.content === "string")
|
|
11
|
+
return;
|
|
12
|
+
for (const block of msg.content) {
|
|
13
|
+
if (block.type === "tool_use")
|
|
14
|
+
names.set(block.id, block.name);
|
|
15
|
+
else if (block.type === "tool_result")
|
|
16
|
+
results.push({ index, block });
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
const clear = new Map();
|
|
20
|
+
for (const { index, block } of results.slice(0, Math.max(0, results.length - keepRecent))) {
|
|
21
|
+
const text = toolResultText(block);
|
|
22
|
+
const hasImage = Array.isArray(block.content) && block.content.some((part) => part.type === "image");
|
|
23
|
+
if (text.startsWith(CLEARED_PREFIX) || (text.length < minChars && !hasImage))
|
|
24
|
+
continue;
|
|
25
|
+
if (!clear.has(index))
|
|
26
|
+
clear.set(index, new Set());
|
|
27
|
+
clear.get(index).add(block);
|
|
28
|
+
}
|
|
29
|
+
return [...clear].map(([index, blocks]) => {
|
|
30
|
+
const content = messages[index].content.map((block) => {
|
|
31
|
+
if (block.type !== "tool_result" || !blocks.has(block))
|
|
32
|
+
return block;
|
|
33
|
+
const text = toolResultText(block);
|
|
34
|
+
const tool = names.get(block.tool_use_id) ?? "the tool";
|
|
35
|
+
const firstLine = text.split("\n", 1)[0].slice(0, 120);
|
|
36
|
+
return {
|
|
37
|
+
...block,
|
|
38
|
+
content: `${CLEARED_PREFIX}: ${tool} returned ${text.length} chars, starting "${firstLine}". Run it again if you need it.]`,
|
|
39
|
+
};
|
|
40
|
+
});
|
|
41
|
+
return { index, message: { ...messages[index], content } };
|
|
42
|
+
});
|
|
43
|
+
}
|