codex-copilot-dx 1.4.10 → 1.4.12
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/bin/cli.mjs +2 -0
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/REFERENCE.md +11 -1
- package/package.json +1 -1
- package/src/access-settings.mjs +3 -1
- package/src/adapter.mjs +14 -5
- package/src/antigravity-handler.mjs +102 -7
- package/src/antigravity-models.mjs +3 -2
- package/src/antigravity-runtime.mjs +61 -18
- package/src/antigravity-usage.mjs +3 -3
- package/src/api-target.mjs +12 -1
- package/src/application-configuration.mjs +2 -1
- package/src/application-control.mjs +6 -3
- package/src/cli-management.mjs +4 -1
- package/src/connection-management.mjs +4 -2
- package/src/connection-policy.mjs +3 -3
- package/src/connection-routing.mjs +28 -10
- package/src/connection-runtime.mjs +4 -0
- package/src/connection-view.mjs +12 -0
- package/src/copilot-client.mjs +3 -2
- package/src/copilot.mjs +13 -2
- package/src/dashboard/connections.js +5 -5
- package/src/dashboard/console.js +9 -4
- package/src/dashboard/context.js +15 -5
- package/src/dashboard/flow.js +1 -0
- package/src/dashboard/gemini.js +40 -10
- package/src/dashboard/index.html +10 -7
- package/src/dashboard/language.js +14 -3
- package/src/dashboard/status.js +15 -2
- package/src/dashboard/tool-activity.js +63 -35
- package/src/dashboard/ui.css +25 -16
- package/src/dashboard-api.mjs +2 -1
- package/src/failure-history.mjs +97 -0
- package/src/messages-tool-schema.mjs +1 -1
- package/src/model-capabilities.mjs +1 -1
- package/src/privacy-transform.mjs +22 -4
- package/src/provider-metadata.mjs +1 -1
- package/src/providers/api-network.mjs +4 -3
- package/src/providers/api.mjs +79 -15
- package/src/response-failures.mjs +3 -1
- package/src/runtime-config.mjs +1 -0
- package/src/source-admission.mjs +1 -1
- package/src/windows-http-network.mjs +4 -3
- package/src/windows-prediction-network.cs +11 -0
package/src/providers/api.mjs
CHANGED
|
@@ -28,7 +28,8 @@ import { redactDiagnosticText } from "../diagnostic-text.mjs";
|
|
|
28
28
|
import { createProviderCooldown, confirmedNetworkFailure } from "../provider-cooldown.mjs";
|
|
29
29
|
import { SOURCE_LIMIT_EVIDENCE, sourceLimitFeedback } from "../source-admission.mjs";
|
|
30
30
|
|
|
31
|
-
const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
|
|
31
|
+
const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions", gemini: "/v1beta/models:generateContent" };
|
|
32
|
+
const geminiModelId = id => typeof id === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,139}$/.test(id) && !id.includes("..");
|
|
32
33
|
export function apiCatalog(config, env = process.env) {
|
|
33
34
|
const revision = deploymentRevision(config, env);
|
|
34
35
|
return config.models.map(model => { const protocol_capabilities = Object.fromEntries(model.protocols.map(protocol => [protocol, resolveModelCapabilities(model, { revision, protocol })]));
|
|
@@ -37,15 +38,16 @@ export function apiCatalog(config, env = process.env) {
|
|
|
37
38
|
capability, protocol_capabilities }); });
|
|
38
39
|
}
|
|
39
40
|
export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork, modelDisplay = () => ({}), now = Date.now, errorCapture } = {}) {
|
|
40
|
-
const cooldowns = Object.fromEntries(
|
|
41
|
+
const cooldowns = Object.fromEntries(Object.keys(paths).map(protocol => [protocol, createProviderCooldown({ now })]));
|
|
41
42
|
const catalog = apiCatalog(config, env);
|
|
42
43
|
const fingerprint = config.key_env ? createHash("sha256").update(env[config.key_env] || "").digest("hex") : "";
|
|
43
44
|
const generation = parseInt(createHash("sha256").update(JSON.stringify(config) + fingerprint).digest("hex").slice(0, 8), 16);
|
|
44
|
-
const profiles = Object.fromEntries(
|
|
45
|
-
endpoint: config.endpoints[protocol] ? new URL(config.endpoints[protocol]).href : null, key: config.secret_ref || fingerprint, auth: protocol === "messages" ? config.auth_header : "bearer",
|
|
45
|
+
const profiles = Object.fromEntries(Object.keys(paths).map(protocol => [protocol, `api:${config.id}:${createHash("sha256").update(JSON.stringify({
|
|
46
|
+
endpoint: config.endpoints[protocol] ? new URL(config.endpoints[protocol]).href : null, key: config.secret_ref || fingerprint, auth: protocol === "messages" ? config.auth_header : protocol === "gemini" ? "x-goog-api-key" : "bearer",
|
|
46
47
|
})).digest("hex").slice(0, 24)}`]));
|
|
47
48
|
const profile = profiles.responses;
|
|
48
|
-
const modelsUrl = config.base_url.replace(/\/+$/, "") + "/models",
|
|
49
|
+
const modelsUrl = config.base_url.replace(/\/+$/, "") + "/models", geminiModelsUrl = config.endpoints.gemini && new URL(config.endpoints.gemini).href;
|
|
50
|
+
const targets = [...Object.values(config.endpoints), modelsUrl];
|
|
49
51
|
if (config.endpoints.messages) targets.push(config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens");
|
|
50
52
|
if (config.endpoints.responses) targets.push(config.endpoints.responses.replace(/\/+$/, "") + "/compact");
|
|
51
53
|
let network, closed = false;
|
|
@@ -60,7 +62,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
60
62
|
retiring.add(previous);
|
|
61
63
|
void Promise.resolve(previous.retire()).then(() => retiring.delete(previous), () => { previous.close();retiring.delete(previous); });
|
|
62
64
|
} else previous?.close();
|
|
63
|
-
return initialization.run("network", sharedSignal => networkFactory({ targets, env, platform, signal: AbortSignal.any([sharedSignal, lifetime.signal]) })
|
|
65
|
+
return initialization.run("network", sharedSignal => networkFactory({ targets, geminiModelsUrl, env, platform, signal: AbortSignal.any([sharedSignal, lifetime.signal]) })
|
|
64
66
|
.then(value => { if (closed || sharedSignal.aborted) { value.close();throw accessError("ccdx_api_closed", 503); }network = value;return value; }), { signal });
|
|
65
67
|
};
|
|
66
68
|
let messageAliases;
|
|
@@ -74,15 +76,19 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
74
76
|
if (config.key_env && !env[config.key_env]) throw accessError("ccdx_api_environment_key_missing", 503);
|
|
75
77
|
const key = config.key_env ? checkedApiKey(env[config.key_env]) : await initialization.run("credential", () => secrets.get(config.secret_ref),
|
|
76
78
|
{ signal: options.signal ? AbortSignal.any([options.signal, lifetime.signal]) : lifetime.signal });
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
+
const stream = api === "gemini" ? options.geminiStream === true : body?.stream === true;
|
|
80
|
+
const requestModel = api === "gemini" ? options.geminiModel : body?.model;
|
|
81
|
+
const headers = { "Content-Type": "application/json", Accept: stream ? "text/event-stream" : "application/json" };
|
|
82
|
+
if (api === "gemini") headers["x-goog-api-key"] = key;
|
|
83
|
+
else if (api === "messages" && config.auth_header === "x-api-key") headers["x-api-key"] = key;
|
|
84
|
+
else headers.Authorization = `Bearer ${key}`;
|
|
79
85
|
if (api === "messages") {
|
|
80
86
|
headers["anthropic-version"] = "2023-06-01";
|
|
81
87
|
for (const name of ["anthropic-version", "anthropic-beta"]) { const value = options.headers?.[name];if (typeof value === "string" && value.length < 8192 && !/[\r\n]/.test(value)) headers[name] = value; }
|
|
82
88
|
}
|
|
83
89
|
if (body && !options.countTokens) {
|
|
84
|
-
const capability = catalog.find(model => model.id ===
|
|
85
|
-
const constrained = constrainModelRequest(body, capability, api);
|
|
90
|
+
const capability = catalog.find(model => model.id === requestModel)?.protocol_capabilities[api];
|
|
91
|
+
const constrained = api === "gemini" ? { body, applied: [] } : constrainModelRequest(body, capability, api);
|
|
86
92
|
if (constrained.body !== body) { body = constrained.body;options = { ...options, bodyText: undefined }; }
|
|
87
93
|
markRequestObservation({ capability_revision: capability?.revision, capability_constraints: constrained.applied.join(",") || "none" });
|
|
88
94
|
markRequestObservation({ context_window_tokens: capability?.values.context_window });
|
|
@@ -94,7 +100,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
94
100
|
try {
|
|
95
101
|
const transport = !closed && network && (network.healthy?.() ?? true) ? network : await getNetwork(options.signal);
|
|
96
102
|
const result = await sourceTransport(options, { send: transport.fetch, receiver: transport, args: [url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal }],
|
|
97
|
-
model:
|
|
103
|
+
model: requestModel, bodyText: serialized, stream, observe: Boolean(body && options.observeUpstream !== false),
|
|
98
104
|
evidence: body && !options.countTokens ? { max_output_tokens_sent: api === "messages" ? body.max_tokens : api === "chat" ? body.max_completion_tokens : body.max_output_tokens,
|
|
99
105
|
reasoning_effort_sent: api === "messages" ? body.output_config?.effort : api === "chat" ? body.reasoning_effort : body.reasoning?.effort } : undefined });
|
|
100
106
|
const temporary = result.status === 502 || result.status === 503 || result.status === 504;
|
|
@@ -164,6 +170,38 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
164
170
|
throw failure;
|
|
165
171
|
}
|
|
166
172
|
}
|
|
173
|
+
async function discoverGemini({ signal }) {
|
|
174
|
+
const models = new Map(), cursors = new Set(), checked_at = new Date().toISOString();
|
|
175
|
+
const deployment = deploymentRevision(config, env);
|
|
176
|
+
let url = geminiModelsUrl, bytes = 0, entries = 0;
|
|
177
|
+
for (let page = 0; page < 25; page++) {
|
|
178
|
+
const response = await request(url, undefined, { signal }, "gemini");
|
|
179
|
+
if (!response.ok) {
|
|
180
|
+
await cancelSourceResponse(response).catch(() => {});
|
|
181
|
+
throw accessError(`ccdx_api_catalog_http_${response.status}`, response.status === 401 || response.status === 403 ? response.status : 502);
|
|
182
|
+
}
|
|
183
|
+
const text = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES - bytes, label: "Gemini model catalog", signal });
|
|
184
|
+
bytes += Buffer.byteLength(text);
|
|
185
|
+
let value;try { value = JSON.parse(text); } catch { throw accessError("ccdx_api_catalog_invalid", 502); }
|
|
186
|
+
if (!Array.isArray(value?.models) || (entries += value.models.length) > 500) throw accessError("ccdx_api_catalog_invalid", 502);
|
|
187
|
+
for (const model of value.models) {
|
|
188
|
+
const id = typeof model?.name === "string" && model.name.startsWith("models/") ? model.name.slice(7) : null;
|
|
189
|
+
if (!geminiModelId(id) || !Array.isArray(model.supportedGenerationMethods)) throw accessError("ccdx_api_catalog_invalid", 502);
|
|
190
|
+
if (!model.supportedGenerationMethods.includes("generateContent") || models.has(id)) continue;
|
|
191
|
+
const capabilities = {};
|
|
192
|
+
if (Number.isSafeInteger(model.inputTokenLimit) && model.inputTokenLimit > 0) capabilities.context_window = model.inputTokenLimit;
|
|
193
|
+
if (Number.isSafeInteger(model.outputTokenLimit) && model.outputTokenLimit > 0) capabilities.max_output_tokens = model.outputTokenLimit;
|
|
194
|
+
models.set(id, { id, display: apiModelDisplay({ ...model, id, display_name: model.displayName }), protocols: ["gemini"],
|
|
195
|
+
metadata: { values: {}, protocols: { gemini: capabilities }, state: "reported", checked_at, deployment } });
|
|
196
|
+
}
|
|
197
|
+
const token = value.nextPageToken;
|
|
198
|
+
if (token === undefined || token === "") return [...models.values()];
|
|
199
|
+
if (typeof token !== "string" || !/^[\w.%~+/=-]{1,2048}$/.test(token) || cursors.has(token) || bytes >= MAX_UPSTREAM_MODEL_CATALOG_BYTES) throw accessError("ccdx_api_catalog_invalid", 502);
|
|
200
|
+
cursors.add(token);
|
|
201
|
+
const next = new URL(geminiModelsUrl);next.searchParams.set("pageToken", token);url = next.href;
|
|
202
|
+
}
|
|
203
|
+
throw accessError("ccdx_api_catalog_limit", 502);
|
|
204
|
+
}
|
|
167
205
|
const counter = createApiTokenCounter({ request: (body, options) => request(config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens", body, options, "messages") });
|
|
168
206
|
const client = {
|
|
169
207
|
[SOURCE_HTTP_CLIENT]: true,
|
|
@@ -184,11 +222,22 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
184
222
|
const outgoing = model.id === body.model ? body : { ...body, model: model.id };
|
|
185
223
|
return options.countTokens ? counter.count(outgoing, options) : request(config.endpoints.messages, outgoing, options, "messages");
|
|
186
224
|
},
|
|
225
|
+
gemini(body, options = {}) {
|
|
226
|
+
const model = selected(body.model, "gemini");
|
|
227
|
+
if (!geminiModelId(model.id)) throw accessError("ccdx_api_model_unavailable");
|
|
228
|
+
const operation = options.countTokens ? "countTokens" : options.stream ? "streamGenerateContent" : "generateContent";
|
|
229
|
+
const url = `${geminiModelsUrl}/${model.id}:${operation}${operation === "streamGenerateContent" ? "?alt=sse" : ""}`;
|
|
230
|
+
if (!Array.isArray(body.request?.contents)) throw accessError("ccdx_api_config_invalid");
|
|
231
|
+
const requestFields = ["contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "safetySettings", "cachedContent"];
|
|
232
|
+
const nativeRequest = Object.fromEntries(requestFields.filter(key => Object.hasOwn(body.request, key)).map(key => [key, body.request[key]]));
|
|
233
|
+
const payload = options.countTokens ? { generateContentRequest: { ...nativeRequest, model: "models/" + model.id } } : nativeRequest;
|
|
234
|
+
return request(url, payload, { ...options, geminiModel: model.id, geminiStream: operation === "streamGenerateContent" }, "gemini");
|
|
235
|
+
},
|
|
187
236
|
};
|
|
188
237
|
return {
|
|
189
238
|
id: config.id, name: config.name, client, registry, configuredModels: true, defaultReviewEffort: null, profileId: (protocol = "responses") => profiles[protocol] || profile,
|
|
190
|
-
models: family => catalog.filter(model => model.supported_endpoints.includes(family === "claude" ? paths.messages : paths.responses))
|
|
191
|
-
.map(model => ({ ...model, ...modelDisplay(model.id), capability: model.protocol_capabilities[family === "claude" ? "messages" : "responses"] })),
|
|
239
|
+
models: family => catalog.filter(model => model.supported_endpoints.includes(family === "claude" ? paths.messages : family === "gemini" ? paths.gemini : paths.responses))
|
|
240
|
+
.map(model => ({ ...model, ...modelDisplay(model.id), capability: model.protocol_capabilities[family === "claude" ? "messages" : family === "gemini" ? "gemini" : "responses"] })),
|
|
192
241
|
catalog: () => catalog,
|
|
193
242
|
health: () => Object.fromEntries(Object.entries(cooldowns).filter(([protocol]) => config.endpoints[protocol]).map(([protocol, cooldown]) => [protocol, cooldown.snapshot()])),
|
|
194
243
|
publicCatalog(allowed = []) { return { source: "configured", checkedAt: config.checked_at || null, upstreamHost: new URL(config.base_url).hostname,
|
|
@@ -197,6 +246,8 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
197
246
|
clients: model => allowed.filter(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)) }).map(model => ({ ...model,
|
|
198
247
|
capability: catalog.find(entry => entry.id === model.id)?.capability, auto_review_efforts: [...(catalog.find(entry => entry.id === model.id)?.protocol_capabilities.responses?.values.reasoning_efforts || [])] })) }; },
|
|
199
248
|
async discover({ signal } = {}) {
|
|
249
|
+
const gemini = geminiModelsUrl ? await discoverGemini({ signal }) : [];
|
|
250
|
+
if (geminiModelsUrl && !config.endpoints.responses && !config.endpoints.messages && !config.endpoints.chat) return gemini;
|
|
200
251
|
const models = [], cursors = new Set(), checked_at = new Date().toISOString();let url = modelsUrl, bytes = 0;
|
|
201
252
|
for (let page = 0; page < 25; page++) {
|
|
202
253
|
const response = await request(url, undefined, { signal }, config.endpoints.responses ? "responses" : "messages");
|
|
@@ -211,8 +262,21 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
211
262
|
for (const model of value.data) { if (!model || typeof model.id !== "string" || !/^[\w][\w./:@+-]{0,159}$/.test(model.id) || model.id.includes("..") || model.id.includes("//")) throw accessError("ccdx_api_catalog_invalid", 502); }
|
|
212
263
|
// A catalog listing is not evidence that every model supports every API.
|
|
213
264
|
models.push(...value.data);
|
|
214
|
-
if (value.has_more !== true)
|
|
215
|
-
|
|
265
|
+
if (value.has_more !== true) {
|
|
266
|
+
const byId = new Map(uniqueModelEntries(models).map(model => [model.id, { id: model.id, display: apiModelDisplay(model),
|
|
267
|
+
metadata: apiModelMetadata(model, { checked_at, deployment: deploymentRevision(config, env) }), protocols: Array.isArray(model.supported_endpoints)
|
|
268
|
+
? Object.entries(paths).filter(([, endpoint]) => model.supported_endpoints.includes(endpoint) || model.supported_endpoints.includes(endpoint.slice(3))).map(([api]) => api).filter(api => config.endpoints[api]) : [] }]));
|
|
269
|
+
for (const model of gemini) {
|
|
270
|
+
const previous = byId.get(model.id);
|
|
271
|
+
if (!previous) byId.set(model.id, model);
|
|
272
|
+
else {
|
|
273
|
+
previous.protocols = [...new Set([...previous.protocols, ...model.protocols])];
|
|
274
|
+
previous.metadata.protocols = { ...previous.metadata.protocols, ...model.metadata.protocols };
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (byId.size > 500) throw accessError("ccdx_api_catalog_limit", 502);
|
|
278
|
+
return [...byId.values()];
|
|
279
|
+
}
|
|
216
280
|
// Follow only the native cursor on the configured origin, never an
|
|
217
281
|
// upstream next-page URL that could disclose this source's credential.
|
|
218
282
|
if (!value.data.length || value.last_id !== value.data.at(-1).id || cursors.has(value.last_id) || bytes >= MAX_UPSTREAM_MODEL_CATALOG_BYTES) throw accessError("ccdx_api_catalog_invalid", 502);
|
|
@@ -145,7 +145,7 @@ export function requestOptionsEvidence(body) {
|
|
|
145
145
|
return result;
|
|
146
146
|
}
|
|
147
147
|
|
|
148
|
-
export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
|
|
148
|
+
export function createHttpFailureDiagnostics({ maxEntries = 20, now, history } = {}) {
|
|
149
149
|
const all = createResponseFailureDiagnostics({ maxEntries, now });
|
|
150
150
|
const actionable = createResponseFailureDiagnostics({ maxEntries, now });
|
|
151
151
|
const protocol = createResponseFailureDiagnostics({ maxEntries: 8, now });
|
|
@@ -165,6 +165,7 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
|
|
|
165
165
|
: details.route === "image_mcp" && details.http_status === 405 ? "protocol"
|
|
166
166
|
: details.route === "not_found" ? "route" : "other";
|
|
167
167
|
counts[category]++;
|
|
168
|
+
if (category === "inference") history?.record(details);
|
|
168
169
|
if (probe) { discovery.record(details);return; }
|
|
169
170
|
if ((category === "inference" || category === "other") && !accessNotice) actionable.record(details);
|
|
170
171
|
if (category === "capability") {
|
|
@@ -205,6 +206,7 @@ export function buildHttpFailureDetails({ statusCode, route, requestId, model, c
|
|
|
205
206
|
}
|
|
206
207
|
const message = (Object.hasOwn(reasons, reason) ? reasons[reason] : null) || (route === "messages_count_tokens" && statusCode === 404 ? "The source's token-count endpoint returned HTTP 404. Message generation is separate."
|
|
207
208
|
: code === "ccdx_api_network_unavailable" ? "Connection to the model source failed."
|
|
209
|
+
: code === "upstream_timeout" && attempt_timings?.length && attempt_timings.at(-1)?.headers_ms == null ? "Timed out waiting for the model source to respond."
|
|
208
210
|
: origin === "privacy" ? "Local privacy processing failed. Review its error code and request timeline."
|
|
209
211
|
: origin === "client_validation" ? "The request was rejected locally before an upstream call."
|
|
210
212
|
: error_body === "empty" ? "Upstream returned no error details." : "HTTP request failed; original response was preserved.");
|
package/src/runtime-config.mjs
CHANGED
|
@@ -41,6 +41,7 @@ export function parseTimerMs(value, fallback) {
|
|
|
41
41
|
export function loadRuntimeConfig(env = process.env) {
|
|
42
42
|
return Object.freeze({
|
|
43
43
|
upstreamTimeoutMs: parseTimerMs(env.CCDX_UPSTREAM_TIMEOUT_MS, RUNTIME_DEFAULTS.upstreamTimeoutMs),
|
|
44
|
+
antigravityCopilotTimeoutMs: parseTimerMs(env.CCDX_ANTIGRAVITY_COPILOT_TIMEOUT_MS, 0) || undefined,
|
|
44
45
|
streamHandshakeTimeoutMs: parseTimerMs(env.CCDX_STREAM_HANDSHAKE_TIMEOUT_MS, RUNTIME_DEFAULTS.streamHandshakeTimeoutMs),
|
|
45
46
|
streamIdleTimeoutMs: parseTimerMs(env.CCDX_STREAM_IDLE_TIMEOUT_MS, RUNTIME_DEFAULTS.streamIdleTimeoutMs),
|
|
46
47
|
requestBodyTimeoutMs: parseTimerMs(env.CCDX_REQUEST_BODY_TIMEOUT_MS, RUNTIME_DEFAULTS.requestBodyTimeoutMs),
|
package/src/source-admission.mjs
CHANGED
|
@@ -283,7 +283,7 @@ export function createSourceAdmission({ now = Date.now, initialLimit = MAX_LIMIT
|
|
|
283
283
|
if (!client || clients.has(client) || client[SOURCE_ADMISSION]?.scheduler === this) return clients.get(client) || client;
|
|
284
284
|
const wrapped = { ...client };
|
|
285
285
|
const sourceContext = { scheduler: this, descriptor };
|
|
286
|
-
for (const method of ["responses", "responsesCompact", "messages", "chatCompletions", "images"]) {
|
|
286
|
+
for (const method of ["responses", "responsesCompact", "messages", "chatCompletions", "images", "gemini"]) {
|
|
287
287
|
if (typeof client[method] !== "function") continue;
|
|
288
288
|
const perform = args => client[method](...args);
|
|
289
289
|
wrapped[method] = (...args) => {
|
|
@@ -11,12 +11,13 @@ function failure(code) {
|
|
|
11
11
|
|
|
12
12
|
// Private, credit-based WinHTTP transport. Each consumer owns its worker and a
|
|
13
13
|
// fixed target group; prediction and M365 cannot share credentials or requests.
|
|
14
|
-
export async function startWindowsHttpNetwork({ settings = {}, target = "prediction", apiTargets = [], validatePac = () => {}, env = process.env, spawnImpl = spawn, timeoutMs = 30_000, onFailure = () => {}, signal } = {}) {
|
|
14
|
+
export async function startWindowsHttpNetwork({ settings = {}, target = "prediction", apiTargets = [], geminiModelsUrl, validatePac = () => {}, env = process.env, spawnImpl = spawn, timeoutMs = 30_000, onFailure = () => {}, signal } = {}) {
|
|
15
15
|
signal?.throwIfAborted();
|
|
16
16
|
if (!["prediction", "m365", "api"].includes(target)) throw failure("proxy_target_invalid");
|
|
17
17
|
if (target === "api" && (!Array.isArray(apiTargets) || !apiTargets.length || apiTargets.length > 8 || apiTargets.some(raw => {
|
|
18
18
|
try { const url = new URL(raw);return url.protocol !== "https:" || url.username || url.password || url.search || url.hash || url.href !== raw; } catch { return true; }
|
|
19
19
|
}))) throw failure("proxy_target_invalid");
|
|
20
|
+
if (geminiModelsUrl && (target !== "api" || !apiTargets.includes(geminiModelsUrl))) throw failure("proxy_target_invalid");
|
|
20
21
|
const allowedHosts = target === "api" ? apiTargets.map(raw => new URL(raw).hostname) : target === "m365" ? [M365_API_HOST] : ["chatgpt.com", "ab.chatgpt.com"];
|
|
21
22
|
const command = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
22
23
|
const source = fileURLToPath(new URL("./windows-prediction-network.cs", import.meta.url));
|
|
@@ -58,7 +59,7 @@ export async function startWindowsHttpNetwork({ settings = {}, target = "predict
|
|
|
58
59
|
req.frame(event);
|
|
59
60
|
}
|
|
60
61
|
});
|
|
61
|
-
write({autoDetect:settings.autoDetect===true,pac:settings.pac||"",...(target !== "prediction" ? {target,timeoutMs} : {}),...(target === "api" ? {apiTargets} : {})});
|
|
62
|
+
write({autoDetect:settings.autoDetect===true,pac:settings.pac||"",...(target !== "prediction" ? {target,timeoutMs} : {}),...(target === "api" ? {apiTargets,geminiModelsUrl} : {})});
|
|
62
63
|
const timer=setTimeout(()=>stop(failure("proxy_wpad_timeout")),timeoutMs);
|
|
63
64
|
let script;
|
|
64
65
|
try{if(signal?.aborted)cancelled();script=await ready;}catch(error){stop(error);throw error;}finally{clearTimeout(timer);signal?.removeEventListener("abort",cancelled);}
|
|
@@ -73,7 +74,7 @@ export async function startWindowsHttpNetwork({ settings = {}, target = "predict
|
|
|
73
74
|
if(!allowedHosts.includes(host)||!String(options.path).startsWith("/")||target !== "api" && String(options.path).startsWith("//"))throw failure("proxy_target_invalid");
|
|
74
75
|
if(target === "m365" && !String(options.path).startsWith("/api/v1/llmapi/")) throw failure("proxy_target_invalid");
|
|
75
76
|
const requestUrl = `https://${host}${options.port && Number(options.port) !== 443 ? `:${options.port}` : ""}${options.path}`;
|
|
76
|
-
if(target === "api" && !apiTargetAllowed(requestUrl, apiTargets, options.method || "GET")) throw failure("proxy_target_invalid");
|
|
77
|
+
if(target === "api" && !apiTargetAllowed(requestUrl, apiTargets, options.method || "GET", geminiModelsUrl)) throw failure("proxy_target_invalid");
|
|
77
78
|
const headers=[];
|
|
78
79
|
for(const [name,value]of Object.entries(options.headers||{})){
|
|
79
80
|
if(!/^[!#$%&'*+.^_`|~0-9a-z-]+$/i.test(name))throw failure("proxy_headers_invalid");
|
|
@@ -32,6 +32,7 @@ public static class CCDXPredictionNetwork {
|
|
|
32
32
|
static IntPtr session;
|
|
33
33
|
static string target = "prediction";
|
|
34
34
|
static HashSet<string> apiTargets = new HashSet<string>(StringComparer.Ordinal);
|
|
35
|
+
static Uri geminiModelsUrl;
|
|
35
36
|
static int requestTimeout = 30000;
|
|
36
37
|
class Work { public IntPtr handle; public ManualResetEventSlim ack = new ManualResetEventSlim(false); public BlockingCollection<byte[]> upload = new BlockingCollection<byte[]>(2); public bool cancelled; }
|
|
37
38
|
static void Check(bool ok) { if(!ok) throw new IOException("winhttp_" + Marshal.GetLastWin32Error()); }
|
|
@@ -76,6 +77,15 @@ public static class CCDXPredictionNetwork {
|
|
|
76
77
|
}
|
|
77
78
|
static bool ApiTargetAllowed(Uri uri, string method) {
|
|
78
79
|
if(apiTargets.Contains(uri.AbsoluteUri))return true;
|
|
80
|
+
if(geminiModelsUrl!=null && uri.Fragment.Length==0 && uri.GetLeftPart(UriPartial.Authority)==geminiModelsUrl.GetLeftPart(UriPartial.Authority)) {
|
|
81
|
+
string root=geminiModelsUrl.AbsolutePath;
|
|
82
|
+
if(method=="GET" && uri.AbsolutePath==root && uri.Query.StartsWith("?pageToken=",StringComparison.Ordinal) && uri.Query.IndexOf('&')<0)
|
|
83
|
+
return System.Text.RegularExpressions.Regex.IsMatch(Uri.UnescapeDataString(uri.Query.Substring(11).Replace("+"," ")),@"^[A-Za-z0-9_.%~+/=\-]{1,2048}$");
|
|
84
|
+
if(method=="POST" && uri.AbsolutePath.StartsWith(root+"/",StringComparison.Ordinal)) {
|
|
85
|
+
var call=System.Text.RegularExpressions.Regex.Match(uri.AbsolutePath.Substring(root.Length+1),@"^[A-Za-z0-9][A-Za-z0-9._\-]{0,139}:(generateContent|streamGenerateContent|countTokens)$");
|
|
86
|
+
if(call.Success)return call.Groups[1].Value=="streamGenerateContent" ? uri.Query=="?alt=sse" : uri.Query.Length==0;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
79
89
|
if(method!="GET" || !uri.AbsolutePath.EndsWith("/models",StringComparison.Ordinal) || !uri.Query.StartsWith("?after_id=",StringComparison.Ordinal) || uri.Query.IndexOf('&')>=0)return false;
|
|
80
90
|
string cursor=Uri.UnescapeDataString(uri.Query.Substring(10));
|
|
81
91
|
return System.Text.RegularExpressions.Regex.IsMatch(cursor,"^[A-Za-z0-9_][A-Za-z0-9_./:@+\\-]{0,159}$") && !cursor.Contains("..") && !cursor.Contains("//") && apiTargets.Contains(uri.GetLeftPart(UriPartial.Path));
|
|
@@ -138,6 +148,7 @@ public static class CCDXPredictionNetwork {
|
|
|
138
148
|
if(initial.ContainsKey("target")) target=(string)initial["target"];
|
|
139
149
|
if(target!="prediction"&&target!="m365"&&target!="api")throw new IOException("winhttp_target_invalid");
|
|
140
150
|
if(target=="api") { if(initial["apiTargets"] is string)throw new IOException("winhttp_target_invalid");foreach(object raw in (System.Collections.IEnumerable)initial["apiTargets"]) { var uri=new Uri((string)raw);if(uri.Scheme!="https"||uri.UserInfo.Length!=0||uri.Query.Length!=0||uri.Fragment.Length!=0)throw new IOException("winhttp_target_invalid");apiTargets.Add(uri.AbsoluteUri);if(apiTargets.Count>8)throw new IOException("winhttp_target_invalid"); }if(apiTargets.Count<1)throw new IOException("winhttp_target_invalid"); }
|
|
151
|
+
if(target=="api" && initial.ContainsKey("geminiModelsUrl")) { geminiModelsUrl=new Uri((string)initial["geminiModelsUrl"]);if(!apiTargets.Contains(geminiModelsUrl.AbsoluteUri))throw new IOException("winhttp_target_invalid"); }
|
|
141
152
|
if(target!="prediction" && initial.ContainsKey("timeoutMs")) requestTimeout=(int)Math.Max(1000,Math.Min(int.MaxValue,Convert.ToInt64(initial["timeoutMs"])));
|
|
142
153
|
session=WinHttpOpen(target=="m365"?"CCDX Microsoft 365":target=="api"?"CCDX API":"CCDX native prediction",4,null,null,0);
|
|
143
154
|
Check(session!=IntPtr.Zero);Check(WinHttpSetTimeouts(session,10000,10000,requestTimeout,requestTimeout));
|