codex-copilot-dx 1.4.11 → 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/REFERENCE.md +10 -0
- 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 +8 -5
- package/src/dashboard/language.js +13 -0
- package/src/dashboard/status.js +15 -2
- package/src/dashboard/tool-activity.js +4 -4
- package/src/dashboard/ui.css +20 -11
- package/src/failure-history.mjs +97 -0
- 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/dashboard/ui.css
CHANGED
|
@@ -499,7 +499,8 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
499
499
|
.source-account-actions { margin-top: 18px; }
|
|
500
500
|
@media(max-width:640px) { .account-summary { grid-template-columns:1fr; } }
|
|
501
501
|
|
|
502
|
-
.flow-
|
|
502
|
+
.flow-viewport { height:290px; overflow:auto; scrollbar-gutter:stable; margin:16px 0 12px; }
|
|
503
|
+
.flow-network { position:relative;display:grid;grid-template-columns:minmax(130px,1fr) 70px minmax(170px,1fr);column-gap:clamp(36px,6vw,92px);align-items:stretch;min-height:100%; }
|
|
503
504
|
.flow-wires { position:absolute;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible; }
|
|
504
505
|
.flow-activity { will-change:transform; }
|
|
505
506
|
.flow-wires .flow-split { visibility:hidden;animation:none; }
|
|
@@ -512,7 +513,7 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
512
513
|
#flow-apps .flow-choice { text-align:right; }
|
|
513
514
|
#flow-apps .flow-count { margin-right:9px; }
|
|
514
515
|
#flow-apps .flow-note { left:auto;right:9px;text-align:right; }
|
|
515
|
-
.flow-hub-column { display:flex;align-items:center;justify-content:center;padding-top:32px; }
|
|
516
|
+
.flow-hub-column { position:sticky;top:0;align-self:start;display:flex;align-items:center;justify-content:center;height:290px;padding-top:32px; }
|
|
516
517
|
.flow-node { position:relative;display:flex;align-items:center;gap:8px;width:max-content;max-width:100%;min-height:34px; }
|
|
517
518
|
.flow-choice { min-width:0;max-width:100%;min-height:34px;padding:7px 9px;border-color:transparent;background:transparent;color:var(--text);font-size:12px;font-weight:600;text-transform:none;text-align:center;overflow-wrap:anywhere; }
|
|
518
519
|
.flow-choice:hover { background:var(--option-hover); }
|
|
@@ -533,7 +534,7 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
533
534
|
#request-flow[data-state="unknown"] .flow-halo-track { opacity:.15; }
|
|
534
535
|
#request-flow[data-paused="true"] .flow-halo-turn { animation-play-state:paused; }
|
|
535
536
|
@keyframes flow-orbit { from { transform:rotate(-90deg); } to { transform:rotate(270deg); } }
|
|
536
|
-
.flow-caption { display:flex;align-items:center;flex-wrap:wrap;gap:
|
|
537
|
+
.flow-caption { display:flex;align-items:center;flex-wrap:wrap;gap:8px 16px;height:40px;overflow:auto;font-size:11px;color:var(--muted); }
|
|
537
538
|
.flow-caption button { padding:5px 9px; }
|
|
538
539
|
.flow-wire { fill:none;stroke:var(--border);stroke-width:1;stroke-linecap:round;stroke-linejoin:round; }
|
|
539
540
|
.flow-live { stroke:var(--accent);opacity:.68; }
|
|
@@ -546,6 +547,7 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
546
547
|
@keyframes flow-dash { from { stroke-dashoffset:0; } to { stroke-dashoffset:24; } }
|
|
547
548
|
@keyframes flow-breathe { 0%,100% { opacity:.45; } 50% { opacity:1; } }
|
|
548
549
|
@media(max-width:760px) {
|
|
550
|
+
.flow-caption { height:72px; }
|
|
549
551
|
.flow-network { grid-template-columns:minmax(105px,1fr) 66px minmax(120px,1fr);column-gap:18px; }
|
|
550
552
|
.flow-choice { font-size:11px;padding-inline:4px; }
|
|
551
553
|
.flow-node { gap:4px; }
|
|
@@ -556,7 +558,7 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
556
558
|
#flow-apps .flow-note { left:auto;right:4px; }
|
|
557
559
|
}
|
|
558
560
|
@media(max-width:460px) {
|
|
559
|
-
.flow-network { grid-template-columns:minmax(
|
|
561
|
+
.flow-network { grid-template-columns:minmax(0,1fr) 48px minmax(0,1.25fr);column-gap:12px; }
|
|
560
562
|
.flow-column-title,.flow-source,.flow-note { font-size:10px; }
|
|
561
563
|
.flow-logo { width:26px;height:26px; }
|
|
562
564
|
#flow-hub,.flow-halo { width:48px;height:48px; }
|
|
@@ -607,9 +609,16 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
607
609
|
|
|
608
610
|
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
|
|
609
611
|
|
|
610
|
-
#flow-models { align-items:stretch; }
|
|
611
|
-
#flow-models .flow-node { width:100%; }
|
|
612
|
-
#flow-models .flow-choice { text-align:left; }
|
|
612
|
+
#flow-models { align-items:stretch; gap:20px; }
|
|
613
|
+
#flow-models .flow-node { --model-inset:9px; display:grid; grid-template-columns:minmax(0,1fr) max-content; gap:3px 8px; width:100%; }
|
|
614
|
+
#flow-models .flow-choice { grid-area:2/1; justify-self:start; text-align:left; }
|
|
615
|
+
#flow-models .flow-count { grid-area:2/2; position:static; }
|
|
616
|
+
#flow-models :is(.flow-source,.flow-note) { position:static; grid-column:1/-1; margin-inline:var(--model-inset); white-space:normal; overflow-wrap:anywhere; }
|
|
617
|
+
#flow-models .flow-source { grid-row:1; }
|
|
618
|
+
#flow-models .flow-note { grid-row:3; }
|
|
619
|
+
@media(max-width:760px) {
|
|
620
|
+
#flow-models .flow-node { --model-inset:4px; }
|
|
621
|
+
}
|
|
613
622
|
.flow-column:last-child .flow-column-title { text-align:left;padding-left:9px; }
|
|
614
623
|
.model-maker { display:block;margin-top:5px;color:var(--muted);font-size:11px;font-weight:400; }
|
|
615
624
|
.model-identity { display:grid;grid-template-columns:auto 1fr;gap:8px 16px;font-size:12px;margin:18px 0; }
|
|
@@ -666,8 +675,8 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
666
675
|
.context-metrics { display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;margin:18px 0; }
|
|
667
676
|
.context-metrics dt { color:var(--muted);font-size:11px; }
|
|
668
677
|
.context-metrics dd { margin:8px 0 0;font-size:23px;font-variant-numeric:tabular-nums; }
|
|
669
|
-
.context-history-chart { min-height:
|
|
670
|
-
.context-history-chart svg { width:100%;height:
|
|
678
|
+
.context-history-chart { min-height:225px;color:var(--muted);margin-top:14px; }
|
|
679
|
+
.context-history-chart svg { width:100%;height:225px;display:block; }
|
|
671
680
|
.context-history-chart text { font-size:11px;fill:var(--muted); }
|
|
672
681
|
.context-grid { stroke:var(--border);stroke-width:1; }
|
|
673
682
|
.context-line { fill:none;stroke:var(--accent);stroke-width:1.6; }
|
|
@@ -684,7 +693,7 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
684
693
|
|
|
685
694
|
.tool-style { display:flex;align-items:center;gap:8px;font-size:12px;color:var(--muted);white-space:nowrap; }
|
|
686
695
|
.tool-style select { max-width:160px; }
|
|
687
|
-
.tool-stage { display:grid;grid-template-columns:minmax(180px,250px) minmax(0,1fr);align-items:
|
|
696
|
+
.tool-stage { display:grid;grid-template-columns:minmax(180px,250px) minmax(0,1fr);align-items:start;gap:24px;min-height:230px; }
|
|
688
697
|
.tool-visual,.tool-content { min-width:0; }
|
|
689
698
|
.tool-orbit { width:100%;height:190px;position:relative; }
|
|
690
699
|
.tool-orbit canvas { display:block;width:100%;height:100%; }
|
|
@@ -706,7 +715,7 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
|
|
|
706
715
|
#tool-cursor { display:inline-block;animation:tool-cursor 1s steps(1) infinite; }
|
|
707
716
|
#tool-activity[data-paused="true"] #tool-cursor { animation:none; }
|
|
708
717
|
@keyframes tool-cursor { 50% { opacity:0; } }
|
|
709
|
-
@media(max-width:620px) { .tool-stage { grid-template-columns:1fr;gap:8px; }.tool-visual { width:100%;max-width:330px;margin:auto; }.tool-content { padding-bottom:8px; }.tool-context { margin-bottom:4px; } }
|
|
718
|
+
@media(max-width:620px) { .tool-stage { grid-template-columns:1fr;grid-template-rows:auto 1fr;gap:8px; }.tool-stage[data-style="off"] { grid-template-rows:1fr; }.tool-visual { width:100%;max-width:330px;margin-inline:auto; }.tool-content { padding-bottom:8px; }.tool-context { margin-bottom:4px; } }
|
|
710
719
|
@media(prefers-reduced-motion:reduce) { #tool-cursor { animation:none; } }
|
|
711
720
|
|
|
712
721
|
/* Compact request statistics in the existing diagnostics panel. */
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { atomicWriteFile } from "./atomic-file.mjs";
|
|
4
|
+
import { readBoundedFile, readBoundedFileSync } from "./bounded-file.mjs";
|
|
5
|
+
import { withFileLock } from "./lock.mjs";
|
|
6
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
7
|
+
|
|
8
|
+
const HOUR = 3600000, HOURS = 24, PER_HOUR = 32, MAX_BYTES = 512 * 1024;
|
|
9
|
+
const APPS = new Set(["codex_app", "codex_cli", "codex", "claude_app", "claude_code", "claude", "gemini_app", "api"]);
|
|
10
|
+
const PHASES = new Set(["local", "send", "headers", "stream", "upstream", "unknown"]);
|
|
11
|
+
export const failureHistoryPath = (home = os.homedir()) => path.join(home, ".local", "share", "codex-copilot-dx", "failure-history.json");
|
|
12
|
+
const requestId = value => typeof value === "string" && /^[\da-f-]{36}$/i.test(value) ? value : null;
|
|
13
|
+
const modelName = value => typeof value === "string" && /^[\w][\w./:@+-]{0,119}$/.test(value) && redactDiagnosticText(value) === value ? value : "unknown";
|
|
14
|
+
const groupKey = value => JSON.stringify([value.application, value.model, value.phase]);
|
|
15
|
+
const hour = now => Math.floor(now / HOUR) * HOUR;
|
|
16
|
+
const keep = (now, value) => Number.isSafeInteger(value) && value >= hour(now) - (HOURS - 1) * HOUR && value <= hour(now) && value % HOUR === 0;
|
|
17
|
+
|
|
18
|
+
function put(buckets, row) {
|
|
19
|
+
let groups = buckets.get(row.hour);
|
|
20
|
+
if (!groups) buckets.set(row.hour, groups = new Map());
|
|
21
|
+
let key = groupKey(row);
|
|
22
|
+
if (!groups.has(key) && groups.size >= PER_HOUR - 1) {
|
|
23
|
+
row = { ...row, application: "api", model: "unknown", phase: "unknown" };
|
|
24
|
+
key = groupKey(row);
|
|
25
|
+
}
|
|
26
|
+
const previous = groups.get(key);
|
|
27
|
+
groups.set(key, { ...row, count: Math.min(Number.MAX_SAFE_INTEGER, (previous?.count || 0) + row.count),
|
|
28
|
+
last: !previous || row.last.at >= previous.last.at ? row.last : previous.last });
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function parse(text, now) {
|
|
32
|
+
const result = new Map();
|
|
33
|
+
for (const row of JSON.parse(text)?.rows || []) {
|
|
34
|
+
if (!row || !keep(now, row.hour) || !APPS.has(row.application) || !PHASES.has(row.phase) ||
|
|
35
|
+
!Number.isSafeInteger(row.count) || row.count < 1 || !Number.isSafeInteger(row.last?.at) || hour(row.last.at) !== row.hour) continue;
|
|
36
|
+
put(result, { hour: row.hour, application: row.application, model: modelName(row.model), phase: row.phase, count: row.count,
|
|
37
|
+
last: { at: row.last.at, status: Number.isInteger(row.last.status) && row.last.status >= 400 && row.last.status <= 599 ? row.last.status : null,
|
|
38
|
+
request_id: requestId(row.last.request_id), client_request_id: requestId(row.last.client_request_id) } });
|
|
39
|
+
}
|
|
40
|
+
return result;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const options = { encoding: "utf8", maxBytes: MAX_BYTES };
|
|
44
|
+
const values = buckets => [...buckets.values()].flatMap(group => [...group.values()]);
|
|
45
|
+
const prune = (buckets, now) => { for (const key of buckets.keys()) if (!keep(now, key)) buckets.delete(key); };
|
|
46
|
+
function phase(details) {
|
|
47
|
+
const attempt = details.attempt_timings?.at(-1);
|
|
48
|
+
if (details.origin === "upstream_http") return "upstream";
|
|
49
|
+
if (details.origin === "upstream_event" || attempt?.headers_ms != null) return "stream";
|
|
50
|
+
if (attempt?.body_sent_ms != null) return "headers";
|
|
51
|
+
return details.upstream_attempts > 0 ? "send" : "local";
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function createFailureHistory({ file, now = Date.now } = {}) {
|
|
55
|
+
let buckets = new Map(), pending = new Map(), saving, cached, clock;
|
|
56
|
+
if (file) try { buckets = parse(readBoundedFileSync(file, options), now()); } catch { /* Optional local history is not required for startup. */ }
|
|
57
|
+
function flush() {
|
|
58
|
+
if (!file || saving || !pending.size) return saving;
|
|
59
|
+
const batch = pending;
|
|
60
|
+
pending = new Map();
|
|
61
|
+
saving = withFileLock(file + ".lock", async () => {
|
|
62
|
+
const current = now();
|
|
63
|
+
let disk = new Map();
|
|
64
|
+
try { disk = parse(await readBoundedFile(file, options), current); }
|
|
65
|
+
catch { /* Start a fresh bounded projection on unreadable history. */ }
|
|
66
|
+
for (const row of values(batch)) if (keep(current, row.hour)) put(disk, row);
|
|
67
|
+
await atomicWriteFile(file, JSON.stringify({ rows: values(disk) }), { mode: 0o600, preserveMode: false });
|
|
68
|
+
}, { timeoutMs: 1000 }).catch(() => { /* An I/O error cannot delay or fail inference. */ })
|
|
69
|
+
.finally(() => { saving = undefined;flush(); });
|
|
70
|
+
return saving;
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
record(details) {
|
|
74
|
+
const at = now(), row = { hour: hour(at), application: APPS.has(details.application) ? details.application : "api",
|
|
75
|
+
model: modelName(details.model), phase: phase(details), count: 1,
|
|
76
|
+
last: { at, status: Number.isInteger(details.http_status) && details.http_status >= 400 ? details.http_status : null,
|
|
77
|
+
request_id: requestId(details.request_id), client_request_id: requestId(details.attempt_timings?.at(-1)?.client_request_id) } };
|
|
78
|
+
put(buckets, row);prune(buckets, at);cached = null;
|
|
79
|
+
if (file) { put(pending, row);prune(pending, at);flush(); }
|
|
80
|
+
},
|
|
81
|
+
snapshot() {
|
|
82
|
+
const at = now(), current = hour(at);
|
|
83
|
+
if (cached && clock === current) return cached;
|
|
84
|
+
prune(buckets, at);clock = current;
|
|
85
|
+
const groups = new Map();
|
|
86
|
+
for (const row of values(buckets)) {
|
|
87
|
+
const key = groupKey(row), previous = groups.get(key);
|
|
88
|
+
groups.set(key, { application: row.application, model: row.model, phase: row.phase, count: (previous?.count || 0) + row.count,
|
|
89
|
+
last: !previous || row.last.at >= previous.last.at ? row.last : previous.last });
|
|
90
|
+
}
|
|
91
|
+
const all = [...groups.values()].sort((a, b) => b.count - a.count || b.last.at - a.last.at);
|
|
92
|
+
return cached = { from: new Date(clock - (HOURS - 1) * HOUR).toISOString(),
|
|
93
|
+
total: all.reduce((sum, group) => sum + group.count, 0), groups: all.slice(0, 40), omitted: Math.max(0, all.length - 40) };
|
|
94
|
+
},
|
|
95
|
+
async flush() { while (flush()) await saving; },
|
|
96
|
+
};
|
|
97
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
|
|
3
|
-
export const MODEL_PROTOCOLS = Object.freeze(["messages", "responses", "chat"]);
|
|
3
|
+
export const MODEL_PROTOCOLS = Object.freeze(["messages", "responses", "chat", "gemini"]);
|
|
4
4
|
export const REASONING_EFFORTS = Object.freeze(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
|
|
5
5
|
const limits = ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_budget_min", "reasoning_budget_max", "max_tool_definitions"];
|
|
6
6
|
export const MODEL_PARAMETERS = Object.freeze(["max_tokens", "max_output_tokens", "max_completion_tokens", "temperature", "top_p", "tools", "tool_choice", "parallel_tool_calls", "thinking", "output_config", "reasoning", "reasoning_effort", "response_format", "text", "stop", "stop_sequences", "stream", "stream_options"]);
|
|
@@ -71,7 +71,17 @@ function requestTexts(body, protocol) {
|
|
|
71
71
|
for (const [key, item] of Object.entries(value)) { if (key === "description" && typeof item === "string") add(value, key, item);else if (item && typeof item === "object") descriptions(item); }
|
|
72
72
|
};
|
|
73
73
|
descriptions(body.tools);
|
|
74
|
-
if (protocol === "
|
|
74
|
+
if (protocol === "gemini") {
|
|
75
|
+
const request = body.request || {};
|
|
76
|
+
descriptions(request.tools);
|
|
77
|
+
for (const part of request.systemInstruction?.parts || []) if (typeof part?.text === "string") add(part, "text", part.text);
|
|
78
|
+
for (const content of request.contents || []) for (const part of content.parts || []) {
|
|
79
|
+
if (part?.thoughtSignature || part?.thought) continue;
|
|
80
|
+
if (typeof part?.text === "string") add(part, "text", part.text);
|
|
81
|
+
if (part?.functionCall?.args) leaves(part.functionCall.args, add, true);
|
|
82
|
+
if (part?.functionResponse?.response) leaves(part.functionResponse.response, add, true);
|
|
83
|
+
}
|
|
84
|
+
} else if (protocol === "messages" || protocol === "chat") {
|
|
75
85
|
text(body, "system");
|
|
76
86
|
for (const message of body.messages || []) {
|
|
77
87
|
text(message, "content");
|
|
@@ -86,6 +96,9 @@ function requestTexts(body, protocol) {
|
|
|
86
96
|
if (typeof body.input === "string") add(body, "input", body.input);
|
|
87
97
|
else for (const item of body.input || []) {
|
|
88
98
|
if (["additional_tools", "tool_search_output"].includes(item.type)) descriptions(item.tools);
|
|
99
|
+
else if (item.type === "mcp_list_tools" && Array.isArray(item.tools)) {
|
|
100
|
+
for (const tool of item.tools) if (typeof tool?.description === "string") add(tool, "description", tool.description);
|
|
101
|
+
}
|
|
89
102
|
else if (item.type === "function_call") args(item, "arguments");
|
|
90
103
|
else if (["function_call_output", "custom_tool_call_output"].includes(item.type)) text(item, "output");
|
|
91
104
|
else if (item.type === "custom_tool_call") text(item, "input");
|
|
@@ -147,8 +160,13 @@ function modelSpanFits(text, start, end, label) {
|
|
|
147
160
|
&& /\b(?:function|class|const|let|var)\s+$/.test(text.slice(Math.max(0, start - 32), start))) return false;
|
|
148
161
|
return true;
|
|
149
162
|
}
|
|
163
|
+
// JSON.rawJSON values are immutable and may hold exact tool numbers.
|
|
164
|
+
function cloneGemini(value) {
|
|
165
|
+
if (!value || typeof value !== "object" || JSON.isRawJSON(value)) return value;
|
|
166
|
+
return Array.isArray(value) ? value.map(cloneGemini) : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, cloneGemini(item)]));
|
|
167
|
+
}
|
|
150
168
|
export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal, onPlan, rules = ruleSpans, seedMappings }) {
|
|
151
|
-
const copy = structuredClone(body), { items, nested } = requestTexts(copy, protocol), texts = items.map(item => item.text);
|
|
169
|
+
const copy = protocol === "gemini" ? cloneGemini(body) : structuredClone(body), { items, nested } = requestTexts(copy, protocol), texts = items.map(item => item.text);
|
|
152
170
|
if (items.length > 8192 || texts.reduce((n, text) => n + Buffer.byteLength(text), 0) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
|
|
153
171
|
const found = texts.length ? await find(texts, { signal, onPlan }) : [], values = new Map(seedMappings), kinds = {}, total = { count: 0, bytes: 0 };
|
|
154
172
|
if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
|
|
@@ -186,10 +204,10 @@ export async function maskPrivacyRequest(body, { protocol, client = "api", perso
|
|
|
186
204
|
if (typeof value === "string") return restoreText(value);
|
|
187
205
|
if (Array.isArray(value)) return value.map(item => restoreValue(item, inToolData));
|
|
188
206
|
if (!value || typeof value !== "object" || JSON.isRawJSON(value)) return value;
|
|
189
|
-
if (!inToolData && (value.encrypted_content || ["thinking", "redacted_thinking", "reasoning"].includes(value.type))) return value;
|
|
207
|
+
if (!inToolData && (value.encrypted_content || ["thinking", "redacted_thinking", "reasoning"].includes(value.type) || protocol === "gemini" && (value.thoughtSignature || value.thought))) return value;
|
|
190
208
|
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, !inToolData && kept.has(key) ? item
|
|
191
209
|
: !inToolData && key === "arguments" && typeof item === "string" && item ? restoreArguments(item)
|
|
192
|
-
: restoreValue(item, inToolData || key === "input" && ["tool_use", "server_tool_use", "mcp_tool_use"].includes(value.type))]));
|
|
210
|
+
: restoreValue(item, inToolData || key === "input" && ["tool_use", "server_tool_use", "mcp_tool_use"].includes(value.type) || protocol === "gemini" && key === "args")]));
|
|
193
211
|
}
|
|
194
212
|
function restoreArguments(text) {
|
|
195
213
|
if (!text.includes(TOKEN_START) && !text.includes("\\u")) return text;
|
|
@@ -15,7 +15,7 @@ export function publicModelCatalog(models, { clients = () => [], selectable = ()
|
|
|
15
15
|
return uniqueModelEntries(models.slice(0, 1000)).filter(model => typeof model?.id === "string").map(model => ({
|
|
16
16
|
id: model.id, ...(isImageModel(model) ? { kind: "image" } : {}), display_name: modelDisplayName(model), vendor: maker(model), ...(model.owned_by ? { owned_by: model.owned_by } : {}),
|
|
17
17
|
endpoints: [["responses", ["/responses", "/v1/responses"]], ["chat", ["/chat/completions", "/v1/chat/completions"]],
|
|
18
|
-
["messages", ["/v1/messages"]], ["images", ["/images/generations", "/v1/images/generations"]], ["image_edits", ["/images/edits", "/v1/images/edits"]]].filter(([, paths]) => paths.some(path => model.supported_endpoints?.includes(path))).map(([label]) => label),
|
|
18
|
+
["messages", ["/v1/messages"]], ["gemini", ["/v1beta/models:generateContent"]], ["images", ["/images/generations", "/v1/images/generations"]], ["image_edits", ["/images/edits", "/v1/images/edits"]]].filter(([, paths]) => paths.some(path => model.supported_endpoints?.includes(path))).map(([label]) => label),
|
|
19
19
|
preview: model.preview === true, selectable: selectable(model), clients: clients(model),
|
|
20
20
|
reasoning_efforts: isImageModel(model) ? null : modelReasoningEfforts(model), auto_review_efforts: isImageModel(model) ? [] : model.capability ? modelReasoningEfforts(model) || [] : autoReviewReasoningEfforts(model),
|
|
21
21
|
context_window: model.capability?.values.context_window ?? (Number.isSafeInteger(model.capabilities?.limits?.max_context_window_tokens)
|
|
@@ -9,10 +9,11 @@ import { privateHelperEnvironment } from "../private-helper-environment.mjs";
|
|
|
9
9
|
import { transportErrorDetails } from "../operation-error.mjs";
|
|
10
10
|
import { apiTargetAllowed } from "../api-target.mjs";
|
|
11
11
|
|
|
12
|
-
export async function createApiNetwork({ targets, env = process.env, platform = process.platform, signal,
|
|
12
|
+
export async function createApiNetwork({ targets, geminiModelsUrl, env = process.env, platform = process.platform, signal,
|
|
13
13
|
requestImpl = https.request, exec = promisify(execFile), startWindowsNetwork } = {}) {
|
|
14
14
|
const urls = new Set(targets.map(raw => new URL(apiUrl(raw)).href));if (!urls.size || urls.size > 8) throw accessError("ccdx_api_url_invalid");
|
|
15
15
|
const first = new URL([...urls][0]);
|
|
16
|
+
if (geminiModelsUrl && !urls.has(new URL(apiUrl(geminiModelsUrl)).href)) throw accessError("ccdx_api_url_invalid");
|
|
16
17
|
let plan = resolveNetworkRoute({ env, checkApi: false }), worker;
|
|
17
18
|
if (!networkProxyFor(first, plan) && !bypassNetworkProxy(first.hostname, first.port || 443, plan)) {
|
|
18
19
|
if (platform === "darwin") {
|
|
@@ -20,7 +21,7 @@ export async function createApiNetwork({ targets, env = process.env, platform =
|
|
|
20
21
|
plan = resolveNetworkRoute({ env, systemProxy: stdout, checkApi: false });
|
|
21
22
|
} else if (platform === "win32") {
|
|
22
23
|
const start = startWindowsNetwork || (await import("../windows-http-network.mjs")).startWindowsHttpNetwork;
|
|
23
|
-
worker = await start({ target: "api", apiTargets: [...urls], env: privateHelperEnvironment(env), signal, timeoutMs: 120000 });
|
|
24
|
+
worker = await start({ target: "api", apiTargets: [...urls], geminiModelsUrl, env: privateHelperEnvironment(env), signal, timeoutMs: 120000 });
|
|
24
25
|
requestImpl = worker.requestImpl;
|
|
25
26
|
}
|
|
26
27
|
}
|
|
@@ -31,7 +32,7 @@ export async function createApiNetwork({ targets, env = process.env, platform =
|
|
|
31
32
|
fetch(raw, init = {}) {
|
|
32
33
|
return new Promise((resolve, reject) => {
|
|
33
34
|
let url;try { url = new URL(raw); } catch { reject(accessError("ccdx_api_url_invalid"));return; }
|
|
34
|
-
if (closed || retiring || !apiTargetAllowed(url.href, [...urls], init.method || "GET") || !["GET", "POST"].includes(init.method || "GET")) { reject(accessError("ccdx_api_url_invalid"));return; }
|
|
35
|
+
if (closed || retiring || !apiTargetAllowed(url.href, [...urls], init.method || "GET", geminiModelsUrl) || !["GET", "POST"].includes(init.method || "GET")) { reject(accessError("ccdx_api_url_invalid"));return; }
|
|
35
36
|
if (init.signal?.aborted) { reject(init.signal.reason);return; }
|
|
36
37
|
active++;
|
|
37
38
|
let req, incoming, socket, phase = "request", handedOff = false, released = false;
|
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));
|