pi-uva-hva 1.4.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/README.md +319 -0
- package/index.ts +1235 -0
- package/package.json +34 -0
package/index.ts
ADDED
|
@@ -0,0 +1,1235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* openai-responses-uva, a Pi coding-agent provider extension
|
|
3
|
+
* ============================================================
|
|
4
|
+
*
|
|
5
|
+
* Registers the UvA LiteLLM proxy (https://llmproxy.uva.nl/v1) as a Pi model
|
|
6
|
+
* provider and works around a proxy bug that otherwise makes every agent turn
|
|
7
|
+
* return "thinking then nothing".
|
|
8
|
+
*
|
|
9
|
+
* The bug
|
|
10
|
+
* -------
|
|
11
|
+
* The UvA proxy speaks the OpenAI **Responses API** (`/v1/responses`). When a
|
|
12
|
+
* request contains NO tool definitions it streams normally. But when tool
|
|
13
|
+
* definitions ARE present (i.e. every agent turn) it collapses the SSE stream
|
|
14
|
+
* to a single terminal `response.completed` event carrying the whole result in
|
|
15
|
+
* `response.output[]`, and emits none of the incremental events
|
|
16
|
+
* (`response.output_item.added`, `response.output_text.delta`,
|
|
17
|
+
* `response.function_call_arguments.delta`, ...).
|
|
18
|
+
*
|
|
19
|
+
* Pi's built-in Responses stream parser builds the assistant reply purely from
|
|
20
|
+
* those incremental events; its terminal handler never harvests
|
|
21
|
+
* `response.output[]`. So the assistant message ends up empty, no text, no
|
|
22
|
+
* tool call, no error.
|
|
23
|
+
*
|
|
24
|
+
* The fix
|
|
25
|
+
* -------
|
|
26
|
+
* This extension registers the UvA provider under a private api id so this
|
|
27
|
+
* handler runs. For each turn it:
|
|
28
|
+
* 1. Lets Pi's pristine built-in `openai-responses` handler BUILD the exact
|
|
29
|
+
* request params (full message + tool conversion, reasoning, caching) via
|
|
30
|
+
* an `onPayload` hook that captures the params and throws BEFORE the
|
|
31
|
+
* network call, so nothing extra is billed.
|
|
32
|
+
* 2. Reissues that request itself and synthesizes Pi's content events,
|
|
33
|
+
* reconciling the incremental SSE events with the terminal
|
|
34
|
+
* `response.output[]` so the collapsed tool call is never lost.
|
|
35
|
+
*
|
|
36
|
+
* Two dispatch paths keep it reliable:
|
|
37
|
+
* - Non-reasoning turns STREAM (`stream:true`). Bytes flow, so the nginx
|
|
38
|
+
* gateway read-timeout keeps resetting and the reply is token-by-token.
|
|
39
|
+
* - Reasoning turns (reasoning.effort low/medium/high) use BACKGROUND + POLL
|
|
40
|
+
* (`background:true` + `GET /responses/{id}`). The model can buffer its
|
|
41
|
+
* whole reasoning phase with zero interim bytes without ever tripping a
|
|
42
|
+
* 504, because each HTTP request is short. A streaming turn that still hits
|
|
43
|
+
* a gateway 5xx before any output falls back to this path automatically.
|
|
44
|
+
*
|
|
45
|
+
* Trade-off: reasoning replies are not token-by-token (they appear at once on
|
|
46
|
+
* completion); plain turns stream normally.
|
|
47
|
+
*
|
|
48
|
+
* Connecting
|
|
49
|
+
* ----------
|
|
50
|
+
* Run `/login` (choose "UvA / HvA proxy") or `/uva-login`: pick a base URL
|
|
51
|
+
* (UvA / HvA / custom), paste your API key, and every model is auto-discovered.
|
|
52
|
+
* The base URL + key are saved to ~/.pi/agent/openai-responses-uva.json so the
|
|
53
|
+
* next launch reconnects with nothing re-entered. Then pick a model via /models.
|
|
54
|
+
*
|
|
55
|
+
* Reasoning models default to thinking ON at medium
|
|
56
|
+
* (set UVA_NO_AUTO_THINKING=1 to disable this; change any model's default in
|
|
57
|
+
* /configure-models).
|
|
58
|
+
*
|
|
59
|
+
* Config (environment variables, all optional; /login is the easy path)
|
|
60
|
+
* ---------------------------------------------------------------------
|
|
61
|
+
* UVA_API_KEY API key, if you prefer env over /login.
|
|
62
|
+
* UVA_BASE_URL Default: https://llmproxy.uva.nl/v1
|
|
63
|
+
* UVA_PROVIDER_ID Provider id in /models. Default: uva
|
|
64
|
+
* UVA_CREDENTIALS_FILE Override the saved-credentials path.
|
|
65
|
+
* UVA_NO_AUTO_THINKING Set to disable the medium thinking default.
|
|
66
|
+
*
|
|
67
|
+
* Only imports the aliased root "@earendil-works/pi-ai" (the extension-facing
|
|
68
|
+
* compat surface), so it works under Pi's jiti extension loader.
|
|
69
|
+
*/
|
|
70
|
+
|
|
71
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
72
|
+
import { getApiProvider, createAssistantMessageEventStream, calculateCost } from "@earendil-works/pi-ai";
|
|
73
|
+
|
|
74
|
+
const BASE_API = "openai-responses"; // pristine built-in handler we delegate to
|
|
75
|
+
const CUSTOM_API = "openai-responses-uva"; // our fixed handler is registered under this
|
|
76
|
+
const DEFAULT_BASE_URL = "https://llmproxy.uva.nl/v1";
|
|
77
|
+
const BASE_URL_PRESETS: Record<string, string> = {
|
|
78
|
+
uva: "https://llmproxy.uva.nl/v1",
|
|
79
|
+
hva: "https://llmproxy.hva.nl/v1",
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const PROVIDER_ID = process.env.UVA_PROVIDER_ID || "uva";
|
|
83
|
+
|
|
84
|
+
// Active connection settings. Seeded from env, overridden by saved credentials
|
|
85
|
+
// (from the /login flow) at startup, and updated live on login.
|
|
86
|
+
let activeBaseUrl = (process.env.UVA_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
87
|
+
let activeApiKey: string | undefined = process.env.UVA_API_KEY || process.env.OPENAI_API_KEY;
|
|
88
|
+
|
|
89
|
+
// Persisted login (base URL + API key) so model discovery works at the next
|
|
90
|
+
// startup with nothing re-entered. Path overridable via UVA_CREDENTIALS_FILE.
|
|
91
|
+
function credsFile(): string {
|
|
92
|
+
if (process.env.UVA_CREDENTIALS_FILE) return process.env.UVA_CREDENTIALS_FILE;
|
|
93
|
+
const os = require("node:os");
|
|
94
|
+
const { join } = require("node:path");
|
|
95
|
+
return join(os.homedir(), ".pi", "agent", "openai-responses-uva.json");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function loadCreds(): { baseUrl?: string; apiKey?: string } | null {
|
|
99
|
+
try {
|
|
100
|
+
const { readFileSync } = require("node:fs");
|
|
101
|
+
const parsed = JSON.parse(readFileSync(credsFile(), "utf8"));
|
|
102
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
103
|
+
} catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function saveCreds(creds: { baseUrl: string; apiKey: string }): void {
|
|
109
|
+
const { writeFileSync, mkdirSync, chmodSync } = require("node:fs");
|
|
110
|
+
const { dirname } = require("node:path");
|
|
111
|
+
const file = credsFile();
|
|
112
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
113
|
+
writeFileSync(file, JSON.stringify(creds, null, 2));
|
|
114
|
+
try {
|
|
115
|
+
chmodSync(file, 0o600); // best-effort owner-only
|
|
116
|
+
} catch {
|
|
117
|
+
/* ignore */
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Models that are not chat/response models, never register these.
|
|
122
|
+
const DENY = /embedding|whisper|audio|tts|speech|dall|(^|[-_])image|document-ai|ocr|rerank|moderation|guard|stable-diffusion/i;
|
|
123
|
+
|
|
124
|
+
// Known-good fallback if /v1/models discovery fails.
|
|
125
|
+
const FALLBACK_MODEL_IDS = ["gpt-5.6-sol", "gpt-5.6-luna", "gpt-5.5", "gpt-5.1", "gpt-5", "gpt-4.1", "gpt-4o"];
|
|
126
|
+
|
|
127
|
+
// ---------------------------------------------------------------------------
|
|
128
|
+
// FALLBACK capability table.
|
|
129
|
+
//
|
|
130
|
+
// The primary source of truth is the proxy's own /model_group/info (real
|
|
131
|
+
// context window, max output, reasoning/vision support, cost, backend). This
|
|
132
|
+
// table only fills fields the proxy leaves blank, common for brand-new
|
|
133
|
+
// deployments whose metadata isn't populated yet (e.g. gpt-5.6-* report empty
|
|
134
|
+
// token limits), and is the whole story only if /model_group/info is
|
|
135
|
+
// unavailable and discovery falls back to /v1/models (ids only).
|
|
136
|
+
//
|
|
137
|
+
// Values are researched per model family. Any positive signal (metadata OR this
|
|
138
|
+
// table) enables reasoning/vision, so a new model is never worse off than its
|
|
139
|
+
// name family. Override per-id via UVA_MODEL_OVERRIDES_FILE.
|
|
140
|
+
//
|
|
141
|
+
// First matching entry wins; order matters (specific → general).
|
|
142
|
+
// ---------------------------------------------------------------------------
|
|
143
|
+
|
|
144
|
+
type Caps = { ctx: number; out: number; reasoning: boolean; vision: boolean };
|
|
145
|
+
|
|
146
|
+
const CAPS: Array<{ re: RegExp; caps: Caps }> = [
|
|
147
|
+
// OpenAI GPT-5.x
|
|
148
|
+
{ re: /^gpt-5\.6/i, caps: { ctx: 1_100_000, out: 128_000, reasoning: true, vision: true } },
|
|
149
|
+
{ re: /^gpt-5\.[45]/i, caps: { ctx: 1_050_000, out: 128_000, reasoning: true, vision: true } },
|
|
150
|
+
{ re: /^gpt-5\.1/i, caps: { ctx: 400_000, out: 128_000, reasoning: true, vision: true } },
|
|
151
|
+
{ re: /^gpt-5(-|$)/i, caps: { ctx: 400_000, out: 128_000, reasoning: true, vision: true } }, // gpt-5 / -mini / -nano
|
|
152
|
+
// OpenAI o-series (o3-mini is text-only)
|
|
153
|
+
{ re: /^o[134](-|$)/i, caps: { ctx: 200_000, out: 100_000, reasoning: true, vision: false } },
|
|
154
|
+
// OpenAI open-weight
|
|
155
|
+
{ re: /gpt-oss/i, caps: { ctx: 131_072, out: 32_768, reasoning: true, vision: false } },
|
|
156
|
+
// OpenAI GPT-4.x (not reasoning)
|
|
157
|
+
{ re: /^gpt-4\.1/i, caps: { ctx: 1_047_576, out: 32_768, reasoning: false, vision: true } },
|
|
158
|
+
{ re: /^gpt-4o/i, caps: { ctx: 128_000, out: 16_384, reasoning: false, vision: true } },
|
|
159
|
+
{ re: /^gpt-4/i, caps: { ctx: 128_000, out: 16_384, reasoning: false, vision: true } },
|
|
160
|
+
{ re: /model-router/i, caps: { ctx: 256_000, out: 32_768, reasoning: false, vision: true } },
|
|
161
|
+
// Anthropic Claude 4.x / 5.x (thinking left off for reliable proxy translation)
|
|
162
|
+
{ re: /claude-opus/i, caps: { ctx: 1_000_000, out: 64_000, reasoning: false, vision: true } },
|
|
163
|
+
{ re: /claude-sonnet-4\.6|claude-sonnet-[5-9]/i, caps: { ctx: 1_000_000, out: 64_000, reasoning: false, vision: true } },
|
|
164
|
+
{ re: /claude-sonnet/i, caps: { ctx: 200_000, out: 64_000, reasoning: false, vision: true } },
|
|
165
|
+
{ re: /claude-haiku/i, caps: { ctx: 200_000, out: 64_000, reasoning: false, vision: true } },
|
|
166
|
+
{ re: /claude/i, caps: { ctx: 200_000, out: 64_000, reasoning: false, vision: true } },
|
|
167
|
+
// Qwen (VL = vision; Qwen3 text, thinking not exposed via responses effort)
|
|
168
|
+
{ re: /qwen.*vl|vl.*qwen/i, caps: { ctx: 128_000, out: 8_192, reasoning: false, vision: true } },
|
|
169
|
+
{ re: /qwen/i, caps: { ctx: 262_144, out: 32_768, reasoning: false, vision: false } },
|
|
170
|
+
// Mistral (small 3.x is multimodal)
|
|
171
|
+
{ re: /mistral-small/i, caps: { ctx: 128_000, out: 32_768, reasoning: false, vision: true } },
|
|
172
|
+
{ re: /mistral/i, caps: { ctx: 128_000, out: 32_768, reasoning: false, vision: false } },
|
|
173
|
+
// Google (if the proxy ever exposes it)
|
|
174
|
+
{ re: /gemini/i, caps: { ctx: 1_000_000, out: 65_536, reasoning: false, vision: true } },
|
|
175
|
+
];
|
|
176
|
+
|
|
177
|
+
// Safe map for reasoning models: low/medium/high are supported by every OpenAI
|
|
178
|
+
// reasoning family; minimal/xhigh/max are hidden because support varies.
|
|
179
|
+
const REASONING_THINKING_MAP = {
|
|
180
|
+
minimal: null,
|
|
181
|
+
low: "low",
|
|
182
|
+
medium: "medium",
|
|
183
|
+
high: "high",
|
|
184
|
+
xhigh: null,
|
|
185
|
+
max: null,
|
|
186
|
+
} as const;
|
|
187
|
+
|
|
188
|
+
// Endpoint routing. Some models speak the OpenAI Responses API (/v1/responses);
|
|
189
|
+
// open-weight vLLM deployments only speak /v1/chat/completions and 404 on
|
|
190
|
+
// /responses. We derive this from the proxy's own /model_group/info metadata
|
|
191
|
+
// (backend `providers`), fall back to a name regex when metadata is absent, and
|
|
192
|
+
// SELF-HEAL at runtime: a Responses turn that 404s is retried on
|
|
193
|
+
// chat-completions and the id is remembered for the rest of the session.
|
|
194
|
+
const RESPONSES_CAPABLE = /^(gpt-4|gpt-5|o[0-9]|claude|model-router|grok|gemini)/i;
|
|
195
|
+
const RESPONSES_PROVIDERS = /azure|bedrock|vertex|anthropic|openai_responses/i;
|
|
196
|
+
|
|
197
|
+
// The model defs from the most recent registration (for the /configure-models
|
|
198
|
+
// menu to show current effective values).
|
|
199
|
+
let currentModels: any[] = [];
|
|
200
|
+
|
|
201
|
+
// id -> route, seeded at registration from metadata / name.
|
|
202
|
+
const modelRoutes = new Map<string, "responses" | "chat">();
|
|
203
|
+
// Runtime self-heal overrides (win over modelRoutes, survive re-registration).
|
|
204
|
+
const routeOverrides = new Map<string, "responses" | "chat">();
|
|
205
|
+
|
|
206
|
+
function routeForModel(id: string, providers?: string[]): "responses" | "chat" {
|
|
207
|
+
if (routeOverrides.has(id)) return routeOverrides.get(id)!;
|
|
208
|
+
if (providers && providers.length) {
|
|
209
|
+
return providers.some((p) => RESPONSES_PROVIDERS.test(p)) ? "responses" : "chat";
|
|
210
|
+
}
|
|
211
|
+
return RESPONSES_CAPABLE.test(id) ? "responses" : "chat";
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function currentRoute(id: string): "responses" | "chat" {
|
|
215
|
+
return routeOverrides.get(id) ?? modelRoutes.get(id) ?? (RESPONSES_CAPABLE.test(id) ? "responses" : "chat");
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function resolveCaps(id: string): Caps {
|
|
219
|
+
for (const { re, caps } of CAPS) if (re.test(id)) return caps;
|
|
220
|
+
// Unknown / future model: infer conservatively.
|
|
221
|
+
const reasoning = /gpt-5|gpt-oss/i.test(id) || /^o[134](-|$)/i.test(id);
|
|
222
|
+
const vision = /gpt-4|gpt-5|claude|gemini|vl|vision|nova/i.test(id);
|
|
223
|
+
return { ctx: reasoning ? 400_000 : 128_000, out: reasoning ? 128_000 : 16_384, reasoning, vision };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// Every model is registered under CUSTOM_API so our streamSimple always runs and
|
|
227
|
+
// decides the endpoint per turn (with self-heal). Capabilities are taken from
|
|
228
|
+
// the proxy metadata when present, falling back to the researched CAPS table for
|
|
229
|
+
// fields the proxy leaves blank (common for brand-new deployments).
|
|
230
|
+
function buildModelDef(info: ModelInfo, overrides: Record<string, any>) {
|
|
231
|
+
const id = info.id;
|
|
232
|
+
const caps = resolveCaps(id);
|
|
233
|
+
const ov = overrides[id] || {};
|
|
234
|
+
const route = routeForModel(id, info.providers);
|
|
235
|
+
modelRoutes.set(id, route);
|
|
236
|
+
const isResponses = route === "responses";
|
|
237
|
+
// Reasoning only on the Responses route (chat-completions rejects
|
|
238
|
+
// reasoning_effort with tools). Any positive signal enables it; incomplete
|
|
239
|
+
// metadata (all-false on new models) is corrected by the CAPS fallback.
|
|
240
|
+
const reasoning = ov.reasoning ?? (isResponses && ((info.reasoning ?? false) || caps.reasoning));
|
|
241
|
+
const vision = ov.vision ?? ((info.vision ?? false) || caps.vision);
|
|
242
|
+
const ctx = ov.contextWindow ?? (info.ctx && info.ctx > 0 ? info.ctx : caps.ctx);
|
|
243
|
+
const out = ov.maxTokens ?? (info.out && info.out > 0 ? info.out : caps.out);
|
|
244
|
+
const hasCost = !!info.cost && (info.cost.input > 0 || info.cost.output > 0);
|
|
245
|
+
const cost = ov.cost ?? (hasCost ? info.cost : { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
|
|
246
|
+
return {
|
|
247
|
+
id,
|
|
248
|
+
name: ov.name || `${id} (UvA)`,
|
|
249
|
+
api: CUSTOM_API,
|
|
250
|
+
reasoning,
|
|
251
|
+
input: (ov.input as string[]) || (vision ? ["text", "image"] : ["text"]),
|
|
252
|
+
cost,
|
|
253
|
+
contextWindow: ctx,
|
|
254
|
+
maxTokens: out,
|
|
255
|
+
...(reasoning ? { thinkingLevelMap: ov.thinkingLevelMap || REASONING_THINKING_MAP } : {}),
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Per-id capability overrides (context window, reasoning, default thinking
|
|
260
|
+
// level, ...) written by the /configure-models menu. Path is
|
|
261
|
+
// UVA_MODEL_OVERRIDES_FILE or ~/.pi/agent/openai-responses-uva.models.json.
|
|
262
|
+
function overridesFile(): string {
|
|
263
|
+
if (process.env.UVA_MODEL_OVERRIDES_FILE) return process.env.UVA_MODEL_OVERRIDES_FILE;
|
|
264
|
+
const os = require("node:os");
|
|
265
|
+
const { join } = require("node:path");
|
|
266
|
+
return join(os.homedir(), ".pi", "agent", "openai-responses-uva.models.json");
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function loadOverrides(): Record<string, any> {
|
|
270
|
+
try {
|
|
271
|
+
const { readFileSync } = require("node:fs");
|
|
272
|
+
const parsed = JSON.parse(readFileSync(overridesFile(), "utf8"));
|
|
273
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
274
|
+
} catch {
|
|
275
|
+
return {};
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function saveOverrides(obj: Record<string, any>): void {
|
|
280
|
+
const { writeFileSync, mkdirSync } = require("node:fs");
|
|
281
|
+
const { dirname } = require("node:path");
|
|
282
|
+
const file = overridesFile();
|
|
283
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
284
|
+
writeFileSync(file, JSON.stringify(obj, null, 2));
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
type ModelInfo = {
|
|
288
|
+
id: string;
|
|
289
|
+
ctx?: number;
|
|
290
|
+
out?: number;
|
|
291
|
+
reasoning?: boolean;
|
|
292
|
+
vision?: boolean;
|
|
293
|
+
cost?: { input: number; output: number; cacheRead: number; cacheWrite: number };
|
|
294
|
+
providers?: string[];
|
|
295
|
+
mode?: string;
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
// Non-chat model modes to skip (LiteLLM `mode` from /model_group/info).
|
|
299
|
+
const EXCLUDED_MODES = new Set([
|
|
300
|
+
"embedding",
|
|
301
|
+
"ocr",
|
|
302
|
+
"image_generation",
|
|
303
|
+
"moderation",
|
|
304
|
+
"rerank",
|
|
305
|
+
"audio",
|
|
306
|
+
"transcription",
|
|
307
|
+
"image",
|
|
308
|
+
]);
|
|
309
|
+
|
|
310
|
+
// Rich per-model metadata from LiteLLM's /model_group/info: real context window,
|
|
311
|
+
// max output, reasoning/vision support, backend providers, and cost. This is the
|
|
312
|
+
// source of truth that lets the extension adapt when the model line-up changes.
|
|
313
|
+
async function fetchModelInfos(apiKey: string | undefined, baseUrl: string): Promise<ModelInfo[]> {
|
|
314
|
+
const root = baseUrl.replace(/\/+$/, "").replace(/\/v1$/, "");
|
|
315
|
+
const res = await fetch(`${root}/model_group/info`, {
|
|
316
|
+
headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {},
|
|
317
|
+
});
|
|
318
|
+
if (!res.ok) throw new Error(`GET ${root}/model_group/info -> HTTP ${res.status}`);
|
|
319
|
+
const data: any = await res.json();
|
|
320
|
+
const rows = Array.isArray(data?.data) ? data.data : [];
|
|
321
|
+
const perM = (v: any) => (typeof v === "number" && v > 0 ? v * 1_000_000 : 0);
|
|
322
|
+
const infos: ModelInfo[] = [];
|
|
323
|
+
for (const m of rows) {
|
|
324
|
+
const id = m?.model_group;
|
|
325
|
+
if (typeof id !== "string" || !id) continue;
|
|
326
|
+
const params: string[] = Array.isArray(m.supported_openai_params) ? m.supported_openai_params : [];
|
|
327
|
+
infos.push({
|
|
328
|
+
id,
|
|
329
|
+
mode: typeof m.mode === "string" ? m.mode : "",
|
|
330
|
+
providers: Array.isArray(m.providers) ? m.providers : [],
|
|
331
|
+
ctx: typeof m.max_input_tokens === "number" ? m.max_input_tokens : 0,
|
|
332
|
+
out: typeof m.max_output_tokens === "number" ? m.max_output_tokens : 0,
|
|
333
|
+
reasoning: !!m.supports_reasoning || params.includes("reasoning_effort"),
|
|
334
|
+
vision: !!m.supports_vision,
|
|
335
|
+
cost: {
|
|
336
|
+
input: perM(m.input_cost_per_token),
|
|
337
|
+
output: perM(m.output_cost_per_token),
|
|
338
|
+
cacheRead: perM(m.cache_read_input_token_cost),
|
|
339
|
+
cacheWrite: perM(m.cache_creation_input_token_cost),
|
|
340
|
+
},
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
return infos;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// Fallback discovery: /v1/models returns ids only (no capabilities).
|
|
347
|
+
async function fetchModelIds(apiKey: string | undefined, baseUrl: string): Promise<string[]> {
|
|
348
|
+
const root = baseUrl.replace(/\/+$/, "");
|
|
349
|
+
const res = await fetch(`${root}/models`, {
|
|
350
|
+
headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {},
|
|
351
|
+
});
|
|
352
|
+
if (!res.ok) throw new Error(`GET ${root}/models -> HTTP ${res.status}`);
|
|
353
|
+
const data: any = await res.json();
|
|
354
|
+
const ids = (Array.isArray(data?.data) ? data.data : [])
|
|
355
|
+
.map((m: any) => m?.id)
|
|
356
|
+
.filter((id: any): id is string => typeof id === "string" && id.length > 0);
|
|
357
|
+
if (ids.length === 0) throw new Error("no models returned by /v1/models");
|
|
358
|
+
return ids;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// Layered discovery: rich metadata first, ids-only fallback. Throws only if
|
|
362
|
+
// BOTH fail, so /login can detect a bad key/URL.
|
|
363
|
+
async function discoverModels(apiKey: string | undefined, baseUrl: string): Promise<ModelInfo[]> {
|
|
364
|
+
try {
|
|
365
|
+
const infos = await fetchModelInfos(apiKey, baseUrl);
|
|
366
|
+
if (infos.length) return infos;
|
|
367
|
+
} catch (err) {
|
|
368
|
+
console.error(
|
|
369
|
+
`[openai-responses-uva] /model_group/info unavailable (${err instanceof Error ? err.message : String(err)}); falling back to /v1/models.`,
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
const ids = await fetchModelIds(apiKey, baseUrl);
|
|
373
|
+
return ids.map((id) => ({ id }));
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// ---------------------------------------------------------------------------
|
|
377
|
+
// Stream fix
|
|
378
|
+
// ---------------------------------------------------------------------------
|
|
379
|
+
|
|
380
|
+
function encodeTextSignatureV1(id: string, phase?: string): string {
|
|
381
|
+
return JSON.stringify(phase ? { v: 1, id, phase } : { v: 1, id });
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function mapStopReason(status: string | undefined): string {
|
|
385
|
+
switch (status) {
|
|
386
|
+
case "completed":
|
|
387
|
+
return "stop";
|
|
388
|
+
case "incomplete":
|
|
389
|
+
return "length";
|
|
390
|
+
case "failed":
|
|
391
|
+
case "cancelled":
|
|
392
|
+
return "error";
|
|
393
|
+
default:
|
|
394
|
+
return "stop";
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** Capture the exact request params the built-in handler would send, without sending. */
|
|
399
|
+
function captureParams(builtin: any, model: any, context: any, options: any): Promise<any> {
|
|
400
|
+
return new Promise((resolve) => {
|
|
401
|
+
let settled = false;
|
|
402
|
+
const finish = (v: any) => {
|
|
403
|
+
if (!settled) {
|
|
404
|
+
settled = true;
|
|
405
|
+
resolve(v);
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
let probe: any;
|
|
409
|
+
try {
|
|
410
|
+
const clone = { ...model, api: BASE_API };
|
|
411
|
+
probe = builtin.streamSimple(clone, context, {
|
|
412
|
+
...options,
|
|
413
|
+
onPayload: (params: any) => {
|
|
414
|
+
finish(params);
|
|
415
|
+
throw new Error("__uva_capture_done__");
|
|
416
|
+
},
|
|
417
|
+
});
|
|
418
|
+
} catch {
|
|
419
|
+
finish(null);
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
(async () => {
|
|
423
|
+
try {
|
|
424
|
+
for await (const _ of probe) {
|
|
425
|
+
/* drain; the probe ends via the thrown onPayload */
|
|
426
|
+
}
|
|
427
|
+
} catch {
|
|
428
|
+
/* ignore */
|
|
429
|
+
}
|
|
430
|
+
finish(null); // in case onPayload never ran
|
|
431
|
+
})();
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** Emit Pi content events for a single Responses `output[]` item. */
|
|
436
|
+
function emitOneItem(out: any, output: any, item: any): void {
|
|
437
|
+
if (item?.type === "reasoning") {
|
|
438
|
+
const thinking =
|
|
439
|
+
(item.summary && item.summary.map((s: any) => s?.text || "").join("\n\n")) ||
|
|
440
|
+
(item.content && item.content.map((c: any) => c?.text || "").join("\n\n")) ||
|
|
441
|
+
"";
|
|
442
|
+
const block: any = { type: "thinking", thinking, thinkingSignature: JSON.stringify(item) };
|
|
443
|
+
output.content.push(block);
|
|
444
|
+
const i = output.content.length - 1;
|
|
445
|
+
out.push({ type: "thinking_start", contentIndex: i, partial: output });
|
|
446
|
+
if (thinking) out.push({ type: "thinking_delta", contentIndex: i, delta: thinking, partial: output });
|
|
447
|
+
out.push({ type: "thinking_end", contentIndex: i, content: thinking, partial: output });
|
|
448
|
+
} else if (item?.type === "message") {
|
|
449
|
+
const parts = Array.isArray(item.content) ? item.content : [];
|
|
450
|
+
const text = parts
|
|
451
|
+
.map((c: any) => (c?.type === "output_text" ? c.text || "" : c?.type === "refusal" ? c.refusal || "" : ""))
|
|
452
|
+
.join("");
|
|
453
|
+
const block: any = { type: "text", text, textSignature: encodeTextSignatureV1(item.id, item.phase ?? undefined) };
|
|
454
|
+
output.content.push(block);
|
|
455
|
+
const i = output.content.length - 1;
|
|
456
|
+
out.push({ type: "text_start", contentIndex: i, partial: output });
|
|
457
|
+
if (text) out.push({ type: "text_delta", contentIndex: i, delta: text, partial: output });
|
|
458
|
+
out.push({ type: "text_end", contentIndex: i, content: text, partial: output });
|
|
459
|
+
} else if (item?.type === "function_call") {
|
|
460
|
+
let args: any = {};
|
|
461
|
+
try {
|
|
462
|
+
args = JSON.parse(item.arguments || "{}");
|
|
463
|
+
} catch {
|
|
464
|
+
args = {};
|
|
465
|
+
}
|
|
466
|
+
const block: any = { type: "toolCall", id: `${item.call_id}|${item.id}`, name: item.name, arguments: args };
|
|
467
|
+
output.content.push(block);
|
|
468
|
+
const i = output.content.length - 1;
|
|
469
|
+
out.push({ type: "toolcall_start", contentIndex: i, partial: output });
|
|
470
|
+
out.push({ type: "toolcall_end", contentIndex: i, toolCall: block, partial: output });
|
|
471
|
+
}
|
|
472
|
+
// other item types (e.g. bare encrypted reasoning) are ignored
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Reconcile the terminal `output[]` against what was already emitted
|
|
477
|
+
* incrementally. Any item whose id was NOT seen in the incremental event
|
|
478
|
+
* stream is emitted now. This covers:
|
|
479
|
+
* - full collapse (no incremental events) -> emit everything
|
|
480
|
+
* - partial collapse (e.g. text streamed but the tool call only appears in
|
|
481
|
+
* the terminal payload, as Anthropic/Bedrock does) -> emit the missing item
|
|
482
|
+
*/
|
|
483
|
+
function reconcileTerminal(out: any, output: any, terminal: any, seenIds: Set<string>): void {
|
|
484
|
+
const items = Array.isArray(terminal?.output) ? terminal.output : [];
|
|
485
|
+
for (const item of items) {
|
|
486
|
+
const id = item?.id;
|
|
487
|
+
if (id && seenIds.has(id)) continue;
|
|
488
|
+
emitOneItem(out, output, item);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function applyUsage(output: any, data: any, model: any): void {
|
|
493
|
+
const u = data?.usage;
|
|
494
|
+
if (u) {
|
|
495
|
+
const cached = u.input_tokens_details?.cached_tokens || 0;
|
|
496
|
+
const cacheWrite = u.input_tokens_details?.cache_write_tokens || 0;
|
|
497
|
+
output.usage.input = Math.max(0, (u.input_tokens || 0) - cached - cacheWrite);
|
|
498
|
+
output.usage.output = u.output_tokens || 0;
|
|
499
|
+
output.usage.cacheRead = cached;
|
|
500
|
+
output.usage.cacheWrite = cacheWrite;
|
|
501
|
+
output.usage.reasoning = u.output_tokens_details?.reasoning_tokens || 0;
|
|
502
|
+
output.usage.totalTokens = u.total_tokens || output.usage.input + output.usage.output + cached + cacheWrite;
|
|
503
|
+
}
|
|
504
|
+
try {
|
|
505
|
+
calculateCost(model, output.usage);
|
|
506
|
+
} catch {
|
|
507
|
+
/* cost is best-effort */
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
512
|
+
|
|
513
|
+
// OpenAI-native families (Azure backend) accept OpenAI-only request params like
|
|
514
|
+
// `prompt_cache_key`. Non-OpenAI backends behind the proxy (Anthropic/Bedrock,
|
|
515
|
+
// Gemini/Vertex, Mistral, Qwen, ...) reject them, e.g.
|
|
516
|
+
// "prompt_cache_key: Extra inputs are not permitted"
|
|
517
|
+
// Keep the param only for OpenAI-native ids; strip it everywhere else (the only
|
|
518
|
+
// cost is losing prompt caching on backends that would have accepted it).
|
|
519
|
+
const OPENAI_NATIVE = /^(gpt-|o[134]([-_]|$)|gpt-oss|model-router)/i;
|
|
520
|
+
|
|
521
|
+
function sanitizeParamsForModel(modelId: string, params: any): any {
|
|
522
|
+
if (OPENAI_NATIVE.test(modelId)) return params;
|
|
523
|
+
const p = { ...params };
|
|
524
|
+
delete p.prompt_cache_key;
|
|
525
|
+
delete p.prompt_cache_retention;
|
|
526
|
+
return p;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* Translate one Responses SSE event into Pi events + block state.
|
|
531
|
+
* Handles the full incremental event set (good streaming case) and records the
|
|
532
|
+
* terminal `response.completed` payload (whose `output[]` is harvested by the
|
|
533
|
+
* caller when the proxy sent no incremental events, the tools-collapse case).
|
|
534
|
+
*/
|
|
535
|
+
function handleSseEvent(
|
|
536
|
+
evt: any,
|
|
537
|
+
out: any,
|
|
538
|
+
output: any,
|
|
539
|
+
slots: Map<number, any>,
|
|
540
|
+
seenIds: Set<string>,
|
|
541
|
+
setTerminal: (r: any) => void,
|
|
542
|
+
): void {
|
|
543
|
+
const t = evt?.type;
|
|
544
|
+
if (t === "response.output_item.added") {
|
|
545
|
+
const item = evt.item;
|
|
546
|
+
const oi = evt.output_index;
|
|
547
|
+
if (item?.id) seenIds.add(item.id);
|
|
548
|
+
if (item?.type === "reasoning") {
|
|
549
|
+
const block: any = { type: "thinking", thinking: "" };
|
|
550
|
+
output.content.push(block);
|
|
551
|
+
const ci = output.content.length - 1;
|
|
552
|
+
slots.set(oi, { type: "thinking", block, ci });
|
|
553
|
+
out.push({ type: "thinking_start", contentIndex: ci, partial: output });
|
|
554
|
+
} else if (item?.type === "message") {
|
|
555
|
+
const block: any = { type: "text", text: "" };
|
|
556
|
+
output.content.push(block);
|
|
557
|
+
const ci = output.content.length - 1;
|
|
558
|
+
slots.set(oi, { type: "text", block, ci });
|
|
559
|
+
out.push({ type: "text_start", contentIndex: ci, partial: output });
|
|
560
|
+
} else if (item?.type === "function_call") {
|
|
561
|
+
const block: any = {
|
|
562
|
+
type: "toolCall",
|
|
563
|
+
id: `${item.call_id}|${item.id}`,
|
|
564
|
+
name: item.name,
|
|
565
|
+
arguments: {},
|
|
566
|
+
partialJson: item.arguments || "",
|
|
567
|
+
};
|
|
568
|
+
output.content.push(block);
|
|
569
|
+
const ci = output.content.length - 1;
|
|
570
|
+
slots.set(oi, { type: "toolCall", block, ci });
|
|
571
|
+
out.push({ type: "toolcall_start", contentIndex: ci, partial: output });
|
|
572
|
+
}
|
|
573
|
+
} else if (t === "response.output_text.delta") {
|
|
574
|
+
const slot = slots.get(evt.output_index);
|
|
575
|
+
if (slot?.type === "text") {
|
|
576
|
+
slot.block.text += evt.delta || "";
|
|
577
|
+
out.push({ type: "text_delta", contentIndex: slot.ci, delta: evt.delta || "", partial: output });
|
|
578
|
+
}
|
|
579
|
+
} else if (t === "response.reasoning_summary_text.delta") {
|
|
580
|
+
const slot = slots.get(evt.output_index);
|
|
581
|
+
if (slot?.type === "thinking") {
|
|
582
|
+
slot.block.thinking += evt.delta || "";
|
|
583
|
+
out.push({ type: "thinking_delta", contentIndex: slot.ci, delta: evt.delta || "", partial: output });
|
|
584
|
+
}
|
|
585
|
+
} else if (t === "response.function_call_arguments.delta") {
|
|
586
|
+
const slot = slots.get(evt.output_index);
|
|
587
|
+
if (slot?.type === "toolCall") {
|
|
588
|
+
slot.block.partialJson = (slot.block.partialJson || "") + (evt.delta || "");
|
|
589
|
+
out.push({ type: "toolcall_delta", contentIndex: slot.ci, delta: evt.delta || "", partial: output });
|
|
590
|
+
}
|
|
591
|
+
} else if (t === "response.output_item.done") {
|
|
592
|
+
const item = evt.item;
|
|
593
|
+
if (item?.id) seenIds.add(item.id);
|
|
594
|
+
const slot = slots.get(evt.output_index);
|
|
595
|
+
if (item?.type === "reasoning" && slot?.type === "thinking") {
|
|
596
|
+
const summary =
|
|
597
|
+
(item.summary && item.summary.map((s: any) => s?.text || "").join("\n\n")) ||
|
|
598
|
+
(item.content && item.content.map((c: any) => c?.text || "").join("\n\n")) ||
|
|
599
|
+
slot.block.thinking;
|
|
600
|
+
slot.block.thinking = summary;
|
|
601
|
+
slot.block.thinkingSignature = JSON.stringify(item);
|
|
602
|
+
out.push({ type: "thinking_end", contentIndex: slot.ci, content: slot.block.thinking, partial: output });
|
|
603
|
+
slots.delete(evt.output_index);
|
|
604
|
+
} else if (item?.type === "message" && slot?.type === "text") {
|
|
605
|
+
const text =
|
|
606
|
+
(item.content &&
|
|
607
|
+
item.content
|
|
608
|
+
.map((c: any) => (c?.type === "output_text" ? c.text || "" : c?.type === "refusal" ? c.refusal || "" : ""))
|
|
609
|
+
.join("")) ||
|
|
610
|
+
slot.block.text;
|
|
611
|
+
slot.block.text = text;
|
|
612
|
+
slot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);
|
|
613
|
+
out.push({ type: "text_end", contentIndex: slot.ci, content: text, partial: output });
|
|
614
|
+
slots.delete(evt.output_index);
|
|
615
|
+
} else if (item?.type === "function_call" && slot?.type === "toolCall") {
|
|
616
|
+
let args: any = {};
|
|
617
|
+
try {
|
|
618
|
+
args = JSON.parse(item.arguments || slot.block.partialJson || "{}");
|
|
619
|
+
} catch {
|
|
620
|
+
args = {};
|
|
621
|
+
}
|
|
622
|
+
slot.block.arguments = args;
|
|
623
|
+
delete slot.block.partialJson;
|
|
624
|
+
out.push({ type: "toolcall_end", contentIndex: slot.ci, toolCall: slot.block, partial: output });
|
|
625
|
+
slots.delete(evt.output_index);
|
|
626
|
+
}
|
|
627
|
+
} else if (t === "response.completed" || t === "response.incomplete") {
|
|
628
|
+
setTerminal(evt.response);
|
|
629
|
+
} else if (t === "response.failed") {
|
|
630
|
+
const e = evt.response?.error;
|
|
631
|
+
throw new Error(`openai-responses-uva: ${e?.code || "failed"}: ${e?.message || "no message"}`);
|
|
632
|
+
} else if (t === "error") {
|
|
633
|
+
throw new Error(`openai-responses-uva: stream error: ${evt.message || evt.code || "unknown"}`);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* One streaming attempt. Streaming keeps the gateway connection alive (bytes
|
|
639
|
+
* flow) so slow generations don't hit an nginx 504. `state.started` is set once
|
|
640
|
+
* we begin emitting, so the caller only retries failures that happen before any
|
|
641
|
+
* output was produced.
|
|
642
|
+
*/
|
|
643
|
+
async function attemptStream(
|
|
644
|
+
url: string,
|
|
645
|
+
apiKey: string,
|
|
646
|
+
body: any,
|
|
647
|
+
out: any,
|
|
648
|
+
output: any,
|
|
649
|
+
model: any,
|
|
650
|
+
signal: any,
|
|
651
|
+
onResponse: any,
|
|
652
|
+
state: { started: boolean },
|
|
653
|
+
): Promise<void> {
|
|
654
|
+
const res = await fetch(url, {
|
|
655
|
+
method: "POST",
|
|
656
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
|
|
657
|
+
body: JSON.stringify(body),
|
|
658
|
+
...(signal ? { signal } : {}),
|
|
659
|
+
});
|
|
660
|
+
try {
|
|
661
|
+
await onResponse?.({ status: res.status, headers: {} }, model);
|
|
662
|
+
} catch {
|
|
663
|
+
/* ignore */
|
|
664
|
+
}
|
|
665
|
+
if (!res.ok || !res.body) {
|
|
666
|
+
const text = await res.text().catch(() => "");
|
|
667
|
+
const err: any = new Error(`openai-responses-uva: HTTP ${res.status}: ${text.slice(0, 200).replace(/\s+/g, " ")}`);
|
|
668
|
+
err.status = res.status;
|
|
669
|
+
throw err;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
state.started = true;
|
|
673
|
+
out.push({ type: "start", partial: output });
|
|
674
|
+
|
|
675
|
+
const reader = (res.body as any).getReader();
|
|
676
|
+
const decoder = new TextDecoder();
|
|
677
|
+
const slots = new Map<number, any>();
|
|
678
|
+
const seenIds = new Set<string>();
|
|
679
|
+
let terminal: any = null;
|
|
680
|
+
let buffer = "";
|
|
681
|
+
|
|
682
|
+
const drainChunk = (chunk: string) => {
|
|
683
|
+
for (const line of chunk.split("\n")) {
|
|
684
|
+
const s = line.trim();
|
|
685
|
+
if (!s.startsWith("data:")) continue;
|
|
686
|
+
const payload = s.slice(5).trim();
|
|
687
|
+
if (!payload || payload === "[DONE]") continue;
|
|
688
|
+
let evt: any;
|
|
689
|
+
try {
|
|
690
|
+
evt = JSON.parse(payload);
|
|
691
|
+
} catch {
|
|
692
|
+
continue;
|
|
693
|
+
}
|
|
694
|
+
handleSseEvent(evt, out, output, slots, seenIds, (r) => (terminal = r));
|
|
695
|
+
}
|
|
696
|
+
};
|
|
697
|
+
|
|
698
|
+
while (true) {
|
|
699
|
+
const { done, value } = await reader.read();
|
|
700
|
+
if (done) break;
|
|
701
|
+
buffer += decoder.decode(value, { stream: true });
|
|
702
|
+
let i: number;
|
|
703
|
+
while ((i = buffer.indexOf("\n\n")) !== -1) {
|
|
704
|
+
drainChunk(buffer.slice(0, i));
|
|
705
|
+
buffer = buffer.slice(i + 2);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
if (buffer.trim()) drainChunk(buffer);
|
|
709
|
+
|
|
710
|
+
// Close any slots the proxy left open without an output_item.done.
|
|
711
|
+
for (const slot of slots.values()) {
|
|
712
|
+
if (slot.type === "text") {
|
|
713
|
+
out.push({ type: "text_end", contentIndex: slot.ci, content: slot.block.text, partial: output });
|
|
714
|
+
} else if (slot.type === "thinking") {
|
|
715
|
+
out.push({ type: "thinking_end", contentIndex: slot.ci, content: slot.block.thinking, partial: output });
|
|
716
|
+
} else if (slot.type === "toolCall") {
|
|
717
|
+
try {
|
|
718
|
+
slot.block.arguments = JSON.parse(slot.block.partialJson || "{}");
|
|
719
|
+
} catch {
|
|
720
|
+
/* keep {} */
|
|
721
|
+
}
|
|
722
|
+
delete slot.block.partialJson;
|
|
723
|
+
out.push({ type: "toolcall_end", contentIndex: slot.ci, toolCall: slot.block, partial: output });
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
slots.clear();
|
|
727
|
+
|
|
728
|
+
// Emit any terminal output[] items that never arrived as incremental events
|
|
729
|
+
// (full or partial collapse, e.g. Anthropic/Bedrock streams text but delivers
|
|
730
|
+
// the tool call only in the terminal payload).
|
|
731
|
+
if (terminal) {
|
|
732
|
+
reconcileTerminal(out, output, terminal, seenIds);
|
|
733
|
+
applyUsage(output, terminal, model);
|
|
734
|
+
output.stopReason = mapStopReason(terminal.status);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* Background + poll path. The POST returns immediately with a stored response
|
|
740
|
+
* id (status `queued`/`in_progress`), then we poll `GET /responses/{id}` until
|
|
741
|
+
* it finishes. Because every HTTP request is short, the nginx gateway
|
|
742
|
+
* read-timeout can never fire, this is the reliable path for long reasoning
|
|
743
|
+
* turns that otherwise buffer server-side and 504.
|
|
744
|
+
*
|
|
745
|
+
* Trade-off: no token-by-token streaming (the proxy delivers background results
|
|
746
|
+
* only as a single terminal payload), so the reply appears at once on completion.
|
|
747
|
+
*/
|
|
748
|
+
async function runBackgroundPoll(
|
|
749
|
+
url: string,
|
|
750
|
+
apiKey: string,
|
|
751
|
+
params: any,
|
|
752
|
+
out: any,
|
|
753
|
+
output: any,
|
|
754
|
+
model: any,
|
|
755
|
+
signal: any,
|
|
756
|
+
onResponse: any,
|
|
757
|
+
state: { started: boolean },
|
|
758
|
+
): Promise<void> {
|
|
759
|
+
const authHeaders = { Authorization: `Bearer ${apiKey}` };
|
|
760
|
+
const body = sanitizeParamsForModel(model.id, { ...params, background: true, store: true, stream: false });
|
|
761
|
+
|
|
762
|
+
// Enqueue (retry a couple times on gateway 5xx, the POST returns fast, so
|
|
763
|
+
// this rarely trips).
|
|
764
|
+
let data: any = null;
|
|
765
|
+
for (let attempt = 0; ; attempt++) {
|
|
766
|
+
if (signal?.aborted) throw new Error("openai-responses-uva: aborted");
|
|
767
|
+
const res = await fetch(url, {
|
|
768
|
+
method: "POST",
|
|
769
|
+
headers: { "Content-Type": "application/json", ...authHeaders },
|
|
770
|
+
body: JSON.stringify(body),
|
|
771
|
+
...(signal ? { signal } : {}),
|
|
772
|
+
});
|
|
773
|
+
try {
|
|
774
|
+
await onResponse?.({ status: res.status, headers: {} }, model);
|
|
775
|
+
} catch {
|
|
776
|
+
/* ignore */
|
|
777
|
+
}
|
|
778
|
+
const text = await res.text();
|
|
779
|
+
if (res.ok) {
|
|
780
|
+
try {
|
|
781
|
+
data = JSON.parse(text);
|
|
782
|
+
} catch {
|
|
783
|
+
throw new Error(`openai-responses-uva: non-JSON enqueue response: ${text.slice(0, 200)}`);
|
|
784
|
+
}
|
|
785
|
+
break;
|
|
786
|
+
}
|
|
787
|
+
const gateway = res.status >= 500 && res.status < 600;
|
|
788
|
+
if (gateway && attempt < 2 && !signal?.aborted) {
|
|
789
|
+
await sleep(1000 * (attempt + 1));
|
|
790
|
+
continue;
|
|
791
|
+
}
|
|
792
|
+
throw new Error(`openai-responses-uva: HTTP ${res.status}: ${text.slice(0, 200).replace(/\s+/g, " ")}`);
|
|
793
|
+
}
|
|
794
|
+
const id = data?.id;
|
|
795
|
+
if (!id) throw new Error("openai-responses-uva: background response missing id");
|
|
796
|
+
|
|
797
|
+
state.started = true;
|
|
798
|
+
out.push({ type: "start", partial: output });
|
|
799
|
+
|
|
800
|
+
// Poll until a terminal status. Every GET is short, so no gateway timeout.
|
|
801
|
+
const getUrl = `${url}/${encodeURIComponent(id)}`;
|
|
802
|
+
const deadline = Date.now() + 15 * 60 * 1000; // 15 min hard cap
|
|
803
|
+
let delay = 1500;
|
|
804
|
+
let getFails = 0;
|
|
805
|
+
let terminal: any = null;
|
|
806
|
+
while (true) {
|
|
807
|
+
if (signal?.aborted) throw new Error("openai-responses-uva: aborted");
|
|
808
|
+
await sleep(delay);
|
|
809
|
+
let g: any;
|
|
810
|
+
try {
|
|
811
|
+
g = await fetch(getUrl, { headers: authHeaders, ...(signal ? { signal } : {}) });
|
|
812
|
+
} catch (e: any) {
|
|
813
|
+
if (signal?.aborted) throw new Error("openai-responses-uva: aborted");
|
|
814
|
+
if (++getFails > 5) throw e;
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
817
|
+
if (!g.ok) {
|
|
818
|
+
if (++getFails > 5) {
|
|
819
|
+
const t = await g.text().catch(() => "");
|
|
820
|
+
throw new Error(`openai-responses-uva: poll HTTP ${g.status}: ${t.slice(0, 160).replace(/\s+/g, " ")}`);
|
|
821
|
+
}
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
getFails = 0;
|
|
825
|
+
let gd: any;
|
|
826
|
+
try {
|
|
827
|
+
gd = await g.json();
|
|
828
|
+
} catch {
|
|
829
|
+
continue;
|
|
830
|
+
}
|
|
831
|
+
const st = gd?.status;
|
|
832
|
+
if (st === "completed" || st === "incomplete") {
|
|
833
|
+
terminal = gd;
|
|
834
|
+
break;
|
|
835
|
+
}
|
|
836
|
+
if (st === "failed" || st === "cancelled") {
|
|
837
|
+
const e = gd?.error;
|
|
838
|
+
throw new Error(`openai-responses-uva: background ${st}: ${e?.message || e?.code || "no message"}`);
|
|
839
|
+
}
|
|
840
|
+
if (Date.now() > deadline) throw new Error("openai-responses-uva: background poll timed out");
|
|
841
|
+
delay = Math.min(delay + 500, 3000);
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
// Background responses carry no incremental events, emit the whole output[].
|
|
845
|
+
reconcileTerminal(out, output, terminal, new Set());
|
|
846
|
+
applyUsage(output, terminal, model);
|
|
847
|
+
output.stopReason = mapStopReason(terminal.status);
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/** Delegate a turn to Pi's built-in chat-completions handler (open-weight models). */
|
|
851
|
+
function chatDelegate(model: any, context: any, options: any): any {
|
|
852
|
+
const builtin = getApiProvider("openai-completions");
|
|
853
|
+
if (!builtin) {
|
|
854
|
+
const out = createAssistantMessageEventStream();
|
|
855
|
+
out.push({
|
|
856
|
+
type: "error",
|
|
857
|
+
reason: "error",
|
|
858
|
+
error: {
|
|
859
|
+
role: "assistant",
|
|
860
|
+
content: [],
|
|
861
|
+
stopReason: "error",
|
|
862
|
+
errorMessage: "openai-responses-uva: openai-completions handler unavailable",
|
|
863
|
+
},
|
|
864
|
+
});
|
|
865
|
+
out.end();
|
|
866
|
+
return out;
|
|
867
|
+
}
|
|
868
|
+
// Strip reasoning: chat-completions rejects reasoning_effort with tools.
|
|
869
|
+
return builtin.streamSimple(
|
|
870
|
+
{ ...model, api: "openai-completions", reasoning: false, thinkingLevelMap: undefined },
|
|
871
|
+
context,
|
|
872
|
+
options,
|
|
873
|
+
);
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
async function pipeInto(out: any, src: any): Promise<void> {
|
|
877
|
+
for await (const ev of src) out.push(ev);
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/** The replacement streamSimple for UvA models. */
|
|
881
|
+
function uvaStreamSimple(model: any, context: any, options: any): any {
|
|
882
|
+
// Open-weight models only speak chat-completions, delegate straight to the
|
|
883
|
+
// built-in handler (standard streaming, no Responses bug to work around).
|
|
884
|
+
if (currentRoute(model.id) === "chat") {
|
|
885
|
+
return chatDelegate(model, context, options);
|
|
886
|
+
}
|
|
887
|
+
const out = createAssistantMessageEventStream();
|
|
888
|
+
(async () => {
|
|
889
|
+
const output: any = {
|
|
890
|
+
role: "assistant",
|
|
891
|
+
content: [],
|
|
892
|
+
api: model.api,
|
|
893
|
+
provider: model.provider,
|
|
894
|
+
model: model.id,
|
|
895
|
+
usage: {
|
|
896
|
+
input: 0,
|
|
897
|
+
output: 0,
|
|
898
|
+
cacheRead: 0,
|
|
899
|
+
cacheWrite: 0,
|
|
900
|
+
reasoning: 0,
|
|
901
|
+
totalTokens: 0,
|
|
902
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
903
|
+
},
|
|
904
|
+
stopReason: "stop",
|
|
905
|
+
timestamp: Date.now(),
|
|
906
|
+
};
|
|
907
|
+
try {
|
|
908
|
+
const builtin = getApiProvider(BASE_API);
|
|
909
|
+
if (!builtin) throw new Error("openai-responses-uva: built-in openai-responses handler not available");
|
|
910
|
+
|
|
911
|
+
const origOnPayload = options?.onPayload;
|
|
912
|
+
let params = await captureParams(builtin, model, context, options);
|
|
913
|
+
if (!params) throw new Error("openai-responses-uva: failed to capture request params");
|
|
914
|
+
if (origOnPayload) {
|
|
915
|
+
const next = await origOnPayload(params, model);
|
|
916
|
+
if (next !== undefined) params = next;
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
const apiKey = options?.apiKey || activeApiKey || process.env.UVA_API_KEY || process.env.OPENAI_API_KEY;
|
|
920
|
+
if (!apiKey) throw new Error("openai-responses-uva: no API key (run /login or set UVA_API_KEY)");
|
|
921
|
+
const url = String(model.baseUrl || activeBaseUrl).replace(/\/+$/, "") + "/responses";
|
|
922
|
+
|
|
923
|
+
const state = { started: false };
|
|
924
|
+
const effort = params?.reasoning?.effort;
|
|
925
|
+
// Reasoning turns buffer server-side (the proxy sends no interim bytes
|
|
926
|
+
// while the model thinks) and can 504 mid-stream. Route them straight to
|
|
927
|
+
// the background+poll path where every HTTP request is short, so the
|
|
928
|
+
// gateway timeout cannot fire. Non-reasoning turns (effort "none"/absent)
|
|
929
|
+
// stream normally for token-by-token output.
|
|
930
|
+
const preferBackground = typeof effort === "string" && effort !== "none";
|
|
931
|
+
|
|
932
|
+
if (preferBackground) {
|
|
933
|
+
await runBackgroundPoll(url, apiKey, params, out, output, model, options?.signal, options?.onResponse, state);
|
|
934
|
+
} else {
|
|
935
|
+
const streamBody = sanitizeParamsForModel(model.id, { ...params, stream: true });
|
|
936
|
+
try {
|
|
937
|
+
await attemptStream(url, apiKey, streamBody, out, output, model, options?.signal, options?.onResponse, state);
|
|
938
|
+
} catch (err: any) {
|
|
939
|
+
const status: number | undefined = err?.status;
|
|
940
|
+
const gateway = status === undefined || (status >= 500 && status < 600);
|
|
941
|
+
// Gateway failure before any output = the proxy buffered with no bytes.
|
|
942
|
+
// Fall back to background+poll (also defeats the 504) instead of
|
|
943
|
+
// retrying the same doomed stream.
|
|
944
|
+
if (!state.started && gateway && !options?.signal?.aborted) {
|
|
945
|
+
await runBackgroundPoll(url, apiKey, params, out, output, model, options?.signal, options?.onResponse, state);
|
|
946
|
+
} else {
|
|
947
|
+
throw err;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
if (output.content.some((b: any) => b.type === "toolCall") && output.stopReason === "stop") {
|
|
953
|
+
output.stopReason = "toolUse";
|
|
954
|
+
}
|
|
955
|
+
out.push({ type: "done", reason: output.stopReason, message: output });
|
|
956
|
+
out.end();
|
|
957
|
+
} catch (error) {
|
|
958
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
959
|
+
// Self-heal: this model isn't on /responses (proxy 404 / "not found").
|
|
960
|
+
// Remember it as chat-only and reissue this turn on chat-completions.
|
|
961
|
+
const notOnResponses =
|
|
962
|
+
(error as any)?.status === 404 || /HTTP 404|not found|does not exist|no model group|NotFound/i.test(msg);
|
|
963
|
+
if (notOnResponses && output.content.length === 0 && !options?.signal?.aborted) {
|
|
964
|
+
routeOverrides.set(model.id, "chat");
|
|
965
|
+
try {
|
|
966
|
+
await pipeInto(out, chatDelegate(model, context, options));
|
|
967
|
+
out.end();
|
|
968
|
+
return;
|
|
969
|
+
} catch {
|
|
970
|
+
/* fall through to error reporting */
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
for (const block of output.content) {
|
|
974
|
+
delete block.partialJson;
|
|
975
|
+
delete block.index;
|
|
976
|
+
}
|
|
977
|
+
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
|
|
978
|
+
output.errorMessage = msg;
|
|
979
|
+
out.push({ type: "error", reason: output.stopReason, error: output });
|
|
980
|
+
out.end();
|
|
981
|
+
}
|
|
982
|
+
})();
|
|
983
|
+
return out;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
// ---------------------------------------------------------------------------
|
|
987
|
+
// Extension entry point
|
|
988
|
+
// ---------------------------------------------------------------------------
|
|
989
|
+
|
|
990
|
+
/** Discover + build the model list for a given key/base URL (falls back on error). */
|
|
991
|
+
async function buildModels(apiKey: string | undefined, baseUrl: string): Promise<any[]> {
|
|
992
|
+
let infos: ModelInfo[];
|
|
993
|
+
try {
|
|
994
|
+
infos = await discoverModels(apiKey, baseUrl);
|
|
995
|
+
} catch (err) {
|
|
996
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
997
|
+
console.error(`[openai-responses-uva] model discovery failed (${msg}); using fallback list.`);
|
|
998
|
+
infos = FALLBACK_MODEL_IDS.map((id) => ({ id }));
|
|
999
|
+
}
|
|
1000
|
+
const overrides = loadOverrides();
|
|
1001
|
+
modelRoutes.clear();
|
|
1002
|
+
return infos
|
|
1003
|
+
.filter((info) => !DENY.test(info.id) && !(info.mode && EXCLUDED_MODES.has(info.mode)))
|
|
1004
|
+
.map((info) => buildModelDef(info, overrides));
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
function registerProviderNow(pi: ExtensionAPI, models: any[], baseUrl: string): void {
|
|
1008
|
+
currentModels = models;
|
|
1009
|
+
pi.registerProvider(PROVIDER_ID, {
|
|
1010
|
+
name: "UvA / HvA (Responses fix)",
|
|
1011
|
+
baseUrl: baseUrl.replace(/\/+$/, ""),
|
|
1012
|
+
apiKey: "$UVA_API_KEY",
|
|
1013
|
+
api: CUSTOM_API,
|
|
1014
|
+
models,
|
|
1015
|
+
streamSimple: uvaStreamSimple as any,
|
|
1016
|
+
oauth: makeOAuth(pi),
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/**
|
|
1021
|
+
* OAuth-shaped config so the connect flow appears under `/login`. It isn't real
|
|
1022
|
+
* OAuth, we reuse the callback prompts to pick a base URL and paste an API key,
|
|
1023
|
+
* then discover models and re-register the provider so `/models` fills in.
|
|
1024
|
+
*/
|
|
1025
|
+
function makeOAuth(pi: ExtensionAPI) {
|
|
1026
|
+
return {
|
|
1027
|
+
name: "UvA / HvA proxy (paste API key)",
|
|
1028
|
+
async login(callbacks: any): Promise<any> {
|
|
1029
|
+
const choice = await callbacks.onSelect({
|
|
1030
|
+
message: "Which proxy do you want to connect to?",
|
|
1031
|
+
options: [
|
|
1032
|
+
{ id: "uva", label: "UvA - llmproxy.uva.nl" },
|
|
1033
|
+
{ id: "hva", label: "HvA - llmproxy.hva.nl" },
|
|
1034
|
+
{ id: "custom", label: "Custom base URL…" },
|
|
1035
|
+
],
|
|
1036
|
+
});
|
|
1037
|
+
if (!choice) throw new Error("login cancelled");
|
|
1038
|
+
let baseUrl = BASE_URL_PRESETS[choice] || DEFAULT_BASE_URL;
|
|
1039
|
+
if (choice === "custom") {
|
|
1040
|
+
const typed = await callbacks.onPrompt({
|
|
1041
|
+
message: "Base URL (include /v1)",
|
|
1042
|
+
placeholder: "https://llmproxy.example.nl/v1",
|
|
1043
|
+
});
|
|
1044
|
+
if (!typed || !typed.trim()) throw new Error("login cancelled");
|
|
1045
|
+
baseUrl = typed.trim();
|
|
1046
|
+
}
|
|
1047
|
+
baseUrl = baseUrl.replace(/\/+$/, "");
|
|
1048
|
+
|
|
1049
|
+
const key = await callbacks.onPrompt({ message: "Paste your API key", placeholder: "sk-…" });
|
|
1050
|
+
if (!key || !key.trim()) throw new Error("login cancelled");
|
|
1051
|
+
const apiKey = key.trim();
|
|
1052
|
+
|
|
1053
|
+
callbacks.onProgress?.("Discovering models…");
|
|
1054
|
+
const infos = await discoverModels(apiKey, baseUrl); // throws on a bad key/url -> login fails
|
|
1055
|
+
callbacks.onProgress?.(`Connected, ${infos.length} models available.`);
|
|
1056
|
+
|
|
1057
|
+
saveCreds({ baseUrl, apiKey });
|
|
1058
|
+
activeApiKey = apiKey;
|
|
1059
|
+
activeBaseUrl = baseUrl;
|
|
1060
|
+
registerProviderNow(pi, await buildModels(apiKey, baseUrl), baseUrl);
|
|
1061
|
+
|
|
1062
|
+
return {
|
|
1063
|
+
access: apiKey,
|
|
1064
|
+
refresh: "",
|
|
1065
|
+
expires: Date.now() + 10 * 365 * 24 * 60 * 60 * 1000, // static key: never auto-refresh
|
|
1066
|
+
baseUrl,
|
|
1067
|
+
};
|
|
1068
|
+
},
|
|
1069
|
+
async refreshToken(cred: any): Promise<any> {
|
|
1070
|
+
return cred; // static API key, nothing to refresh
|
|
1071
|
+
},
|
|
1072
|
+
getApiKey(cred: any): string {
|
|
1073
|
+
if (cred?.baseUrl) activeBaseUrl = String(cred.baseUrl).replace(/\/+$/, "");
|
|
1074
|
+
const key = (cred && cred.access) || activeApiKey || "";
|
|
1075
|
+
if (key) activeApiKey = key;
|
|
1076
|
+
return key;
|
|
1077
|
+
},
|
|
1078
|
+
modifyModels(models: any[], cred: any): any[] {
|
|
1079
|
+
const b = (cred?.baseUrl ? String(cred.baseUrl) : activeBaseUrl).replace(/\/+$/, "");
|
|
1080
|
+
return models.map((m) => (m.provider === PROVIDER_ID ? { ...m, baseUrl: b } : m));
|
|
1081
|
+
},
|
|
1082
|
+
};
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
// Enforce the preferred default: thinking ON at medium for reasoning models.
|
|
1086
|
+
// Applied whenever a UvA reasoning model becomes active. Disable with
|
|
1087
|
+
// UVA_NO_AUTO_THINKING=1. A per-model default (set in /configure-models) wins.
|
|
1088
|
+
function applyThinkingDefault(pi: ExtensionAPI, model: any): void {
|
|
1089
|
+
if (process.env.UVA_NO_AUTO_THINKING) return;
|
|
1090
|
+
if (!model || model.provider !== PROVIDER_ID || !model.reasoning) return;
|
|
1091
|
+
const ov = loadOverrides()[model.id] || {};
|
|
1092
|
+
const level = ov.defaultThinkingLevel || "medium";
|
|
1093
|
+
try {
|
|
1094
|
+
pi.setThinkingLevel(level);
|
|
1095
|
+
} catch {
|
|
1096
|
+
/* ignore */
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
/** Interactive per-model settings loop for /configure-models (mutates `draft`). */
|
|
1101
|
+
async function configureOneModel(ctx: any, id: string, draft: Record<string, any>): Promise<void> {
|
|
1102
|
+
const def = currentModels.find((m) => m.id === id);
|
|
1103
|
+
const ov = draft[id] || (draft[id] = {});
|
|
1104
|
+
const eff = (k: string, fallback: any) => (ov[k] !== undefined ? ov[k] : fallback);
|
|
1105
|
+
const num = (v: any) => parseInt(String(v ?? "").replace(/[_,\s]/g, ""), 10);
|
|
1106
|
+
const RESET = "\u27f2 Reset this model to auto (remove override)";
|
|
1107
|
+
const BACK = "\u2190 Back to model list";
|
|
1108
|
+
while (true) {
|
|
1109
|
+
const reasoning = eff("reasoning", def?.reasoning ?? false);
|
|
1110
|
+
const visionOn = eff("vision", (def?.input || []).includes("image"));
|
|
1111
|
+
const defLevel = eff("defaultThinkingLevel", reasoning ? "medium" : "n/a");
|
|
1112
|
+
const items = [
|
|
1113
|
+
`Context window: ${eff("contextWindow", def?.contextWindow ?? "?")}`,
|
|
1114
|
+
`Max output tokens: ${eff("maxTokens", def?.maxTokens ?? "?")}`,
|
|
1115
|
+
`Reasoning: ${reasoning ? "on" : "off"}`,
|
|
1116
|
+
`Default thinking level: ${defLevel}`,
|
|
1117
|
+
`Vision (image input): ${visionOn ? "on" : "off"}`,
|
|
1118
|
+
RESET,
|
|
1119
|
+
BACK,
|
|
1120
|
+
];
|
|
1121
|
+
const pick = await ctx.ui.select(`${id} - pick a setting to change`, items);
|
|
1122
|
+
if (pick === undefined || pick === BACK) return;
|
|
1123
|
+
if (pick === RESET) {
|
|
1124
|
+
delete draft[id];
|
|
1125
|
+
ctx.ui.notify(`${id}: override cleared.`, "info");
|
|
1126
|
+
return;
|
|
1127
|
+
}
|
|
1128
|
+
if (pick.startsWith("Context window")) {
|
|
1129
|
+
const v = await ctx.ui.input(`${id} - context window (tokens)`, String(eff("contextWindow", def?.contextWindow ?? "")));
|
|
1130
|
+
const n = num(v);
|
|
1131
|
+
if (Number.isFinite(n) && n > 0) ov.contextWindow = n;
|
|
1132
|
+
else if (v !== undefined) ctx.ui.notify("Enter a positive integer.", "warning");
|
|
1133
|
+
} else if (pick.startsWith("Max output")) {
|
|
1134
|
+
const v = await ctx.ui.input(`${id} - max output tokens`, String(eff("maxTokens", def?.maxTokens ?? "")));
|
|
1135
|
+
const n = num(v);
|
|
1136
|
+
if (Number.isFinite(n) && n > 0) ov.maxTokens = n;
|
|
1137
|
+
else if (v !== undefined) ctx.ui.notify("Enter a positive integer.", "warning");
|
|
1138
|
+
} else if (pick.startsWith("Reasoning:")) {
|
|
1139
|
+
const v = await ctx.ui.select(`${id} - reasoning (thinking) support`, ["on", "off"]);
|
|
1140
|
+
if (v) ov.reasoning = v === "on";
|
|
1141
|
+
} else if (pick.startsWith("Default thinking")) {
|
|
1142
|
+
const v = await ctx.ui.select(`${id} - default thinking level when selected`, ["off", "low", "medium", "high"]);
|
|
1143
|
+
if (v) ov.defaultThinkingLevel = v;
|
|
1144
|
+
} else if (pick.startsWith("Vision")) {
|
|
1145
|
+
const v = await ctx.ui.select(`${id} - vision (image input)`, ["on", "off"]);
|
|
1146
|
+
if (v) ov.vision = v === "on";
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
export default async function (pi: ExtensionAPI): Promise<void> {
|
|
1152
|
+
const creds = loadCreds();
|
|
1153
|
+
if (creds?.baseUrl) activeBaseUrl = String(creds.baseUrl).replace(/\/+$/, "");
|
|
1154
|
+
if (creds?.apiKey) activeApiKey = creds.apiKey;
|
|
1155
|
+
|
|
1156
|
+
registerProviderNow(pi, await buildModels(activeApiKey, activeBaseUrl), activeBaseUrl);
|
|
1157
|
+
|
|
1158
|
+
// Default thinking level (medium) on selection and at startup.
|
|
1159
|
+
pi.on("model_select", (event: any) => applyThinkingDefault(pi, event?.model));
|
|
1160
|
+
pi.on("session_start", (_event: any, ctx: any) => applyThinkingDefault(pi, ctx?.model));
|
|
1161
|
+
|
|
1162
|
+
// Named convenience command; the same flow is also reachable via `/login`.
|
|
1163
|
+
pi.registerCommand("uva-login", {
|
|
1164
|
+
description: "Connect a UvA/HvA proxy: pick base URL, paste API key, auto-discover models",
|
|
1165
|
+
handler: async (_args: string, ctx: any) => {
|
|
1166
|
+
if (!ctx.hasUI) {
|
|
1167
|
+
ctx.ui.notify("/uva-login needs interactive UI (or set UVA_API_KEY + UVA_BASE_URL).", "error");
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
const oauth = makeOAuth(pi);
|
|
1171
|
+
try {
|
|
1172
|
+
const cred = await oauth.login({
|
|
1173
|
+
onSelect: (p: any) =>
|
|
1174
|
+
ctx.ui
|
|
1175
|
+
.select(
|
|
1176
|
+
p.message,
|
|
1177
|
+
p.options.map((o: any) => o.label),
|
|
1178
|
+
)
|
|
1179
|
+
.then((label: string | undefined) =>
|
|
1180
|
+
label ? p.options.find((o: any) => o.label === label)?.id : undefined,
|
|
1181
|
+
),
|
|
1182
|
+
onPrompt: (p: any) => ctx.ui.input(p.message, p.placeholder).then((v: string | undefined) => v ?? ""),
|
|
1183
|
+
onProgress: (m: string) => ctx.ui.notify(m, "info"),
|
|
1184
|
+
onAuth: () => {},
|
|
1185
|
+
onDeviceCode: () => {},
|
|
1186
|
+
});
|
|
1187
|
+
ctx.ui.notify(`Connected to ${cred.baseUrl}. Open /models to pick one.`, "info");
|
|
1188
|
+
} catch (err) {
|
|
1189
|
+
ctx.ui.notify(`Login failed: ${err instanceof Error ? err.message : String(err)}`, "error");
|
|
1190
|
+
}
|
|
1191
|
+
},
|
|
1192
|
+
});
|
|
1193
|
+
|
|
1194
|
+
pi.registerCommand("configure-models", {
|
|
1195
|
+
description: "Override a model's context window, max output, reasoning, and default thinking level",
|
|
1196
|
+
handler: async (_args: string, ctx: any) => {
|
|
1197
|
+
if (!ctx.hasUI) {
|
|
1198
|
+
ctx.ui.notify("/configure-models needs interactive UI.", "error");
|
|
1199
|
+
return;
|
|
1200
|
+
}
|
|
1201
|
+
if (!currentModels.length) {
|
|
1202
|
+
ctx.ui.notify("No models loaded yet - run /login (or set UVA_API_KEY) first.", "error");
|
|
1203
|
+
return;
|
|
1204
|
+
}
|
|
1205
|
+
const draft: Record<string, any> = JSON.parse(JSON.stringify(loadOverrides()));
|
|
1206
|
+
const SAVE = "\u2714 Save & apply changes";
|
|
1207
|
+
const DISCARD = "\u2718 Discard & exit";
|
|
1208
|
+
while (true) {
|
|
1209
|
+
const ids = currentModels.map((m) => m.id);
|
|
1210
|
+
const marked = ids.map((id) => (draft[id] && Object.keys(draft[id]).length ? `${id} (edited)` : id));
|
|
1211
|
+
const pick = await ctx.ui.select("Configure model overrides", [...marked, SAVE, DISCARD]);
|
|
1212
|
+
if (pick === undefined || pick === DISCARD) {
|
|
1213
|
+
ctx.ui.notify("No changes applied.", "info");
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
if (pick === SAVE) {
|
|
1217
|
+
for (const k of Object.keys(draft)) {
|
|
1218
|
+
if (!draft[k] || Object.keys(draft[k]).length === 0) delete draft[k];
|
|
1219
|
+
}
|
|
1220
|
+
try {
|
|
1221
|
+
saveOverrides(draft);
|
|
1222
|
+
registerProviderNow(pi, await buildModels(activeApiKey, activeBaseUrl), activeBaseUrl);
|
|
1223
|
+
if (ctx.model) applyThinkingDefault(pi, ctx.model);
|
|
1224
|
+
ctx.ui.notify(`Saved & applied overrides for ${Object.keys(draft).length} model(s).`, "info");
|
|
1225
|
+
} catch (err) {
|
|
1226
|
+
ctx.ui.notify(`Save failed: ${err instanceof Error ? err.message : String(err)}`, "error");
|
|
1227
|
+
}
|
|
1228
|
+
return;
|
|
1229
|
+
}
|
|
1230
|
+
const id = pick.replace(/ \(edited\)$/, "");
|
|
1231
|
+
await configureOneModel(ctx, id, draft);
|
|
1232
|
+
}
|
|
1233
|
+
},
|
|
1234
|
+
});
|
|
1235
|
+
}
|