@phren/agent 0.3.31 → 0.3.32
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 +3 -0
- package/dist/bin.js +1 -1
- package/dist/commands/model.js +4 -5
- package/dist/config.js +21 -4
- package/dist/herdr-hooks.js +89 -9
- package/dist/index.js +52 -17
- package/dist/mcp-client.js +5 -1
- package/dist/model-discovery.js +467 -0
- package/dist/models-list.js +20 -25
- package/dist/models.js +32 -9
- package/dist/multi/model-picker.js +87 -46
- package/dist/multi/picker-navigation.js +28 -0
- package/dist/multi/provider-manager.js +27 -57
- package/dist/provider-connectors.js +89 -0
- package/dist/providers/anthropic.js +20 -9
- package/dist/providers/codex.js +7 -7
- package/dist/providers/openai-compat.js +26 -1
- package/dist/providers/openai-responses.js +270 -0
- package/dist/providers/openrouter.js +14 -6
- package/dist/providers/resolve.js +67 -30
- package/dist/repl.js +2 -1
- package/dist/settings.js +72 -3
- package/dist/tools/registry.js +6 -1
- package/dist/tui/components/ModelPicker.js +24 -5
- package/dist/tui/ink-entry.js +12 -17
- package/package.json +2 -2
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { IncompleteStreamError, withPartialUsage } from "./types.js";
|
|
2
|
+
import { parseResponsesOutput, toResponsesInput, toResponsesTools } from "./codex.js";
|
|
3
|
+
import { wireAdvertisedReasoningEffort } from "./openai-compat.js";
|
|
4
|
+
import { lookupContextWindow, lookupMaxOutputTokens, modelSupportsVision } from "../models.js";
|
|
5
|
+
const PROVIDER_NAME = "openai";
|
|
6
|
+
const CATALOG_PROVIDER = "openai";
|
|
7
|
+
const DEFAULT_BASE_URL = "https://api.openai.com/v1";
|
|
8
|
+
const MAX_ERROR_TEXT = 4_096;
|
|
9
|
+
function boundedText(value) {
|
|
10
|
+
return value.length > MAX_ERROR_TEXT ? `${value.slice(0, MAX_ERROR_TEXT)}…` : value;
|
|
11
|
+
}
|
|
12
|
+
function responseUsage(value) {
|
|
13
|
+
if (!value || typeof value !== "object")
|
|
14
|
+
return undefined;
|
|
15
|
+
const usage = value;
|
|
16
|
+
const input = typeof usage.input_tokens === "number" ? usage.input_tokens : 0;
|
|
17
|
+
const output = typeof usage.output_tokens === "number" ? usage.output_tokens : 0;
|
|
18
|
+
return { input_tokens: input, output_tokens: output };
|
|
19
|
+
}
|
|
20
|
+
function responseError(event) {
|
|
21
|
+
const response = event.response && typeof event.response === "object" ? event.response : undefined;
|
|
22
|
+
const detail = event.error ?? response?.error;
|
|
23
|
+
const error = detail && typeof detail === "object" ? detail : undefined;
|
|
24
|
+
const message = typeof error?.message === "string" ? error.message
|
|
25
|
+
: typeof detail === "string" ? detail
|
|
26
|
+
: "Provider reported a Responses API error";
|
|
27
|
+
const code = typeof error?.code === "string" ? ` (${error.code})` : "";
|
|
28
|
+
return new Error(`OpenAI Responses API error${code}: ${boundedText(message)}`);
|
|
29
|
+
}
|
|
30
|
+
function itemRecord(value) {
|
|
31
|
+
return value && typeof value === "object" ? value : {};
|
|
32
|
+
}
|
|
33
|
+
/** Parse the Responses API's HTTP SSE event stream into the agent's deltas. */
|
|
34
|
+
async function* parseResponsesStream(res) {
|
|
35
|
+
if (!res.body)
|
|
36
|
+
throw new Error("Provider returned empty response body");
|
|
37
|
+
const reader = res.body.getReader();
|
|
38
|
+
const decoder = new TextDecoder();
|
|
39
|
+
let buffer = "";
|
|
40
|
+
let completed = false;
|
|
41
|
+
let sawDone = false;
|
|
42
|
+
let stopReason = "end_turn";
|
|
43
|
+
let usage;
|
|
44
|
+
const callByItem = new Map();
|
|
45
|
+
const calls = new Map();
|
|
46
|
+
const handleEvent = (event) => {
|
|
47
|
+
const type = typeof event.type === "string" ? event.type : "";
|
|
48
|
+
const deltas = [];
|
|
49
|
+
if (type === "error" || type === "response.failed") {
|
|
50
|
+
throw responseError(event);
|
|
51
|
+
}
|
|
52
|
+
if (type === "response.output_text.delta") {
|
|
53
|
+
if (typeof event.delta === "string" && event.delta)
|
|
54
|
+
deltas.push({ type: "text_delta", text: event.delta });
|
|
55
|
+
}
|
|
56
|
+
else if (type === "response.reasoning_summary_text.delta") {
|
|
57
|
+
if (typeof event.delta === "string" && event.delta)
|
|
58
|
+
deltas.push({ type: "reasoning_delta", text: event.delta });
|
|
59
|
+
}
|
|
60
|
+
else if (type === "response.output_item.added") {
|
|
61
|
+
const item = itemRecord(event.item);
|
|
62
|
+
const itemType = item.type;
|
|
63
|
+
if (itemType === "function_call") {
|
|
64
|
+
const itemId = typeof item.id === "string" ? item.id : undefined;
|
|
65
|
+
const id = typeof item.call_id === "string" ? item.call_id : itemId;
|
|
66
|
+
if (id) {
|
|
67
|
+
if (itemId)
|
|
68
|
+
callByItem.set(itemId, id);
|
|
69
|
+
calls.set(id, { ended: false });
|
|
70
|
+
deltas.push({ type: "tool_use_start", id, name: typeof item.name === "string" ? item.name : "" });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
else if (type === "response.function_call_arguments.delta") {
|
|
75
|
+
const itemId = typeof event.item_id === "string" ? event.item_id : undefined;
|
|
76
|
+
const id = (typeof event.call_id === "string" ? event.call_id : undefined)
|
|
77
|
+
?? (itemId ? callByItem.get(itemId) : undefined)
|
|
78
|
+
?? itemId;
|
|
79
|
+
if (id && typeof event.delta === "string") {
|
|
80
|
+
if (!calls.has(id)) {
|
|
81
|
+
calls.set(id, { ended: false });
|
|
82
|
+
if (itemId)
|
|
83
|
+
callByItem.set(itemId, id);
|
|
84
|
+
deltas.push({ type: "tool_use_start", id, name: typeof event.name === "string" ? event.name : "" });
|
|
85
|
+
}
|
|
86
|
+
deltas.push({ type: "tool_use_delta", id, json: event.delta });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
else if (type === "response.function_call_arguments.done") {
|
|
90
|
+
const itemId = typeof event.item_id === "string" ? event.item_id : undefined;
|
|
91
|
+
const id = (typeof event.call_id === "string" ? event.call_id : undefined)
|
|
92
|
+
?? (itemId ? callByItem.get(itemId) : undefined)
|
|
93
|
+
?? itemId;
|
|
94
|
+
const call = id ? calls.get(id) : undefined;
|
|
95
|
+
if (id && call && !call.ended) {
|
|
96
|
+
call.ended = true;
|
|
97
|
+
deltas.push({ type: "tool_use_end", id });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
else if (type === "response.output_item.done") {
|
|
101
|
+
const item = itemRecord(event.item);
|
|
102
|
+
if (item.type === "reasoning") {
|
|
103
|
+
const id = typeof item.id === "string" ? item.id : undefined;
|
|
104
|
+
deltas.push({
|
|
105
|
+
type: "reasoning_end",
|
|
106
|
+
...(id ? { id } : {}),
|
|
107
|
+
...(typeof item.encrypted_content === "string" ? { encrypted_content: item.encrypted_content } : {}),
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
else if (item.type === "function_call") {
|
|
111
|
+
const itemId = typeof item.id === "string" ? item.id : undefined;
|
|
112
|
+
const id = (typeof item.call_id === "string" ? item.call_id : undefined)
|
|
113
|
+
?? (itemId ? callByItem.get(itemId) : undefined)
|
|
114
|
+
?? itemId;
|
|
115
|
+
const call = id ? calls.get(id) : undefined;
|
|
116
|
+
if (id && call && !call.ended) {
|
|
117
|
+
call.ended = true;
|
|
118
|
+
deltas.push({ type: "tool_use_end", id });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
else if (type === "response.completed") {
|
|
123
|
+
const response = itemRecord(event.response);
|
|
124
|
+
usage = responseUsage(response.usage) ?? usage;
|
|
125
|
+
const output = Array.isArray(response.output) ? response.output : [];
|
|
126
|
+
if (output.some((item) => itemRecord(item).type === "function_call") || calls.size > 0)
|
|
127
|
+
stopReason = "tool_use";
|
|
128
|
+
completed = true;
|
|
129
|
+
}
|
|
130
|
+
else if (type === "response.incomplete") {
|
|
131
|
+
const response = itemRecord(event.response);
|
|
132
|
+
usage = responseUsage(response.usage) ?? usage;
|
|
133
|
+
stopReason = "max_tokens";
|
|
134
|
+
completed = true;
|
|
135
|
+
}
|
|
136
|
+
return deltas;
|
|
137
|
+
};
|
|
138
|
+
try {
|
|
139
|
+
read: for (;;) {
|
|
140
|
+
const { done, value } = await reader.read();
|
|
141
|
+
if (done) {
|
|
142
|
+
buffer += decoder.decode();
|
|
143
|
+
if (buffer.trim() === "data: [DONE]")
|
|
144
|
+
sawDone = true;
|
|
145
|
+
else if (buffer) {
|
|
146
|
+
const line = buffer.replace(/\r$/, "");
|
|
147
|
+
if (line.startsWith("data:")) {
|
|
148
|
+
const raw = line.slice(5).trim();
|
|
149
|
+
if (raw === "[DONE]")
|
|
150
|
+
sawDone = true;
|
|
151
|
+
else {
|
|
152
|
+
try {
|
|
153
|
+
for (const delta of handleEvent(JSON.parse(raw)))
|
|
154
|
+
yield delta;
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
if (error instanceof SyntaxError) { /* Ignore a malformed trailing event. */ }
|
|
158
|
+
else
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
break;
|
|
165
|
+
}
|
|
166
|
+
buffer += decoder.decode(value, { stream: true });
|
|
167
|
+
const lines = buffer.split("\n");
|
|
168
|
+
buffer = lines.pop() ?? "";
|
|
169
|
+
for (const rawLine of lines) {
|
|
170
|
+
const line = rawLine.replace(/\r$/, "");
|
|
171
|
+
if (!line.startsWith("data:"))
|
|
172
|
+
continue;
|
|
173
|
+
const raw = line.slice(5).trim();
|
|
174
|
+
if (raw === "[DONE]") {
|
|
175
|
+
sawDone = true;
|
|
176
|
+
break read;
|
|
177
|
+
}
|
|
178
|
+
let event;
|
|
179
|
+
try {
|
|
180
|
+
event = JSON.parse(raw);
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
for (const delta of handleEvent(event))
|
|
186
|
+
yield delta;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (!completed && !sawDone) {
|
|
190
|
+
throw withPartialUsage(new IncompleteStreamError("Responses stream ended before response.completed"), usage);
|
|
191
|
+
}
|
|
192
|
+
if (!completed) {
|
|
193
|
+
throw withPartialUsage(new IncompleteStreamError("Responses stream ended at [DONE] before response.completed"), usage);
|
|
194
|
+
}
|
|
195
|
+
for (const [id, call] of calls) {
|
|
196
|
+
if (!call.ended)
|
|
197
|
+
yield { type: "tool_use_end", id };
|
|
198
|
+
}
|
|
199
|
+
yield { type: "done", stop_reason: stopReason, usage };
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
throw withPartialUsage(error, usage);
|
|
203
|
+
}
|
|
204
|
+
finally {
|
|
205
|
+
await reader.cancel().catch(() => { });
|
|
206
|
+
reader.releaseLock();
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
export class OpenAiResponsesProvider {
|
|
210
|
+
name = PROVIDER_NAME;
|
|
211
|
+
contextWindow;
|
|
212
|
+
maxOutputTokens;
|
|
213
|
+
baseUrl;
|
|
214
|
+
apiKey;
|
|
215
|
+
model;
|
|
216
|
+
reasoningEffort;
|
|
217
|
+
constructor(apiKey, model, baseUrl, maxOutputTokens, reasoningEffort) {
|
|
218
|
+
this.apiKey = apiKey;
|
|
219
|
+
this.model = model ?? "gpt-5.4";
|
|
220
|
+
this.baseUrl = (baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
221
|
+
this.maxOutputTokens = maxOutputTokens ?? lookupMaxOutputTokens(this.model, CATALOG_PROVIDER);
|
|
222
|
+
this.reasoningEffort = reasoningEffort;
|
|
223
|
+
this.contextWindow = lookupContextWindow(this.model, CATALOG_PROVIDER);
|
|
224
|
+
}
|
|
225
|
+
requestBody(system, messages, tools, stream) {
|
|
226
|
+
const body = {
|
|
227
|
+
model: this.model,
|
|
228
|
+
instructions: system,
|
|
229
|
+
input: toResponsesInput(messages, modelSupportsVision(CATALOG_PROVIDER, this.model), this.name),
|
|
230
|
+
max_output_tokens: this.maxOutputTokens,
|
|
231
|
+
store: false,
|
|
232
|
+
stream,
|
|
233
|
+
include: ["reasoning.encrypted_content"],
|
|
234
|
+
};
|
|
235
|
+
const effort = wireAdvertisedReasoningEffort(CATALOG_PROVIDER, this.model, this.reasoningEffort);
|
|
236
|
+
if (effort)
|
|
237
|
+
body.reasoning = { effort };
|
|
238
|
+
if (tools.length > 0) {
|
|
239
|
+
body.tools = toResponsesTools(tools);
|
|
240
|
+
body.tool_choice = "auto";
|
|
241
|
+
}
|
|
242
|
+
return body;
|
|
243
|
+
}
|
|
244
|
+
async request(body, signal) {
|
|
245
|
+
if (signal?.aborted)
|
|
246
|
+
throw signal.reason instanceof Error ? signal.reason : new Error("Request aborted");
|
|
247
|
+
const res = await fetch(`${this.baseUrl}/responses`, {
|
|
248
|
+
method: "POST",
|
|
249
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}` },
|
|
250
|
+
body: JSON.stringify(body),
|
|
251
|
+
signal,
|
|
252
|
+
});
|
|
253
|
+
if (!res.ok) {
|
|
254
|
+
const text = await res.text();
|
|
255
|
+
throw new Error(`OpenAI Responses API error ${res.status}: ${boundedText(text)}`);
|
|
256
|
+
}
|
|
257
|
+
return res;
|
|
258
|
+
}
|
|
259
|
+
async chat(system, messages, tools, signal) {
|
|
260
|
+
const res = await this.request(this.requestBody(system, messages, tools, false), signal);
|
|
261
|
+
const data = await res.json();
|
|
262
|
+
if (data.status === "failed" || data.error)
|
|
263
|
+
throw responseError(data);
|
|
264
|
+
return parseResponsesOutput(data, this.name);
|
|
265
|
+
}
|
|
266
|
+
async *chatStream(system, messages, tools, signal) {
|
|
267
|
+
const res = await this.request(this.requestBody(system, messages, tools, true), signal);
|
|
268
|
+
yield* parseResponsesStream(res);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { toOpenAiTools, toOpenAiMessages, parseOpenAiResponse, parseOpenAiStream, replaysAllReasoning,
|
|
1
|
+
import { toOpenAiTools, toOpenAiMessages, parseOpenAiResponse, parseOpenAiStream, replaysAllReasoning, isDeepSeekRoute, wireAdvertisedReasoningEffort, } from "./openai-compat.js";
|
|
2
2
|
import { lookupContextWindow, lookupMaxOutputTokens, modelSupportsVision } from "../models.js";
|
|
3
3
|
export class OpenRouterProvider {
|
|
4
4
|
name = "openrouter";
|
|
@@ -19,7 +19,9 @@ export class OpenRouterProvider {
|
|
|
19
19
|
applyReasoning(body) {
|
|
20
20
|
if (!this.reasoningEffort)
|
|
21
21
|
return;
|
|
22
|
-
const effort = this.
|
|
22
|
+
const effort = wireAdvertisedReasoningEffort(this.name, this.model, this.reasoningEffort);
|
|
23
|
+
if (!effort)
|
|
24
|
+
return;
|
|
23
25
|
body.reasoning = { effort };
|
|
24
26
|
}
|
|
25
27
|
async chat(system, messages, tools, signal) {
|
|
@@ -117,9 +119,12 @@ export class OpenAiProvider {
|
|
|
117
119
|
messages: this.toMessages(system, messages),
|
|
118
120
|
max_tokens: this.maxOutputTokens,
|
|
119
121
|
};
|
|
120
|
-
const effort =
|
|
121
|
-
if (effort)
|
|
122
|
+
const effort = wireAdvertisedReasoningEffort(this.name, this.model, this.reasoningEffort);
|
|
123
|
+
if (effort) {
|
|
122
124
|
body.reasoning_effort = effort;
|
|
125
|
+
if (isDeepSeekRoute(this.name, this.model))
|
|
126
|
+
body.thinking = { type: effort === "none" ? "disabled" : "enabled" };
|
|
127
|
+
}
|
|
123
128
|
if (tools.length > 0)
|
|
124
129
|
body.tools = toOpenAiTools(tools);
|
|
125
130
|
const res = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
@@ -142,9 +147,12 @@ export class OpenAiProvider {
|
|
|
142
147
|
stream: true,
|
|
143
148
|
stream_options: { include_usage: true },
|
|
144
149
|
};
|
|
145
|
-
const effort =
|
|
146
|
-
if (effort)
|
|
150
|
+
const effort = wireAdvertisedReasoningEffort(this.name, this.model, this.reasoningEffort);
|
|
151
|
+
if (effort) {
|
|
147
152
|
body.reasoning_effort = effort;
|
|
153
|
+
if (isDeepSeekRoute(this.name, this.model))
|
|
154
|
+
body.thinking = { type: effort === "none" ? "disabled" : "enabled" };
|
|
155
|
+
}
|
|
148
156
|
if (tools.length > 0)
|
|
149
157
|
body.tools = toOpenAiTools(tools);
|
|
150
158
|
const res = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
@@ -5,8 +5,33 @@ import { OllamaProvider } from "./ollama.js";
|
|
|
5
5
|
import { CodexProvider } from "./codex.js";
|
|
6
6
|
import { ReplayProvider } from "./replay.js";
|
|
7
7
|
import { codexConfiguredModel, hasCodexToken } from "./codex-auth.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
8
|
+
import { resolveConnector } from "../provider-connectors.js";
|
|
9
|
+
import { acceptsNoReasoning, isDeepSeekRoute } from "./openai-compat.js";
|
|
10
|
+
import { OpenAiResponsesProvider } from "./openai-responses.js";
|
|
11
|
+
import { getModelMetadata, getDiscoveredModels, getDefaultModel, getDefaultReasoningEffort, lookupMaxOutputTokens, normalizeProviderId, normalizeReasoningEffort, } from "../models.js";
|
|
12
|
+
function normalizeSelectedReasoning(raw) {
|
|
13
|
+
if (!raw)
|
|
14
|
+
return undefined;
|
|
15
|
+
const effort = normalizeReasoningEffort(raw);
|
|
16
|
+
if (!effort)
|
|
17
|
+
throw new Error(`Unknown reasoning effort "${raw}".`);
|
|
18
|
+
return effort;
|
|
19
|
+
}
|
|
20
|
+
/** Validate before changing the active provider, so status matches the request. */
|
|
21
|
+
function selectedEffort(provider, model, raw) {
|
|
22
|
+
const effort = normalizeSelectedReasoning(raw);
|
|
23
|
+
if (!effort)
|
|
24
|
+
return getDefaultReasoningEffort(provider, model);
|
|
25
|
+
if (effort === "none" && !isDeepSeekRoute(provider, model) && provider !== "anthropic"
|
|
26
|
+
&& !((provider === "openai" || provider === "openai-codex") && acceptsNoReasoning(model))) {
|
|
27
|
+
throw new Error(`${provider}/${model} does not advertise reasoning off; choose a supported effort or omit --reasoning.`);
|
|
28
|
+
}
|
|
29
|
+
const metadata = getModelMetadata(provider, model);
|
|
30
|
+
if (metadata && !metadata.reasoningRange.includes(effort) && effort !== "none") {
|
|
31
|
+
throw new Error(`${provider}/${model} does not support reasoning ${effort}. Supported: ${metadata.reasoningRange.join(", ") || "model default only"}.`);
|
|
32
|
+
}
|
|
33
|
+
return effort;
|
|
34
|
+
}
|
|
10
35
|
function normalizeProviderSelection(overrideProvider, overrideModel) {
|
|
11
36
|
let provider = normalizeProviderId(overrideProvider ?? process.env.PHREN_AGENT_PROVIDER);
|
|
12
37
|
let model = overrideModel;
|
|
@@ -47,7 +72,7 @@ function deepSeekBaseUrl(options) {
|
|
|
47
72
|
const fromEnv = normalizeProviderId(process.env.PHREN_AGENT_PROVIDER) === "deepseek"
|
|
48
73
|
? process.env.PHREN_AGENT_BASE_URL
|
|
49
74
|
: undefined;
|
|
50
|
-
return (options.baseUrl ?? sessionDeepSeekUrl ?? fromEnv ?? DEEPSEEK_BASE_URL
|
|
75
|
+
return resolveConnector("deepseek", options.baseUrl ?? sessionDeepSeekUrl ?? fromEnv).baseUrl ?? DEEPSEEK_BASE_URL;
|
|
51
76
|
}
|
|
52
77
|
/** A positive integer token count from a flag or env value, else undefined. */
|
|
53
78
|
export function parseTokenCount(raw) {
|
|
@@ -78,67 +103,79 @@ function resolveCatalogProvider(overrideProvider, overrideModel, overrideMaxOutp
|
|
|
78
103
|
// handled before normalization and needs an explicit model.
|
|
79
104
|
const rawProvider = (overrideProvider ?? process.env.PHREN_AGENT_PROVIDER)?.toLowerCase();
|
|
80
105
|
if (rawProvider === "openai-compat" || rawProvider === "compat") {
|
|
81
|
-
const
|
|
106
|
+
const connector = resolveConnector("openai-compat", options.baseUrl);
|
|
107
|
+
const baseUrl = connector.baseUrl;
|
|
82
108
|
if (!baseUrl) {
|
|
83
109
|
throw new Error("openai-compat needs an endpoint: pass --base-url <url> or set PHREN_AGENT_BASE_URL (e.g. https://host/v1).");
|
|
84
110
|
}
|
|
85
|
-
|
|
111
|
+
const model = overrideModel ?? connector.model ?? getDiscoveredModels("openai-compat")?.find(model => model.catalogSource !== "fallback")?.id;
|
|
112
|
+
if (!model)
|
|
86
113
|
throw new Error("openai-compat needs --model <id> (the endpoint's model name).");
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
114
|
+
// OpenCode's configured Go/Zen connector can be reused without copying
|
|
115
|
+
// its key into a second Phren-specific variable. No key is ever printed.
|
|
116
|
+
const key = connector.apiKey ?? "";
|
|
117
|
+
const reasoning = selectedEffort("openai-compat", model, overrideReasoning ?? process.env.PHREN_AGENT_REASONING);
|
|
118
|
+
return new OpenAiProvider(key, model, baseUrl, overrideMaxOutput, reasoning).withName("openai-compat", overrideMaxOutput);
|
|
90
119
|
}
|
|
91
120
|
const { provider: explicit, model: normalizedModel } = normalizeProviderSelection(overrideProvider, overrideModel);
|
|
92
121
|
if (rawProvider && !explicit) {
|
|
93
122
|
// A typo must not silently fall through to auto-detection.
|
|
94
123
|
throw new Error(`Unknown provider "${rawProvider}". Supported: openai-codex, openai, openrouter, anthropic, deepseek, openai-compat, ollama.`);
|
|
95
124
|
}
|
|
96
|
-
const
|
|
97
|
-
const
|
|
98
|
-
const
|
|
99
|
-
const
|
|
125
|
+
const openRouter = resolveConnector("openrouter", explicit === "openrouter" ? options.baseUrl : undefined);
|
|
126
|
+
const anthropic = resolveConnector("anthropic", explicit === "anthropic" ? options.baseUrl : undefined);
|
|
127
|
+
const openAi = resolveConnector("openai", explicit === "openai" ? options.baseUrl : undefined);
|
|
128
|
+
const openRouterKey = openRouter.apiKey;
|
|
129
|
+
const anthropicKey = anthropic.apiKey;
|
|
130
|
+
const openAiKey = openAi.apiKey;
|
|
100
131
|
// Resolve max output tokens: CLI override > model lookup > default 8192
|
|
101
132
|
const resolveLimit = (provider, model) => overrideMaxOutput ?? lookupMaxOutputTokens(model, provider);
|
|
102
|
-
const resolveReasoning = (provider, model) =>
|
|
103
|
-
// Prefer Codex subscription and
|
|
133
|
+
const resolveReasoning = (provider, model) => selectedEffort(provider, model, overrideReasoning ?? process.env.PHREN_AGENT_REASONING);
|
|
134
|
+
// Prefer the installed Codex subscription and its selected model when available.
|
|
104
135
|
if (explicit === "openai-codex" || (!explicit && hasCodexToken())) {
|
|
105
136
|
const model = normalizedModel ?? codexConfiguredModel() ?? getDefaultModel("openai-codex");
|
|
106
137
|
return new CodexProvider(model, resolveLimit("openai-codex", model), resolveReasoning("openai-codex", model));
|
|
107
138
|
}
|
|
108
|
-
if (explicit === "openai" || (!explicit &&
|
|
139
|
+
if (explicit === "openai" || (!explicit && openAi.configured)) {
|
|
109
140
|
if (!openAiKey)
|
|
110
141
|
throw new Error("OpenAI credentials are required. Set OPENAI_API_KEY or run 'phren auth set-key openai'.");
|
|
111
|
-
const model = normalizedModel ?? getDefaultModel("openai");
|
|
112
|
-
|
|
142
|
+
const model = normalizedModel ?? openAi.model ?? getDefaultModel("openai");
|
|
143
|
+
const Provider = /^(gpt-[56]|o[134])(?:[.-]|$)/.test(model) ? OpenAiResponsesProvider : OpenAiProvider;
|
|
144
|
+
return new Provider(openAiKey, model, openAi.baseUrl, resolveLimit("openai", model), resolveReasoning("openai", model));
|
|
113
145
|
}
|
|
114
|
-
if (explicit === "openrouter" || (!explicit &&
|
|
146
|
+
if (explicit === "openrouter" || (!explicit && openRouter.configured)) {
|
|
115
147
|
if (!openRouterKey)
|
|
116
148
|
throw new Error("OpenRouter credentials are required. Set OPENROUTER_API_KEY or run 'phren auth set-key openrouter'.");
|
|
117
|
-
const model = normalizedModel ?? getDefaultModel("openrouter");
|
|
118
|
-
return new OpenRouterProvider(openRouterKey, model,
|
|
149
|
+
const model = normalizedModel ?? openRouter.model ?? getDefaultModel("openrouter");
|
|
150
|
+
return new OpenRouterProvider(openRouterKey, model, openRouter.baseUrl, resolveLimit("openrouter", model), resolveReasoning("openrouter", model));
|
|
119
151
|
}
|
|
120
|
-
if (explicit === "anthropic" || (!explicit &&
|
|
152
|
+
if (explicit === "anthropic" || (!explicit && anthropic.configured)) {
|
|
121
153
|
if (!anthropicKey)
|
|
122
154
|
throw new Error("Anthropic credentials are required. Set ANTHROPIC_API_KEY or run 'phren auth set-key anthropic'.");
|
|
123
|
-
const model = normalizedModel ?? getDefaultModel("anthropic");
|
|
124
|
-
return new AnthropicProvider(anthropicKey, model, resolveLimit("anthropic", model), true, resolveReasoning("anthropic", model));
|
|
155
|
+
const model = normalizedModel ?? anthropic.model ?? getDefaultModel("anthropic");
|
|
156
|
+
return new AnthropicProvider(anthropicKey, model, resolveLimit("anthropic", model), true, resolveReasoning("anthropic", model), anthropic.baseUrl);
|
|
125
157
|
}
|
|
126
|
-
const
|
|
127
|
-
|
|
158
|
+
const deepseek = resolveConnector("deepseek");
|
|
159
|
+
const deepseekKey = deepseek.apiKey;
|
|
160
|
+
if (explicit === "deepseek" || (!explicit && deepseek.configured)) {
|
|
128
161
|
if (!deepseekKey)
|
|
129
162
|
throw new Error("DeepSeek credentials are required. Set DEEPSEEK_API_KEY.");
|
|
130
|
-
const model = normalizedModel ?? getDefaultModel("deepseek");
|
|
163
|
+
const model = normalizedModel ?? deepseek.model ?? getDefaultModel("deepseek");
|
|
131
164
|
const baseUrl = deepSeekBaseUrl(options);
|
|
132
165
|
return new OpenAiProvider(deepseekKey, model, baseUrl, resolveLimit("deepseek", model), resolveReasoning("deepseek", model))
|
|
133
166
|
.withName("deepseek", overrideMaxOutput ?? lookupMaxOutputTokens(model, "deepseek"));
|
|
134
167
|
}
|
|
135
|
-
if (
|
|
136
|
-
|
|
137
|
-
|
|
168
|
+
if (!explicit && resolveConnector("openai-compat").configured) {
|
|
169
|
+
return resolveCatalogProvider("openai-compat", normalizedModel, overrideMaxOutput, overrideReasoning, options);
|
|
170
|
+
}
|
|
171
|
+
const local = resolveConnector("ollama");
|
|
172
|
+
if (explicit === "ollama" || (!explicit && local.configured)) {
|
|
173
|
+
const model = normalizedModel ?? local.model ?? getDefaultModel("ollama");
|
|
174
|
+
return new OllamaProvider(model, local.baseUrl, resolveLimit("ollama", model));
|
|
138
175
|
}
|
|
139
176
|
// Last resort: try Ollama at default URL
|
|
140
177
|
if (!explicit) {
|
|
141
|
-
const model = normalizedModel ?? getDefaultModel("ollama");
|
|
178
|
+
const model = normalizedModel ?? local.model ?? getDefaultModel("ollama");
|
|
142
179
|
return new OllamaProvider(model, undefined, resolveLimit("ollama", model));
|
|
143
180
|
}
|
|
144
181
|
throw new Error(`Unknown provider "${explicit}". Supported: openai-codex, openai, openrouter, anthropic, deepseek, openai-compat, ollama.\n` +
|
package/dist/repl.js
CHANGED
|
@@ -10,7 +10,7 @@ import { createSession, runTurn } from "./agent-loop.js";
|
|
|
10
10
|
import { handleCommand, resolveSkillGesture, resolveCustomCommand } from "./commands.js";
|
|
11
11
|
import { isMcpPromptCommand, resolveMcpPromptCommand } from "./mcp-prompts.js";
|
|
12
12
|
import { resolveProvider } from "./providers/resolve.js";
|
|
13
|
-
import { loadInputMode } from "./settings.js";
|
|
13
|
+
import { loadInputMode, saveModelSelection } from "./settings.js";
|
|
14
14
|
const HISTORY_DIR = path.join(os.homedir(), ".phren-agent");
|
|
15
15
|
const HISTORY_FILE = path.join(HISTORY_DIR, "repl-history.txt");
|
|
16
16
|
const MAX_HISTORY = 500;
|
|
@@ -89,6 +89,7 @@ export async function startRepl(config) {
|
|
|
89
89
|
promote: config.promote,
|
|
90
90
|
onModelChange: (result) => {
|
|
91
91
|
config.provider = resolveProvider(result.provider ?? config.provider.name, result.model || undefined, undefined, result.reasoning ?? undefined);
|
|
92
|
+
saveModelSelection({ provider: config.provider.name, model: config.provider.model, reasoning: config.provider.reasoningEffort }, process.cwd());
|
|
92
93
|
config.costTracker?.reprice(config.provider.model ?? config.provider.name, config.provider.name, config.provider.baseUrl);
|
|
93
94
|
return config.provider;
|
|
94
95
|
},
|
package/dist/settings.js
CHANGED
|
@@ -2,10 +2,14 @@
|
|
|
2
2
|
import * as fs from "fs";
|
|
3
3
|
import * as path from "path";
|
|
4
4
|
import * as os from "os";
|
|
5
|
+
import { normalizeProviderId, normalizeReasoningEffort } from "./models.js";
|
|
5
6
|
export const SETTINGS_FILE = path.join(os.homedir(), ".phren-agent", "settings.json");
|
|
7
|
+
function settingsFile() {
|
|
8
|
+
return path.join(os.homedir(), ".phren-agent", "settings.json");
|
|
9
|
+
}
|
|
6
10
|
function readSettings() {
|
|
7
11
|
try {
|
|
8
|
-
const data = JSON.parse(fs.readFileSync(
|
|
12
|
+
const data = JSON.parse(fs.readFileSync(settingsFile(), "utf-8"));
|
|
9
13
|
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
|
10
14
|
}
|
|
11
15
|
catch {
|
|
@@ -14,8 +18,11 @@ function readSettings() {
|
|
|
14
18
|
}
|
|
15
19
|
function writeSettings(data) {
|
|
16
20
|
try {
|
|
17
|
-
|
|
18
|
-
fs.
|
|
21
|
+
const file = settingsFile();
|
|
22
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
23
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
24
|
+
fs.writeFileSync(temp, JSON.stringify(data, null, 2) + "\n", { mode: 0o600 });
|
|
25
|
+
fs.renameSync(temp, file);
|
|
19
26
|
}
|
|
20
27
|
catch { /* best effort */ }
|
|
21
28
|
}
|
|
@@ -70,3 +77,65 @@ export function loadInputHistory() {
|
|
|
70
77
|
export function saveInputHistory(lines) {
|
|
71
78
|
update("inputHistory", lines.slice(-500));
|
|
72
79
|
}
|
|
80
|
+
/** The last explicit picker/CLI selection for each project working tree. */
|
|
81
|
+
export function loadModelSelection(projectRoot = process.cwd()) {
|
|
82
|
+
const selections = readSettings().modelSelections;
|
|
83
|
+
if (!selections || typeof selections !== "object" || Array.isArray(selections))
|
|
84
|
+
return undefined;
|
|
85
|
+
const value = selections[modelProjectRoot(projectRoot)];
|
|
86
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
87
|
+
return undefined;
|
|
88
|
+
const row = value;
|
|
89
|
+
if (typeof row.provider !== "string" || !row.provider)
|
|
90
|
+
return undefined;
|
|
91
|
+
return {
|
|
92
|
+
provider: row.provider,
|
|
93
|
+
...(typeof row.model === "string" && row.model ? { model: row.model } : {}),
|
|
94
|
+
...(typeof row.reasoning === "string" && row.reasoning ? { reasoning: row.reasoning } : {}),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
export function saveModelSelection(selection, projectRoot = process.cwd()) {
|
|
98
|
+
const data = readSettings();
|
|
99
|
+
const existing = data.modelSelections && typeof data.modelSelections === "object" && !Array.isArray(data.modelSelections)
|
|
100
|
+
? data.modelSelections
|
|
101
|
+
: {};
|
|
102
|
+
existing[modelProjectRoot(projectRoot)] = {
|
|
103
|
+
provider: selection.provider,
|
|
104
|
+
...(selection.model ? { model: selection.model } : {}),
|
|
105
|
+
...(selection.reasoning ? { reasoning: selection.reasoning } : {}),
|
|
106
|
+
};
|
|
107
|
+
data.modelSelections = existing;
|
|
108
|
+
writeSettings(data);
|
|
109
|
+
}
|
|
110
|
+
/** Subdirectories share the checkout's choice; linked worktrees stay independent. */
|
|
111
|
+
function modelProjectRoot(cwd) {
|
|
112
|
+
const start = path.resolve(cwd);
|
|
113
|
+
let current = start;
|
|
114
|
+
while (true) {
|
|
115
|
+
if (fs.existsSync(path.join(current, ".git")))
|
|
116
|
+
return current;
|
|
117
|
+
const parent = path.dirname(current);
|
|
118
|
+
if (parent === current)
|
|
119
|
+
return start;
|
|
120
|
+
current = parent;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
export function restoreModelSelection(explicit, saved, env = process.env) {
|
|
124
|
+
let provider = explicit.provider ?? env.PHREN_AGENT_PROVIDER;
|
|
125
|
+
let model = explicit.model ?? env.PHREN_AGENT_MODEL;
|
|
126
|
+
// Only the two historic qualified prefixes are unambiguous; Router IDs
|
|
127
|
+
// contain slashes too, so they stay under the explicitly selected provider.
|
|
128
|
+
const qualified = /^(openai-codex|openai)\/(.+)$/.exec(model ?? "");
|
|
129
|
+
if (!provider && qualified) {
|
|
130
|
+
provider = qualified[1];
|
|
131
|
+
model = qualified[2];
|
|
132
|
+
}
|
|
133
|
+
const sameProvider = !provider || normalizeProviderId(provider) === normalizeProviderId(saved?.provider);
|
|
134
|
+
const sameModel = !model || model === saved?.model;
|
|
135
|
+
return {
|
|
136
|
+
provider: provider ?? (model ? undefined : saved?.provider),
|
|
137
|
+
model: model ?? (sameProvider ? saved?.model : undefined),
|
|
138
|
+
reasoning: explicit.reasoning ?? normalizeReasoningEffort(env.PHREN_AGENT_REASONING)
|
|
139
|
+
?? (sameProvider && sameModel ? normalizeReasoningEffort(saved?.reasoning) : undefined),
|
|
140
|
+
};
|
|
141
|
+
}
|
package/dist/tools/registry.js
CHANGED
|
@@ -6,6 +6,8 @@ export class ToolRegistry {
|
|
|
6
6
|
tools = new Map();
|
|
7
7
|
/** Override the default permission prompt (e.g. for Ink TUI). */
|
|
8
8
|
askUser = defaultAskUser;
|
|
9
|
+
/** Root harness approval channel; unavailable responses fall back to askUser. */
|
|
10
|
+
externalApproval;
|
|
9
11
|
permissionConfig = {
|
|
10
12
|
mode: "suggest",
|
|
11
13
|
projectRoot: process.cwd(),
|
|
@@ -57,7 +59,10 @@ export class ToolRegistry {
|
|
|
57
59
|
return { output: `Permission denied: ${rule.reason}`, is_error: true, permissionDenied: true };
|
|
58
60
|
}
|
|
59
61
|
if (rule.verdict === "ask") {
|
|
60
|
-
const
|
|
62
|
+
const external = await this.externalApproval?.(name, input, signal);
|
|
63
|
+
if (signal?.aborted)
|
|
64
|
+
return { output: "Cancelled by user.", is_error: true };
|
|
65
|
+
const allowed = external ?? await this.askUser(name, input, rule.reason);
|
|
61
66
|
if (!allowed) {
|
|
62
67
|
return { output: "User denied permission.", is_error: true, permissionDenied: true };
|
|
63
68
|
}
|