cortico-provider-gemini-gateway 0.1.2 → 0.1.3
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 +8 -0
- package/README.md +3 -1
- package/dist/webui.js +18 -1
- package/package.json +1 -1
- package/src/client.ts +15 -6
- package/src/control.ts +35 -3
- package/src/http.ts +74 -8
- package/src/index.ts +8 -1
- package/src/options.ts +5 -0
- package/src/quota.ts +5 -3
- package/src/shim.ts +76 -3
- package/src/webui/client.ts +20 -2
- package/src/webui/server.ts +26 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.3
|
|
4
|
+
|
|
5
|
+
🥣 给知更鸟粮仓装上了「精打细算省粮三件套」+「独立代理小通道」:
|
|
6
|
+
- 历史图片瘦身:只带当前最新一轮的新图(含本轮刚截的屏),老图片统统换成轻量占位 `[Earlier image omitted]`,再也不会一轮工具调用把旧截图反复重喂啦!
|
|
7
|
+
- 历史思考链自动卸货:回放对话时不再把之前轮次的思考草稿当纯文本塞回去滚雪球(本轮实时思考照常显示)。
|
|
8
|
+
- 工具表无损去噪:清掉 `$schema`、`additionalProperties` 等纯样板噪声,所有工具说明、参数名和枚举 100% 完整保留,省一点是一点还不影响桌宠干活~
|
|
9
|
+
- 独立代理地址(可选):第一步新增「独立代理地址」输入框(支持直接填端口号如 `7890` 或 `http://127.0.0.1:7890`,留空自动跟随系统代理),系统代理继续挂香港逛网页,桌宠单独走日/美端口互不打架!
|
|
10
|
+
|
|
3
11
|
## 0.1.2
|
|
4
12
|
|
|
5
13
|
🐦 给粮仓换上了超可爱的新头像(趴在星星上的知更鸟小团子来报到啦!),还把卡片简介和整篇 README 里的冷冰冰公文腔统统赶跑,换成更贴近桌宠投喂日常的轻松小指南~
|
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
```text
|
|
18
18
|
cortico-provider-gemini-gateway
|
|
19
19
|
```
|
|
20
|
-
> 小提示:刚发新版未满 24 小时想抢鲜体验,记得把版本号带上,比如 `cortico-provider-gemini-gateway@0.1.
|
|
20
|
+
> 小提示:刚发新版未满 24 小时想抢鲜体验,记得把版本号带上,比如 `cortico-provider-gemini-gateway@0.1.3`。
|
|
21
21
|
3. 点 **「安装」**,装完 **重启 Coopanion**,去 **模型供应商 → 新建** 选它就能开喂啦!
|
|
22
22
|
|
|
23
23
|
**装不上?先看这两条避坑小纸条:**
|
|
@@ -43,6 +43,8 @@
|
|
|
43
43
|
- **账号打码防社死**:所有邮箱全局默认打成 `5***3@gmail.com`,截图、录屏、发教程都安心;想核对原名时点一下 **「显示账号名」** 就能一键显隐。
|
|
44
44
|
- **条款状态小助手**:新绑进来的号,或者上游提示还没同意服务条款时,对应卡片会亮出 **「同意条款」** 按钮,点一下搞定,通过后按钮自动消失。
|
|
45
45
|
- **原生传图不串号**:发给桌宠看的图片会按账号单独缓存和上传,切号重试时绝不会拿 A 号的附件去撞 B 号的墙。
|
|
46
|
+
- **内置省粮瘦身三件套**:专门针对桌宠长对话 + 多步调工具的耗粮痛点做了底层减负——① **历史图片只带最新一轮**,旧轮次截图自动换成 `[Earlier image omitted]` 占位,不再反复重读;② **自动剥离旧轮次思考链**,不把上几轮的草稿文本滚雪球喂回去(当前轮思考照常输出);③ **工具 Schema 无损去噪**,只剔除 `$schema`、`additionalProperties`、空数组等纯格式样板,完整保留全部工具说明与参数定义,省额度同时绝不让桌宠忘掉怎么调工具。
|
|
47
|
+
- **独立代理小通道(可选)**:第一步「测试连接」上方新增了 **独立代理地址** 输入框(留空默认跟系统代理,支持直接填 `7890` 或 `http://127.0.0.1:7890` 的 HTTP/混合代理端口)。日常系统代理继续挂香港逛网页打游戏,给桌宠单独分一条美/日/新端口,全平台(Windows / macOS / Linux)都能轻松分流,OAuth 登录、查额度、传图和对话全链路生效。
|
|
46
48
|
- **额度小看板**:第三步自带 **5 小时窗口 + 每周上限** 双进度条;小科普一下,Robin 是按算力权重扣的(上下文越长、开深度思考、用 Pro/Neon 档掉得越快;Fast/Hydrogen 档日常最划算;Flash-Lite 最轻,主额度吃空后通常也会自动回落到它兜底)。
|
|
47
49
|
|
|
48
50
|
---
|
package/dist/webui.js
CHANGED
|
@@ -1562,6 +1562,12 @@ var gatewayPanel = {
|
|
|
1562
1562
|
const tempCheck = ui.checkbox(t("\u542F\u7528\u65E0\u75D5\u4F1A\u8BDD\u6807\u5FD7 (temporary_chat)", "Send temporary_chat flag"), {
|
|
1563
1563
|
onChange: () => void saveOptions()
|
|
1564
1564
|
});
|
|
1565
|
+
const proxyUrlInput = ui.input({
|
|
1566
|
+
cls: "mono",
|
|
1567
|
+
placeholder: t("\u7559\u7A7A\u8DDF\u968F\u7CFB\u7EDF\u4EE3\u7406\uFF1B\u652F\u6301 7890 \u6216 http://127.0.0.1:7890", "Leave blank for system proxy; e.g. 7890 or http://127.0.0.1:7890"),
|
|
1568
|
+
onChange: () => void saveOptions()
|
|
1569
|
+
});
|
|
1570
|
+
const proxyUrlField = ui.field(t("\u72EC\u7ACB\u4EE3\u7406\u5730\u5740\uFF08\u53EF\u9009\uFF09", "Dedicated proxy URL (optional)"), proxyUrlInput);
|
|
1565
1571
|
const testRow = ui.rowbar();
|
|
1566
1572
|
const testBtn = ui.button(t("\u6D4B\u8BD5\u8FDE\u63A5", "Test connection"), {
|
|
1567
1573
|
size: "sm",
|
|
@@ -1575,11 +1581,13 @@ var gatewayPanel = {
|
|
|
1575
1581
|
baseUrlField,
|
|
1576
1582
|
ui.field(t("\u8BA4\u8BC1\u6A21\u5F0F", "Auth mode"), authModeSelect),
|
|
1577
1583
|
tempCheck.el,
|
|
1584
|
+
proxyUrlField,
|
|
1578
1585
|
testRow,
|
|
1579
1586
|
message
|
|
1580
1587
|
);
|
|
1581
1588
|
let saving = false;
|
|
1582
1589
|
let currentProtocol = "robin";
|
|
1590
|
+
let lastSavedProxyUrl = "";
|
|
1583
1591
|
function modeDescription(protocol) {
|
|
1584
1592
|
if (protocol === "robin") return t("RobinService HTTP/2 gRPC\uFF08\u81EA\u52A8\u5207\u6362\u5B98\u65B9\u7AEF\u70B9\u4E0E\u8DEF\u7531\uFF09", "RobinService HTTP/2 gRPC (auto endpoint & routes)");
|
|
1585
1593
|
if (protocol === "gemini") return t("\u539F\u751F Gemini REST SSE\uFF08\u81EA\u52A8\u62FC\u63A5\u6D41\u5F0F\u751F\u6210\u8DEF\u7531\uFF09", "Native Gemini REST SSE (auto stream route)");
|
|
@@ -1592,6 +1600,8 @@ var gatewayPanel = {
|
|
|
1592
1600
|
rpcBtn.classList.toggle("primary", state.protocol === "rpc");
|
|
1593
1601
|
authModeSelect.value = state.authMode;
|
|
1594
1602
|
tempCheck.setChecked(state.temporaryChat);
|
|
1603
|
+
lastSavedProxyUrl = state.proxyUrl ?? "";
|
|
1604
|
+
proxyUrlInput.value = lastSavedProxyUrl;
|
|
1595
1605
|
baseUrlField.hidden = state.protocol === "robin";
|
|
1596
1606
|
if (state.protocol !== "robin") {
|
|
1597
1607
|
baseUrlInput.value = state.baseUrl;
|
|
@@ -1635,7 +1645,7 @@ var gatewayPanel = {
|
|
|
1635
1645
|
}
|
|
1636
1646
|
}
|
|
1637
1647
|
async function saveOptions(overrides = {}) {
|
|
1638
|
-
if (saving || signal.aborted) return;
|
|
1648
|
+
if (saving || signal.aborted) return false;
|
|
1639
1649
|
saving = true;
|
|
1640
1650
|
message.textContent = "";
|
|
1641
1651
|
message.classList.remove("bad");
|
|
@@ -1645,6 +1655,7 @@ var gatewayPanel = {
|
|
|
1645
1655
|
protocol: currentProtocol,
|
|
1646
1656
|
authMode: overrides.authMode ?? authModeSelect.value,
|
|
1647
1657
|
temporaryChat: tempCheck.checked,
|
|
1658
|
+
proxyUrl: proxyUrlInput.value,
|
|
1648
1659
|
...currentProtocol !== "robin" ? { baseUrl: baseUrlInput.value } : {}
|
|
1649
1660
|
}]);
|
|
1650
1661
|
if (!signal.aborted) {
|
|
@@ -1658,17 +1669,23 @@ var gatewayPanel = {
|
|
|
1658
1669
|
});
|
|
1659
1670
|
message.textContent = t("\u914D\u7F6E\u5DF2\u81EA\u52A8\u540C\u6B65\uFF08\u8BF7\u70B9\u51FB\u9875\u9762\u5E95\u90E8\u300C\u4FDD\u5B58\u300D\u751F\u6548\uFF09\u3002", "Options synced. Click Save below to persist.");
|
|
1660
1671
|
}
|
|
1672
|
+
return true;
|
|
1661
1673
|
} catch (err) {
|
|
1662
1674
|
if (!signal.aborted) {
|
|
1663
1675
|
message.textContent = err instanceof Error ? err.message : String(err);
|
|
1664
1676
|
message.classList.add("bad");
|
|
1665
1677
|
}
|
|
1678
|
+
return false;
|
|
1666
1679
|
} finally {
|
|
1667
1680
|
saving = false;
|
|
1668
1681
|
}
|
|
1669
1682
|
}
|
|
1670
1683
|
async function runTest() {
|
|
1671
1684
|
if (saving || signal.aborted) return;
|
|
1685
|
+
if (proxyUrlInput.value.trim() !== lastSavedProxyUrl) {
|
|
1686
|
+
const savedOk = await saveOptions();
|
|
1687
|
+
if (!savedOk || signal.aborted) return;
|
|
1688
|
+
}
|
|
1672
1689
|
testBtn.disabled = true;
|
|
1673
1690
|
message.textContent = t("\u6B63\u5728\u6D4B\u8BD5\u8FDE\u63A5\u2026", "Testing connection\u2026");
|
|
1674
1691
|
message.classList.remove("bad");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cortico-provider-gemini-gateway",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "### 📦**Gemini 多合一粮仓(Robin / Web2API / 自定义 RPC)**\n给自家桌宠搭的三合一 Gemini 喂食通道,WebUI 面板随切随用:\n- **🐦 知更鸟模式(Robin)**:支持绑多个号轮着喂(主备切号 / 雨露均沾 / 谁额度多先吃谁),自带 5h & 周额度小看板、原生传图和账号打码防社死。\n- **🔑 Web2API 模式**:切过去直接填官方 Gemini API Key 或自建反代 Key,零门槛开箱即用。\n- **🛠️ 自定义 RPC**:给喜欢自己搭网关的折腾党留的后门。",
|
|
6
6
|
"author": "云纪&云洄",
|
package/src/client.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { requestJson } from 'cortico/providers/transport/response-http.ts';
|
|
3
3
|
import { gatewayFrames } from './frames.ts';
|
|
4
|
-
import {
|
|
4
|
+
import { createHttp2Connector, createProxyFetchFor, type Http2Connector } from './http.ts';
|
|
5
5
|
import { GatewayError, inspectHttpError, SerialQueue } from './queue.ts';
|
|
6
6
|
import {
|
|
7
7
|
detectRobinImageMime,
|
|
@@ -53,6 +53,7 @@ export interface GatewayClientOptions {
|
|
|
53
53
|
resolveRobinModeCategory?: (model: string, accountId?: string) => number | undefined;
|
|
54
54
|
onRobinRouting?: (observation: RobinRoutingObservation, accountId?: string) => void;
|
|
55
55
|
onCleanupError?: (error: unknown) => void;
|
|
56
|
+
proxyUrl?: string;
|
|
56
57
|
fetch?: typeof fetch;
|
|
57
58
|
connectHttp2?: Http2Connector;
|
|
58
59
|
}
|
|
@@ -89,6 +90,7 @@ const ROBIN_UPLOAD_CACHE_MAX = 32;
|
|
|
89
90
|
export class GatewayClient {
|
|
90
91
|
private readonly queue = new SerialQueue();
|
|
91
92
|
private readonly request: typeof fetch;
|
|
93
|
+
private readonly h2Connector: Http2Connector;
|
|
92
94
|
private readonly protocol: GatewayProtocol;
|
|
93
95
|
private readonly base: string;
|
|
94
96
|
private readonly options: GatewayClientOptions;
|
|
@@ -97,7 +99,8 @@ export class GatewayClient {
|
|
|
97
99
|
constructor(options: GatewayClientOptions) {
|
|
98
100
|
this.options = options;
|
|
99
101
|
this.base = httpUrl(options.baseUrl).href;
|
|
100
|
-
this.request = options.fetch ??
|
|
102
|
+
this.request = options.fetch ?? createProxyFetchFor(options.proxyUrl);
|
|
103
|
+
this.h2Connector = options.connectHttp2 ?? createHttp2Connector(options.proxyUrl);
|
|
101
104
|
this.protocol = options.protocol ?? 'rpc';
|
|
102
105
|
}
|
|
103
106
|
|
|
@@ -233,13 +236,16 @@ export class GatewayClient {
|
|
|
233
236
|
input.contents.forEach((turn, turnIndex) => collect('turn', turnIndex, turn.parts));
|
|
234
237
|
if (!candidates.length) return { request: input, uploader: undefined };
|
|
235
238
|
|
|
236
|
-
// Keep
|
|
239
|
+
// Keep only supported images from the latest turn, within Robin's per-request count & byte budgets.
|
|
240
|
+
// Earlier-turn images are never re-uploaded or re-inferred; they become compact text placeholders.
|
|
241
|
+
const lastTurnIndex = input.contents.length - 1;
|
|
237
242
|
const keptKeys = new Set<string>();
|
|
238
243
|
const keptList: InlineCandidate[] = [];
|
|
239
244
|
let totalBytes = 0;
|
|
240
245
|
for (let i = candidates.length - 1; i >= 0; i--) {
|
|
241
246
|
const candidate = candidates[i];
|
|
242
247
|
if (!candidate.mimeType) continue;
|
|
248
|
+
if (candidate.section !== 'turn' || candidate.turnIndex !== lastTurnIndex) continue;
|
|
243
249
|
if (keptList.length >= ROBIN_MAX_IMAGES_PER_REQUEST) continue;
|
|
244
250
|
if (totalBytes + candidate.bytes.length > ROBIN_MAX_IMAGE_BYTES) continue;
|
|
245
251
|
totalBytes += candidate.bytes.length;
|
|
@@ -264,7 +270,7 @@ export class GatewayClient {
|
|
|
264
270
|
headers,
|
|
265
271
|
origin: this.options.robinUploadOrigin,
|
|
266
272
|
signal,
|
|
267
|
-
connectHttp2: this.
|
|
273
|
+
connectHttp2: this.h2Connector,
|
|
268
274
|
});
|
|
269
275
|
const expiresAt = Date.now() + ROBIN_UPLOAD_CACHE_TTL_MS;
|
|
270
276
|
for (let i = 0; i < toUpload.length; i++) {
|
|
@@ -287,9 +293,12 @@ export class GatewayClient {
|
|
|
287
293
|
const key = `${section}:${turnIndex}:${partIndex}`;
|
|
288
294
|
const candidate = byKey.get(key);
|
|
289
295
|
if (!candidate || !keptKeys.has(key)) {
|
|
296
|
+
if (candidate?.mimeType && (candidate.section !== 'turn' || candidate.turnIndex !== lastTurnIndex)) {
|
|
297
|
+
return { text: '[Earlier image omitted]' };
|
|
298
|
+
}
|
|
290
299
|
const reason = !candidate?.mimeType
|
|
291
300
|
? `unsupported Robin attachment (${part.inlineData.mimeType})`
|
|
292
|
-
: '
|
|
301
|
+
: 'oversized or excess image omitted';
|
|
293
302
|
return { text: `[Attachment omitted: ${reason}]` };
|
|
294
303
|
}
|
|
295
304
|
const cached = this.robinImageCache.get(candidate.cacheKey)!;
|
|
@@ -356,7 +365,7 @@ export class GatewayClient {
|
|
|
356
365
|
overrideModeCategory,
|
|
357
366
|
temporaryChat: this.options.temporaryChat ?? true,
|
|
358
367
|
signal,
|
|
359
|
-
connectHttp2: this.
|
|
368
|
+
connectHttp2: this.h2Connector,
|
|
360
369
|
onStatus: (httpStatus, requestId) => onMeta({ status: httpStatus, requestId }),
|
|
361
370
|
})) {
|
|
362
371
|
signal.throwIfAborted();
|
package/src/control.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { copyFileSync, existsSync, mkdirSync } from 'node:fs';
|
|
|
2
2
|
import { dirname, join, resolve } from 'node:path';
|
|
3
3
|
import type { LLMProviderEntry } from 'cortico/core/types.ts';
|
|
4
4
|
import type { ProviderHost } from 'cortico/providers/base.ts';
|
|
5
|
-
import {
|
|
5
|
+
import { createHttp2Connector, createProxyFetchFor, normalizeProxyUrl } from './http.ts';
|
|
6
6
|
import {
|
|
7
7
|
API_KEY_FILE,
|
|
8
8
|
maskSecretHint,
|
|
@@ -80,6 +80,8 @@ export function gatewayControl(host: Pick<ProviderHost, 'stateDir'>, entry: LLMP
|
|
|
80
80
|
control = new GatewayControl(oauthDir);
|
|
81
81
|
controls.set(key, control);
|
|
82
82
|
}
|
|
83
|
+
const rawProxy = typeof entry.options?.proxyUrl === 'string' ? entry.options.proxyUrl : undefined;
|
|
84
|
+
control.setProxyUrl(rawProxy ? normalizeProxyUrl(rawProxy) : undefined);
|
|
83
85
|
return control;
|
|
84
86
|
}
|
|
85
87
|
|
|
@@ -145,6 +147,8 @@ export class GatewayControl {
|
|
|
145
147
|
private readonly observedRouting = new Map<string, RobinRoutingObservation>();
|
|
146
148
|
private rrCursor = 0;
|
|
147
149
|
private emailsMasked = true;
|
|
150
|
+
private activeProxyUrl?: string;
|
|
151
|
+
private cachedProxyFetch?: { proxyUrl?: string; fn: typeof fetch };
|
|
148
152
|
|
|
149
153
|
private static emptyOAuthConfig() {
|
|
150
154
|
return {
|
|
@@ -155,12 +159,31 @@ export class GatewayControl {
|
|
|
155
159
|
};
|
|
156
160
|
}
|
|
157
161
|
|
|
158
|
-
constructor(oauthDir: string, request
|
|
162
|
+
constructor(oauthDir: string, request?: typeof fetch) {
|
|
159
163
|
this.oauthDir = oauthDir;
|
|
160
164
|
const custom = readOAuthConfig(oauthDir);
|
|
161
165
|
const bundled = custom ? undefined : readBundledOAuthConfig();
|
|
162
166
|
const config = custom ?? bundled ?? GatewayControl.emptyOAuthConfig();
|
|
163
|
-
|
|
167
|
+
const oauthFetch: typeof fetch = request ?? ((input, init) => this.fetchForProxy()(input, init));
|
|
168
|
+
this.auth = new DesktopOAuth(config, oauthDir, oauthFetch, Boolean(custom));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
private fetchForProxy(): typeof fetch {
|
|
172
|
+
if (!this.cachedProxyFetch || this.cachedProxyFetch.proxyUrl !== this.activeProxyUrl) {
|
|
173
|
+
this.cachedProxyFetch = {
|
|
174
|
+
proxyUrl: this.activeProxyUrl,
|
|
175
|
+
fn: createProxyFetchFor(this.activeProxyUrl),
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
return this.cachedProxyFetch.fn;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
setProxyUrl(proxyUrl?: string): void {
|
|
182
|
+
const normalized = proxyUrl ? normalizeProxyUrl(proxyUrl) : undefined;
|
|
183
|
+
if (this.activeProxyUrl !== normalized) {
|
|
184
|
+
this.activeProxyUrl = normalized;
|
|
185
|
+
this.cachedProxyFetch = undefined;
|
|
186
|
+
}
|
|
164
187
|
}
|
|
165
188
|
|
|
166
189
|
private ensureRuntime(accountId: string): AccountRuntimeState {
|
|
@@ -450,6 +473,7 @@ export class GatewayControl {
|
|
|
450
473
|
): Promise<RobinUserStatus | null> {
|
|
451
474
|
this.refreshBundledConfig();
|
|
452
475
|
const config = configuration(entry);
|
|
476
|
+
this.setProxyUrl(config.proxyUrl);
|
|
453
477
|
if (config.protocol !== 'robin') return null;
|
|
454
478
|
if (!this.authEnabled(entry)) return null;
|
|
455
479
|
const resolvedId = accountId ?? this.auth.primaryAccountId();
|
|
@@ -460,6 +484,7 @@ export class GatewayControl {
|
|
|
460
484
|
return rt.userStatus.value;
|
|
461
485
|
}
|
|
462
486
|
const baseHeaders = resolveHeaders(entry, host, false);
|
|
487
|
+
const h2Connector = createHttp2Connector(config.proxyUrl);
|
|
463
488
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
464
489
|
const headers = new Headers(baseHeaders);
|
|
465
490
|
const token = await this.auth.accessTokenFor(resolvedId, attempt === 1);
|
|
@@ -469,6 +494,7 @@ export class GatewayControl {
|
|
|
469
494
|
baseUrl: config.baseUrl,
|
|
470
495
|
headers,
|
|
471
496
|
signal,
|
|
497
|
+
connectHttp2: h2Connector,
|
|
472
498
|
});
|
|
473
499
|
rt.userStatus = { value: status, expiresAt: Date.now() + ROBIN_STATUS_TTL_MS };
|
|
474
500
|
return status;
|
|
@@ -490,6 +516,7 @@ export class GatewayControl {
|
|
|
490
516
|
): Promise<QuotaSnapshot> {
|
|
491
517
|
this.refreshBundledConfig();
|
|
492
518
|
const config = configuration(entry);
|
|
519
|
+
this.setProxyUrl(config.proxyUrl);
|
|
493
520
|
const useOAuth = this.authEnabled(entry);
|
|
494
521
|
const headers = resolveHeaders(entry, host, false, this.oauthDir);
|
|
495
522
|
|
|
@@ -501,6 +528,7 @@ export class GatewayControl {
|
|
|
501
528
|
headers,
|
|
502
529
|
authHeader: config.authHeader,
|
|
503
530
|
authPrefix: config.authPrefix,
|
|
531
|
+
...(config.proxyUrl ? { proxyUrl: config.proxyUrl } : {}),
|
|
504
532
|
}, signal);
|
|
505
533
|
if (snapshot.plan || snapshot.userTier) {
|
|
506
534
|
this.ensureRuntime('__default__').plan = {
|
|
@@ -555,6 +583,7 @@ export class GatewayControl {
|
|
|
555
583
|
auth: { accessToken: force => this.auth.accessTokenFor(acct.id, force) },
|
|
556
584
|
authHeader: config.authHeader,
|
|
557
585
|
authPrefix: config.authPrefix,
|
|
586
|
+
...(config.proxyUrl ? { proxyUrl: config.proxyUrl } : {}),
|
|
558
587
|
}, signal);
|
|
559
588
|
rt.quota = snap;
|
|
560
589
|
if (snap.plan || snap.userTier) {
|
|
@@ -631,6 +660,7 @@ export class GatewayControl {
|
|
|
631
660
|
): Promise<RobinTermsResult> {
|
|
632
661
|
this.refreshBundledConfig();
|
|
633
662
|
const config = configuration(entry);
|
|
663
|
+
this.setProxyUrl(config.proxyUrl);
|
|
634
664
|
if (config.protocol !== 'robin') {
|
|
635
665
|
throw new Error('仅 Robin 协议需要确认 Gemini 桌面服务条款。');
|
|
636
666
|
}
|
|
@@ -639,6 +669,7 @@ export class GatewayControl {
|
|
|
639
669
|
throw new Error('请先完成浏览器 OAuth 认证后再确认服务条款。');
|
|
640
670
|
}
|
|
641
671
|
const baseHeaders = resolveHeaders(entry, host, false);
|
|
672
|
+
const h2Connector = createHttp2Connector(config.proxyUrl);
|
|
642
673
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
643
674
|
const headers = new Headers(baseHeaders);
|
|
644
675
|
const token = await this.auth.accessTokenFor(resolvedId, attempt === 1);
|
|
@@ -649,6 +680,7 @@ export class GatewayControl {
|
|
|
649
680
|
headers,
|
|
650
681
|
language,
|
|
651
682
|
signal,
|
|
683
|
+
connectHttp2: h2Connector,
|
|
652
684
|
});
|
|
653
685
|
this.markAccountTermsAccepted(resolvedId, { version: result.version, acceptedAt: result.acceptedAt });
|
|
654
686
|
this.clearAccountCooldown(resolvedId);
|
package/src/http.ts
CHANGED
|
@@ -25,6 +25,7 @@ export interface ProxyFetchOptions {
|
|
|
25
25
|
env?: NodeJS.ProcessEnv;
|
|
26
26
|
execArgv?: readonly string[];
|
|
27
27
|
platform?: NodeJS.Platform;
|
|
28
|
+
proxyUrl?: string;
|
|
28
29
|
fallbackFetch?: typeof fetch;
|
|
29
30
|
readSystemProxy?: () => ProxyConfig | undefined;
|
|
30
31
|
}
|
|
@@ -38,16 +39,53 @@ export function resetProxyCache(): void {
|
|
|
38
39
|
export function normalizeProxyUrl(value: string): string | undefined {
|
|
39
40
|
const trimmed = value.trim();
|
|
40
41
|
if (!trimmed) return undefined;
|
|
42
|
+
const portMatch = /^:?(\d{1,5})$/.exec(trimmed);
|
|
43
|
+
if (portMatch) {
|
|
44
|
+
const port = Number(portMatch[1]);
|
|
45
|
+
if (port < 1 || port > 65535) return undefined;
|
|
46
|
+
return `http://127.0.0.1:${port}/`;
|
|
47
|
+
}
|
|
41
48
|
const candidate = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
|
|
42
49
|
try {
|
|
43
50
|
const url = new URL(candidate);
|
|
44
51
|
if (!['http:', 'https:'].includes(url.protocol) || !url.hostname) return undefined;
|
|
52
|
+
if (url.port) {
|
|
53
|
+
const p = Number(url.port);
|
|
54
|
+
if (!Number.isInteger(p) || p < 1 || p > 65535) return undefined;
|
|
55
|
+
}
|
|
45
56
|
return url.href;
|
|
46
57
|
} catch {
|
|
47
58
|
return undefined;
|
|
48
59
|
}
|
|
49
60
|
}
|
|
50
61
|
|
|
62
|
+
export function parseProxyUrlInput(value: string): string | undefined {
|
|
63
|
+
const trimmed = value.trim();
|
|
64
|
+
if (!trimmed) return undefined;
|
|
65
|
+
const schemeMatch = /^([a-z][a-z0-9+.-]*):\/\//i.exec(trimmed);
|
|
66
|
+
if (schemeMatch && !['http', 'https'].includes(schemeMatch[1].toLowerCase())) {
|
|
67
|
+
throw new Error('代理地址仅支持 HTTP/HTTPS 代理(例如 http://127.0.0.1:7890 或直接填端口 7890);使用 Clash/v2rayN 请填写混合/HTTP 端口。');
|
|
68
|
+
}
|
|
69
|
+
const normalized = normalizeProxyUrl(trimmed);
|
|
70
|
+
if (!normalized) {
|
|
71
|
+
throw new Error('代理地址格式无效,请输入 http://127.0.0.1:7890、127.0.0.1:7890 或纯端口号(如 7890)。');
|
|
72
|
+
}
|
|
73
|
+
const parsed = new URL(normalized);
|
|
74
|
+
return parsed.pathname === '/' && !parsed.search && !parsed.hash ? parsed.href.slice(0, -1) : parsed.href;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function maskProxyDisplay(proxyUrl: string): string {
|
|
78
|
+
try {
|
|
79
|
+
const parsed = new URL(proxyUrl);
|
|
80
|
+
if (!parsed.username && !parsed.password) return proxyUrl;
|
|
81
|
+
parsed.username = '';
|
|
82
|
+
parsed.password = '';
|
|
83
|
+
return parsed.pathname === '/' && !parsed.search && !parsed.hash ? parsed.href.slice(0, -1) : parsed.href;
|
|
84
|
+
} catch {
|
|
85
|
+
return proxyUrl;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
51
89
|
export function parseWindowsProxyServer(server: string): Pick<ProxyConfig, 'httpProxy' | 'httpsProxy'> {
|
|
52
90
|
const parts = server.split(';').map(item => item.trim()).filter(Boolean);
|
|
53
91
|
let httpProxy: string | undefined;
|
|
@@ -431,12 +469,10 @@ export function createProxyFetch(options: ProxyFetchOptions = {}): typeof fetch
|
|
|
431
469
|
const execArgv = options.execArgv ?? process.execArgv;
|
|
432
470
|
const platform = options.platform ?? process.platform;
|
|
433
471
|
const fallbackFetch = options.fallbackFetch;
|
|
472
|
+
const explicitProxy = options.proxyUrl ? normalizeProxyUrl(options.proxyUrl) : undefined;
|
|
434
473
|
|
|
435
474
|
return async (input: FetchInput, init?: RequestInit): Promise<Response> => {
|
|
436
475
|
const baseFetch = fallbackFetch ?? globalThis.fetch;
|
|
437
|
-
if (!fallbackFetch && globalThis.fetch !== NATIVE_FETCH) return baseFetch(input, init);
|
|
438
|
-
if (hasHostProxy(env, execArgv)) return baseFetch(input, init);
|
|
439
|
-
|
|
440
476
|
const rawUrl = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
|
441
477
|
let target: URL;
|
|
442
478
|
try {
|
|
@@ -444,6 +480,21 @@ export function createProxyFetch(options: ProxyFetchOptions = {}): typeof fetch
|
|
|
444
480
|
} catch {
|
|
445
481
|
return baseFetch(input, init);
|
|
446
482
|
}
|
|
483
|
+
|
|
484
|
+
if (explicitProxy) {
|
|
485
|
+
const explicitConfig: ProxyConfig = {
|
|
486
|
+
httpProxy: explicitProxy,
|
|
487
|
+
httpsProxy: explicitProxy,
|
|
488
|
+
allProxy: explicitProxy,
|
|
489
|
+
};
|
|
490
|
+
const resolveTargetProxy = (candidate: URL) => proxyForUrl(candidate, explicitConfig);
|
|
491
|
+
if (!resolveTargetProxy(target)) return baseFetch(input, init);
|
|
492
|
+
return sendViaProxy(input, init, resolveTargetProxy, baseFetch);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
if (!fallbackFetch && globalThis.fetch !== NATIVE_FETCH) return baseFetch(input, init);
|
|
496
|
+
if (hasHostProxy(env, execArgv)) return baseFetch(input, init);
|
|
497
|
+
|
|
447
498
|
const config = resolveProxyConfig(env, platform, options.readSystemProxy);
|
|
448
499
|
const resolveTargetProxy = (candidate: URL) => proxyForUrl(candidate, config);
|
|
449
500
|
if (!resolveTargetProxy(target)) return baseFetch(input, init);
|
|
@@ -453,10 +504,16 @@ export function createProxyFetch(options: ProxyFetchOptions = {}): typeof fetch
|
|
|
453
504
|
|
|
454
505
|
export const proxyFetch: typeof fetch = createProxyFetch();
|
|
455
506
|
|
|
507
|
+
export function createProxyFetchFor(proxyUrl?: string): typeof fetch {
|
|
508
|
+
const normalized = proxyUrl ? normalizeProxyUrl(proxyUrl) : undefined;
|
|
509
|
+
return normalized ? createProxyFetch({ proxyUrl: normalized }) : proxyFetch;
|
|
510
|
+
}
|
|
511
|
+
|
|
456
512
|
export interface ConnectHttp2Options {
|
|
457
513
|
signal?: AbortSignal;
|
|
458
514
|
env?: NodeJS.ProcessEnv;
|
|
459
515
|
platform?: NodeJS.Platform;
|
|
516
|
+
proxyUrl?: string;
|
|
460
517
|
readSystemProxy?: () => ProxyConfig | undefined;
|
|
461
518
|
}
|
|
462
519
|
|
|
@@ -568,11 +625,14 @@ export async function connectHttp2(origin: string | URL, options: ConnectHttp2Op
|
|
|
568
625
|
ensureConnectAttemptTimeout();
|
|
569
626
|
const target = typeof origin === 'string' ? new URL(origin) : new URL(origin.href);
|
|
570
627
|
options.signal?.throwIfAborted();
|
|
571
|
-
const
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
628
|
+
const explicitProxy = options.proxyUrl ? normalizeProxyUrl(options.proxyUrl) : undefined;
|
|
629
|
+
const config = explicitProxy
|
|
630
|
+
? { httpProxy: explicitProxy, httpsProxy: explicitProxy, allProxy: explicitProxy }
|
|
631
|
+
: resolveProxyConfig(
|
|
632
|
+
options.env ?? process.env,
|
|
633
|
+
options.platform ?? process.platform,
|
|
634
|
+
options.readSystemProxy,
|
|
635
|
+
);
|
|
576
636
|
const proxyUrl = proxyForUrl(target, config);
|
|
577
637
|
if (proxyUrl && target.protocol === 'https:') {
|
|
578
638
|
const tlsSocket = await openProxyTlsTunnel(target, proxyUrl, options.signal);
|
|
@@ -580,3 +640,9 @@ export async function connectHttp2(origin: string | URL, options: ConnectHttp2Op
|
|
|
580
640
|
}
|
|
581
641
|
return http2.connect(target.origin);
|
|
582
642
|
}
|
|
643
|
+
|
|
644
|
+
export function createHttp2Connector(proxyUrl?: string): Http2Connector {
|
|
645
|
+
const normalized = proxyUrl ? normalizeProxyUrl(proxyUrl) : undefined;
|
|
646
|
+
if (!normalized) return connectHttp2;
|
|
647
|
+
return (origin, options = {}) => connectHttp2(origin, { ...options, proxyUrl: normalized });
|
|
648
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { ProviderModule } from 'cortico/providers/base.ts';
|
|
|
5
5
|
import { geminiBaseline, ModelCatalog, type ModelMetadata } from './catalog.ts';
|
|
6
6
|
import { GatewayClient } from './client.ts';
|
|
7
7
|
import { gatewayControl, type GatewayControl } from './control.ts';
|
|
8
|
+
import { createHttp2Connector, createProxyFetchFor } from './http.ts';
|
|
8
9
|
import { CustomGeminiProvider } from './native.ts';
|
|
9
10
|
import { configuration, option, resolveHeaders } from './options.ts';
|
|
10
11
|
import { resolveProviderPrices } from './pricing.ts';
|
|
@@ -22,7 +23,7 @@ import { gatewayWebUi } from './webui/server.ts';
|
|
|
22
23
|
const catalogs = new Map<string, ModelCatalog>();
|
|
23
24
|
const robinAccounts = new Map<string, GatewayControl>();
|
|
24
25
|
const catalogKey = (entry: LLMProviderEntry) => JSON.stringify([
|
|
25
|
-
entry.baseUrl, entry.options?.modelsDevUrl, entry.options?.openRouterUrl,
|
|
26
|
+
entry.baseUrl, entry.options?.modelsDevUrl, entry.options?.openRouterUrl, entry.options?.proxyUrl,
|
|
26
27
|
]);
|
|
27
28
|
const accountKey = (entry: LLMProviderEntry) => JSON.stringify([
|
|
28
29
|
entry.baseUrl, entry.options?.oauthProfile ?? '',
|
|
@@ -162,6 +163,7 @@ export const GEMINI_GATEWAY = {
|
|
|
162
163
|
const key = catalogKey(entry);
|
|
163
164
|
const constructCatalog = () => new ModelCatalog(host.stateDir, {
|
|
164
165
|
modelsDevUrl: option(entry, 'modelsDevUrl'), openRouterUrl: option(entry, 'openRouterUrl'),
|
|
166
|
+
fetch: createProxyFetchFor(options.proxyUrl),
|
|
165
167
|
warn: message => host.log.warn(message),
|
|
166
168
|
});
|
|
167
169
|
const catalog = host.resource?.(`gemini-catalog:${key}`, constructCatalog) ?? constructCatalog();
|
|
@@ -179,19 +181,24 @@ export const GEMINI_GATEWAY = {
|
|
|
179
181
|
const gateway = new GatewayClient({
|
|
180
182
|
...options,
|
|
181
183
|
headers,
|
|
184
|
+
fetch: (input, init) => createProxyFetchFor(configuration(current()).proxyUrl)(input, init),
|
|
185
|
+
connectHttp2: (origin, h2Opts) => createHttp2Connector(configuration(current()).proxyUrl)(origin, h2Opts),
|
|
182
186
|
resolveHeaders: () => resolveHeaders(current(), host, true, oauth.oauthDir),
|
|
183
187
|
auth: {
|
|
184
188
|
enabled: () => oauth.authEnabled(current()),
|
|
185
189
|
accessToken: force => {
|
|
186
190
|
oauth.refreshBundledConfig();
|
|
191
|
+
oauth.setProxyUrl(configuration(current()).proxyUrl);
|
|
187
192
|
return oauth.auth.accessToken(force);
|
|
188
193
|
},
|
|
189
194
|
selectAccounts: () => {
|
|
190
195
|
oauth.refreshBundledConfig();
|
|
196
|
+
oauth.setProxyUrl(configuration(current()).proxyUrl);
|
|
191
197
|
return oauth.pickAccountOrder(configuration(current()).accountRouting);
|
|
192
198
|
},
|
|
193
199
|
accessTokenFor: (accountId, force) => {
|
|
194
200
|
oauth.refreshBundledConfig();
|
|
201
|
+
oauth.setProxyUrl(configuration(current()).proxyUrl);
|
|
195
202
|
return oauth.auth.accessTokenFor(accountId, force);
|
|
196
203
|
},
|
|
197
204
|
onAccountSuccess: accountId => {
|
package/src/options.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type { LLMProviderEntry } from 'cortico/core/types.ts';
|
|
|
4
4
|
import type { ProviderHost } from 'cortico/providers/base.ts';
|
|
5
5
|
import type { GatewayClientOptions } from './client.ts';
|
|
6
6
|
import { readStoredApiKey } from './api-key.ts';
|
|
7
|
+
import { parseProxyUrlInput } from './http.ts';
|
|
7
8
|
import { OAUTH_ACCOUNTS_FILE, OAUTH_CONFIG_FILE, OAUTH_TOKENS_FILE } from './oauth.ts';
|
|
8
9
|
import type { GatewayProtocol } from './shim.ts';
|
|
9
10
|
import { httpUrl, stringMap } from './state.ts';
|
|
@@ -17,6 +18,7 @@ export interface GatewayConfiguration extends GatewayClientOptions {
|
|
|
17
18
|
authMode: AuthMode;
|
|
18
19
|
accountRouting: AccountRoutingMode;
|
|
19
20
|
quotaEndpoint?: string;
|
|
21
|
+
proxyUrl?: string;
|
|
20
22
|
credentialHeader?: string;
|
|
21
23
|
credentialPrefix?: string;
|
|
22
24
|
secretHeaders: Record<string, string>;
|
|
@@ -72,6 +74,8 @@ export function configuration(entry: LLMProviderEntry): GatewayConfiguration {
|
|
|
72
74
|
for (const url of [modelsDevUrl, openRouterUrl]) {
|
|
73
75
|
if (url !== undefined) httpUrl(url);
|
|
74
76
|
}
|
|
77
|
+
const rawProxyUrl = option(entry, 'proxyUrl');
|
|
78
|
+
const proxyUrl = rawProxyUrl !== undefined ? parseProxyUrlInput(rawProxyUrl) : undefined;
|
|
75
79
|
const oauthProfile = option(entry, 'oauthProfile');
|
|
76
80
|
if (oauthProfile !== undefined && !/^[a-f0-9-]{36}$/.test(oauthProfile)) {
|
|
77
81
|
throw new Error('Invalid OAuth profile');
|
|
@@ -102,6 +106,7 @@ export function configuration(entry: LLMProviderEntry): GatewayConfiguration {
|
|
|
102
106
|
uploadEndpoint,
|
|
103
107
|
deleteEndpoint,
|
|
104
108
|
quotaEndpoint,
|
|
109
|
+
proxyUrl,
|
|
105
110
|
temporaryChat,
|
|
106
111
|
headers,
|
|
107
112
|
secretHeaders,
|
package/src/quota.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createHttp2Connector, createProxyFetchFor, type Http2Connector } from './http.ts';
|
|
2
2
|
import type { AccountRoutingMode } from './options.ts';
|
|
3
3
|
import { GatewayError, inspectHttpError } from './queue.ts';
|
|
4
4
|
import { isRobinGrpcRoute, queryRobinGrpcUsageInfo, ROBIN_GRPC_GET_USAGE_INFO } from './robin-grpc.ts';
|
|
@@ -64,6 +64,7 @@ export interface QuotaQueryOptions {
|
|
|
64
64
|
auth?: { accessToken(force?: boolean): Promise<string> };
|
|
65
65
|
authHeader?: string;
|
|
66
66
|
authPrefix?: string;
|
|
67
|
+
proxyUrl?: string;
|
|
67
68
|
fetch?: typeof fetch;
|
|
68
69
|
connectHttp2?: Http2Connector;
|
|
69
70
|
}
|
|
@@ -224,7 +225,8 @@ export async function queryGatewayQuota(options: QuotaQueryOptions, signal?: Abo
|
|
|
224
225
|
|
|
225
226
|
const useGrpc = options.protocol === 'robin' && isRobinGrpcRoute(route);
|
|
226
227
|
const url = httpUrl(new URL(route, options.baseUrl.replace(/\/+$/, '') + '/').href).href;
|
|
227
|
-
const request = options.fetch ??
|
|
228
|
+
const request = options.fetch ?? createProxyFetchFor(options.proxyUrl);
|
|
229
|
+
const h2Connector = options.connectHttp2 ?? createHttp2Connector(options.proxyUrl);
|
|
228
230
|
const deadline = AbortSignal.timeout(15_000);
|
|
229
231
|
const combinedSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
230
232
|
|
|
@@ -242,7 +244,7 @@ export async function queryGatewayQuota(options: QuotaQueryOptions, signal?: Abo
|
|
|
242
244
|
path: route,
|
|
243
245
|
headers,
|
|
244
246
|
signal: combinedSignal,
|
|
245
|
-
connectHttp2:
|
|
247
|
+
connectHttp2: h2Connector,
|
|
246
248
|
});
|
|
247
249
|
} catch (error) {
|
|
248
250
|
if (error instanceof GatewayError && error.status === 401 && attempt === 0 && options.auth && !combinedSignal.aborted) {
|
package/src/shim.ts
CHANGED
|
@@ -167,7 +167,9 @@ function formatRobinPart(
|
|
|
167
167
|
imageLabels?: Map<ScriptPart, string>,
|
|
168
168
|
): string {
|
|
169
169
|
if (part.type === 'text') {
|
|
170
|
-
|
|
170
|
+
// Robin replays history as plain text without native thought signatures;
|
|
171
|
+
// strip historical thinking traces to avoid compounding token/GXU usage across turns.
|
|
172
|
+
if (part.thought) return '';
|
|
171
173
|
return role === 'model' ? cleanHistoricalAssistantText(part.text) : part.text;
|
|
172
174
|
}
|
|
173
175
|
if (part.type === 'function_call') return `${TOOL_OPEN}${JSON.stringify(part.call)}${TOOL_CLOSE}`;
|
|
@@ -177,6 +179,77 @@ function formatRobinPart(
|
|
|
177
179
|
return `[Attachment: ${part.id} (${part.mimeType})]`;
|
|
178
180
|
}
|
|
179
181
|
|
|
182
|
+
/**
|
|
183
|
+
* Losslessly strips pure JSON Schema boilerplate ($schema, $id, $comment, boolean
|
|
184
|
+
* additionalProperties, empty required/properties/description, redundant title)
|
|
185
|
+
* from Robin's serialized tool list while preserving every semantic constraint,
|
|
186
|
+
* description, enum, and parameter name.
|
|
187
|
+
*/
|
|
188
|
+
function pruneRobinToolSchema(node: unknown, propName?: string, depth = 0): unknown {
|
|
189
|
+
if (depth > 16 || !node || typeof node !== 'object') return node;
|
|
190
|
+
if (Array.isArray(node)) return node.map(item => pruneRobinToolSchema(item, undefined, depth + 1));
|
|
191
|
+
|
|
192
|
+
const src = node as Record<string, unknown>;
|
|
193
|
+
const hasDescription = typeof src.description === 'string' && src.description.trim().length > 0;
|
|
194
|
+
const out: Record<string, unknown> = {};
|
|
195
|
+
|
|
196
|
+
for (const [key, value] of Object.entries(src)) {
|
|
197
|
+
if (value === undefined) continue;
|
|
198
|
+
if (key === '$schema' || key === '$id' || key === '$comment') continue;
|
|
199
|
+
if (key === 'additionalProperties' && typeof value === 'boolean') continue;
|
|
200
|
+
if (key === 'required' && Array.isArray(value) && value.length === 0) continue;
|
|
201
|
+
if (key === 'description' && typeof value === 'string' && !value.trim()) continue;
|
|
202
|
+
if (key === 'title' && typeof value === 'string') {
|
|
203
|
+
const trimmed = value.trim();
|
|
204
|
+
if (!trimmed || hasDescription || (propName && trimmed.toLowerCase() === propName.toLowerCase())) continue;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (key === 'properties' && value && typeof value === 'object' && !Array.isArray(value)) {
|
|
208
|
+
const props: Record<string, unknown> = {};
|
|
209
|
+
for (const [pName, pSchema] of Object.entries(value as Record<string, unknown>)) {
|
|
210
|
+
props[pName] = pruneRobinToolSchema(pSchema, pName, depth + 1);
|
|
211
|
+
}
|
|
212
|
+
if (Object.keys(props).length === 0) continue;
|
|
213
|
+
out[key] = props;
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
if ((key === '$defs' || key === 'definitions') && value && typeof value === 'object' && !Array.isArray(value)) {
|
|
218
|
+
const defs: Record<string, unknown> = {};
|
|
219
|
+
for (const [dName, dSchema] of Object.entries(value as Record<string, unknown>)) {
|
|
220
|
+
defs[dName] = pruneRobinToolSchema(dSchema, dName, depth + 1);
|
|
221
|
+
}
|
|
222
|
+
if (Object.keys(defs).length === 0) continue;
|
|
223
|
+
out[key] = defs;
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (key === 'items' || key === 'additionalProperties' || key === 'not') {
|
|
228
|
+
out[key] = pruneRobinToolSchema(value, undefined, depth + 1);
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if ((key === 'anyOf' || key === 'oneOf' || key === 'allOf' || key === 'prefixItems') && Array.isArray(value)) {
|
|
233
|
+
out[key] = value.map(item => pruneRobinToolSchema(item, undefined, depth + 1));
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
out[key] = value;
|
|
238
|
+
}
|
|
239
|
+
return out;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function compactRobinTools(tools: ContextScript['tools']): unknown[] {
|
|
243
|
+
return tools.map(tool => {
|
|
244
|
+
const description = typeof tool.description === 'string' ? tool.description.trim() : '';
|
|
245
|
+
return {
|
|
246
|
+
name: tool.name,
|
|
247
|
+
...(description ? { description } : {}),
|
|
248
|
+
parameters: pruneRobinToolSchema(tool.parameters, tool.name),
|
|
249
|
+
};
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
180
253
|
export async function toRobinRequest(request: GeminiRequest, upload?: UploadAttachment, _temporaryChat = true): Promise<{ query: { text: string; attachments?: { id: string; mimeType: string }[] } }> {
|
|
181
254
|
const rpc = await toRpcRequest(request, upload, _temporaryChat);
|
|
182
255
|
const sections: string[] = [];
|
|
@@ -200,7 +273,7 @@ export async function toRobinRequest(request: GeminiRequest, upload?: UploadAtta
|
|
|
200
273
|
if (systemText) sections.push(`<system_instruction>\n${systemText}\n</system_instruction>`);
|
|
201
274
|
|
|
202
275
|
if (rpc.script.tools.length) {
|
|
203
|
-
sections.push(`<available_tools>\n${JSON.stringify(rpc.script.tools)}\n</available_tools>\n<tool_protocol>\n${ROBIN_TOOL_PROTOCOL}\n</tool_protocol>`);
|
|
276
|
+
sections.push(`<available_tools>\n${JSON.stringify(compactRobinTools(rpc.script.tools))}\n</available_tools>\n<tool_protocol>\n${ROBIN_TOOL_PROTOCOL}\n</tool_protocol>`);
|
|
204
277
|
}
|
|
205
278
|
|
|
206
279
|
if (rpc.script.turns.length === 1 && rpc.script.turns[0].role === 'user' && !systemText && !rpc.script.tools.length) {
|
|
@@ -221,7 +294,7 @@ export async function toRobinRequest(request: GeminiRequest, upload?: UploadAtta
|
|
|
221
294
|
if (toolResults.length) {
|
|
222
295
|
const toolOnlyAttachments = userParts.length > 0 && userParts.every(part => part.type === 'attachment');
|
|
223
296
|
const resultParts = toolOnlyAttachments ? [...toolResults, ...userParts] : toolResults;
|
|
224
|
-
historyBlocks.push(`[Caller Tool Result]\n${resultParts.map(part => formatRobinPart(part, 'user', imageLabels)).join('\n')}`);
|
|
297
|
+
historyBlocks.push(`[Caller Tool Result]\n${resultParts.map(part => formatRobinPart(part, 'user', imageLabels)).filter(Boolean).join('\n')}`);
|
|
225
298
|
if (toolOnlyAttachments) continue;
|
|
226
299
|
}
|
|
227
300
|
if (userParts.length) {
|
package/src/webui/client.ts
CHANGED
|
@@ -1475,6 +1475,13 @@ const gatewayPanel: WebUiPanel = {
|
|
|
1475
1475
|
onChange: () => void saveOptions(),
|
|
1476
1476
|
});
|
|
1477
1477
|
|
|
1478
|
+
const proxyUrlInput = ui.input({
|
|
1479
|
+
cls: 'mono',
|
|
1480
|
+
placeholder: t('留空跟随系统代理;支持 7890 或 http://127.0.0.1:7890', 'Leave blank for system proxy; e.g. 7890 or http://127.0.0.1:7890'),
|
|
1481
|
+
onChange: () => void saveOptions(),
|
|
1482
|
+
});
|
|
1483
|
+
const proxyUrlField = ui.field(t('独立代理地址(可选)', 'Dedicated proxy URL (optional)'), proxyUrlInput);
|
|
1484
|
+
|
|
1478
1485
|
const testRow = ui.rowbar();
|
|
1479
1486
|
const testBtn = ui.button(t('测试连接', 'Test connection'), {
|
|
1480
1487
|
size: 'sm',
|
|
@@ -1490,12 +1497,14 @@ const gatewayPanel: WebUiPanel = {
|
|
|
1490
1497
|
baseUrlField,
|
|
1491
1498
|
ui.field(t('认证模式', 'Auth mode'), authModeSelect),
|
|
1492
1499
|
tempCheck.el,
|
|
1500
|
+
proxyUrlField,
|
|
1493
1501
|
testRow,
|
|
1494
1502
|
message,
|
|
1495
1503
|
);
|
|
1496
1504
|
|
|
1497
1505
|
let saving = false;
|
|
1498
1506
|
let currentProtocol: GatewayPanelState['protocol'] = 'robin';
|
|
1507
|
+
let lastSavedProxyUrl = '';
|
|
1499
1508
|
|
|
1500
1509
|
function modeDescription(protocol: GatewayPanelState['protocol']): string {
|
|
1501
1510
|
if (protocol === 'robin') return t('RobinService HTTP/2 gRPC(自动切换官方端点与路由)', 'RobinService HTTP/2 gRPC (auto endpoint & routes)');
|
|
@@ -1511,6 +1520,8 @@ const gatewayPanel: WebUiPanel = {
|
|
|
1511
1520
|
|
|
1512
1521
|
authModeSelect.value = state.authMode;
|
|
1513
1522
|
tempCheck.setChecked(state.temporaryChat);
|
|
1523
|
+
lastSavedProxyUrl = state.proxyUrl ?? '';
|
|
1524
|
+
proxyUrlInput.value = lastSavedProxyUrl;
|
|
1514
1525
|
|
|
1515
1526
|
baseUrlField.hidden = state.protocol === 'robin';
|
|
1516
1527
|
if (state.protocol !== 'robin') {
|
|
@@ -1558,8 +1569,8 @@ const gatewayPanel: WebUiPanel = {
|
|
|
1558
1569
|
}
|
|
1559
1570
|
}
|
|
1560
1571
|
|
|
1561
|
-
async function saveOptions(overrides: { authMode?: AuthMode } = {}) {
|
|
1562
|
-
if (saving || signal.aborted) return;
|
|
1572
|
+
async function saveOptions(overrides: { authMode?: AuthMode } = {}): Promise<boolean> {
|
|
1573
|
+
if (saving || signal.aborted) return false;
|
|
1563
1574
|
saving = true;
|
|
1564
1575
|
message.textContent = '';
|
|
1565
1576
|
message.classList.remove('bad');
|
|
@@ -1569,6 +1580,7 @@ const gatewayPanel: WebUiPanel = {
|
|
|
1569
1580
|
protocol: currentProtocol,
|
|
1570
1581
|
authMode: overrides.authMode ?? authModeSelect.value,
|
|
1571
1582
|
temporaryChat: tempCheck.checked,
|
|
1583
|
+
proxyUrl: proxyUrlInput.value,
|
|
1572
1584
|
...(currentProtocol !== 'robin' ? { baseUrl: baseUrlInput.value } : {}),
|
|
1573
1585
|
}]);
|
|
1574
1586
|
if (!signal.aborted) {
|
|
@@ -1582,11 +1594,13 @@ const gatewayPanel: WebUiPanel = {
|
|
|
1582
1594
|
});
|
|
1583
1595
|
message.textContent = t('配置已自动同步(请点击页面底部「保存」生效)。', 'Options synced. Click Save below to persist.');
|
|
1584
1596
|
}
|
|
1597
|
+
return true;
|
|
1585
1598
|
} catch (err) {
|
|
1586
1599
|
if (!signal.aborted) {
|
|
1587
1600
|
message.textContent = err instanceof Error ? err.message : String(err);
|
|
1588
1601
|
message.classList.add('bad');
|
|
1589
1602
|
}
|
|
1603
|
+
return false;
|
|
1590
1604
|
} finally {
|
|
1591
1605
|
saving = false;
|
|
1592
1606
|
}
|
|
@@ -1594,6 +1608,10 @@ const gatewayPanel: WebUiPanel = {
|
|
|
1594
1608
|
|
|
1595
1609
|
async function runTest() {
|
|
1596
1610
|
if (saving || signal.aborted) return;
|
|
1611
|
+
if (proxyUrlInput.value.trim() !== lastSavedProxyUrl) {
|
|
1612
|
+
const savedOk = await saveOptions();
|
|
1613
|
+
if (!savedOk || signal.aborted) return;
|
|
1614
|
+
}
|
|
1597
1615
|
testBtn.disabled = true;
|
|
1598
1616
|
message.textContent = t('正在测试连接…', 'Testing connection…');
|
|
1599
1617
|
message.classList.remove('bad');
|
package/src/webui/server.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { connectionBlocks } from 'cortico/providers/webui/config.ts';
|
|
|
5
5
|
import type { ProviderWebUiHost } from 'cortico/providers/webui/types.ts';
|
|
6
6
|
import type { WebUiPageContribution } from 'cortico/web/shared/webui-protocol.ts';
|
|
7
7
|
import type { GatewayInstanceControl } from '../index.ts';
|
|
8
|
+
import { maskProxyDisplay, parseProxyUrlInput } from '../http.ts';
|
|
8
9
|
import type { AccountTermsStatus } from '../oauth.ts';
|
|
9
10
|
import {
|
|
10
11
|
configuration,
|
|
@@ -98,6 +99,7 @@ export interface GatewayPanelState {
|
|
|
98
99
|
uploadEndpoint: string;
|
|
99
100
|
deleteEndpoint: string;
|
|
100
101
|
quotaEndpoint: string;
|
|
102
|
+
proxyUrl: string;
|
|
101
103
|
temporaryChat: boolean;
|
|
102
104
|
authEnabled: boolean;
|
|
103
105
|
}
|
|
@@ -133,6 +135,7 @@ function asGatewayState(entry: LLMProviderEntry, authEnabled: boolean): GatewayP
|
|
|
133
135
|
uploadEndpoint: cfg.uploadEndpoint ?? '',
|
|
134
136
|
deleteEndpoint: cfg.deleteEndpoint ?? '',
|
|
135
137
|
quotaEndpoint: cfg.quotaEndpoint ?? '',
|
|
138
|
+
proxyUrl: cfg.proxyUrl ?? '',
|
|
136
139
|
temporaryChat: cfg.temporaryChat ?? true,
|
|
137
140
|
authEnabled,
|
|
138
141
|
};
|
|
@@ -390,6 +393,7 @@ export function gatewayWebUi(host: ProviderWebUiHost): Partial<WebUiPageContribu
|
|
|
390
393
|
const apiKeyConfigured = typeof entry.options?.apiKeyConfigured === 'boolean' ? entry.options.apiKeyConfigured : undefined;
|
|
391
394
|
const credentialHeader = typeof entry.options?.credentialHeader === 'string' ? entry.options.credentialHeader : undefined;
|
|
392
395
|
const credentialPrefix = typeof entry.options?.credentialPrefix === 'string' ? entry.options.credentialPrefix : undefined;
|
|
396
|
+
const proxyUrl = typeof entry.options?.proxyUrl === 'string' ? entry.options.proxyUrl : undefined;
|
|
393
397
|
const next: LLMProviderEntry = {
|
|
394
398
|
...entry,
|
|
395
399
|
baseUrl: preset.baseUrl,
|
|
@@ -405,6 +409,7 @@ export function gatewayWebUi(host: ProviderWebUiHost): Partial<WebUiPageContribu
|
|
|
405
409
|
...(apiKeyConfigured !== undefined ? { apiKeyConfigured } : {}),
|
|
406
410
|
...(credentialHeader ? { credentialHeader } : {}),
|
|
407
411
|
...(credentialPrefix ? { credentialPrefix } : {}),
|
|
412
|
+
...(proxyUrl ? { proxyUrl } : {}),
|
|
408
413
|
},
|
|
409
414
|
};
|
|
410
415
|
configuration(next);
|
|
@@ -426,12 +431,19 @@ export function gatewayWebUi(host: ProviderWebUiHost): Partial<WebUiPageContribu
|
|
|
426
431
|
...(typeof entry.options?.apiKeyConfigured === 'boolean' ? { apiKeyConfigured: entry.options.apiKeyConfigured } : {}),
|
|
427
432
|
...(typeof entry.options?.credentialHeader === 'string' ? { credentialHeader: entry.options.credentialHeader } : {}),
|
|
428
433
|
...(typeof entry.options?.credentialPrefix === 'string' ? { credentialPrefix: entry.options.credentialPrefix } : {}),
|
|
434
|
+
...(typeof entry.options?.proxyUrl === 'string' ? { proxyUrl: entry.options.proxyUrl } : {}),
|
|
429
435
|
}
|
|
430
436
|
: { ...entry.options };
|
|
431
437
|
|
|
432
438
|
if (raw.protocol !== undefined) nextOptions.protocol = raw.protocol;
|
|
433
439
|
if (raw.authMode !== undefined) nextOptions.authMode = raw.authMode;
|
|
434
440
|
if (raw.temporaryChat !== undefined) nextOptions.temporaryChat = raw.temporaryChat;
|
|
441
|
+
if (raw.proxyUrl !== undefined) {
|
|
442
|
+
if (typeof raw.proxyUrl !== 'string') throw new Error('Option proxyUrl must be a string');
|
|
443
|
+
const normalizedProxy = parseProxyUrlInput(raw.proxyUrl);
|
|
444
|
+
if (normalizedProxy) nextOptions.proxyUrl = normalizedProxy;
|
|
445
|
+
else delete nextOptions.proxyUrl;
|
|
446
|
+
}
|
|
435
447
|
for (const key of STRING_OPTION_KEYS) {
|
|
436
448
|
if (raw[key] === undefined) continue;
|
|
437
449
|
if (typeof raw[key] !== 'string') throw new Error(`Option ${key} must be a string`);
|
|
@@ -448,15 +460,20 @@ export function gatewayWebUi(host: ProviderWebUiHost): Partial<WebUiPageContribu
|
|
|
448
460
|
}
|
|
449
461
|
|
|
450
462
|
const next: LLMProviderEntry = { ...entry, baseUrl: nextBaseUrl, options: nextOptions };
|
|
451
|
-
configuration(next);
|
|
463
|
+
const nextCfg = configuration(next);
|
|
452
464
|
host.save(name, next);
|
|
453
465
|
const control = host.instance(name).control as GatewayInstanceControl;
|
|
466
|
+
control.oauth.setProxyUrl(nextCfg.proxyUrl);
|
|
454
467
|
return asGatewayState(next, control.oauth.authEnabled(next));
|
|
455
468
|
}
|
|
456
469
|
if (method === 'test') {
|
|
457
470
|
const started = Date.now();
|
|
458
471
|
const cfg = configuration(entry);
|
|
459
472
|
const control = host.instance(name).control as GatewayInstanceControl;
|
|
473
|
+
control.oauth.setProxyUrl(cfg.proxyUrl);
|
|
474
|
+
const proxyNote = cfg.proxyUrl
|
|
475
|
+
? (en ? ` · via ${maskProxyDisplay(cfg.proxyUrl)}` : ` · 经代理 ${maskProxyDisplay(cfg.proxyUrl)}`)
|
|
476
|
+
: '';
|
|
460
477
|
if (cfg.protocol === 'robin') {
|
|
461
478
|
const quota = await control.queryQuota();
|
|
462
479
|
if (quota.authRequired) {
|
|
@@ -483,8 +500,8 @@ export function gatewayWebUi(host: ProviderWebUiHost): Partial<WebUiPageContribu
|
|
|
483
500
|
ok: true,
|
|
484
501
|
elapsedMs: Date.now() - started,
|
|
485
502
|
summary: en
|
|
486
|
-
? `Connected (Robin HTTP/2 gRPC${plan}${poolNote})`
|
|
487
|
-
: `连接正常(Robin HTTP/2 gRPC${plan}${poolNote})`,
|
|
503
|
+
? `Connected (Robin HTTP/2 gRPC${plan}${poolNote}${proxyNote})`
|
|
504
|
+
: `连接正常(Robin HTTP/2 gRPC${plan}${poolNote}${proxyNote})`,
|
|
488
505
|
};
|
|
489
506
|
}
|
|
490
507
|
if (cfg.authMode === 'api-key') {
|
|
@@ -500,16 +517,16 @@ export function gatewayWebUi(host: ProviderWebUiHost): Partial<WebUiPageContribu
|
|
|
500
517
|
ok: true,
|
|
501
518
|
elapsedMs: Date.now() - started,
|
|
502
519
|
summary: en
|
|
503
|
-
? `Configuration valid (${cfg.protocol.toUpperCase()} · API Key ready -> ${entry.baseUrl})`
|
|
504
|
-
: `配置有效(${cfg.protocol.toUpperCase()} · API Key
|
|
520
|
+
? `Configuration valid (${cfg.protocol.toUpperCase()} · API Key ready${proxyNote} -> ${entry.baseUrl})`
|
|
521
|
+
: `配置有效(${cfg.protocol.toUpperCase()} · API Key 已就绪${proxyNote} -> ${entry.baseUrl})`,
|
|
505
522
|
};
|
|
506
523
|
}
|
|
507
524
|
return {
|
|
508
525
|
ok: true,
|
|
509
526
|
elapsedMs: Date.now() - started,
|
|
510
527
|
summary: en
|
|
511
|
-
? `Configuration valid (${cfg.protocol.toUpperCase()} -> ${entry.baseUrl})`
|
|
512
|
-
: `配置有效(${cfg.protocol.toUpperCase()} -> ${entry.baseUrl})`,
|
|
528
|
+
? `Configuration valid (${cfg.protocol.toUpperCase()}${proxyNote} -> ${entry.baseUrl})`
|
|
529
|
+
: `配置有效(${cfg.protocol.toUpperCase()}${proxyNote} -> ${entry.baseUrl})`,
|
|
513
530
|
};
|
|
514
531
|
}
|
|
515
532
|
throw new Error(en ? 'Unknown gateway action' : '未知配置操作');
|
|
@@ -591,6 +608,7 @@ export function gatewayWebUi(host: ProviderWebUiHost): Partial<WebUiPageContribu
|
|
|
591
608
|
entry = ensureDraftDefaults(name, entry);
|
|
592
609
|
}
|
|
593
610
|
const control = host.instance(name).control as GatewayInstanceControl;
|
|
611
|
+
control.oauth.setProxyUrl(configuration(entry).proxyUrl);
|
|
594
612
|
control.oauth.refreshBundledConfig();
|
|
595
613
|
if (!control.status().configured) {
|
|
596
614
|
throw new Error(
|
|
@@ -614,6 +632,7 @@ export function gatewayWebUi(host: ProviderWebUiHost): Partial<WebUiPageContribu
|
|
|
614
632
|
throw new Error(en ? 'Paste the callback URL from your browser address bar.' : '请粘贴浏览器地址栏里的回调地址。');
|
|
615
633
|
}
|
|
616
634
|
const control = host.instance(name).control as GatewayInstanceControl;
|
|
635
|
+
control.oauth.setProxyUrl(configuration(entry).proxyUrl);
|
|
617
636
|
await control.oauth.auth.completeLogin(raw.redirectUrl);
|
|
618
637
|
return asAuthStatus(control, entry, !host.editing);
|
|
619
638
|
}
|