@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
package/dist/mcp-client.js
CHANGED
|
@@ -7,6 +7,7 @@ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
|
7
7
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
8
8
|
import { spawn } from "child_process";
|
|
9
9
|
import * as fs from "fs";
|
|
10
|
+
import * as path from "path";
|
|
10
11
|
import * as readline from "readline";
|
|
11
12
|
import { McpOAuthProvider } from "./mcp-oauth.js";
|
|
12
13
|
import { VERSION } from "./package-metadata.js";
|
|
@@ -383,6 +384,20 @@ function formatToolResult(result) {
|
|
|
383
384
|
})
|
|
384
385
|
.join("\n");
|
|
385
386
|
}
|
|
387
|
+
/**
|
|
388
|
+
* Longest MCP tool result the model gets, in chars (about 25k tokens, Claude
|
|
389
|
+
* Code's default). One server answering with a whole database dump must not
|
|
390
|
+
* fill the context. PHREN_AGENT_MCP_MAX_OUTPUT_CHARS changes it.
|
|
391
|
+
*/
|
|
392
|
+
function maxMcpOutputChars() {
|
|
393
|
+
const raw = Number(process.env.PHREN_AGENT_MCP_MAX_OUTPUT_CHARS);
|
|
394
|
+
return Number.isFinite(raw) && raw > 0 ? raw : 100_000;
|
|
395
|
+
}
|
|
396
|
+
export function capMcpOutput(text, max = maxMcpOutputChars()) {
|
|
397
|
+
if (text.length <= max)
|
|
398
|
+
return text;
|
|
399
|
+
return `${text.slice(0, max)}\n\n[MCP output truncated: ${text.length} chars, showing the first ${max}. Ask the tool for less, with a filter or a page, if it takes one.]`;
|
|
400
|
+
}
|
|
386
401
|
/** Wrap an MCP tool as an AgentTool. */
|
|
387
402
|
function wrapMcpTool(conn, def) {
|
|
388
403
|
return {
|
|
@@ -392,7 +407,7 @@ function wrapMcpTool(conn, def) {
|
|
|
392
407
|
async execute(input, signal) {
|
|
393
408
|
try {
|
|
394
409
|
const result = await conn.callTool(def.name, input, signal);
|
|
395
|
-
const text = formatToolResult(result);
|
|
410
|
+
const text = capMcpOutput(formatToolResult(result));
|
|
396
411
|
return result?.isError ? { output: text, is_error: true } : { output: text };
|
|
397
412
|
}
|
|
398
413
|
catch (err) {
|
|
@@ -485,6 +500,28 @@ export async function connectMcpServers(servers, verbose = false) {
|
|
|
485
500
|
},
|
|
486
501
|
};
|
|
487
502
|
}
|
|
503
|
+
/**
|
|
504
|
+
* The MCP servers a session gets without flags: the user's
|
|
505
|
+
* `~/.phren-agent/mcp.json`, then the project's `.mcp.json` (Claude Code's
|
|
506
|
+
* file) and `.phren-agent/mcp.json`. A project file starts commands from
|
|
507
|
+
* whatever repository is checked out, so it loads only for a project the
|
|
508
|
+
* user trusted (`--trust-project-mcp`, remembered); otherwise it is reported
|
|
509
|
+
* in `untrusted`.
|
|
510
|
+
*/
|
|
511
|
+
export function loadDefaultMcpConfig(cwd, opts) {
|
|
512
|
+
const servers = { ...loadMcpConfig(path.join(opts.home, ".phren-agent", "mcp.json")) };
|
|
513
|
+
const untrusted = [];
|
|
514
|
+
for (const file of [path.join(cwd, ".mcp.json"), path.join(cwd, ".phren-agent", "mcp.json")]) {
|
|
515
|
+
const found = loadMcpConfig(file);
|
|
516
|
+
if (Object.keys(found).length === 0)
|
|
517
|
+
continue;
|
|
518
|
+
if (opts.trusted)
|
|
519
|
+
Object.assign(servers, found);
|
|
520
|
+
else
|
|
521
|
+
untrusted.push({ file, names: Object.keys(found) });
|
|
522
|
+
}
|
|
523
|
+
return { servers, untrusted };
|
|
524
|
+
}
|
|
488
525
|
/** Load MCP server config from a JSON file (same format as Claude Code's mcpServers). */
|
|
489
526
|
export function loadMcpConfig(configPath) {
|
|
490
527
|
if (!fs.existsSync(configPath))
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP prompts as slash commands, the way Claude Code offers them:
|
|
3
|
+
* `/mcp__<server>__<prompt> [args]` fetches the prompt from its server and
|
|
4
|
+
* sends what it returns as the next message.
|
|
5
|
+
*
|
|
6
|
+
* Arguments are positional, in the order the prompt declares them; the last
|
|
7
|
+
* one takes the rest of the line, so a single free-text argument needs no
|
|
8
|
+
* quoting.
|
|
9
|
+
*/
|
|
10
|
+
import { mcpRegistry } from "./mcp-client.js";
|
|
11
|
+
const PREFIX = "/mcp__";
|
|
12
|
+
let known = [];
|
|
13
|
+
/** Ask every connected server for its prompts; a server without prompts is skipped. */
|
|
14
|
+
export async function loadMcpPrompts() {
|
|
15
|
+
const out = [];
|
|
16
|
+
for (const server of mcpRegistry.listServers()) {
|
|
17
|
+
try {
|
|
18
|
+
out.push(...await mcpRegistry.listPrompts(server));
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// Prompts are optional in MCP; "method not found" is normal.
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
known = out;
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
export function mcpPromptCommandName(prompt) {
|
|
28
|
+
return `${PREFIX}${prompt.server}__${prompt.name}`;
|
|
29
|
+
}
|
|
30
|
+
/** Slash command names for the prompts found by loadMcpPrompts, for completion and help. */
|
|
31
|
+
export function mcpPromptCommandNames() {
|
|
32
|
+
return known.map(mcpPromptCommandName);
|
|
33
|
+
}
|
|
34
|
+
export function isMcpPromptCommand(input) {
|
|
35
|
+
return input.startsWith(PREFIX);
|
|
36
|
+
}
|
|
37
|
+
/** Map the words after the command onto the prompt's declared arguments. */
|
|
38
|
+
export function promptArguments(prompt, rest) {
|
|
39
|
+
const names = (prompt.arguments ?? []).map((a) => a.name);
|
|
40
|
+
const args = {};
|
|
41
|
+
let remaining = rest.trim();
|
|
42
|
+
names.forEach((name, i) => {
|
|
43
|
+
if (!remaining)
|
|
44
|
+
return;
|
|
45
|
+
if (i === names.length - 1) {
|
|
46
|
+
args[name] = remaining;
|
|
47
|
+
remaining = "";
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const match = /^(\S+)\s*([\s\S]*)$/.exec(remaining);
|
|
51
|
+
args[name] = match[1];
|
|
52
|
+
remaining = match[2];
|
|
53
|
+
});
|
|
54
|
+
return args;
|
|
55
|
+
}
|
|
56
|
+
function contentText(content) {
|
|
57
|
+
const blocks = Array.isArray(content) ? content : [content];
|
|
58
|
+
return blocks
|
|
59
|
+
.map((b) => (typeof b.text === "string" ? b.text : b.resource?.text ?? (b.resource?.uri ? `[resource ${b.resource.uri}]` : "")))
|
|
60
|
+
.filter(Boolean)
|
|
61
|
+
.join("\n");
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The message an `/mcp__server__prompt …` line becomes. Throws with a message
|
|
65
|
+
* fit for the user when the prompt is unknown, an argument is missing, or the
|
|
66
|
+
* server fails.
|
|
67
|
+
*/
|
|
68
|
+
export async function resolveMcpPromptCommand(input) {
|
|
69
|
+
const trimmed = input.trim();
|
|
70
|
+
const command = trimmed.split(/\s+/, 1)[0];
|
|
71
|
+
const rest = trimmed.slice(command.length);
|
|
72
|
+
const prompt = known.find((p) => mcpPromptCommandName(p) === command);
|
|
73
|
+
if (!prompt)
|
|
74
|
+
throw new Error(`No MCP prompt ${command}.${known.length > 0 ? ` Known: ${mcpPromptCommandNames().join(", ")}` : " No connected server offers prompts."}`);
|
|
75
|
+
const args = promptArguments(prompt, rest);
|
|
76
|
+
const missing = (prompt.arguments ?? []).filter((a) => a.required && !args[a.name]).map((a) => a.name);
|
|
77
|
+
if (missing.length > 0)
|
|
78
|
+
throw new Error(`${command} needs: ${(prompt.arguments ?? []).map((a) => (a.required ? a.name : `[${a.name}]`)).join(" ")}`);
|
|
79
|
+
const result = await mcpRegistry.getPrompt(prompt.server, prompt.name, args);
|
|
80
|
+
const text = (result.messages ?? [])
|
|
81
|
+
.map((m) => {
|
|
82
|
+
const body = contentText(m.content);
|
|
83
|
+
return m.role === "assistant" && body ? `(assistant) ${body}` : body;
|
|
84
|
+
})
|
|
85
|
+
.filter(Boolean)
|
|
86
|
+
.join("\n\n");
|
|
87
|
+
if (!text)
|
|
88
|
+
throw new Error(`${command} returned no text.`);
|
|
89
|
+
return text;
|
|
90
|
+
}
|
|
91
|
+
/** Test seam. */
|
|
92
|
+
export function setMcpPrompts(prompts) {
|
|
93
|
+
known = prompts;
|
|
94
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quick chat: the system prompt for `--mode chat`. No tools, so everything the
|
|
3
|
+
* model knows from phren is read up front, from files only (no index build,
|
|
4
|
+
* no search), to keep the first answer about a second away.
|
|
5
|
+
*/
|
|
6
|
+
import * as fs from "fs";
|
|
7
|
+
import { storeAwareProjectPath } from "@phren/cli/store-routing";
|
|
8
|
+
import { readFindings } from "@phren/cli/data/access";
|
|
9
|
+
import { readTruths } from "./context.js";
|
|
10
|
+
/** Budget for the whole memory section; a chat prompt stays small. */
|
|
11
|
+
export const CHAT_MEMORY_MAX_CHARS = 12_000;
|
|
12
|
+
const RECENT_FINDINGS = 8;
|
|
13
|
+
function readSummary(ctx, project) {
|
|
14
|
+
try {
|
|
15
|
+
const file = storeAwareProjectPath(ctx.phrenPath, project, "summary.md");
|
|
16
|
+
if (!file || !fs.existsSync(file))
|
|
17
|
+
return "";
|
|
18
|
+
// The archive block's markers are for the summarizer, not the model.
|
|
19
|
+
return fs.readFileSync(file, "utf-8").replace(/<!--[\s\S]*?-->\n?/g, "").trim();
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return "";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** Read-only phren memory for a quick chat: truths, the project summary and its newest findings. */
|
|
26
|
+
export function buildChatMemory(ctx) {
|
|
27
|
+
if (!ctx)
|
|
28
|
+
return "";
|
|
29
|
+
const sections = [];
|
|
30
|
+
const global = readTruths(ctx.phrenPath, "global");
|
|
31
|
+
if (global.length > 0)
|
|
32
|
+
sections.push(`## Pinned truths (global)\n\n${global.join("\n")}`);
|
|
33
|
+
if (ctx.project && ctx.project !== "global") {
|
|
34
|
+
const truths = readTruths(ctx.phrenPath, ctx.project);
|
|
35
|
+
if (truths.length > 0)
|
|
36
|
+
sections.push(`## Pinned truths (${ctx.project})\n\n${truths.join("\n")}`);
|
|
37
|
+
const summary = readSummary(ctx, ctx.project);
|
|
38
|
+
if (summary)
|
|
39
|
+
sections.push(`## Project summary (${ctx.project})\n\n${summary}`);
|
|
40
|
+
try {
|
|
41
|
+
const result = readFindings(ctx.phrenPath, ctx.project);
|
|
42
|
+
if (result.ok && result.data) {
|
|
43
|
+
const recent = result.data
|
|
44
|
+
.filter((f) => f.status === "active" && f.tier !== "archived")
|
|
45
|
+
.slice(-RECENT_FINDINGS)
|
|
46
|
+
.map((f) => `- ${f.text}`);
|
|
47
|
+
if (recent.length > 0)
|
|
48
|
+
sections.push(`## Recent findings (${ctx.project})\n\n${recent.join("\n")}`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
catch { /* silent */ }
|
|
52
|
+
}
|
|
53
|
+
let memory = sections.join("\n\n");
|
|
54
|
+
if (memory.length > CHAT_MEMORY_MAX_CHARS)
|
|
55
|
+
memory = `${memory.slice(0, CHAT_MEMORY_MAX_CHARS)}\n\n[memory truncated]`;
|
|
56
|
+
return memory;
|
|
57
|
+
}
|
|
58
|
+
export function buildChatSystemPrompt(memory, providerInfo) {
|
|
59
|
+
const modelNote = providerInfo ? ` You are running on ${providerInfo.name}${providerInfo.model ? ` (model: ${providerInfo.model})` : ""}.` : "";
|
|
60
|
+
const parts = [
|
|
61
|
+
`You are phren, in quick chat with the owner.${modelNote}`,
|
|
62
|
+
"",
|
|
63
|
+
"Answer directly and conversationally, like a chat assistant. Lead with the answer; keep it short unless asked for depth. Replies may be read aloud, so prefer plain sentences over tables and long code.",
|
|
64
|
+
"",
|
|
65
|
+
"You have no tools in this chat: you cannot read files, run commands, search the web or change phren memory. What phren remembers is below. If a request needs tools, say so in one line and suggest /promote, which continues this conversation as a phren agent with tools.",
|
|
66
|
+
];
|
|
67
|
+
if (memory)
|
|
68
|
+
parts.push("", "# What phren remembers (read-only)", "", memory);
|
|
69
|
+
return parts.join("\n");
|
|
70
|
+
}
|
package/dist/memory/context.js
CHANGED
|
@@ -36,7 +36,7 @@ export async function buildPhrenContext(projectOverride) {
|
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
38
|
/** Read truths.md pinned entries for a project. */
|
|
39
|
-
function readTruths(phrenPath, project) {
|
|
39
|
+
export function readTruths(phrenPath, project) {
|
|
40
40
|
try {
|
|
41
41
|
// Store-aware: upsertCanonical writes via storeAwareProjectPath, so team-store
|
|
42
42
|
// truths live under the store root, not necessarily <phrenPath>/<project>/.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
let scoped;
|
|
2
|
+
/** Pin the overrides to `model`, or clear them when none are set. */
|
|
3
|
+
export function scopeModelOverrides(model, overrides) {
|
|
4
|
+
const set = Object.values(overrides).some((v) => v !== undefined);
|
|
5
|
+
scoped = model && set ? { model, ...overrides } : undefined;
|
|
6
|
+
}
|
|
7
|
+
/** The overrides that apply to `model`; none for any other model. */
|
|
8
|
+
export function overridesFor(model) {
|
|
9
|
+
if (!scoped || model !== scoped.model)
|
|
10
|
+
return {};
|
|
11
|
+
const { model: _model, ...overrides } = scoped;
|
|
12
|
+
return overrides;
|
|
13
|
+
}
|
|
14
|
+
/** The current scope, for a subagent's spawn payload. */
|
|
15
|
+
export function scopedModelOverrides() {
|
|
16
|
+
return scoped ? { ...scoped } : undefined;
|
|
17
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `phren-agent models --json`: the models this computer can run, for the
|
|
3
|
+
* phren Hook's model picker. Only providers with credentials here are
|
|
4
|
+
* listed, in the order auto-detection picks them, so the first is the
|
|
5
|
+
* default. Each id is `<provider>/<model>`; the Hook passes it back as
|
|
6
|
+
* `--provider` and `--model`. Loads no agent runtime and makes no request.
|
|
7
|
+
*/
|
|
8
|
+
import { resolveApiKey } from "@phren/cli/auth/profiles";
|
|
9
|
+
import { codexConfiguredModel, hasCodexToken } from "./providers/codex-auth.js";
|
|
10
|
+
import { getBuiltinModels, getDefaultModel } from "./models.js";
|
|
11
|
+
const PROVIDER_NAMES = {
|
|
12
|
+
"openai-codex": "ChatGPT subscription",
|
|
13
|
+
openai: "OpenAI API",
|
|
14
|
+
openrouter: "OpenRouter",
|
|
15
|
+
anthropic: "Anthropic API",
|
|
16
|
+
deepseek: "DeepSeek API",
|
|
17
|
+
ollama: "Ollama",
|
|
18
|
+
};
|
|
19
|
+
/** Providers with credentials on this computer, in resolveProvider's order.
|
|
20
|
+
* openai-compat needs an endpoint and model of its own, so it is never listed. */
|
|
21
|
+
export function credentialedProviders(env = process.env) {
|
|
22
|
+
const providers = [];
|
|
23
|
+
if (hasCodexToken())
|
|
24
|
+
providers.push("openai-codex");
|
|
25
|
+
if (resolveApiKey("openai", "OPENAI_API_KEY"))
|
|
26
|
+
providers.push("openai");
|
|
27
|
+
if (resolveApiKey("openrouter", "OPENROUTER_API_KEY"))
|
|
28
|
+
providers.push("openrouter");
|
|
29
|
+
if (resolveApiKey("anthropic", "ANTHROPIC_API_KEY"))
|
|
30
|
+
providers.push("anthropic");
|
|
31
|
+
if (env.DEEPSEEK_API_KEY)
|
|
32
|
+
providers.push("deepseek");
|
|
33
|
+
if (env.PHREN_OLLAMA_URL && env.PHREN_OLLAMA_URL !== "off")
|
|
34
|
+
providers.push("ollama");
|
|
35
|
+
return providers;
|
|
36
|
+
}
|
|
37
|
+
export function listModels(providers = credentialedProviders()) {
|
|
38
|
+
const models = [];
|
|
39
|
+
for (const provider of providers) {
|
|
40
|
+
const entries = getBuiltinModels(provider);
|
|
41
|
+
// Codex's own config can name a model the catalog doesn't have yet.
|
|
42
|
+
const configured = provider === "openai-codex" ? codexConfiguredModel() : undefined;
|
|
43
|
+
if (configured && !entries.some(entry => entry.id === configured)) {
|
|
44
|
+
entries.unshift({ ...entries[0], id: configured, label: configured });
|
|
45
|
+
}
|
|
46
|
+
const preferred = configured ?? getDefaultModel(provider);
|
|
47
|
+
for (const entry of entries) {
|
|
48
|
+
models.push({
|
|
49
|
+
id: `${provider}/${entry.id}`,
|
|
50
|
+
name: entry.label,
|
|
51
|
+
provider,
|
|
52
|
+
description: PROVIDER_NAMES[provider] ?? provider,
|
|
53
|
+
...(!models.some(model => model.isDefault) && entry.id === preferred ? { isDefault: true } : {}),
|
|
54
|
+
...(entry.reasoningDefault && entry.reasoningDefault !== "none" ? { defaultReasoningEffort: entry.reasoningDefault } : {}),
|
|
55
|
+
supportedReasoningEfforts: entry.reasoningRange.filter(level => level !== "none"),
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return models;
|
|
60
|
+
}
|
|
61
|
+
export function printModels(args) {
|
|
62
|
+
const models = listModels();
|
|
63
|
+
if (args.includes("--json")) {
|
|
64
|
+
console.log(JSON.stringify({ models }));
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (!models.length) {
|
|
68
|
+
console.log("No provider credentials found. See phren-agent --help.");
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
for (const model of models)
|
|
72
|
+
console.log(`${model.isDefault ? "*" : " "} ${model.id.padEnd(48)} ${model.name} (${model.description})`);
|
|
73
|
+
}
|
package/dist/models.js
CHANGED
|
@@ -1,4 +1,21 @@
|
|
|
1
|
+
/** Levels the pickers step through ("none" is CLI/env only). */
|
|
1
2
|
export const REASONING_LEVELS = ["low", "medium", "high", "xhigh"];
|
|
3
|
+
/**
|
|
4
|
+
* DeepSeek V4.1 Flash, direct or through an OpenAI-compatible relay: 1M
|
|
5
|
+
* context, 393,216 max output, effort low/high/max (picker "xhigh" = max).
|
|
6
|
+
* Off-peak rates; DeepSeek bills 2x at peak (weekdays 01-04 and 06-10 UTC).
|
|
7
|
+
* Checked against https://api-docs.deepseek.com/quick_start/pricing on
|
|
8
|
+
* 2026-10-01: cache hit $0.003 / miss $0.15 / output $0.60 off-peak
|
|
9
|
+
* ($0.006 / $0.30 / $1.20 peak).
|
|
10
|
+
*/
|
|
11
|
+
const DEEPSEEK_FLASH = {
|
|
12
|
+
vision: true,
|
|
13
|
+
contextWindow: 1_000_000,
|
|
14
|
+
maxOutputTokens: 393_216,
|
|
15
|
+
reasoningDefault: null,
|
|
16
|
+
reasoningRange: ["low", "high", "xhigh"],
|
|
17
|
+
pricing: { inputPer1M: 0.15, outputPer1M: 0.6, cacheReadPer1M: 0.003 },
|
|
18
|
+
};
|
|
2
19
|
const BUILTIN_MODELS = {
|
|
3
20
|
anthropic: [
|
|
4
21
|
{
|
|
@@ -279,16 +296,8 @@ const BUILTIN_MODELS = {
|
|
|
279
296
|
},
|
|
280
297
|
],
|
|
281
298
|
deepseek: [
|
|
282
|
-
{
|
|
283
|
-
|
|
284
|
-
provider: "deepseek",
|
|
285
|
-
label: "DeepSeek V4.1 Flash (direct)",
|
|
286
|
-
contextWindow: 1_000_000,
|
|
287
|
-
maxOutputTokens: 65_536,
|
|
288
|
-
reasoningDefault: null,
|
|
289
|
-
reasoningRange: ["low", "medium", "high"],
|
|
290
|
-
pricing: { inputPer1M: 0.3, outputPer1M: 1.2 },
|
|
291
|
-
},
|
|
299
|
+
{ ...DEEPSEEK_FLASH, id: "deepseek-flash", provider: "deepseek", label: "DeepSeek V4.1 Flash (direct)" },
|
|
300
|
+
{ ...DEEPSEEK_FLASH, id: "deepseek-v4-flash", provider: "deepseek", label: "DeepSeek V4.1 Flash (legacy id)" },
|
|
292
301
|
{
|
|
293
302
|
id: "deepseek-v4-pro",
|
|
294
303
|
provider: "deepseek",
|
|
@@ -296,10 +305,15 @@ const BUILTIN_MODELS = {
|
|
|
296
305
|
contextWindow: 1_000_000,
|
|
297
306
|
maxOutputTokens: 65_536,
|
|
298
307
|
reasoningDefault: null,
|
|
299
|
-
reasoningRange: ["low", "
|
|
300
|
-
pricing: { inputPer1M:
|
|
308
|
+
reasoningRange: ["low", "high", "xhigh"],
|
|
309
|
+
pricing: { inputPer1M: 0.66, outputPer1M: 1.98, cacheReadPer1M: 0.022 },
|
|
301
310
|
},
|
|
302
311
|
],
|
|
312
|
+
// Model ids for a generic OpenAI-compatible endpoint (OpenCode Go/Zen…).
|
|
313
|
+
// Pricing applies to metered relays; see isUnmeteredEndpoint for Go.
|
|
314
|
+
"openai-compat": [
|
|
315
|
+
{ ...DEEPSEEK_FLASH, id: "deepseek-v4.1-flash", provider: "openai-compat", label: "DeepSeek V4.1 Flash" },
|
|
316
|
+
],
|
|
303
317
|
ollama: [
|
|
304
318
|
{
|
|
305
319
|
id: "qwen2.5-coder:14b",
|
|
@@ -373,6 +387,7 @@ const LEGACY_CONTEXT_LIMITS = [
|
|
|
373
387
|
["o3", 200_000],
|
|
374
388
|
["o4-mini", 200_000],
|
|
375
389
|
["gemini", 1_000_000],
|
|
390
|
+
["deepseek-v4", 1_000_000],
|
|
376
391
|
["deepseek", 128_000],
|
|
377
392
|
["llama", 128_000],
|
|
378
393
|
["qwen", 128_000],
|
|
@@ -426,11 +441,14 @@ export function normalizeProviderId(provider) {
|
|
|
426
441
|
return undefined;
|
|
427
442
|
if (provider === "codex")
|
|
428
443
|
return "openai-codex";
|
|
444
|
+
if (provider === "compat")
|
|
445
|
+
return "openai-compat";
|
|
429
446
|
if (provider === "openrouter" ||
|
|
430
447
|
provider === "anthropic" ||
|
|
431
448
|
provider === "openai" ||
|
|
432
449
|
provider === "openai-codex" ||
|
|
433
450
|
provider === "deepseek" ||
|
|
451
|
+
provider === "openai-compat" ||
|
|
434
452
|
provider === "ollama") {
|
|
435
453
|
return provider;
|
|
436
454
|
}
|
|
@@ -442,10 +460,19 @@ export function normalizeReasoningEffort(raw) {
|
|
|
442
460
|
const value = raw.toLowerCase();
|
|
443
461
|
if (value === "max")
|
|
444
462
|
return "xhigh";
|
|
445
|
-
if (value === "
|
|
463
|
+
if (value === "off")
|
|
464
|
+
return "none";
|
|
465
|
+
if (value === "none" || value === "low" || value === "medium" || value === "high" || value === "xhigh")
|
|
446
466
|
return value;
|
|
447
467
|
return undefined;
|
|
448
468
|
}
|
|
469
|
+
/**
|
|
470
|
+
* OpenCode Go is a flat subscription: requests through it are not billed per
|
|
471
|
+
* token, so cost shows as included and --budget does not trip.
|
|
472
|
+
*/
|
|
473
|
+
export function isUnmeteredEndpoint(baseUrl) {
|
|
474
|
+
return !!baseUrl && /^https?:\/\/opencode\.ai\/zen\/go(?:\/|$)/i.test(baseUrl);
|
|
475
|
+
}
|
|
449
476
|
export function getDefaultModel(provider) {
|
|
450
477
|
return BUILTIN_MODELS[provider][0].id;
|
|
451
478
|
}
|
|
@@ -502,9 +529,9 @@ export function lookupContextWindow(model, provider) {
|
|
|
502
529
|
}
|
|
503
530
|
return 200_000;
|
|
504
531
|
}
|
|
505
|
-
export function lookupPricing(model, provider) {
|
|
532
|
+
export function lookupPricing(model, provider, baseUrl) {
|
|
506
533
|
const normalizedProvider = normalizeProviderId(provider);
|
|
507
|
-
if (normalizedProvider === "openai-codex") {
|
|
534
|
+
if (normalizedProvider === "openai-codex" || isUnmeteredEndpoint(baseUrl)) {
|
|
508
535
|
return { pricing: { inputPer1M: 0, outputPer1M: 0 }, metered: false };
|
|
509
536
|
}
|
|
510
537
|
const metadata = getModelMetadata(provider, model);
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* 6. Shuts down gracefully on ShutdownRequest
|
|
10
10
|
*/
|
|
11
11
|
import { MAX_SPAWN_DEPTH } from "./types.js";
|
|
12
|
+
import { createIpcHooks } from "./ipc-hooks.js";
|
|
12
13
|
import { resolveProvider } from "../providers/resolve.js";
|
|
13
14
|
import { ToolRegistry } from "../tools/registry.js";
|
|
14
15
|
import { readFileTool } from "../tools/read-file.js";
|
|
@@ -34,6 +35,7 @@ import { buildPhrenContext, } from "../memory/context.js";
|
|
|
34
35
|
import { startSession, endSession, } from "../memory/session.js";
|
|
35
36
|
import { runAgent, } from "../agent-loop.js";
|
|
36
37
|
import { createCostTracker } from "../cost.js";
|
|
38
|
+
import { scopeModelOverrides } from "../model-overrides.js";
|
|
37
39
|
import { getAgentType, applyAgentType } from "./agent-types.js";
|
|
38
40
|
import { AgentSpawner } from "./spawner.js";
|
|
39
41
|
import { createSpawnAgentTool, createSendMessageTool, createListAgentsTool } from "../tools/spawn-agent.js";
|
|
@@ -43,29 +45,6 @@ function send(msg) {
|
|
|
43
45
|
process.send(msg);
|
|
44
46
|
}
|
|
45
47
|
}
|
|
46
|
-
/** Build TurnHooks that relay all events to the parent via IPC. */
|
|
47
|
-
function createIpcHooks(agentId) {
|
|
48
|
-
return {
|
|
49
|
-
onTextDelta(text) {
|
|
50
|
-
send({ type: "text_delta", agentId, text });
|
|
51
|
-
},
|
|
52
|
-
onTextDone() {
|
|
53
|
-
// No-op — parent reconstructs from deltas
|
|
54
|
-
},
|
|
55
|
-
onTextBlock(text) {
|
|
56
|
-
send({ type: "text_block", agentId, text });
|
|
57
|
-
},
|
|
58
|
-
onToolStart(name, input, count) {
|
|
59
|
-
send({ type: "tool_start", agentId, toolName: name, input, count });
|
|
60
|
-
},
|
|
61
|
-
onToolEnd(name, input, output, isError, durationMs) {
|
|
62
|
-
send({ type: "tool_end", agentId, toolName: name, input, output, isError, durationMs });
|
|
63
|
-
},
|
|
64
|
-
onStatus(msg) {
|
|
65
|
-
send({ type: "status", agentId, message: msg });
|
|
66
|
-
},
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
48
|
/** Build a lightweight system prompt for child agents. No "search memory first" forcing. */
|
|
70
49
|
function buildChildPrompt(task) {
|
|
71
50
|
return [
|
|
@@ -82,8 +61,13 @@ async function initAgentState(payload) {
|
|
|
82
61
|
const { agentId, task: _task, cwd, provider: providerName, model, project, permissions, maxTurns, budget, plan, verbose } = payload;
|
|
83
62
|
// Set cwd (use worktree path if provided)
|
|
84
63
|
process.chdir(payload.worktreePath ?? cwd);
|
|
85
|
-
// Resolve LLM provider
|
|
86
|
-
|
|
64
|
+
// Resolve LLM provider; the parent's --context-window / --price-* apply
|
|
65
|
+
// only if this child runs the model they were given for.
|
|
66
|
+
if (payload.modelOverrides) {
|
|
67
|
+
const { model: overridden, ...overrides } = payload.modelOverrides;
|
|
68
|
+
scopeModelOverrides(overridden, overrides);
|
|
69
|
+
}
|
|
70
|
+
const provider = resolveProvider(providerName, model, undefined, payload.reasoning, { baseUrl: payload.baseUrl });
|
|
87
71
|
// Child agents get a lightweight prompt — no "search memory first" forcing
|
|
88
72
|
const systemPrompt = buildChildPrompt(_task);
|
|
89
73
|
// Quick phren init — just resolve context, skip slow FTS5 search
|
|
@@ -99,6 +83,8 @@ async function initAgentState(payload) {
|
|
|
99
83
|
allowedPaths: payload.allowedPaths ?? [],
|
|
100
84
|
projectRoot: payload.worktreePath ?? cwd,
|
|
101
85
|
sandboxMode: payload.sandboxMode,
|
|
86
|
+
network: payload.network,
|
|
87
|
+
rules: payload.rules,
|
|
102
88
|
});
|
|
103
89
|
// Headless child: an "ask" verdict has no human to answer it, and the
|
|
104
90
|
// default readline prompt would hang forever on a closed stdin. Deny with
|
|
@@ -142,11 +128,11 @@ async function initAgentState(payload) {
|
|
|
142
128
|
registry.register(gitCommitTool);
|
|
143
129
|
// Cost tracker
|
|
144
130
|
const modelName = provider.model ?? model ?? provider.name;
|
|
145
|
-
const costTracker = createCostTracker(modelName, budget, provider.name);
|
|
131
|
+
const costTracker = createCostTracker(modelName, budget, provider.name, provider.baseUrl);
|
|
146
132
|
let spawner = null;
|
|
147
133
|
const depth = payload.depth ?? 0;
|
|
148
134
|
if (depth < MAX_SPAWN_DEPTH) {
|
|
149
|
-
spawner = new AgentSpawner({ costTracker, depth, getPermissionDefaults: () => registry.permissionConfig });
|
|
135
|
+
spawner = new AgentSpawner({ costTracker, depth, getPermissionDefaults: () => registry.permissionConfig, getParentProvider: () => provider });
|
|
150
136
|
registry.register(createSpawnAgentTool(spawner, () => registry.permissionConfig));
|
|
151
137
|
registry.register(createSendMessageTool(spawner));
|
|
152
138
|
registry.register(createListAgentsTool(spawner));
|
|
@@ -169,7 +155,7 @@ async function initAgentState(payload) {
|
|
|
169
155
|
maxTurns,
|
|
170
156
|
verbose,
|
|
171
157
|
plan,
|
|
172
|
-
hooks: createIpcHooks(agentId),
|
|
158
|
+
hooks: createIpcHooks(agentId, send),
|
|
173
159
|
spawner,
|
|
174
160
|
pendingDms: [],
|
|
175
161
|
taskCount: 0,
|
|
@@ -179,6 +165,8 @@ async function initAgentState(payload) {
|
|
|
179
165
|
async function runTask(state, task) {
|
|
180
166
|
const beforeInput = state.costTracker.totalInputTokens;
|
|
181
167
|
const beforeOutput = state.costTracker.totalOutputTokens;
|
|
168
|
+
const beforeCacheRead = state.costTracker.totalCacheReadTokens;
|
|
169
|
+
const beforeCacheWrite = state.costTracker.totalCacheWriteTokens;
|
|
182
170
|
const beforeCost = state.costTracker.totalCost;
|
|
183
171
|
const config = {
|
|
184
172
|
provider: state.provider,
|
|
@@ -200,6 +188,8 @@ async function runTask(state, task) {
|
|
|
200
188
|
totalCost: result.totalCost,
|
|
201
189
|
inputTokens: state.costTracker.totalInputTokens - beforeInput,
|
|
202
190
|
outputTokens: state.costTracker.totalOutputTokens - beforeOutput,
|
|
191
|
+
cacheReadTokens: state.costTracker.totalCacheReadTokens - beforeCacheRead,
|
|
192
|
+
cacheWriteTokens: state.costTracker.totalCacheWriteTokens - beforeCacheWrite,
|
|
203
193
|
costUsd: state.costTracker.totalCost - beforeCost,
|
|
204
194
|
};
|
|
205
195
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Build TurnHooks that relay all events to the parent via IPC. */
|
|
2
|
+
export function createIpcHooks(agentId, sendMessage) {
|
|
3
|
+
// Characters streamed by the current model call, so a retry can tell the
|
|
4
|
+
// parent how much of its text to drop.
|
|
5
|
+
let attemptChars = 0;
|
|
6
|
+
return {
|
|
7
|
+
onTextDelta(text) {
|
|
8
|
+
attemptChars += text.length;
|
|
9
|
+
sendMessage({ type: "text_delta", agentId, text });
|
|
10
|
+
},
|
|
11
|
+
onStreamRetry() {
|
|
12
|
+
sendMessage({ type: "stream_retry", agentId, discard: attemptChars });
|
|
13
|
+
attemptChars = 0;
|
|
14
|
+
},
|
|
15
|
+
onAssistantMessage() {
|
|
16
|
+
attemptChars = 0;
|
|
17
|
+
},
|
|
18
|
+
onTextDone() {
|
|
19
|
+
// No-op — parent reconstructs from deltas
|
|
20
|
+
},
|
|
21
|
+
onTextBlock(text) {
|
|
22
|
+
sendMessage({ type: "text_block", agentId, text });
|
|
23
|
+
},
|
|
24
|
+
onToolStart(name, input, count) {
|
|
25
|
+
sendMessage({ type: "tool_start", agentId, toolName: name, input, count });
|
|
26
|
+
},
|
|
27
|
+
onToolEnd(name, input, output, isError, durationMs) {
|
|
28
|
+
sendMessage({ type: "tool_end", agentId, toolName: name, input, output, isError, durationMs });
|
|
29
|
+
},
|
|
30
|
+
onStatus(msg) {
|
|
31
|
+
sendMessage({ type: "status", agentId, message: msg });
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|