@phren/agent 0.0.1 → 0.1.0
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/dist/agent-loop.js +1 -1
- package/dist/commands.js +68 -0
- package/dist/config.js +4 -0
- package/dist/context/pruner.js +97 -8
- package/dist/cost.js +35 -0
- package/dist/index.js +1 -1
- package/dist/multi/agent-colors.js +0 -5
- package/dist/multi/child-entry.js +1 -2
- package/dist/multi/markdown.js +11 -1
- package/dist/multi/model-picker.js +154 -0
- package/dist/multi/provider-manager.js +151 -0
- package/dist/multi/syntax-highlight.js +188 -0
- package/dist/multi/tui-multi.js +0 -9
- package/dist/permissions/allowlist.js +4 -1
- package/dist/permissions/prompt.js +36 -22
- package/dist/permissions/shell-safety.js +2 -0
- package/dist/providers/anthropic.js +5 -3
- package/dist/providers/codex-auth.js +1 -1
- package/dist/providers/codex.js +4 -2
- package/dist/providers/ollama.js +5 -1
- package/dist/providers/openrouter.js +10 -6
- package/dist/providers/resolve.js +16 -7
- package/dist/repl.js +1 -36
- package/dist/settings.js +42 -0
- package/dist/system-prompt.js +11 -0
- package/dist/tools/edit-file.js +13 -0
- package/dist/tools/git.js +13 -0
- package/dist/tools/write-file.js +12 -0
- package/dist/tui.js +209 -83
- package/package.json +7 -7
- package/dist/multi/progress.js +0 -32
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ala Arab
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/agent-loop.js
CHANGED
|
@@ -317,7 +317,7 @@ export async function runTurn(userInput, session, config, hooks) {
|
|
|
317
317
|
export async function runAgent(task, config) {
|
|
318
318
|
const contextLimit = config.provider.contextWindow ?? 200_000;
|
|
319
319
|
const session = createSession(contextLimit);
|
|
320
|
-
const result = await runTurn(task, session, config);
|
|
320
|
+
const result = await runTurn(task, session, config, config.hooks);
|
|
321
321
|
return {
|
|
322
322
|
finalText: result.text,
|
|
323
323
|
turns: result.turns,
|
package/dist/commands.js
CHANGED
|
@@ -2,6 +2,8 @@ import { estimateMessageTokens } from "./context/token-counter.js";
|
|
|
2
2
|
import { pruneMessages } from "./context/pruner.js";
|
|
3
3
|
import { listPresets, loadPreset, savePreset, deletePreset, formatPreset } from "./multi/presets.js";
|
|
4
4
|
import { renderMarkdown } from "./multi/markdown.js";
|
|
5
|
+
import { showModelPicker } from "./multi/model-picker.js";
|
|
6
|
+
import { formatProviderList, formatModelAddHelp, addCustomModel, removeCustomModel } from "./multi/provider-manager.js";
|
|
5
7
|
const DIM = "\x1b[2m";
|
|
6
8
|
const BOLD = "\x1b[1m";
|
|
7
9
|
const CYAN = "\x1b[36m";
|
|
@@ -35,6 +37,10 @@ export function handleCommand(input, ctx) {
|
|
|
35
37
|
case "/help":
|
|
36
38
|
process.stderr.write(`${DIM}Commands:
|
|
37
39
|
/help Show this help
|
|
40
|
+
/model Interactive model + reasoning picker
|
|
41
|
+
/model add <id> Add a custom model
|
|
42
|
+
/model remove <id> Remove a custom model
|
|
43
|
+
/provider Show configured providers + auth status
|
|
38
44
|
/turns Show turn and tool call counts
|
|
39
45
|
/clear Clear conversation history
|
|
40
46
|
/cost Show token usage and estimated cost
|
|
@@ -48,6 +54,68 @@ export function handleCommand(input, ctx) {
|
|
|
48
54
|
/preset [name|save|delete|list] Config presets
|
|
49
55
|
/exit Exit the REPL${RESET}\n`);
|
|
50
56
|
return true;
|
|
57
|
+
case "/model": {
|
|
58
|
+
const sub = parts[1]?.toLowerCase();
|
|
59
|
+
// /model add <id> [provider=X] [context=N] [reasoning=X]
|
|
60
|
+
if (sub === "add") {
|
|
61
|
+
const modelId = parts[2];
|
|
62
|
+
if (!modelId) {
|
|
63
|
+
process.stderr.write(formatModelAddHelp() + "\n");
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
let provider = ctx.providerName ?? "openrouter";
|
|
67
|
+
let contextWindow = 128_000;
|
|
68
|
+
let reasoning = null;
|
|
69
|
+
const reasoningRange = [];
|
|
70
|
+
for (const arg of parts.slice(3)) {
|
|
71
|
+
const [k, v] = arg.split("=", 2);
|
|
72
|
+
if (k === "provider")
|
|
73
|
+
provider = v;
|
|
74
|
+
else if (k === "context")
|
|
75
|
+
contextWindow = parseInt(v, 10) || 128_000;
|
|
76
|
+
else if (k === "reasoning") {
|
|
77
|
+
reasoning = v;
|
|
78
|
+
reasoningRange.push("low", "medium", "high");
|
|
79
|
+
if (v === "max")
|
|
80
|
+
reasoningRange.push("max");
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
addCustomModel(modelId, provider, { contextWindow, reasoning, reasoningRange });
|
|
84
|
+
process.stderr.write(`${GREEN}→ Added ${modelId} to ${provider}${RESET}\n`);
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
// /model remove <id>
|
|
88
|
+
if (sub === "remove" || sub === "rm") {
|
|
89
|
+
const modelId = parts[2];
|
|
90
|
+
if (!modelId) {
|
|
91
|
+
process.stderr.write(`${DIM}Usage: /model remove <model-id>${RESET}\n`);
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
const ok = removeCustomModel(modelId);
|
|
95
|
+
process.stderr.write(ok ? `${GREEN}→ Removed ${modelId}${RESET}\n` : `${DIM}Model "${modelId}" not found in custom models.${RESET}\n`);
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
// /model (no sub) — interactive picker
|
|
99
|
+
if (!ctx.providerName) {
|
|
100
|
+
process.stderr.write(`${DIM}Provider not configured. Start with --provider to set one.${RESET}\n`);
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
showModelPicker(ctx.providerName, ctx.currentModel, process.stdout).then((result) => {
|
|
104
|
+
if (result && ctx.onModelChange) {
|
|
105
|
+
ctx.onModelChange(result);
|
|
106
|
+
const reasoningLabel = result.reasoning ? ` (reasoning: ${result.reasoning})` : "";
|
|
107
|
+
process.stderr.write(`${GREEN}→ ${result.model}${reasoningLabel}${RESET}\n`);
|
|
108
|
+
}
|
|
109
|
+
else if (result) {
|
|
110
|
+
process.stderr.write(`${DIM}Model selected: ${result.model} — restart to apply.${RESET}\n`);
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
case "/provider": {
|
|
116
|
+
process.stderr.write(formatProviderList());
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
51
119
|
case "/turns": {
|
|
52
120
|
const tokens = estimateMessageTokens(ctx.session.messages);
|
|
53
121
|
const pct = ctx.contextLimit > 0 ? ((tokens / ctx.contextLimit) * 100).toFixed(1) : "?";
|
package/dist/config.js
CHANGED
|
@@ -8,6 +8,7 @@ Options:
|
|
|
8
8
|
--model <model> Override LLM model
|
|
9
9
|
--project <name> Force phren project context
|
|
10
10
|
--max-turns <n> Max tool-use turns (default: 50)
|
|
11
|
+
--max-output <n> Max output tokens per response (default: auto per model)
|
|
11
12
|
--budget <dollars> Max spend in USD (aborts when exceeded)
|
|
12
13
|
--plan Plan mode: show plan before executing tools
|
|
13
14
|
--permissions <mode> Permission mode: suggest, auto-confirm, full-auto (default: auto-confirm)
|
|
@@ -113,6 +114,9 @@ export function parseArgs(argv) {
|
|
|
113
114
|
else if (arg === "--max-turns" && argv[i + 1]) {
|
|
114
115
|
args.maxTurns = parseInt(argv[++i], 10) || 50;
|
|
115
116
|
}
|
|
117
|
+
else if (arg === "--max-output" && argv[i + 1]) {
|
|
118
|
+
args.maxOutput = parseInt(argv[++i], 10) || undefined;
|
|
119
|
+
}
|
|
116
120
|
else if (arg === "--budget" && argv[i + 1]) {
|
|
117
121
|
args.budget = parseFloat(argv[++i]) || null;
|
|
118
122
|
}
|
package/dist/context/pruner.js
CHANGED
|
@@ -10,6 +10,102 @@ export function shouldPrune(systemPrompt, messages, config) {
|
|
|
10
10
|
const msgTokens = estimateMessageTokens(messages);
|
|
11
11
|
return (systemTokens + msgTokens) > limit * 0.75;
|
|
12
12
|
}
|
|
13
|
+
// ── Fact extraction (regex only, no LLM) ────────────────────────────────────
|
|
14
|
+
const FILE_TOOL_NAMES = new Set(["edit_file", "write_file"]);
|
|
15
|
+
const SEARCH_TOOL_NAMES = new Set(["phren_search"]);
|
|
16
|
+
const DECISION_RE = /\b(?:I'll|Let's|The fix is|Changed|because|decided to|switched to|replaced|removed|added|created|updated|refactored)\b/i;
|
|
17
|
+
/** Extract key facts from messages about to be pruned. Fast regex-only scan. */
|
|
18
|
+
export function extractFacts(messages) {
|
|
19
|
+
const filesSet = new Set();
|
|
20
|
+
const errorsSet = new Set();
|
|
21
|
+
const actionsSet = new Set();
|
|
22
|
+
const searchesSet = new Set();
|
|
23
|
+
for (const msg of messages) {
|
|
24
|
+
if (typeof msg.content === "string") {
|
|
25
|
+
// Scan assistant text messages for key decisions
|
|
26
|
+
if (msg.role === "assistant") {
|
|
27
|
+
extractDecisions(msg.content, actionsSet);
|
|
28
|
+
}
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
for (const block of msg.content) {
|
|
32
|
+
if (block.type === "tool_use") {
|
|
33
|
+
extractFromToolUse(block, filesSet, searchesSet);
|
|
34
|
+
}
|
|
35
|
+
else if (block.type === "tool_result" && block.is_error) {
|
|
36
|
+
extractError(block, errorsSet);
|
|
37
|
+
}
|
|
38
|
+
else if (block.type === "text" && msg.role === "assistant") {
|
|
39
|
+
extractDecisions(block.text, actionsSet);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
filesModified: [...filesSet],
|
|
45
|
+
errors: [...errorsSet],
|
|
46
|
+
keyActions: [...actionsSet],
|
|
47
|
+
searches: [...searchesSet],
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function extractFromToolUse(block, filesSet, searchesSet) {
|
|
51
|
+
if (FILE_TOOL_NAMES.has(block.name)) {
|
|
52
|
+
const fp = block.input?.file_path;
|
|
53
|
+
if (typeof fp === "string" && fp) {
|
|
54
|
+
filesSet.add(fp);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (SEARCH_TOOL_NAMES.has(block.name)) {
|
|
58
|
+
const q = block.input?.query;
|
|
59
|
+
if (typeof q === "string" && q) {
|
|
60
|
+
searchesSet.add(q);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function extractError(block, errorsSet) {
|
|
65
|
+
const firstLine = block.content.split("\n")[0].trim();
|
|
66
|
+
if (firstLine) {
|
|
67
|
+
// Cap length to keep summary concise
|
|
68
|
+
errorsSet.add(firstLine.length > 120 ? firstLine.slice(0, 120) + "..." : firstLine);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const MAX_KEY_ACTIONS = 5;
|
|
72
|
+
function extractDecisions(text, actionsSet) {
|
|
73
|
+
if (actionsSet.size >= MAX_KEY_ACTIONS)
|
|
74
|
+
return;
|
|
75
|
+
for (const line of text.split("\n")) {
|
|
76
|
+
const trimmed = line.trim();
|
|
77
|
+
if (trimmed && DECISION_RE.test(trimmed)) {
|
|
78
|
+
const capped = trimmed.length > 100 ? trimmed.slice(0, 100) + "..." : trimmed;
|
|
79
|
+
actionsSet.add(capped);
|
|
80
|
+
if (actionsSet.size >= MAX_KEY_ACTIONS)
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// ── Summary formatting ──────────────────────────────────────────────────────
|
|
86
|
+
function formatFactSummary(middle, toolsUsed) {
|
|
87
|
+
const facts = extractFacts(middle);
|
|
88
|
+
const lines = [
|
|
89
|
+
`[Context compacted: ${middle.length} messages removed]`,
|
|
90
|
+
];
|
|
91
|
+
if (toolsUsed.size > 0) {
|
|
92
|
+
lines.push(`Tools used: ${[...toolsUsed].join(", ")}`);
|
|
93
|
+
}
|
|
94
|
+
if (facts.filesModified.length > 0) {
|
|
95
|
+
lines.push(`Files modified: ${facts.filesModified.join(", ")}`);
|
|
96
|
+
}
|
|
97
|
+
if (facts.errors.length > 0) {
|
|
98
|
+
lines.push(`Errors encountered: ${facts.errors.join(", ")}`);
|
|
99
|
+
}
|
|
100
|
+
if (facts.keyActions.length > 0) {
|
|
101
|
+
lines.push(`Key actions: ${facts.keyActions.join(", ")}`);
|
|
102
|
+
}
|
|
103
|
+
if (facts.searches.length > 0) {
|
|
104
|
+
lines.push(`Searches: ${facts.searches.map(q => `"${q}"`).join(", ")}`);
|
|
105
|
+
}
|
|
106
|
+
return lines.join("\n");
|
|
107
|
+
}
|
|
108
|
+
// ── Pruner ──────────────────────────────────────────────────────────────────
|
|
13
109
|
/** Prune messages, keeping the first (original task) and last N turn pairs. */
|
|
14
110
|
export function pruneMessages(messages, config) {
|
|
15
111
|
const keepRecent = config?.keepRecentTurns ?? DEFAULT_CONFIG.keepRecentTurns;
|
|
@@ -47,16 +143,9 @@ export function pruneMessages(messages, config) {
|
|
|
47
143
|
}
|
|
48
144
|
}
|
|
49
145
|
}
|
|
50
|
-
const summaryText = [
|
|
51
|
-
`[Context compacted: ${middle.length} messages removed]`,
|
|
52
|
-
toolsUsed.size > 0 ? `Tools used: ${[...toolsUsed].join(", ")}` : null,
|
|
53
|
-
`Key points: ${middle.length} intermediate turns were compacted to fit context window.`,
|
|
54
|
-
]
|
|
55
|
-
.filter(Boolean)
|
|
56
|
-
.join("\n");
|
|
57
146
|
const summaryMessage = {
|
|
58
147
|
role: "user",
|
|
59
|
-
content:
|
|
148
|
+
content: formatFactSummary(middle, toolsUsed),
|
|
60
149
|
};
|
|
61
150
|
return [first, summaryMessage, ...tail];
|
|
62
151
|
}
|
package/dist/cost.js
CHANGED
|
@@ -25,6 +25,41 @@ const PRICING = [
|
|
|
25
25
|
["ollama", { inputPer1M: 0, outputPer1M: 0 }],
|
|
26
26
|
];
|
|
27
27
|
PRICING.sort((a, b) => b[0].length - a[0].length); // longest prefix first
|
|
28
|
+
// Max output token limits per model — prefix match (most specific wins)
|
|
29
|
+
const OUTPUT_LIMITS = [
|
|
30
|
+
// Anthropic
|
|
31
|
+
["claude-opus-4", 32768],
|
|
32
|
+
["claude-sonnet-4", 16384],
|
|
33
|
+
["claude-haiku-4", 8192],
|
|
34
|
+
["claude-3-5-sonnet", 8192],
|
|
35
|
+
["claude-3-5-haiku", 8192],
|
|
36
|
+
["claude-3-opus", 4096],
|
|
37
|
+
// OpenAI
|
|
38
|
+
["gpt-5", 16384],
|
|
39
|
+
["gpt-4.1", 32768],
|
|
40
|
+
["gpt-4o", 16384],
|
|
41
|
+
["gpt-4-turbo", 4096],
|
|
42
|
+
["o3", 100000],
|
|
43
|
+
["o4-mini", 100000],
|
|
44
|
+
// OpenRouter prefixed
|
|
45
|
+
["anthropic/claude-opus-4", 32768],
|
|
46
|
+
["anthropic/claude-sonnet-4", 16384],
|
|
47
|
+
["anthropic/claude-haiku-4", 8192],
|
|
48
|
+
["openai/gpt-4o", 16384],
|
|
49
|
+
// Codex
|
|
50
|
+
["gpt-5.2-codex", 16384],
|
|
51
|
+
// Local
|
|
52
|
+
["qwen", 8192],
|
|
53
|
+
];
|
|
54
|
+
OUTPUT_LIMITS.sort((a, b) => b[0].length - a[0].length); // longest prefix first
|
|
55
|
+
export function lookupMaxOutputTokens(model) {
|
|
56
|
+
const lower = model.toLowerCase();
|
|
57
|
+
for (const [prefix, limit] of OUTPUT_LIMITS) {
|
|
58
|
+
if (lower.startsWith(prefix))
|
|
59
|
+
return limit;
|
|
60
|
+
}
|
|
61
|
+
return 8192; // default
|
|
62
|
+
}
|
|
28
63
|
function lookupPricing(model) {
|
|
29
64
|
const lower = model.toLowerCase();
|
|
30
65
|
for (const [prefix, pricing] of PRICING) {
|
package/dist/index.js
CHANGED
|
@@ -57,7 +57,7 @@ export async function runAgentCli(raw) {
|
|
|
57
57
|
// Resolve LLM provider
|
|
58
58
|
let provider;
|
|
59
59
|
try {
|
|
60
|
-
provider = resolveProvider(args.provider, args.model);
|
|
60
|
+
provider = resolveProvider(args.provider, args.model, args.maxOutput);
|
|
61
61
|
}
|
|
62
62
|
catch (err) {
|
|
63
63
|
console.error(err instanceof Error ? err.message : String(err));
|
|
@@ -34,8 +34,3 @@ export function formatAgentName(name, index) {
|
|
|
34
34
|
const { color, icon } = getAgentStyle(index);
|
|
35
35
|
return color(`${icon} ${name}`);
|
|
36
36
|
}
|
|
37
|
-
/** Prefix a line with the agent's icon in its color. */
|
|
38
|
-
export function prefixLine(line, index) {
|
|
39
|
-
const { color, icon } = getAgentStyle(index);
|
|
40
|
-
return `${color(icon)} ${line}`;
|
|
41
|
-
}
|
|
@@ -25,7 +25,6 @@ import { loadProjectContext } from "../memory/project-context.js";
|
|
|
25
25
|
import { buildSystemPrompt } from "../system-prompt.js";
|
|
26
26
|
import { runAgent } from "../agent-loop.js";
|
|
27
27
|
import { createCostTracker } from "../cost.js";
|
|
28
|
-
let cancelled = false;
|
|
29
28
|
/** Send a typed message to the parent process. */
|
|
30
29
|
function send(msg) {
|
|
31
30
|
if (process.send) {
|
|
@@ -118,6 +117,7 @@ async function runChildAgent(payload) {
|
|
|
118
117
|
phrenCtx,
|
|
119
118
|
costTracker,
|
|
120
119
|
plan,
|
|
120
|
+
hooks: createIpcHooks(agentId),
|
|
121
121
|
};
|
|
122
122
|
// Run the agent
|
|
123
123
|
try {
|
|
@@ -162,7 +162,6 @@ process.on("message", (msg) => {
|
|
|
162
162
|
});
|
|
163
163
|
}
|
|
164
164
|
else if (msg.type === "cancel") {
|
|
165
|
-
cancelled = true;
|
|
166
165
|
process.exit(130);
|
|
167
166
|
}
|
|
168
167
|
});
|
package/dist/multi/markdown.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* Regex-based, no AST parser. Handles the common subset of markdown
|
|
4
4
|
* that LLMs produce: headers, bold, inline code, code blocks, bullet lists.
|
|
5
5
|
*/
|
|
6
|
+
import { highlightCode, detectLanguage } from "./syntax-highlight.js";
|
|
6
7
|
const ESC = "\x1b[";
|
|
7
8
|
const RESET = `${ESC}0m`;
|
|
8
9
|
const BOLD = `${ESC}1m`;
|
|
@@ -20,24 +21,33 @@ export function renderMarkdown(text) {
|
|
|
20
21
|
const out = [];
|
|
21
22
|
let inCodeBlock = false;
|
|
22
23
|
let codeLang = "";
|
|
24
|
+
let codeBuffer = [];
|
|
23
25
|
for (const line of lines) {
|
|
24
26
|
// Code block fences
|
|
25
27
|
if (line.trimStart().startsWith("```")) {
|
|
26
28
|
if (!inCodeBlock) {
|
|
27
29
|
inCodeBlock = true;
|
|
28
30
|
codeLang = line.trimStart().slice(3).trim();
|
|
31
|
+
codeBuffer = [];
|
|
29
32
|
const label = codeLang ? ` ${codeLang}` : "";
|
|
30
33
|
out.push(`${DIM} ┌──${label}${"─".repeat(Math.max(0, MAX_WIDTH - 6 - label.length))}${RESET}`);
|
|
31
34
|
}
|
|
32
35
|
else {
|
|
36
|
+
// Flush code buffer through syntax highlighter
|
|
37
|
+
const lang = codeLang ? detectLanguage(codeLang) : "generic";
|
|
38
|
+
const highlighted = highlightCode(codeBuffer.join("\n"), lang);
|
|
39
|
+
for (const hl of highlighted.split("\n")) {
|
|
40
|
+
out.push(`${DIM} │ ${RESET}${hl}`);
|
|
41
|
+
}
|
|
33
42
|
inCodeBlock = false;
|
|
34
43
|
codeLang = "";
|
|
44
|
+
codeBuffer = [];
|
|
35
45
|
out.push(`${DIM} └${"─".repeat(MAX_WIDTH - 3)}${RESET}`);
|
|
36
46
|
}
|
|
37
47
|
continue;
|
|
38
48
|
}
|
|
39
49
|
if (inCodeBlock) {
|
|
40
|
-
|
|
50
|
+
codeBuffer.push(line.slice(0, MAX_WIDTH - 4));
|
|
41
51
|
continue;
|
|
42
52
|
}
|
|
43
53
|
// Headers
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
const ESC = "\x1b[";
|
|
2
|
+
const s = {
|
|
3
|
+
bold: (t) => `${ESC}1m${t}${ESC}0m`,
|
|
4
|
+
dim: (t) => `${ESC}2m${t}${ESC}0m`,
|
|
5
|
+
cyan: (t) => `${ESC}36m${t}${ESC}0m`,
|
|
6
|
+
green: (t) => `${ESC}32m${t}${ESC}0m`,
|
|
7
|
+
yellow: (t) => `${ESC}33m${t}${ESC}0m`,
|
|
8
|
+
magenta: (t) => `${ESC}35m${t}${ESC}0m`,
|
|
9
|
+
gray: (t) => `${ESC}90m${t}${ESC}0m`,
|
|
10
|
+
};
|
|
11
|
+
const REASONING_LEVELS = ["low", "medium", "high", "max"];
|
|
12
|
+
/** Models available per provider. Extend as needed. */
|
|
13
|
+
export function getAvailableModels(provider, currentModel) {
|
|
14
|
+
const models = [];
|
|
15
|
+
switch (provider) {
|
|
16
|
+
case "anthropic":
|
|
17
|
+
models.push({ id: "claude-sonnet-4-20250514", provider: "anthropic", label: "Sonnet 4", reasoning: "medium", reasoningRange: ["low", "medium", "high"], contextWindow: 200_000 }, { id: "claude-opus-4-20250514", provider: "anthropic", label: "Opus 4", reasoning: "high", reasoningRange: ["low", "medium", "high", "max"], contextWindow: 200_000 }, { id: "claude-haiku-4-5-20251001", provider: "anthropic", label: "Haiku 4.5", reasoning: null, reasoningRange: [], contextWindow: 200_000 });
|
|
18
|
+
break;
|
|
19
|
+
case "openrouter":
|
|
20
|
+
models.push({ id: "anthropic/claude-sonnet-4-20250514", provider: "openrouter", label: "Sonnet 4", reasoning: "medium", reasoningRange: ["low", "medium", "high"], contextWindow: 200_000 }, { id: "anthropic/claude-opus-4-20250514", provider: "openrouter", label: "Opus 4", reasoning: "high", reasoningRange: ["low", "medium", "high", "max"], contextWindow: 200_000 }, { id: "openai/gpt-4o", provider: "openrouter", label: "GPT-4o", reasoning: null, reasoningRange: [], contextWindow: 128_000 }, { id: "openai/o4-mini", provider: "openrouter", label: "o4-mini", reasoning: "medium", reasoningRange: ["low", "medium", "high"], contextWindow: 128_000 }, { id: "google/gemini-2.5-pro", provider: "openrouter", label: "Gemini 2.5 Pro", reasoning: "medium", reasoningRange: ["low", "medium", "high"], contextWindow: 1_000_000 }, { id: "deepseek/deepseek-r1", provider: "openrouter", label: "DeepSeek R1", reasoning: "high", reasoningRange: ["medium", "high"], contextWindow: 128_000 });
|
|
21
|
+
break;
|
|
22
|
+
case "openai":
|
|
23
|
+
models.push({ id: "gpt-4o", provider: "openai", label: "GPT-4o", reasoning: null, reasoningRange: [], contextWindow: 128_000 }, { id: "o4-mini", provider: "openai", label: "o4-mini", reasoning: "medium", reasoningRange: ["low", "medium", "high"], contextWindow: 128_000 }, { id: "o3", provider: "openai", label: "o3", reasoning: "high", reasoningRange: ["low", "medium", "high", "max"], contextWindow: 200_000 });
|
|
24
|
+
break;
|
|
25
|
+
case "codex":
|
|
26
|
+
models.push({ id: "gpt-4o", provider: "codex", label: "GPT-4o", reasoning: null, reasoningRange: [], contextWindow: 128_000 }, { id: "o4-mini", provider: "codex", label: "o4-mini", reasoning: "medium", reasoningRange: ["low", "medium", "high"], contextWindow: 128_000 }, { id: "o3", provider: "codex", label: "o3", reasoning: "high", reasoningRange: ["low", "medium", "high", "max"], contextWindow: 200_000 });
|
|
27
|
+
break;
|
|
28
|
+
case "ollama":
|
|
29
|
+
models.push({ id: "qwen2.5-coder:14b", provider: "ollama", label: "Qwen 2.5 Coder 14B", reasoning: null, reasoningRange: [], contextWindow: 32_000 }, { id: "llama3.2", provider: "ollama", label: "Llama 3.2", reasoning: null, reasoningRange: [], contextWindow: 128_000 }, { id: "deepseek-r1:14b", provider: "ollama", label: "DeepSeek R1 14B", reasoning: "medium", reasoningRange: ["medium", "high"], contextWindow: 128_000 });
|
|
30
|
+
break;
|
|
31
|
+
}
|
|
32
|
+
// If user has a custom model not in the list, add it
|
|
33
|
+
if (currentModel && !models.some((m) => m.id === currentModel)) {
|
|
34
|
+
models.unshift({
|
|
35
|
+
id: currentModel,
|
|
36
|
+
provider: provider,
|
|
37
|
+
label: currentModel,
|
|
38
|
+
reasoning: null,
|
|
39
|
+
reasoningRange: [],
|
|
40
|
+
contextWindow: 200_000,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return models;
|
|
44
|
+
}
|
|
45
|
+
// ── Reasoning meter rendering ───────────────────────────────────────────────
|
|
46
|
+
function renderReasoningMeter(level, range) {
|
|
47
|
+
if (range.length === 0 || level === null)
|
|
48
|
+
return s.dim("─────");
|
|
49
|
+
const maxSlots = 5;
|
|
50
|
+
const levelIdx = REASONING_LEVELS.indexOf(level);
|
|
51
|
+
const filled = levelIdx < 0 ? 0 : Math.min(levelIdx + 1, maxSlots);
|
|
52
|
+
let meter = "";
|
|
53
|
+
for (let i = 0; i < maxSlots; i++) {
|
|
54
|
+
meter += i < filled ? "●" : "○";
|
|
55
|
+
}
|
|
56
|
+
const color = filled >= 4 ? s.magenta : filled >= 3 ? s.yellow : filled >= 2 ? s.green : s.cyan;
|
|
57
|
+
const label = level ?? "n/a";
|
|
58
|
+
return `${color(meter)} ${s.dim(label)}`;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Show interactive model picker. Returns selected model + reasoning, or null on cancel.
|
|
62
|
+
* Works in raw mode — caller must be in raw mode already (TUI) or we'll set it.
|
|
63
|
+
*/
|
|
64
|
+
export function showModelPicker(provider, currentModel, w) {
|
|
65
|
+
const models = getAvailableModels(provider, currentModel);
|
|
66
|
+
if (models.length === 0) {
|
|
67
|
+
w.write(s.dim(" No models available for this provider.\n"));
|
|
68
|
+
return Promise.resolve(null);
|
|
69
|
+
}
|
|
70
|
+
let cursor = models.findIndex((m) => m.id === currentModel);
|
|
71
|
+
if (cursor < 0)
|
|
72
|
+
cursor = 0;
|
|
73
|
+
// Clone reasoning levels so we can adjust them
|
|
74
|
+
const reasoningState = models.map((m) => m.reasoning);
|
|
75
|
+
function render() {
|
|
76
|
+
// Clear previous render (move up by model count + header + footer + blank)
|
|
77
|
+
const totalLines = models.length + 4;
|
|
78
|
+
w.write(`${ESC}${totalLines}A${ESC}J`);
|
|
79
|
+
drawPicker();
|
|
80
|
+
}
|
|
81
|
+
function drawPicker() {
|
|
82
|
+
const maxLabel = Math.max(...models.map((m) => m.label.length));
|
|
83
|
+
w.write(`\n ${s.bold("Select model")} ${s.dim("(↑↓ navigate, ←→ reasoning, enter select, esc cancel)")}\n\n`);
|
|
84
|
+
for (let i = 0; i < models.length; i++) {
|
|
85
|
+
const m = models[i];
|
|
86
|
+
const selected = i === cursor;
|
|
87
|
+
const arrow = selected ? s.cyan("▸") : " ";
|
|
88
|
+
const label = selected ? s.bold(m.label) : s.dim(m.label);
|
|
89
|
+
const padded = m.label + " ".repeat(maxLabel - m.label.length);
|
|
90
|
+
const labelStr = selected ? s.bold(padded) : s.dim(padded);
|
|
91
|
+
const meter = renderReasoningMeter(reasoningState[i], m.reasoningRange);
|
|
92
|
+
const ctx = s.dim(`${(m.contextWindow / 1000).toFixed(0)}k`);
|
|
93
|
+
w.write(` ${arrow} ${labelStr} ${meter} ${ctx}\n`);
|
|
94
|
+
}
|
|
95
|
+
w.write(`\n`);
|
|
96
|
+
}
|
|
97
|
+
// Initial draw
|
|
98
|
+
drawPicker();
|
|
99
|
+
return new Promise((resolve) => {
|
|
100
|
+
const wasRaw = process.stdin.isRaw;
|
|
101
|
+
function onKey(_ch, key) {
|
|
102
|
+
if (!key)
|
|
103
|
+
return;
|
|
104
|
+
if (key.name === "escape" || (key.ctrl && key.name === "c")) {
|
|
105
|
+
cleanup();
|
|
106
|
+
resolve(null);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (key.name === "return") {
|
|
110
|
+
const m = models[cursor];
|
|
111
|
+
cleanup();
|
|
112
|
+
resolve({ model: m.id, reasoning: reasoningState[cursor] });
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (key.name === "up") {
|
|
116
|
+
cursor = (cursor - 1 + models.length) % models.length;
|
|
117
|
+
render();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (key.name === "down") {
|
|
121
|
+
cursor = (cursor + 1) % models.length;
|
|
122
|
+
render();
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
// Left/Right: adjust reasoning level
|
|
126
|
+
if (key.name === "left" || key.name === "right") {
|
|
127
|
+
const m = models[cursor];
|
|
128
|
+
if (m.reasoningRange.length === 0)
|
|
129
|
+
return; // no reasoning for this model
|
|
130
|
+
const current = reasoningState[cursor];
|
|
131
|
+
const idx = current ? REASONING_LEVELS.indexOf(current) : -1;
|
|
132
|
+
const rangeIndices = m.reasoningRange.map((r) => REASONING_LEVELS.indexOf(r));
|
|
133
|
+
if (key.name === "right") {
|
|
134
|
+
// Go higher
|
|
135
|
+
const next = rangeIndices.find((ri) => ri > idx);
|
|
136
|
+
if (next !== undefined)
|
|
137
|
+
reasoningState[cursor] = REASONING_LEVELS[next];
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
// Go lower
|
|
141
|
+
const prev = [...rangeIndices].reverse().find((ri) => ri < idx);
|
|
142
|
+
if (prev !== undefined)
|
|
143
|
+
reasoningState[cursor] = REASONING_LEVELS[prev];
|
|
144
|
+
}
|
|
145
|
+
render();
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function cleanup() {
|
|
150
|
+
process.stdin.removeListener("keypress", onKey);
|
|
151
|
+
}
|
|
152
|
+
process.stdin.on("keypress", onKey);
|
|
153
|
+
});
|
|
154
|
+
}
|