@zero-gravity/zero-gravity 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/LICENSE +21 -0
- package/README.md +50 -2
- package/THIRD-PARTY-NOTICES.md +100 -0
- package/dist/adv-context-SLTP32JQ.js +36 -0
- package/dist/advanced-EPLZB6DG.js +164 -0
- package/dist/agents-JYRQHH7R.js +181 -0
- package/dist/chat-AEHVCKXX.js +47 -0
- package/dist/chunk-2OH5KHWO.js +112 -0
- package/dist/chunk-2ZYSAYMJ.js +108 -0
- package/dist/chunk-4BZ4IXTO.js +161 -0
- package/dist/chunk-4ITJY25Z.js +144 -0
- package/dist/chunk-4JBLZQAQ.js +65 -0
- package/dist/chunk-6QLYRU3N.js +28 -0
- package/dist/chunk-7TACFVY2.js +57 -0
- package/dist/chunk-AY36KJTH.js +3023 -0
- package/dist/chunk-BJABQO7S.js +378 -0
- package/dist/chunk-C2GFK4JP.js +387 -0
- package/dist/chunk-CDC2K2KP.js +47 -0
- package/dist/chunk-DKCCXMSE.js +27 -0
- package/dist/chunk-FC3UOHOO.js +194 -0
- package/dist/chunk-FIASMDLX.js +216 -0
- package/dist/chunk-GMVDCQVW.js +88 -0
- package/dist/chunk-JQYZX56A.js +231 -0
- package/dist/chunk-JU5PGDOD.js +138 -0
- package/dist/chunk-JUZP5SXD.js +309 -0
- package/dist/chunk-KGA7VWQG.js +70 -0
- package/dist/chunk-L7VNR5LM.js +407 -0
- package/dist/chunk-LOSXCWHU.js +145 -0
- package/dist/chunk-NVC433AX.js +24 -0
- package/dist/chunk-QH27MDJM.js +248 -0
- package/dist/chunk-QUC5URWQ.js +708 -0
- package/dist/chunk-R2CPYTSP.js +31 -0
- package/dist/chunk-R5KQACGR.js +2833 -0
- package/dist/chunk-R6DONQKN.js +153 -0
- package/dist/chunk-RIX4S3J7.js +4747 -0
- package/dist/chunk-SZKAZ2VN.js +35 -0
- package/dist/chunk-T6DDNE3W.js +1338 -0
- package/dist/chunk-U4URD6TU.js +4605 -0
- package/dist/chunk-U5UIUB6L.js +51 -0
- package/dist/chunk-UMC77TR3.js +79 -0
- package/dist/chunk-UQURXFAE.js +80 -0
- package/dist/chunk-VBG7T7XY.js +1703 -0
- package/dist/chunk-VCCMJIAG.js +326 -0
- package/dist/chunk-VS375NYD.js +91 -0
- package/dist/chunk-WANZOLI5.js +1073 -0
- package/dist/chunk-WUF3TVAE.js +51 -0
- package/dist/chunk-XCWLFZSM.js +149 -0
- package/dist/chunk-YJEUXO5I.js +76 -0
- package/dist/chunk-YR6RCC6Y.js +894 -0
- package/dist/chunk-ZQFAX275.js +35 -0
- package/dist/config-ELG4FQ3K.js +30 -0
- package/dist/config-IEWRCG7R.js +50 -0
- package/dist/doctor-ZZC2D3RW.js +357 -0
- package/dist/ext-context-RIMZMEPB.js +37 -0
- package/dist/index.js +20 -0
- package/dist/init-UB3E47KM.js +22 -0
- package/dist/integrations-HW4VTLN4.js +183 -0
- package/dist/main-RAWWT22W.js +115 -0
- package/dist/mcp-SWD4SO35.js +232 -0
- package/dist/mcp-context-PM5FY665.js +28 -0
- package/dist/memory-QQ54GRCN.js +128 -0
- package/dist/memory-session-R6DGT6CS.js +14 -0
- package/dist/memory-summary-4P26B2ZY.js +18 -0
- package/dist/plugins-VUGTEUNV.js +166 -0
- package/dist/providers-O3WOVP5Q.js +417 -0
- package/dist/report-DDIZ6BLF.js +28 -0
- package/dist/sec-context-VQHW6TOZ.js +15 -0
- package/dist/security-SAYW4LU4.js +95 -0
- package/dist/sessions-CL6CRNQL.js +160 -0
- package/dist/skills-7KDGTTKX.js +126 -0
- package/dist/version-6E6A23B3.js +13 -0
- package/package.json +70 -4
|
@@ -0,0 +1,1073 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
ProviderFailure,
|
|
4
|
+
Secret,
|
|
5
|
+
fail,
|
|
6
|
+
toProviderError
|
|
7
|
+
} from "./chunk-4ITJY25Z.js";
|
|
8
|
+
import {
|
|
9
|
+
validateEndpoint,
|
|
10
|
+
validateModelId
|
|
11
|
+
} from "./chunk-KGA7VWQG.js";
|
|
12
|
+
|
|
13
|
+
// src/providers/auth.ts
|
|
14
|
+
var VALID_KEY = /^[\x21-\x7E]+$/;
|
|
15
|
+
function clean(value) {
|
|
16
|
+
if (value === void 0) return null;
|
|
17
|
+
const trimmed = value.trim();
|
|
18
|
+
return trimmed === "" ? null : trimmed;
|
|
19
|
+
}
|
|
20
|
+
function looksQuoted(value) {
|
|
21
|
+
return /^["']|["']$/.test(value);
|
|
22
|
+
}
|
|
23
|
+
function resolveCredentialStatus(spec, env) {
|
|
24
|
+
if (spec.kind === "none") return { state: "not-required" };
|
|
25
|
+
for (const name of spec.envVars) {
|
|
26
|
+
const value = clean(env[name]);
|
|
27
|
+
if (value === null) continue;
|
|
28
|
+
if (!VALID_KEY.test(value) || looksQuoted(value)) return { state: "invalid", envVar: name };
|
|
29
|
+
return { state: "present", envVar: name };
|
|
30
|
+
}
|
|
31
|
+
return spec.kind === "optional" ? { state: "optional-absent", envVars: spec.envVars } : { state: "missing", envVars: spec.envVars };
|
|
32
|
+
}
|
|
33
|
+
function readCredential(spec, env) {
|
|
34
|
+
const status = resolveCredentialStatus(spec, env);
|
|
35
|
+
if (status.state !== "present") return null;
|
|
36
|
+
const value = clean(env[status.envVar]);
|
|
37
|
+
return value === null ? null : { secret: new Secret(value), envVar: status.envVar };
|
|
38
|
+
}
|
|
39
|
+
function shellInstructions(envVar, os) {
|
|
40
|
+
const posix = {
|
|
41
|
+
shell: os === "android" ? "Termux (bash)" : os === "macos" ? "macOS (zsh/bash)" : "Linux (bash/zsh)",
|
|
42
|
+
set: [
|
|
43
|
+
`export ${envVar}="<your-key>" # this terminal session only`,
|
|
44
|
+
`# To keep it: add that line to ${os === "macos" ? "~/.zshrc" : "~/.bashrc"}, then restart the terminal`
|
|
45
|
+
],
|
|
46
|
+
unset: [`unset ${envVar}`, `# and delete the export line from your shell profile if you added one`]
|
|
47
|
+
};
|
|
48
|
+
const powershell = {
|
|
49
|
+
shell: "Windows PowerShell",
|
|
50
|
+
set: [
|
|
51
|
+
`$env:${envVar} = "<your-key>" # this session only`,
|
|
52
|
+
`[Environment]::SetEnvironmentVariable("${envVar}", "<your-key>", "User") # persistent; open a new terminal`
|
|
53
|
+
],
|
|
54
|
+
unset: [`Remove-Item Env:${envVar}`, `[Environment]::SetEnvironmentVariable("${envVar}", $null, "User") # remove the persistent value`]
|
|
55
|
+
};
|
|
56
|
+
const cmd = {
|
|
57
|
+
shell: "Windows CMD",
|
|
58
|
+
set: [`set ${envVar}=<your-key> (this window only; do not add quotes)`, `setx ${envVar} "<your-key>" (persistent; open a new window)`],
|
|
59
|
+
unset: [`set ${envVar}=`, `reg delete HKCU\\Environment /v ${envVar} /f (remove the persistent value)`]
|
|
60
|
+
};
|
|
61
|
+
return os === "windows" ? [powershell, cmd] : [posix];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// src/providers/backend.ts
|
|
65
|
+
async function* guardStream(provider, signal, secrets, inner) {
|
|
66
|
+
let terminal = false;
|
|
67
|
+
try {
|
|
68
|
+
for await (const event of inner) {
|
|
69
|
+
if (terminal) break;
|
|
70
|
+
if (signal?.aborted) {
|
|
71
|
+
terminal = true;
|
|
72
|
+
yield { type: "error", error: toProviderError(provider, fail(provider, "cancelled"), secrets) };
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (event.type === "text" && event.text === "") continue;
|
|
76
|
+
yield event;
|
|
77
|
+
if (event.type === "done" || event.type === "error") {
|
|
78
|
+
terminal = true;
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (!terminal) {
|
|
83
|
+
const code = signal?.aborted ? "cancelled" : "stream-interrupted";
|
|
84
|
+
yield { type: "error", error: toProviderError(provider, fail(provider, code), secrets) };
|
|
85
|
+
}
|
|
86
|
+
} catch (err) {
|
|
87
|
+
if (terminal) return;
|
|
88
|
+
if (signal?.aborted) {
|
|
89
|
+
yield { type: "error", error: toProviderError(provider, fail(provider, "cancelled"), secrets) };
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const normalized = err instanceof ProviderFailure ? err : fail(provider, "stream-interrupted", { detail: err instanceof Error ? err.message : String(err), secrets });
|
|
93
|
+
yield { type: "error", error: toProviderError(provider, normalized, secrets) };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function cancelBody(res) {
|
|
97
|
+
try {
|
|
98
|
+
void res.body?.cancel().catch(() => void 0);
|
|
99
|
+
} catch {
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// src/providers/http.ts
|
|
104
|
+
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
105
|
+
var MAX_ERROR_BODY = 4096;
|
|
106
|
+
async function readLimitedText(res, max = MAX_ERROR_BODY) {
|
|
107
|
+
try {
|
|
108
|
+
const text = await res.text();
|
|
109
|
+
return text.length > max ? text.slice(0, max) : text;
|
|
110
|
+
} catch {
|
|
111
|
+
return "";
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function causeCode(err) {
|
|
115
|
+
const cause = err?.cause;
|
|
116
|
+
const code = cause?.code ?? err?.code;
|
|
117
|
+
return typeof code === "string" ? code : void 0;
|
|
118
|
+
}
|
|
119
|
+
function mapNetworkError(ctx, err, userAborted, timedOut) {
|
|
120
|
+
const base = { envVar: ctx.envVar, endpoint: ctx.endpoint, secrets: ctx.secrets };
|
|
121
|
+
if (userAborted) return fail(ctx.provider, "cancelled", base);
|
|
122
|
+
if (timedOut) return fail(ctx.provider, "timeout", base);
|
|
123
|
+
const code = causeCode(err);
|
|
124
|
+
if (code === "ENOTFOUND" || code === "EAI_AGAIN") return fail(ctx.provider, ctx.localServer ? "server-unavailable" : "dns-failure", base);
|
|
125
|
+
if (code === "ECONNREFUSED" && ctx.localServer) return fail(ctx.provider, "server-unavailable", base);
|
|
126
|
+
if (code === "UND_ERR_CONNECT_TIMEOUT" || code === "ETIMEDOUT") return fail(ctx.provider, ctx.localServer ? "server-unavailable" : "timeout", base);
|
|
127
|
+
if (ctx.localServer) return fail(ctx.provider, "server-unavailable", base);
|
|
128
|
+
return fail(ctx.provider, "network-unavailable", { ...base, detail: code });
|
|
129
|
+
}
|
|
130
|
+
function parseRetryAfter(res) {
|
|
131
|
+
const raw = res.headers.get("retry-after");
|
|
132
|
+
if (!raw) return void 0;
|
|
133
|
+
const secs = Number(raw);
|
|
134
|
+
if (Number.isFinite(secs) && secs >= 0) return Math.min(Math.ceil(secs), 3600);
|
|
135
|
+
return void 0;
|
|
136
|
+
}
|
|
137
|
+
async function errorFromResponse(ctx, res) {
|
|
138
|
+
const body = await readLimitedText(res);
|
|
139
|
+
const lower = body.toLowerCase();
|
|
140
|
+
const base = { status: res.status, detail: body, envVar: ctx.envVar, endpoint: ctx.endpoint, secrets: ctx.secrets };
|
|
141
|
+
const s = res.status;
|
|
142
|
+
if (s >= 300 && s < 400) {
|
|
143
|
+
return fail(ctx.provider, "endpoint-error", {
|
|
144
|
+
...base,
|
|
145
|
+
detail: void 0,
|
|
146
|
+
message: "The endpoint tried to redirect the request. Redirects are not followed so your API key is never sent to another host.",
|
|
147
|
+
status: s
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
if (s === 401) return fail(ctx.provider, "auth-failed", base);
|
|
151
|
+
if (s === 403) return fail(ctx.provider, "permission-denied", base);
|
|
152
|
+
if (s === 408) return fail(ctx.provider, "timeout", base);
|
|
153
|
+
if (s === 413) return fail(ctx.provider, "context-length-exceeded", base);
|
|
154
|
+
if (s === 429) {
|
|
155
|
+
const retryAfterSeconds = parseRetryAfter(res);
|
|
156
|
+
return fail(ctx.provider, "rate-limited", retryAfterSeconds === void 0 ? base : { ...base, retryAfterSeconds });
|
|
157
|
+
}
|
|
158
|
+
if (s === 404) return fail(ctx.provider, ctx.notFoundCode ?? "endpoint-error", base);
|
|
159
|
+
if (s === 400 || s === 422) {
|
|
160
|
+
if (/context.?(length|window)|too many tokens|maximum context|prompt is too long|token limit|exceeds the (maximum|context)/.test(lower)) {
|
|
161
|
+
return fail(ctx.provider, "context-length-exceeded", base);
|
|
162
|
+
}
|
|
163
|
+
if (/model/.test(lower) && /(not found|does not exist|not supported|invalid|unknown|unavailable)/.test(lower)) {
|
|
164
|
+
return fail(ctx.provider, "invalid-model", base);
|
|
165
|
+
}
|
|
166
|
+
if (/api.?key|credential|unauthori[sz]ed/.test(lower)) return fail(ctx.provider, "auth-failed", base);
|
|
167
|
+
return fail(ctx.provider, "invalid-request", base);
|
|
168
|
+
}
|
|
169
|
+
if (s === 500 || s === 502 || s === 503 || s === 504 || s === 529) return fail(ctx.provider, "service-unavailable", base);
|
|
170
|
+
return fail(ctx.provider, "unknown", { ...base, message: `The provider returned HTTP ${s}.` });
|
|
171
|
+
}
|
|
172
|
+
async function send(ctx, url, init, signal) {
|
|
173
|
+
const controller = new AbortController();
|
|
174
|
+
let timedOut = false;
|
|
175
|
+
const timer = setTimeout(() => {
|
|
176
|
+
timedOut = true;
|
|
177
|
+
controller.abort();
|
|
178
|
+
}, ctx.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
179
|
+
const onAbort = () => controller.abort();
|
|
180
|
+
if (signal) {
|
|
181
|
+
if (signal.aborted) {
|
|
182
|
+
clearTimeout(timer);
|
|
183
|
+
throw fail(ctx.provider, "cancelled");
|
|
184
|
+
}
|
|
185
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
const res = await ctx.fetch(url, { ...init, redirect: "manual", signal: controller.signal });
|
|
189
|
+
clearTimeout(timer);
|
|
190
|
+
if (signal) {
|
|
191
|
+
signal.removeEventListener("abort", onAbort);
|
|
192
|
+
signal.addEventListener("abort", () => controller.abort(), { once: true });
|
|
193
|
+
}
|
|
194
|
+
if (res.status < 200 || res.status >= 300) throw await errorFromResponse(ctx, res);
|
|
195
|
+
return res;
|
|
196
|
+
} catch (err) {
|
|
197
|
+
clearTimeout(timer);
|
|
198
|
+
if (err instanceof ProviderFailure) throw err;
|
|
199
|
+
throw mapNetworkError(ctx, err, signal?.aborted === true, timedOut);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
function parseJsonSafe(text) {
|
|
203
|
+
try {
|
|
204
|
+
return JSON.parse(text);
|
|
205
|
+
} catch {
|
|
206
|
+
return void 0;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// src/providers/sse.ts
|
|
211
|
+
async function* parseSse(body) {
|
|
212
|
+
const decoder = new TextDecoder("utf-8");
|
|
213
|
+
const reader = body.getReader();
|
|
214
|
+
let buffer = "";
|
|
215
|
+
let event;
|
|
216
|
+
let data = [];
|
|
217
|
+
const flush = () => {
|
|
218
|
+
if (data.length === 0) {
|
|
219
|
+
event = void 0;
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
const out = { event, data: data.join("\n") };
|
|
223
|
+
event = void 0;
|
|
224
|
+
data = [];
|
|
225
|
+
return out;
|
|
226
|
+
};
|
|
227
|
+
function* drain() {
|
|
228
|
+
let idx;
|
|
229
|
+
while ((idx = buffer.search(/\r\n|\n|\r(?!$)/)) !== -1) {
|
|
230
|
+
const m = /^(\r\n|\n|\r)/.exec(buffer.slice(idx));
|
|
231
|
+
const termLen = m?.[0].length ?? 1;
|
|
232
|
+
const line = buffer.slice(0, idx);
|
|
233
|
+
buffer = buffer.slice(idx + termLen);
|
|
234
|
+
if (line === "") {
|
|
235
|
+
const ev = flush();
|
|
236
|
+
if (ev) yield ev;
|
|
237
|
+
} else if (line.startsWith(":")) {
|
|
238
|
+
continue;
|
|
239
|
+
} else {
|
|
240
|
+
const colon = line.indexOf(":");
|
|
241
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
242
|
+
let val = colon === -1 ? "" : line.slice(colon + 1);
|
|
243
|
+
if (val.startsWith(" ")) val = val.slice(1);
|
|
244
|
+
if (field === "data") data.push(val);
|
|
245
|
+
else if (field === "event") event = val;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
try {
|
|
250
|
+
for (; ; ) {
|
|
251
|
+
const { value, done } = await reader.read();
|
|
252
|
+
if (done) {
|
|
253
|
+
buffer += decoder.decode();
|
|
254
|
+
if (buffer.endsWith("\r")) buffer += "\n";
|
|
255
|
+
yield* drain();
|
|
256
|
+
break;
|
|
257
|
+
}
|
|
258
|
+
buffer += decoder.decode(value, { stream: true });
|
|
259
|
+
yield* drain();
|
|
260
|
+
}
|
|
261
|
+
} finally {
|
|
262
|
+
reader.releaseLock();
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
async function* parseNdjson(body) {
|
|
266
|
+
const decoder = new TextDecoder("utf-8");
|
|
267
|
+
const reader = body.getReader();
|
|
268
|
+
let buffer = "";
|
|
269
|
+
try {
|
|
270
|
+
for (; ; ) {
|
|
271
|
+
const { value, done } = await reader.read();
|
|
272
|
+
if (done) break;
|
|
273
|
+
buffer += decoder.decode(value, { stream: true });
|
|
274
|
+
let idx;
|
|
275
|
+
while ((idx = buffer.indexOf("\n")) !== -1) {
|
|
276
|
+
const line = buffer.slice(0, idx).trim();
|
|
277
|
+
buffer = buffer.slice(idx + 1);
|
|
278
|
+
if (line) yield line;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
} finally {
|
|
282
|
+
reader.releaseLock();
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// src/providers/anthropic/index.ts
|
|
287
|
+
var ANTHROPIC_BASE = "https://api.anthropic.com/v1";
|
|
288
|
+
var API_VERSION = "2023-06-01";
|
|
289
|
+
var DEFAULT_MAX_TOKENS = 4096;
|
|
290
|
+
function num(v) {
|
|
291
|
+
return typeof v === "number" && Number.isFinite(v) ? v : void 0;
|
|
292
|
+
}
|
|
293
|
+
function stopReason(raw) {
|
|
294
|
+
if (raw === "end_turn" || raw === "stop_sequence") return "stop";
|
|
295
|
+
if (raw === "max_tokens") return "length";
|
|
296
|
+
if (raw === "refusal") return "content-filter";
|
|
297
|
+
return "other";
|
|
298
|
+
}
|
|
299
|
+
var AnthropicBackend = class {
|
|
300
|
+
id = "anthropic";
|
|
301
|
+
displayName = "Anthropic Claude";
|
|
302
|
+
supportsStreaming = true;
|
|
303
|
+
model;
|
|
304
|
+
#o;
|
|
305
|
+
constructor(options) {
|
|
306
|
+
this.#o = options;
|
|
307
|
+
this.model = options.model;
|
|
308
|
+
}
|
|
309
|
+
#http(extra = {}) {
|
|
310
|
+
const secrets = this.#o.secret ? [this.#o.secret] : [];
|
|
311
|
+
return { provider: this.id, fetch: this.#o.fetch, secrets, envVar: this.#o.envVar, endpoint: ANTHROPIC_BASE, ...this.#o.timeoutMs ? { timeoutMs: this.#o.timeoutMs } : {}, ...extra };
|
|
312
|
+
}
|
|
313
|
+
#headers() {
|
|
314
|
+
if (!this.#o.secret) throw fail(this.id, "missing-credentials", { envVar: this.#o.envVar });
|
|
315
|
+
return { "x-api-key": this.#o.secret.reveal(), "anthropic-version": API_VERSION };
|
|
316
|
+
}
|
|
317
|
+
chat(messages, options = {}) {
|
|
318
|
+
return guardStream(this.id, options.signal, this.#http().secrets, this.#stream(messages, options));
|
|
319
|
+
}
|
|
320
|
+
async *#stream(messages, options) {
|
|
321
|
+
const system = messages.filter((m) => m.role === "system").map((m) => m.content).join("\n\n");
|
|
322
|
+
const body = {
|
|
323
|
+
model: this.model,
|
|
324
|
+
max_tokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
|
325
|
+
stream: options.stream !== false,
|
|
326
|
+
messages: messages.filter((m) => m.role !== "system").map((m) => ({ role: m.role, content: m.content }))
|
|
327
|
+
};
|
|
328
|
+
if (system) body["system"] = system;
|
|
329
|
+
const res = await send(
|
|
330
|
+
this.#http({ notFoundCode: "invalid-model" }),
|
|
331
|
+
`${ANTHROPIC_BASE}/messages`,
|
|
332
|
+
{ method: "POST", headers: { "content-type": "application/json", ...this.#headers() }, body: JSON.stringify(body) },
|
|
333
|
+
options.signal
|
|
334
|
+
);
|
|
335
|
+
if (body["stream"] === false) {
|
|
336
|
+
const json = parseJsonSafe(await res.text());
|
|
337
|
+
if (!json || !Array.isArray(json.content)) throw fail(this.id, "malformed-response", { secrets: this.#http().secrets });
|
|
338
|
+
const text = json.content.filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join("");
|
|
339
|
+
yield { type: "text", text };
|
|
340
|
+
const i = num(json.usage?.["input_tokens"]);
|
|
341
|
+
const o = num(json.usage?.["output_tokens"]);
|
|
342
|
+
const usage2 = {};
|
|
343
|
+
if (i !== void 0) usage2.inputTokens = i;
|
|
344
|
+
if (o !== void 0) usage2.outputTokens = o;
|
|
345
|
+
if (i !== void 0 && o !== void 0) usage2.totalTokens = i + o;
|
|
346
|
+
if (Object.keys(usage2).length) yield { type: "usage", usage: usage2 };
|
|
347
|
+
yield { type: "done", finishReason: stopReason(json.stop_reason) };
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
if (!res.body) throw fail(this.id, "malformed-response", { secrets: this.#http().secrets });
|
|
351
|
+
let inputTokens;
|
|
352
|
+
let outputTokens;
|
|
353
|
+
let reason = "stop";
|
|
354
|
+
let stopped = false;
|
|
355
|
+
try {
|
|
356
|
+
for await (const ev of parseSse(res.body)) {
|
|
357
|
+
const json = parseJsonSafe(ev.data);
|
|
358
|
+
if (!json || typeof json !== "object") throw fail(this.id, "malformed-response", { secrets: this.#http().secrets });
|
|
359
|
+
const type = ev.event ?? json.type;
|
|
360
|
+
if (type === "message_start") {
|
|
361
|
+
inputTokens = num(json.message?.usage?.input_tokens) ?? inputTokens;
|
|
362
|
+
outputTokens = num(json.message?.usage?.output_tokens) ?? outputTokens;
|
|
363
|
+
} else if (type === "content_block_delta") {
|
|
364
|
+
const delta = json.delta;
|
|
365
|
+
if (delta?.type === "text_delta" && typeof delta.text === "string" && delta.text !== "") yield { type: "text", text: delta.text };
|
|
366
|
+
} else if (type === "message_delta") {
|
|
367
|
+
if (json.delta?.stop_reason) reason = stopReason(json.delta.stop_reason);
|
|
368
|
+
outputTokens = num(json.usage?.output_tokens) ?? outputTokens;
|
|
369
|
+
} else if (type === "message_stop") {
|
|
370
|
+
stopped = true;
|
|
371
|
+
break;
|
|
372
|
+
} else if (type === "error") {
|
|
373
|
+
const kind = json.error?.type;
|
|
374
|
+
const detail = typeof json.error?.message === "string" ? json.error.message : "stream error";
|
|
375
|
+
if (kind === "overloaded_error") throw fail(this.id, "service-unavailable", { detail, secrets: this.#http().secrets });
|
|
376
|
+
if (kind === "rate_limit_error") throw fail(this.id, "rate-limited", { detail, secrets: this.#http().secrets });
|
|
377
|
+
if (kind === "authentication_error") throw fail(this.id, "auth-failed", { envVar: this.#o.envVar, secrets: this.#http().secrets });
|
|
378
|
+
throw fail(this.id, "endpoint-error", { detail, secrets: this.#http().secrets });
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
} finally {
|
|
382
|
+
cancelBody(res);
|
|
383
|
+
}
|
|
384
|
+
if (!stopped) return;
|
|
385
|
+
const usage = {};
|
|
386
|
+
if (inputTokens !== void 0) usage.inputTokens = inputTokens;
|
|
387
|
+
if (outputTokens !== void 0) usage.outputTokens = outputTokens;
|
|
388
|
+
if (inputTokens !== void 0 && outputTokens !== void 0) usage.totalTokens = inputTokens + outputTokens;
|
|
389
|
+
if (Object.keys(usage).length) yield { type: "usage", usage };
|
|
390
|
+
yield { type: "done", finishReason: reason };
|
|
391
|
+
}
|
|
392
|
+
async #fetchModels(signal) {
|
|
393
|
+
const res = await send(this.#http(), `${ANTHROPIC_BASE}/models?limit=100`, { method: "GET", headers: this.#headers() }, signal);
|
|
394
|
+
const json = parseJsonSafe(await readLimitedText(res, 2e6));
|
|
395
|
+
if (!json || !Array.isArray(json.data)) throw fail(this.id, "malformed-response");
|
|
396
|
+
return json.data.map((m) => m.id).filter((x) => typeof x === "string");
|
|
397
|
+
}
|
|
398
|
+
async listModels(signal) {
|
|
399
|
+
const ids = await this.#fetchModels(signal);
|
|
400
|
+
return { source: "live", models: ids.map((id) => ({ id })), note: "Models your key can list (first 100)." };
|
|
401
|
+
}
|
|
402
|
+
async validateConnection(signal) {
|
|
403
|
+
const started = Date.now();
|
|
404
|
+
try {
|
|
405
|
+
const ids = await this.#fetchModels(signal);
|
|
406
|
+
const verified = ids.includes(this.model);
|
|
407
|
+
return {
|
|
408
|
+
state: "connected",
|
|
409
|
+
detail: verified ? `Authenticated; model ${this.model} is listed.` : `Authenticated, but ${this.model} was not in the first 100 listed models.`,
|
|
410
|
+
modelVerified: verified ? true : ids.length >= 100 ? null : false,
|
|
411
|
+
latencyMs: Date.now() - started
|
|
412
|
+
};
|
|
413
|
+
} catch (err) {
|
|
414
|
+
const error = toProviderError(this.id, err, this.#http().secrets);
|
|
415
|
+
return { state: "failed", detail: error.message, modelVerified: null, error };
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
// src/providers/gemini/index.ts
|
|
421
|
+
var GEMINI_BASE = "https://generativelanguage.googleapis.com/v1beta";
|
|
422
|
+
function num2(v) {
|
|
423
|
+
return typeof v === "number" && Number.isFinite(v) ? v : void 0;
|
|
424
|
+
}
|
|
425
|
+
function finishFrom(raw) {
|
|
426
|
+
if (raw === "STOP") return "stop";
|
|
427
|
+
if (raw === "MAX_TOKENS") return "length";
|
|
428
|
+
if (raw === "SAFETY" || raw === "RECITATION" || raw === "BLOCKLIST" || raw === "PROHIBITED_CONTENT") return "content-filter";
|
|
429
|
+
return "other";
|
|
430
|
+
}
|
|
431
|
+
function textOf(c) {
|
|
432
|
+
const parts = c?.content?.parts;
|
|
433
|
+
if (!Array.isArray(parts)) return "";
|
|
434
|
+
return parts.filter((p) => p.thought !== true && typeof p.text === "string").map((p) => p.text).join("");
|
|
435
|
+
}
|
|
436
|
+
function usageOf(meta) {
|
|
437
|
+
if (!meta) return void 0;
|
|
438
|
+
const usage = {};
|
|
439
|
+
const i = num2(meta["promptTokenCount"]);
|
|
440
|
+
const o = num2(meta["candidatesTokenCount"]);
|
|
441
|
+
const t = num2(meta["totalTokenCount"]);
|
|
442
|
+
if (i !== void 0) usage.inputTokens = i;
|
|
443
|
+
if (o !== void 0) usage.outputTokens = o;
|
|
444
|
+
if (t !== void 0) usage.totalTokens = t;
|
|
445
|
+
return Object.keys(usage).length ? usage : void 0;
|
|
446
|
+
}
|
|
447
|
+
var GeminiBackend = class {
|
|
448
|
+
id = "gemini";
|
|
449
|
+
displayName = "Google Gemini";
|
|
450
|
+
supportsStreaming = true;
|
|
451
|
+
model;
|
|
452
|
+
#o;
|
|
453
|
+
constructor(options) {
|
|
454
|
+
this.#o = options;
|
|
455
|
+
this.model = options.model;
|
|
456
|
+
}
|
|
457
|
+
#http(extra = {}) {
|
|
458
|
+
const secrets = this.#o.secret ? [this.#o.secret] : [];
|
|
459
|
+
return { provider: this.id, fetch: this.#o.fetch, secrets, envVar: this.#o.envVar, endpoint: GEMINI_BASE, ...this.#o.timeoutMs ? { timeoutMs: this.#o.timeoutMs } : {}, ...extra };
|
|
460
|
+
}
|
|
461
|
+
/** The key goes in a header, never in the URL, so it cannot appear in URLs, logs or error text. */
|
|
462
|
+
#headers() {
|
|
463
|
+
if (!this.#o.secret) throw fail(this.id, "missing-credentials", { envVar: this.#o.envVar });
|
|
464
|
+
return { "x-goog-api-key": this.#o.secret.reveal() };
|
|
465
|
+
}
|
|
466
|
+
chat(messages, options = {}) {
|
|
467
|
+
return guardStream(this.id, options.signal, this.#http().secrets, this.#stream(messages, options));
|
|
468
|
+
}
|
|
469
|
+
async *#stream(messages, options) {
|
|
470
|
+
const streaming = options.stream !== false;
|
|
471
|
+
const system = messages.filter((m) => m.role === "system").map((m) => m.content).join("\n\n");
|
|
472
|
+
const body = {
|
|
473
|
+
contents: messages.filter((m) => m.role !== "system").map((m) => ({ role: m.role === "assistant" ? "model" : "user", parts: [{ text: m.content }] }))
|
|
474
|
+
};
|
|
475
|
+
if (system) body["systemInstruction"] = { parts: [{ text: system }] };
|
|
476
|
+
if (options.maxTokens !== void 0) body["generationConfig"] = { maxOutputTokens: options.maxTokens };
|
|
477
|
+
const path = streaming ? `models/${encodeURIComponent(this.model)}:streamGenerateContent?alt=sse` : `models/${encodeURIComponent(this.model)}:generateContent`;
|
|
478
|
+
const res = await send(
|
|
479
|
+
this.#http({ notFoundCode: "invalid-model" }),
|
|
480
|
+
`${GEMINI_BASE}/${path}`,
|
|
481
|
+
{ method: "POST", headers: { "content-type": "application/json", ...this.#headers() }, body: JSON.stringify(body) },
|
|
482
|
+
options.signal
|
|
483
|
+
);
|
|
484
|
+
const secrets = this.#http().secrets;
|
|
485
|
+
if (!streaming) {
|
|
486
|
+
const json = parseJsonSafe(await res.text());
|
|
487
|
+
if (!json) throw fail(this.id, "malformed-response", { secrets });
|
|
488
|
+
if (json.promptFeedback?.blockReason) throw fail(this.id, "invalid-request", { message: "The prompt was blocked by the provider's safety filters.", secrets });
|
|
489
|
+
const cand = json.candidates?.[0];
|
|
490
|
+
if (!cand) throw fail(this.id, "malformed-response", { secrets });
|
|
491
|
+
yield { type: "text", text: textOf(cand) };
|
|
492
|
+
const u = usageOf(json.usageMetadata);
|
|
493
|
+
if (u) yield { type: "usage", usage: u };
|
|
494
|
+
yield { type: "done", finishReason: finishFrom(cand.finishReason) };
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
if (!res.body) throw fail(this.id, "malformed-response", { secrets });
|
|
498
|
+
let finish;
|
|
499
|
+
let usage;
|
|
500
|
+
try {
|
|
501
|
+
for await (const ev of parseSse(res.body)) {
|
|
502
|
+
const json = parseJsonSafe(ev.data);
|
|
503
|
+
if (!json || typeof json !== "object") throw fail(this.id, "malformed-response", { secrets });
|
|
504
|
+
if (json.error) throw fail(this.id, "endpoint-error", { detail: typeof json.error.message === "string" ? json.error.message : "stream error", secrets });
|
|
505
|
+
if (json.promptFeedback?.blockReason) throw fail(this.id, "invalid-request", { message: "The prompt was blocked by the provider's safety filters.", secrets });
|
|
506
|
+
const cand = json.candidates?.[0];
|
|
507
|
+
const t = textOf(cand);
|
|
508
|
+
if (t !== "") yield { type: "text", text: t };
|
|
509
|
+
if (cand?.finishReason) finish = finishFrom(cand.finishReason);
|
|
510
|
+
usage = usageOf(json.usageMetadata) ?? usage;
|
|
511
|
+
}
|
|
512
|
+
} finally {
|
|
513
|
+
cancelBody(res);
|
|
514
|
+
}
|
|
515
|
+
if (finish === void 0) return;
|
|
516
|
+
if (usage) yield { type: "usage", usage };
|
|
517
|
+
yield { type: "done", finishReason: finish };
|
|
518
|
+
}
|
|
519
|
+
async #fetchModels(signal) {
|
|
520
|
+
const res = await send(this.#http(), `${GEMINI_BASE}/models?pageSize=200`, { method: "GET", headers: this.#headers() }, signal);
|
|
521
|
+
const json = parseJsonSafe(await readLimitedText(res, 2e6));
|
|
522
|
+
if (!json || !Array.isArray(json.models)) throw fail(this.id, "malformed-response");
|
|
523
|
+
return json.models.filter((m) => {
|
|
524
|
+
const methods = m.supportedGenerationMethods;
|
|
525
|
+
return Array.isArray(methods) && methods.includes("generateContent");
|
|
526
|
+
}).map((m) => m.name).filter((x) => typeof x === "string").map((n) => n.replace(/^models\//, ""));
|
|
527
|
+
}
|
|
528
|
+
async listModels(signal) {
|
|
529
|
+
const ids = await this.#fetchModels(signal);
|
|
530
|
+
return { source: "live", models: ids.map((id) => ({ id })), note: "Models that support generateContent for your key." };
|
|
531
|
+
}
|
|
532
|
+
async validateConnection(signal) {
|
|
533
|
+
const started = Date.now();
|
|
534
|
+
try {
|
|
535
|
+
const ids = await this.#fetchModels(signal);
|
|
536
|
+
const verified = ids.includes(this.model);
|
|
537
|
+
return {
|
|
538
|
+
state: "connected",
|
|
539
|
+
detail: verified ? `Authenticated; model ${this.model} is available.` : `Authenticated, but ${this.model} was not in the model list.`,
|
|
540
|
+
modelVerified: verified,
|
|
541
|
+
latencyMs: Date.now() - started
|
|
542
|
+
};
|
|
543
|
+
} catch (err) {
|
|
544
|
+
const error = toProviderError(this.id, err, this.#http().secrets);
|
|
545
|
+
return { state: "failed", detail: error.message, modelVerified: null, error };
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
};
|
|
549
|
+
|
|
550
|
+
// src/providers/ollama/index.ts
|
|
551
|
+
var OLLAMA_DEFAULT_ENDPOINT = "http://localhost:11434";
|
|
552
|
+
function num3(v) {
|
|
553
|
+
return typeof v === "number" && Number.isFinite(v) ? v : void 0;
|
|
554
|
+
}
|
|
555
|
+
var OllamaBackend = class {
|
|
556
|
+
id = "ollama";
|
|
557
|
+
displayName = "Ollama (local)";
|
|
558
|
+
supportsStreaming = true;
|
|
559
|
+
model;
|
|
560
|
+
#o;
|
|
561
|
+
constructor(options) {
|
|
562
|
+
this.#o = options;
|
|
563
|
+
this.model = options.model;
|
|
564
|
+
}
|
|
565
|
+
#http(extra = {}) {
|
|
566
|
+
const secrets = this.#o.secret ? [this.#o.secret] : [];
|
|
567
|
+
return { provider: this.id, fetch: this.#o.fetch, secrets, envVar: this.#o.envVar, endpoint: this.#o.endpoint, localServer: true, ...this.#o.timeoutMs ? { timeoutMs: this.#o.timeoutMs } : {}, ...extra };
|
|
568
|
+
}
|
|
569
|
+
#headers() {
|
|
570
|
+
return this.#o.secret ? { authorization: `Bearer ${this.#o.secret.reveal()}` } : {};
|
|
571
|
+
}
|
|
572
|
+
chat(messages, options = {}) {
|
|
573
|
+
return guardStream(this.id, options.signal, this.#http().secrets, this.#stream(messages, options));
|
|
574
|
+
}
|
|
575
|
+
async *#stream(messages, options) {
|
|
576
|
+
if (!this.model) throw fail(this.id, "invalid-model", { message: "No Ollama model is selected.", hint: "Run `ollama list` to see installed models, then /model <name> (or `zg provider use ollama --model <name>`). zg never downloads models for you." });
|
|
577
|
+
const streaming = options.stream !== false;
|
|
578
|
+
const body = {
|
|
579
|
+
model: this.model,
|
|
580
|
+
stream: streaming,
|
|
581
|
+
messages: messages.map((m) => ({ role: m.role, content: m.content }))
|
|
582
|
+
};
|
|
583
|
+
if (options.maxTokens !== void 0) body["options"] = { num_predict: options.maxTokens };
|
|
584
|
+
const res = await send(
|
|
585
|
+
this.#http({ notFoundCode: "invalid-model" }),
|
|
586
|
+
`${this.#o.endpoint}/api/chat`,
|
|
587
|
+
{ method: "POST", headers: { "content-type": "application/json", ...this.#headers() }, body: JSON.stringify(body) },
|
|
588
|
+
options.signal
|
|
589
|
+
);
|
|
590
|
+
const secrets = this.#http().secrets;
|
|
591
|
+
const usageFrom2 = (j) => {
|
|
592
|
+
const i = num3(j["prompt_eval_count"]);
|
|
593
|
+
const o = num3(j["eval_count"]);
|
|
594
|
+
if (i === void 0 && o === void 0) return void 0;
|
|
595
|
+
const u = {};
|
|
596
|
+
if (i !== void 0) u.inputTokens = i;
|
|
597
|
+
if (o !== void 0) u.outputTokens = o;
|
|
598
|
+
if (i !== void 0 && o !== void 0) u.totalTokens = i + o;
|
|
599
|
+
return u;
|
|
600
|
+
};
|
|
601
|
+
const reasonOf = (j) => j.done_reason === "length" ? "length" : "stop";
|
|
602
|
+
if (!streaming) {
|
|
603
|
+
const json = parseJsonSafe(await res.text());
|
|
604
|
+
const whole = json?.message?.content;
|
|
605
|
+
if (!json || typeof whole !== "string") throw fail(this.id, "malformed-response", { secrets });
|
|
606
|
+
yield { type: "text", text: whole };
|
|
607
|
+
const u = usageFrom2(json);
|
|
608
|
+
if (u) yield { type: "usage", usage: u };
|
|
609
|
+
yield { type: "done", finishReason: reasonOf(json) };
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
if (!res.body) throw fail(this.id, "malformed-response", { secrets });
|
|
613
|
+
let finished = false;
|
|
614
|
+
let usage;
|
|
615
|
+
let reason = "stop";
|
|
616
|
+
try {
|
|
617
|
+
for await (const line of parseNdjson(res.body)) {
|
|
618
|
+
const json = parseJsonSafe(line);
|
|
619
|
+
if (!json || typeof json !== "object") throw fail(this.id, "malformed-response", { secrets });
|
|
620
|
+
if (typeof json.error === "string") {
|
|
621
|
+
const lower = json.error.toLowerCase();
|
|
622
|
+
if (lower.includes("not found")) throw fail(this.id, "invalid-model", { detail: json.error, hint: `Install it yourself with \`ollama pull ${this.model}\`, or pick an installed model with /models.`, secrets });
|
|
623
|
+
throw fail(this.id, "endpoint-error", { detail: json.error, secrets });
|
|
624
|
+
}
|
|
625
|
+
const content = json.message?.content;
|
|
626
|
+
if (typeof content === "string" && content !== "") yield { type: "text", text: content };
|
|
627
|
+
if (json.done === true) {
|
|
628
|
+
finished = true;
|
|
629
|
+
usage = usageFrom2(json);
|
|
630
|
+
reason = reasonOf(json);
|
|
631
|
+
break;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
} finally {
|
|
635
|
+
cancelBody(res);
|
|
636
|
+
}
|
|
637
|
+
if (!finished) return;
|
|
638
|
+
if (usage) yield { type: "usage", usage };
|
|
639
|
+
yield { type: "done", finishReason: reason };
|
|
640
|
+
}
|
|
641
|
+
async #fetchInstalled(signal) {
|
|
642
|
+
const res = await send(this.#http(), `${this.#o.endpoint}/api/tags`, { method: "GET", headers: this.#headers() }, signal);
|
|
643
|
+
const json = parseJsonSafe(await readLimitedText(res, 2e6));
|
|
644
|
+
if (!json || !Array.isArray(json.models)) throw fail(this.id, "malformed-response", { message: "The server answered, but not like an Ollama server (unexpected /api/tags response)." });
|
|
645
|
+
return json.models.map((m) => m.name).filter((x) => typeof x === "string");
|
|
646
|
+
}
|
|
647
|
+
async listModels(signal) {
|
|
648
|
+
const names = await this.#fetchInstalled(signal);
|
|
649
|
+
return { source: "local", models: names.map((id) => ({ id })), note: "Models installed on the Ollama server. zg never downloads models; use `ollama pull <name>` yourself." };
|
|
650
|
+
}
|
|
651
|
+
async validateConnection(signal) {
|
|
652
|
+
const started = Date.now();
|
|
653
|
+
try {
|
|
654
|
+
const names = await this.#fetchInstalled(signal);
|
|
655
|
+
if (!this.model) {
|
|
656
|
+
return { state: "connected", detail: `Ollama is reachable with ${names.length} installed model(s). No model is selected yet.`, modelVerified: null, latencyMs: Date.now() - started };
|
|
657
|
+
}
|
|
658
|
+
const wanted = this.model;
|
|
659
|
+
const installed = names.includes(wanted) || !wanted.includes(":") && names.includes(`${wanted}:latest`);
|
|
660
|
+
return {
|
|
661
|
+
state: "connected",
|
|
662
|
+
detail: installed ? `Ollama is reachable; model ${wanted} is installed.` : `Ollama is reachable, but ${wanted} is not installed (run \`ollama pull ${wanted}\` yourself).`,
|
|
663
|
+
modelVerified: installed,
|
|
664
|
+
latencyMs: Date.now() - started
|
|
665
|
+
};
|
|
666
|
+
} catch (err) {
|
|
667
|
+
const error = toProviderError(this.id, err, this.#http().secrets);
|
|
668
|
+
return { state: "failed", detail: error.message, modelVerified: null, error };
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
|
|
673
|
+
// src/providers/openai-protocol.ts
|
|
674
|
+
function num4(v) {
|
|
675
|
+
return typeof v === "number" && Number.isFinite(v) ? v : void 0;
|
|
676
|
+
}
|
|
677
|
+
function usageFrom(raw) {
|
|
678
|
+
if (!raw || typeof raw !== "object") return void 0;
|
|
679
|
+
const u = raw;
|
|
680
|
+
const usage = {};
|
|
681
|
+
const i = num4(u["prompt_tokens"]);
|
|
682
|
+
const o = num4(u["completion_tokens"]);
|
|
683
|
+
const t = num4(u["total_tokens"]);
|
|
684
|
+
if (i !== void 0) usage.inputTokens = i;
|
|
685
|
+
if (o !== void 0) usage.outputTokens = o;
|
|
686
|
+
if (t !== void 0) usage.totalTokens = t;
|
|
687
|
+
return Object.keys(usage).length ? usage : void 0;
|
|
688
|
+
}
|
|
689
|
+
function finishFrom2(reason) {
|
|
690
|
+
if (reason === "stop") return "stop";
|
|
691
|
+
if (reason === "length") return "length";
|
|
692
|
+
if (reason === "content_filter") return "content-filter";
|
|
693
|
+
return "other";
|
|
694
|
+
}
|
|
695
|
+
function firstChoice(json) {
|
|
696
|
+
const choices = json?.choices;
|
|
697
|
+
if (!Array.isArray(choices)) return void 0;
|
|
698
|
+
const c = choices[0];
|
|
699
|
+
return c && typeof c === "object" ? c : void 0;
|
|
700
|
+
}
|
|
701
|
+
async function* completions(req) {
|
|
702
|
+
const body = {
|
|
703
|
+
model: req.model,
|
|
704
|
+
messages: req.messages.map((m) => ({ role: m.role, content: m.content })),
|
|
705
|
+
stream: req.stream
|
|
706
|
+
};
|
|
707
|
+
if (req.stream) body["stream_options"] = { include_usage: true };
|
|
708
|
+
if (req.maxTokens !== void 0) body[req.maxTokensField] = req.maxTokens;
|
|
709
|
+
const res = await send(
|
|
710
|
+
req.http,
|
|
711
|
+
req.url,
|
|
712
|
+
{ method: "POST", headers: { "content-type": "application/json", ...req.headers }, body: JSON.stringify(body) },
|
|
713
|
+
req.signal
|
|
714
|
+
);
|
|
715
|
+
if (!req.stream) {
|
|
716
|
+
const json = parseJsonSafe(await res.text());
|
|
717
|
+
const choice = firstChoice(json);
|
|
718
|
+
const message = choice?.["message"];
|
|
719
|
+
if (!choice || typeof message?.content !== "string") throw fail(req.http.provider, "malformed-response", { secrets: req.http.secrets });
|
|
720
|
+
yield { type: "text", text: message.content };
|
|
721
|
+
const usage = usageFrom(json.usage);
|
|
722
|
+
if (usage) yield { type: "usage", usage };
|
|
723
|
+
yield { type: "done", finishReason: finishFrom2(choice["finish_reason"]) };
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
if (!res.body) throw fail(req.http.provider, "malformed-response", { secrets: req.http.secrets });
|
|
727
|
+
let finish;
|
|
728
|
+
let sawDone = false;
|
|
729
|
+
try {
|
|
730
|
+
for await (const ev of parseSse(res.body)) {
|
|
731
|
+
if (ev.data === "[DONE]") {
|
|
732
|
+
sawDone = true;
|
|
733
|
+
break;
|
|
734
|
+
}
|
|
735
|
+
const json = parseJsonSafe(ev.data);
|
|
736
|
+
if (json === void 0 || typeof json !== "object" || json === null) {
|
|
737
|
+
throw fail(req.http.provider, "malformed-response", { secrets: req.http.secrets });
|
|
738
|
+
}
|
|
739
|
+
const errObj = json.error;
|
|
740
|
+
if (errObj) {
|
|
741
|
+
throw fail(req.http.provider, "endpoint-error", {
|
|
742
|
+
detail: typeof errObj.message === "string" ? errObj.message : "stream error",
|
|
743
|
+
secrets: req.http.secrets
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
const choice = firstChoice(json);
|
|
747
|
+
const delta = choice?.["delta"];
|
|
748
|
+
if (typeof delta?.content === "string" && delta.content !== "") yield { type: "text", text: delta.content };
|
|
749
|
+
if (choice && choice["finish_reason"] != null) finish = finishFrom2(choice["finish_reason"]);
|
|
750
|
+
const usage = usageFrom(json.usage);
|
|
751
|
+
if (usage) yield { type: "usage", usage };
|
|
752
|
+
}
|
|
753
|
+
} finally {
|
|
754
|
+
cancelBody(res);
|
|
755
|
+
}
|
|
756
|
+
if (sawDone || !req.requireDoneSentinel && finish !== void 0) {
|
|
757
|
+
yield { type: "done", finishReason: finish ?? "stop" };
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
// src/providers/openai/index.ts
|
|
762
|
+
var OPENAI_DEFAULT_BASE = "https://api.openai.com/v1";
|
|
763
|
+
var OpenAIBackend = class {
|
|
764
|
+
id = "openai";
|
|
765
|
+
displayName = "OpenAI";
|
|
766
|
+
supportsStreaming = true;
|
|
767
|
+
model;
|
|
768
|
+
#o;
|
|
769
|
+
constructor(options) {
|
|
770
|
+
this.#o = options;
|
|
771
|
+
this.model = options.model;
|
|
772
|
+
}
|
|
773
|
+
#http(extra = {}) {
|
|
774
|
+
const secrets = this.#o.secret ? [this.#o.secret] : [];
|
|
775
|
+
return { provider: this.id, fetch: this.#o.fetch, secrets, envVar: this.#o.envVar, endpoint: OPENAI_DEFAULT_BASE, ...this.#o.timeoutMs ? { timeoutMs: this.#o.timeoutMs } : {}, ...extra };
|
|
776
|
+
}
|
|
777
|
+
#headers() {
|
|
778
|
+
if (!this.#o.secret) throw fail(this.id, "missing-credentials", { envVar: this.#o.envVar });
|
|
779
|
+
return { authorization: `Bearer ${this.#o.secret.reveal()}` };
|
|
780
|
+
}
|
|
781
|
+
chat(messages, options = {}) {
|
|
782
|
+
return guardStream(this.id, options.signal, this.#http().secrets, this.#stream(messages, options));
|
|
783
|
+
}
|
|
784
|
+
async *#stream(messages, options) {
|
|
785
|
+
yield* completions({
|
|
786
|
+
http: this.#http({ notFoundCode: "invalid-model" }),
|
|
787
|
+
url: `${OPENAI_DEFAULT_BASE}/chat/completions`,
|
|
788
|
+
headers: this.#headers(),
|
|
789
|
+
model: this.model,
|
|
790
|
+
messages,
|
|
791
|
+
stream: options.stream !== false,
|
|
792
|
+
...options.maxTokens !== void 0 ? { maxTokens: options.maxTokens } : {},
|
|
793
|
+
maxTokensField: "max_completion_tokens",
|
|
794
|
+
requireDoneSentinel: true,
|
|
795
|
+
...options.signal ? { signal: options.signal } : {}
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
async #fetchModels(signal) {
|
|
799
|
+
const res = await send(this.#http(), `${OPENAI_DEFAULT_BASE}/models`, { method: "GET", headers: this.#headers() }, signal);
|
|
800
|
+
const json = parseJsonSafe(await readLimitedText(res, 2e6));
|
|
801
|
+
if (!json || !Array.isArray(json.data)) throw fail(this.id, "malformed-response");
|
|
802
|
+
return json.data.map((m) => m.id).filter((x) => typeof x === "string").sort();
|
|
803
|
+
}
|
|
804
|
+
async listModels(signal) {
|
|
805
|
+
const ids = await this.#fetchModels(signal);
|
|
806
|
+
return { source: "live", models: ids.map((id) => ({ id })), note: "Models your key can list. Listing does not guarantee every model supports chat." };
|
|
807
|
+
}
|
|
808
|
+
async validateConnection(signal) {
|
|
809
|
+
const started = Date.now();
|
|
810
|
+
try {
|
|
811
|
+
const ids = await this.#fetchModels(signal);
|
|
812
|
+
const verified = ids.includes(this.model);
|
|
813
|
+
return {
|
|
814
|
+
state: "connected",
|
|
815
|
+
detail: verified ? `Authenticated; model ${this.model} is listed.` : `Authenticated, but ${this.model} was not in the model list.`,
|
|
816
|
+
modelVerified: verified,
|
|
817
|
+
latencyMs: Date.now() - started
|
|
818
|
+
};
|
|
819
|
+
} catch (err) {
|
|
820
|
+
const error = toProviderError(this.id, err, this.#http().secrets);
|
|
821
|
+
return { state: "failed", detail: error.message, modelVerified: null, error };
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
};
|
|
825
|
+
|
|
826
|
+
// src/providers/openai-compatible/index.ts
|
|
827
|
+
var OpenAICompatibleBackend = class {
|
|
828
|
+
id = "openai-compatible";
|
|
829
|
+
displayName;
|
|
830
|
+
supportsStreaming = true;
|
|
831
|
+
model;
|
|
832
|
+
#o;
|
|
833
|
+
constructor(options) {
|
|
834
|
+
this.#o = options;
|
|
835
|
+
this.model = options.model;
|
|
836
|
+
this.displayName = options.displayName ?? "Custom endpoint";
|
|
837
|
+
}
|
|
838
|
+
#http(extra = {}) {
|
|
839
|
+
const secrets = this.#o.secret ? [this.#o.secret] : [];
|
|
840
|
+
return { provider: this.id, fetch: this.#o.fetch, secrets, endpoint: this.#o.endpoint, ...this.#o.envVar ? { envVar: this.#o.envVar } : {}, ...this.#o.timeoutMs ? { timeoutMs: this.#o.timeoutMs } : {}, ...extra };
|
|
841
|
+
}
|
|
842
|
+
#headers() {
|
|
843
|
+
if (this.#o.secret) return { authorization: `Bearer ${this.#o.secret.reveal()}` };
|
|
844
|
+
if (this.#o.authRequired) throw fail(this.id, "missing-credentials", { ...this.#o.envVar ? { envVar: this.#o.envVar } : {} });
|
|
845
|
+
return {};
|
|
846
|
+
}
|
|
847
|
+
chat(messages, options = {}) {
|
|
848
|
+
return guardStream(this.id, options.signal, this.#http().secrets, this.#stream(messages, options));
|
|
849
|
+
}
|
|
850
|
+
async *#stream(messages, options) {
|
|
851
|
+
yield* completions({
|
|
852
|
+
http: this.#http({ notFoundCode: "endpoint-error" }),
|
|
853
|
+
url: `${this.#o.endpoint}/chat/completions`,
|
|
854
|
+
headers: this.#headers(),
|
|
855
|
+
model: this.model,
|
|
856
|
+
messages,
|
|
857
|
+
stream: options.stream !== false,
|
|
858
|
+
...options.maxTokens !== void 0 ? { maxTokens: options.maxTokens } : {},
|
|
859
|
+
maxTokensField: "max_tokens",
|
|
860
|
+
requireDoneSentinel: false,
|
|
861
|
+
...options.signal ? { signal: options.signal } : {}
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
async #fetchModels(signal) {
|
|
865
|
+
const res = await send(this.#http({ notFoundCode: "unsupported" }), `${this.#o.endpoint}/models`, { method: "GET", headers: this.#headers() }, signal);
|
|
866
|
+
const json = parseJsonSafe(await readLimitedText(res, 2e6));
|
|
867
|
+
if (!json || !Array.isArray(json.data)) throw fail(this.id, "malformed-response", { message: "The endpoint's /models response is not OpenAI-compatible." });
|
|
868
|
+
return json.data.map((m) => m.id).filter((x) => typeof x === "string");
|
|
869
|
+
}
|
|
870
|
+
async listModels(signal) {
|
|
871
|
+
const ids = await this.#fetchModels(signal);
|
|
872
|
+
return { source: "live", models: ids.map((id) => ({ id })), note: "Reported by the endpoint's /models route. Not every compatible server implements it." };
|
|
873
|
+
}
|
|
874
|
+
async validateConnection(signal) {
|
|
875
|
+
const started = Date.now();
|
|
876
|
+
try {
|
|
877
|
+
const ids = await this.#fetchModels(signal);
|
|
878
|
+
const verified = ids.includes(this.model);
|
|
879
|
+
return {
|
|
880
|
+
state: this.#o.secret || !this.#o.authRequired ? "connected" : "unverified",
|
|
881
|
+
detail: verified ? `Endpoint answered; model ${this.model} is listed.` : `Endpoint answered, but ${this.model} was not in its model list.`,
|
|
882
|
+
modelVerified: verified,
|
|
883
|
+
latencyMs: Date.now() - started
|
|
884
|
+
};
|
|
885
|
+
} catch (err) {
|
|
886
|
+
const error = toProviderError(this.id, err, this.#http().secrets);
|
|
887
|
+
if (error.code === "unsupported") {
|
|
888
|
+
return { state: "unverified", detail: "The endpoint has no /models route, so the connection and model could not be verified. Sending a message will show whether it works.", modelVerified: null, error };
|
|
889
|
+
}
|
|
890
|
+
return { state: "failed", detail: error.message, modelVerified: null, error };
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
};
|
|
894
|
+
|
|
895
|
+
// src/providers/types.ts
|
|
896
|
+
var BUILTIN_PROVIDER_IDS = ["openai", "anthropic", "gemini", "ollama", "openai-compatible"];
|
|
897
|
+
|
|
898
|
+
// src/providers/registry.ts
|
|
899
|
+
var KNOWN_NOTE = "Static identifiers bundled with zg; not verified against your account or the live API. Use `zg models list <provider>` for a live list.";
|
|
900
|
+
function insecureOk(env) {
|
|
901
|
+
return env["ZG_ALLOW_INSECURE_HTTP"] === "1";
|
|
902
|
+
}
|
|
903
|
+
function pickModel(desc, input) {
|
|
904
|
+
const explicit = input.model ?? (input.config.defaultProvider === desc.id ? input.config.defaultModel : null);
|
|
905
|
+
return explicit ?? desc.defaultModel;
|
|
906
|
+
}
|
|
907
|
+
function requireModel(id, model) {
|
|
908
|
+
if (!model) {
|
|
909
|
+
throw fail(id, "invalid-model", { message: "No model is selected for this provider.", hint: "Pick one with /model <id> or `zg provider use <provider> --model <id>`." });
|
|
910
|
+
}
|
|
911
|
+
const v = validateModelId(model);
|
|
912
|
+
if (!v.ok) throw fail(id, "invalid-model", { message: v.reason });
|
|
913
|
+
return v.value;
|
|
914
|
+
}
|
|
915
|
+
function simpleCreds(envVar) {
|
|
916
|
+
return () => ({ kind: "required", envVars: [envVar] });
|
|
917
|
+
}
|
|
918
|
+
var PROVIDERS = [
|
|
919
|
+
{
|
|
920
|
+
id: "openai",
|
|
921
|
+
displayName: "OpenAI",
|
|
922
|
+
description: "OpenAI API (api.openai.com), streaming chat completions.",
|
|
923
|
+
defaultModel: "gpt-4o-mini",
|
|
924
|
+
knownModels: ["gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini"],
|
|
925
|
+
knownModelsNote: KNOWN_NOTE,
|
|
926
|
+
supportsStreaming: true,
|
|
927
|
+
configRequirements: ["OPENAI_API_KEY environment variable"],
|
|
928
|
+
credentialSpec: simpleCreds("OPENAI_API_KEY"),
|
|
929
|
+
createBackend(input) {
|
|
930
|
+
const spec = this.credentialSpec(input.config);
|
|
931
|
+
const cred = readCredential(spec, input.env);
|
|
932
|
+
return new OpenAIBackend({ model: requireModel("openai", pickModel(this, input)), secret: cred?.secret ?? null, envVar: "OPENAI_API_KEY", fetch: input.fetch, ...input.timeoutMs ? { timeoutMs: input.timeoutMs } : {} });
|
|
933
|
+
}
|
|
934
|
+
},
|
|
935
|
+
{
|
|
936
|
+
id: "anthropic",
|
|
937
|
+
displayName: "Anthropic Claude",
|
|
938
|
+
description: "Anthropic Messages API (api.anthropic.com), streaming.",
|
|
939
|
+
defaultModel: "claude-sonnet-5-5",
|
|
940
|
+
knownModels: ["claude-fable-5-1", "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5"],
|
|
941
|
+
knownModelsNote: KNOWN_NOTE,
|
|
942
|
+
supportsStreaming: true,
|
|
943
|
+
configRequirements: ["ANTHROPIC_API_KEY environment variable"],
|
|
944
|
+
credentialSpec: simpleCreds("ANTHROPIC_API_KEY"),
|
|
945
|
+
createBackend(input) {
|
|
946
|
+
const cred = readCredential(this.credentialSpec(input.config), input.env);
|
|
947
|
+
return new AnthropicBackend({ model: requireModel("anthropic", pickModel(this, input)), secret: cred?.secret ?? null, envVar: "ANTHROPIC_API_KEY", fetch: input.fetch, ...input.timeoutMs ? { timeoutMs: input.timeoutMs } : {} });
|
|
948
|
+
}
|
|
949
|
+
},
|
|
950
|
+
{
|
|
951
|
+
id: "gemini",
|
|
952
|
+
displayName: "Google Gemini",
|
|
953
|
+
description: "Google Gemini API (generativelanguage.googleapis.com), streaming.",
|
|
954
|
+
defaultModel: "gemini-2.5-flash",
|
|
955
|
+
knownModels: ["gemini-2.5-pro", "gemini-2.5-flash"],
|
|
956
|
+
knownModelsNote: KNOWN_NOTE,
|
|
957
|
+
supportsStreaming: true,
|
|
958
|
+
configRequirements: ["GEMINI_API_KEY environment variable"],
|
|
959
|
+
credentialSpec: simpleCreds("GEMINI_API_KEY"),
|
|
960
|
+
createBackend(input) {
|
|
961
|
+
const cred = readCredential(this.credentialSpec(input.config), input.env);
|
|
962
|
+
return new GeminiBackend({ model: requireModel("gemini", pickModel(this, input)), secret: cred?.secret ?? null, envVar: "GEMINI_API_KEY", fetch: input.fetch, ...input.timeoutMs ? { timeoutMs: input.timeoutMs } : {} });
|
|
963
|
+
}
|
|
964
|
+
},
|
|
965
|
+
{
|
|
966
|
+
id: "ollama",
|
|
967
|
+
displayName: "Ollama (local)",
|
|
968
|
+
description: "A local Ollama server. No cloud account; models run on your machine.",
|
|
969
|
+
defaultModel: null,
|
|
970
|
+
knownModels: [],
|
|
971
|
+
knownModelsNote: "Ollama models are whatever is installed locally. Use `zg models list ollama` (the server must be running).",
|
|
972
|
+
supportsStreaming: true,
|
|
973
|
+
configRequirements: [`Ollama running (default ${OLLAMA_DEFAULT_ENDPOINT}; change with \`zg config set ollamaEndpoint <url>\`)`, "a model you have pulled yourself (zg never downloads models)", "OLLAMA_API_KEY only if your server sits behind authentication (optional)"],
|
|
974
|
+
credentialSpec: () => ({ kind: "optional", envVars: ["OLLAMA_API_KEY"] }),
|
|
975
|
+
createBackend(input) {
|
|
976
|
+
const raw = input.config.ollamaEndpoint ?? OLLAMA_DEFAULT_ENDPOINT;
|
|
977
|
+
const v = validateEndpoint(raw, { allowInsecureHttp: insecureOk(input.env) });
|
|
978
|
+
if (!v.ok) throw fail("ollama", "invalid-request", { message: `Invalid Ollama endpoint: ${v.reason}`, hint: "Fix it with `zg config set ollamaEndpoint <url>`." });
|
|
979
|
+
const cred = readCredential(this.credentialSpec(input.config), input.env);
|
|
980
|
+
const model = pickModel(this, input);
|
|
981
|
+
return new OllamaBackend({ model: model ? requireModel("ollama", model) : null, endpoint: v.value, secret: cred?.secret ?? null, envVar: "OLLAMA_API_KEY", fetch: input.fetch, ...input.timeoutMs ? { timeoutMs: input.timeoutMs } : {} });
|
|
982
|
+
}
|
|
983
|
+
},
|
|
984
|
+
{
|
|
985
|
+
id: "openai-compatible",
|
|
986
|
+
displayName: "OpenAI-compatible endpoint",
|
|
987
|
+
description: "Any server that implements POST <url>/chat/completions (LM Studio, vLLM, OpenRouter, LiteLLM, ...). Compatibility varies by server.",
|
|
988
|
+
defaultModel: null,
|
|
989
|
+
knownModels: [],
|
|
990
|
+
knownModelsNote: "Depends on the endpoint. Use `zg models list openai-compatible` if the server implements /models.",
|
|
991
|
+
supportsStreaming: true,
|
|
992
|
+
configRequirements: ["endpoint URL (https, or http for localhost)", "model name", "name of the env var holding the key (not the key itself), unless the server needs none"],
|
|
993
|
+
credentialSpec(config) {
|
|
994
|
+
const ce = config.customEndpoint;
|
|
995
|
+
if (!ce) return { kind: "none", envVars: [] };
|
|
996
|
+
if (!ce.requiresKey) return { kind: "none", envVars: [] };
|
|
997
|
+
return { kind: "required", envVars: ce.envVar ? [ce.envVar] : [] };
|
|
998
|
+
},
|
|
999
|
+
createBackend(input) {
|
|
1000
|
+
const ce = input.config.customEndpoint;
|
|
1001
|
+
if (!ce) {
|
|
1002
|
+
throw fail("openai-compatible", "not-configured", { message: "No custom endpoint is configured.", hint: "Run `zg provider use openai-compatible --endpoint <url> --model <id> --env-var <NAME>`." });
|
|
1003
|
+
}
|
|
1004
|
+
const v = validateEndpoint(ce.url, { allowInsecureHttp: insecureOk(input.env) });
|
|
1005
|
+
if (!v.ok) throw fail("openai-compatible", "invalid-request", { message: `Invalid endpoint: ${v.reason}` });
|
|
1006
|
+
const spec = this.credentialSpec(input.config);
|
|
1007
|
+
const cred = readCredential(spec, input.env);
|
|
1008
|
+
return new OpenAICompatibleBackend({
|
|
1009
|
+
model: requireModel("openai-compatible", pickModel(this, input)),
|
|
1010
|
+
endpoint: v.value,
|
|
1011
|
+
...ce.displayName ? { displayName: ce.displayName } : {},
|
|
1012
|
+
secret: cred?.secret ?? null,
|
|
1013
|
+
envVar: ce.envVar,
|
|
1014
|
+
authRequired: ce.requiresKey,
|
|
1015
|
+
fetch: input.fetch,
|
|
1016
|
+
...input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
];
|
|
1021
|
+
function getProvider(id) {
|
|
1022
|
+
return PROVIDERS.find((p) => p.id === id);
|
|
1023
|
+
}
|
|
1024
|
+
function requireProvider(id) {
|
|
1025
|
+
const found = getProvider(id.trim().toLowerCase());
|
|
1026
|
+
if (!found) throw new UnknownProviderError(id);
|
|
1027
|
+
return found;
|
|
1028
|
+
}
|
|
1029
|
+
var UnknownProviderError = class extends Error {
|
|
1030
|
+
constructor(id) {
|
|
1031
|
+
super(`unknown provider "${id.slice(0, 40)}". Valid providers: ${BUILTIN_PROVIDER_IDS.join(", ")}`);
|
|
1032
|
+
this.name = "UnknownProviderError";
|
|
1033
|
+
}
|
|
1034
|
+
};
|
|
1035
|
+
function describeProviderStatus(desc, config, env) {
|
|
1036
|
+
const credential = resolveCredentialStatus(desc.credentialSpec(config), env);
|
|
1037
|
+
const model = pickModel(desc, { config, env, fetch: void 0 });
|
|
1038
|
+
const base = { id: desc.id, displayName: desc.displayName, credential, model, connectionVerified: false };
|
|
1039
|
+
if (desc.id === "openai-compatible") {
|
|
1040
|
+
const ce = config.customEndpoint;
|
|
1041
|
+
if (!ce) return { ...base, readiness: "needs-config", detail: "No custom endpoint configured." };
|
|
1042
|
+
const v = validateEndpoint(ce.url, { allowInsecureHttp: insecureOk(env) });
|
|
1043
|
+
if (!v.ok) return { ...base, readiness: "needs-config", detail: `Endpoint invalid: ${v.reason}` };
|
|
1044
|
+
if (!model) return { ...base, readiness: "needs-config", detail: "No model selected." };
|
|
1045
|
+
if (ce.requiresKey && !ce.envVar) return { ...base, readiness: "needs-config", detail: "The endpoint requires a key but no environment variable name is configured." };
|
|
1046
|
+
}
|
|
1047
|
+
switch (credential.state) {
|
|
1048
|
+
case "missing":
|
|
1049
|
+
return { ...base, readiness: "missing-credentials", detail: `${credential.envVars.join(" or ")} is not set.` };
|
|
1050
|
+
case "invalid":
|
|
1051
|
+
return { ...base, readiness: "invalid-credentials-format", detail: `${credential.envVar} is set but contains characters that are not valid in a key (quotes, spaces or line breaks?).` };
|
|
1052
|
+
case "present":
|
|
1053
|
+
return { ...base, readiness: "ready", detail: `Key found in ${credential.envVar} (not verified until you connect).` };
|
|
1054
|
+
case "optional-absent":
|
|
1055
|
+
return { ...base, readiness: "ready", detail: "No key needed unless your server requires one." };
|
|
1056
|
+
case "not-required":
|
|
1057
|
+
return { ...base, readiness: "ready", detail: "No key required." };
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
function knownModelList(desc) {
|
|
1061
|
+
return { source: "known", models: desc.knownModels.map((id) => ({ id })), note: desc.knownModelsNote };
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
export {
|
|
1065
|
+
resolveCredentialStatus,
|
|
1066
|
+
shellInstructions,
|
|
1067
|
+
PROVIDERS,
|
|
1068
|
+
getProvider,
|
|
1069
|
+
requireProvider,
|
|
1070
|
+
UnknownProviderError,
|
|
1071
|
+
describeProviderStatus,
|
|
1072
|
+
knownModelList
|
|
1073
|
+
};
|