opencode-openai-session-router 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +674 -0
- package/README.md +217 -2
- package/dist/accounts.d.ts +31 -0
- package/dist/bun.lock.txt +671 -0
- package/dist/chunks/index-85yd61pa.js +29 -0
- package/dist/chunks/index-n7sr1hee.js +803 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +1842 -0
- package/dist/network.d.ts +8 -0
- package/dist/panel-contract.d.ts +14 -0
- package/dist/persistence.d.ts +40 -0
- package/dist/relay-protocol.d.ts +86 -0
- package/dist/relay.d.ts +50 -0
- package/dist/retry-control.d.ts +41 -0
- package/dist/router.d.ts +55 -0
- package/dist/rpc.d.ts +98 -0
- package/dist/rpc.js +7 -0
- package/dist/runtime.d.ts +94 -0
- package/dist/settings.d.ts +32 -0
- package/dist/sidebar-colors.d.ts +10 -0
- package/dist/sidebar-model.d.ts +82 -0
- package/dist/sidebar.d.ts +33 -0
- package/dist/sidebar.js +12 -0
- package/dist/tui.d.ts +3 -0
- package/dist/tui.js +25 -0
- package/package.json +52 -4
- package/scripts/build.ts +39 -0
- package/src/accounts.ts +130 -0
- package/src/index.ts +203 -0
- package/src/network.ts +25 -0
- package/src/panel-contract.ts +15 -0
- package/src/persistence.ts +96 -0
- package/src/relay-protocol.ts +157 -0
- package/src/relay.ts +593 -0
- package/src/retry-control.ts +92 -0
- package/src/router.ts +156 -0
- package/src/rpc.ts +28 -0
- package/src/runtime.ts +319 -0
- package/src/settings.ts +68 -0
- package/src/sidebar-colors.ts +132 -0
- package/src/sidebar-model.ts +257 -0
- package/src/sidebar.tsx +438 -0
- package/src/tui.tsx +12 -0
- package/tsconfig.build.json +12 -0
- package/tsconfig.json +16 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1842 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
RouterRpc
|
|
4
|
+
} from "./chunks/index-85yd61pa.js";
|
|
5
|
+
|
|
6
|
+
// src/index.ts
|
|
7
|
+
import { Plugin, Integration, Provider } from "@opencode/plugin/effect";
|
|
8
|
+
import { Effect as Effect2, Stream } from "effect";
|
|
9
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
10
|
+
|
|
11
|
+
// src/accounts.ts
|
|
12
|
+
function family(methodID) {
|
|
13
|
+
if (methodID === "chatgpt-browser" || methodID === "chatgpt-headless")
|
|
14
|
+
return "codex";
|
|
15
|
+
if (methodID === "chatgpt-token-sharing")
|
|
16
|
+
return "token-sharing";
|
|
17
|
+
}
|
|
18
|
+
var nativeBase = (value) => value === "codex" ? "https://chatgpt.com/backend-api/codex" : "https://api.openai.com/v1";
|
|
19
|
+
var nativeMenu = (connections) => connections.filter((connection) => connection.type === "credential").sort((a, b) => a.label.localeCompare(b.label) || a.id.localeCompare(b.id));
|
|
20
|
+
|
|
21
|
+
class NativeAccounts {
|
|
22
|
+
port;
|
|
23
|
+
runtime;
|
|
24
|
+
connections = new Map;
|
|
25
|
+
families = new Map;
|
|
26
|
+
tail = Promise.resolve();
|
|
27
|
+
closed = false;
|
|
28
|
+
constructor(port, runtime) {
|
|
29
|
+
this.port = port;
|
|
30
|
+
this.runtime = runtime;
|
|
31
|
+
}
|
|
32
|
+
invalidate() {
|
|
33
|
+
this.families.clear();
|
|
34
|
+
}
|
|
35
|
+
refreshMetadata(signal) {
|
|
36
|
+
const next = this.tail.then(async () => {
|
|
37
|
+
if (this.closed || signal?.aborted)
|
|
38
|
+
return;
|
|
39
|
+
const connections = await this.port.connections(signal);
|
|
40
|
+
if (this.closed || signal?.aborted)
|
|
41
|
+
return;
|
|
42
|
+
const native = nativeMenu(connections);
|
|
43
|
+
const ids = new Set(native.map(({ id }) => id));
|
|
44
|
+
for (const id of this.families.keys())
|
|
45
|
+
if (!ids.has(id))
|
|
46
|
+
this.families.delete(id);
|
|
47
|
+
this.connections = new Map([...this.connections].filter(([id]) => ids.has(id)));
|
|
48
|
+
this.runtime.setNativeOrder(native.map(({ id }, index) => ({ id, index })));
|
|
49
|
+
});
|
|
50
|
+
this.tail = next.catch(() => {});
|
|
51
|
+
return next;
|
|
52
|
+
}
|
|
53
|
+
pool(signal) {
|
|
54
|
+
const next = this.tail.then(async () => {
|
|
55
|
+
if (this.closed || signal?.aborted)
|
|
56
|
+
return;
|
|
57
|
+
const active = await this.port.active(signal);
|
|
58
|
+
if (this.closed || signal?.aborted)
|
|
59
|
+
return;
|
|
60
|
+
if (active?.type !== "credential" || active.method !== "oauth" || active.status)
|
|
61
|
+
return;
|
|
62
|
+
const credential = await this.port.resolve(active, signal);
|
|
63
|
+
if (this.closed || signal?.aborted)
|
|
64
|
+
return;
|
|
65
|
+
if (credential?.type !== "oauth")
|
|
66
|
+
return;
|
|
67
|
+
const selected = family(credential.methodID);
|
|
68
|
+
if (!selected)
|
|
69
|
+
return;
|
|
70
|
+
this.families.set(active.id, selected);
|
|
71
|
+
const connections = await this.port.connections(signal);
|
|
72
|
+
if (this.closed || signal?.aborted)
|
|
73
|
+
return;
|
|
74
|
+
const native = nativeMenu(connections);
|
|
75
|
+
const identities = new Set(native.map(({ id }) => id));
|
|
76
|
+
for (const id of this.families.keys())
|
|
77
|
+
if (!identities.has(id))
|
|
78
|
+
this.families.delete(id);
|
|
79
|
+
const available = [];
|
|
80
|
+
const nextConnections = new Map;
|
|
81
|
+
for (const [index, connection] of native.entries()) {
|
|
82
|
+
if (this.closed || signal?.aborted)
|
|
83
|
+
return;
|
|
84
|
+
if (connection.method !== "oauth" || connection.status)
|
|
85
|
+
continue;
|
|
86
|
+
nextConnections.set(connection.id, connection);
|
|
87
|
+
if (!this.families.has(connection.id)) {
|
|
88
|
+
try {
|
|
89
|
+
const resolved = connection.id === active.id ? credential : await this.port.resolve(connection, signal);
|
|
90
|
+
this.families.set(connection.id, resolved?.type === "oauth" ? family(resolved.methodID) : undefined);
|
|
91
|
+
} catch {
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (this.families.get(connection.id) === selected)
|
|
96
|
+
available.push({ id: connection.id, index });
|
|
97
|
+
}
|
|
98
|
+
if (this.closed || signal?.aborted)
|
|
99
|
+
return;
|
|
100
|
+
this.connections = nextConnections;
|
|
101
|
+
this.runtime.setAccounts(available, native.map(({ id }, index) => ({ id, index })));
|
|
102
|
+
return selected;
|
|
103
|
+
});
|
|
104
|
+
this.tail = next.catch(() => {});
|
|
105
|
+
return next;
|
|
106
|
+
}
|
|
107
|
+
async headers(id, selected, source, signal) {
|
|
108
|
+
if (this.closed || signal?.aborted)
|
|
109
|
+
throw new Error("Native account resolver closed or cancelled.");
|
|
110
|
+
const connection = this.connections.get(id);
|
|
111
|
+
if (!connection)
|
|
112
|
+
throw new Error("Native account no longer available.");
|
|
113
|
+
const credential = await this.port.resolve(connection, signal);
|
|
114
|
+
if (this.closed || signal?.aborted)
|
|
115
|
+
throw new Error("Native account resolver closed or cancelled.");
|
|
116
|
+
if (credential?.type !== "oauth" || family(credential.methodID) !== selected) {
|
|
117
|
+
throw new Error("Native account is no longer compatible.");
|
|
118
|
+
}
|
|
119
|
+
const headers = upstreamHeaders(source);
|
|
120
|
+
headers.set("authorization", `Bearer ${credential.access}`);
|
|
121
|
+
if (selected === "codex" && typeof credential.metadata?.accountID === "string") {
|
|
122
|
+
headers.set("chatgpt-account-id", credential.metadata.accountID);
|
|
123
|
+
}
|
|
124
|
+
return headers;
|
|
125
|
+
}
|
|
126
|
+
stop() {
|
|
127
|
+
this.closed = true;
|
|
128
|
+
}
|
|
129
|
+
dispose() {
|
|
130
|
+
this.stop();
|
|
131
|
+
this.connections.clear();
|
|
132
|
+
this.families.clear();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
var LOCAL_AUTH = "x-opencode-local-router-auth";
|
|
136
|
+
function upstreamHeaders(source) {
|
|
137
|
+
const headers = new Headers(source);
|
|
138
|
+
const connectionFields = new Set((headers.get("connection") ?? "").toLowerCase().split(",").map((value) => value.trim()));
|
|
139
|
+
for (const key of [...headers.keys()]) {
|
|
140
|
+
if (key.startsWith("x-opencode-local-") || key === "authorization" || key === "proxy-authorization" || key === "chatgpt-account-id" || key === "cookie" || key === "x-api-key" || key === "api-key" || key === "host" || key === "origin" || key === "connection" || key === "upgrade" || key === "content-length" || key.startsWith("sec-websocket-") || key === "transfer-encoding" || key === "proxy-connection" || key === "forwarded" || key.startsWith("x-forwarded-") || key === "x-real-ip" || key === "te" || key === "trailer" || connectionFields.has(key))
|
|
141
|
+
headers.delete(key);
|
|
142
|
+
}
|
|
143
|
+
return headers;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// src/router.ts
|
|
147
|
+
class NoAccountsError extends Error {
|
|
148
|
+
constructor() {
|
|
149
|
+
super("No accounts are available.");
|
|
150
|
+
this.name = "NoAccountsError";
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
class SessionRouter {
|
|
155
|
+
accounts = [];
|
|
156
|
+
nextAccountId;
|
|
157
|
+
cursorOrder = [];
|
|
158
|
+
assignments = new Map;
|
|
159
|
+
revisions = new Map;
|
|
160
|
+
revision = 0;
|
|
161
|
+
constructor(accountIds) {
|
|
162
|
+
this.setAccounts(accountIds);
|
|
163
|
+
}
|
|
164
|
+
setAccounts(accountIds) {
|
|
165
|
+
if (accountIds.some((id) => !id) || new Set(accountIds).size !== accountIds.length) {
|
|
166
|
+
throw new Error("Account IDs must be nonempty and unique.");
|
|
167
|
+
}
|
|
168
|
+
const available = new Set(accountIds);
|
|
169
|
+
if (!accountIds.length) {
|
|
170
|
+
this.accounts = [];
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const nextIndex = this.cursorOrder.indexOf(this.nextAccountId ?? "");
|
|
174
|
+
let next;
|
|
175
|
+
for (let offset = 0;nextIndex >= 0 && offset < this.cursorOrder.length; offset++) {
|
|
176
|
+
const id = this.cursorOrder[(nextIndex + offset) % this.cursorOrder.length];
|
|
177
|
+
if (available.has(id)) {
|
|
178
|
+
next = id;
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
this.accounts = [...accountIds];
|
|
183
|
+
this.nextAccountId = next ?? this.accounts[0];
|
|
184
|
+
this.cursorOrder = [...accountIds];
|
|
185
|
+
}
|
|
186
|
+
state() {
|
|
187
|
+
return { assignments: this.entries(), cursor: { nextAccountID: this.nextAccountId ?? null, order: [...this.cursorOrder] } };
|
|
188
|
+
}
|
|
189
|
+
restore(state) {
|
|
190
|
+
if (this.assignments.size || this.accounts.length)
|
|
191
|
+
throw new Error("Routing restore requires an unused router.");
|
|
192
|
+
for (const [sessionID, accountID] of state.assignments) {
|
|
193
|
+
this.assignments.set(sessionID, accountID);
|
|
194
|
+
this.revisions.set(sessionID, ++this.revision);
|
|
195
|
+
}
|
|
196
|
+
this.nextAccountId = state.cursor.nextAccountID ?? undefined;
|
|
197
|
+
this.cursorOrder = [...state.cursor.order];
|
|
198
|
+
}
|
|
199
|
+
getAssignedAccount(sessionId) {
|
|
200
|
+
return this.assignments.get(sessionId);
|
|
201
|
+
}
|
|
202
|
+
entries() {
|
|
203
|
+
return [...this.assignments];
|
|
204
|
+
}
|
|
205
|
+
removeSession(sessionId) {
|
|
206
|
+
this.assignments.delete(sessionId);
|
|
207
|
+
this.revisions.delete(sessionId);
|
|
208
|
+
}
|
|
209
|
+
begin(sessionId) {
|
|
210
|
+
const candidates = this.getCandidates(sessionId);
|
|
211
|
+
return { sessionId, candidates, revision: this.revisions.get(sessionId) };
|
|
212
|
+
}
|
|
213
|
+
commit(request, accountId) {
|
|
214
|
+
if (this.revisions.get(request.sessionId) !== request.revision || !request.candidates.includes(accountId) || !this.accounts.includes(accountId))
|
|
215
|
+
return false;
|
|
216
|
+
this.assignments.set(request.sessionId, accountId);
|
|
217
|
+
this.revisions.set(request.sessionId, ++this.revision);
|
|
218
|
+
return true;
|
|
219
|
+
}
|
|
220
|
+
getCandidates(sessionId) {
|
|
221
|
+
if (this.accounts.length === 0)
|
|
222
|
+
throw new NoAccountsError;
|
|
223
|
+
let assigned = this.assignments.get(sessionId);
|
|
224
|
+
if (assigned === undefined || !this.accounts.includes(assigned)) {
|
|
225
|
+
assigned = this.nextAccountId;
|
|
226
|
+
this.assignments.set(sessionId, assigned);
|
|
227
|
+
this.revisions.set(sessionId, ++this.revision);
|
|
228
|
+
const index = this.accounts.indexOf(assigned);
|
|
229
|
+
this.nextAccountId = this.accounts[(index + 1) % this.accounts.length];
|
|
230
|
+
}
|
|
231
|
+
const start = this.accounts.indexOf(assigned);
|
|
232
|
+
return [...this.accounts.slice(start), ...this.accounts.slice(0, start)];
|
|
233
|
+
}
|
|
234
|
+
async run(sessionId, attempt, isRateLimit) {
|
|
235
|
+
const request = this.begin(sessionId);
|
|
236
|
+
const candidates = request.candidates;
|
|
237
|
+
let lastError = new NoAccountsError;
|
|
238
|
+
for (const accountId of candidates) {
|
|
239
|
+
if (!this.accounts.includes(accountId))
|
|
240
|
+
continue;
|
|
241
|
+
let result;
|
|
242
|
+
try {
|
|
243
|
+
result = await attempt(accountId);
|
|
244
|
+
} catch (error) {
|
|
245
|
+
if (!isRateLimit(error))
|
|
246
|
+
throw error;
|
|
247
|
+
lastError = error;
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
this.commit(request, accountId);
|
|
251
|
+
return result;
|
|
252
|
+
}
|
|
253
|
+
throw lastError;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// src/retry-control.ts
|
|
258
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "crypto";
|
|
259
|
+
var CONTROL = "_opencode_local_router";
|
|
260
|
+
var ORIGINAL = "_opencode_local_original";
|
|
261
|
+
var digest = (value) => createHash("sha256").update(value).digest("hex");
|
|
262
|
+
var record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
263
|
+
|
|
264
|
+
class RetryControl {
|
|
265
|
+
runtimeID;
|
|
266
|
+
#key = randomBytes(32);
|
|
267
|
+
#closed = false;
|
|
268
|
+
constructor(runtimeID) {
|
|
269
|
+
this.runtimeID = runtimeID;
|
|
270
|
+
}
|
|
271
|
+
mac(value) {
|
|
272
|
+
return createHmac("sha256", this.#key).update(value).digest();
|
|
273
|
+
}
|
|
274
|
+
seal(original, failure, requestURL) {
|
|
275
|
+
if (this.#closed)
|
|
276
|
+
throw new Error("Routing runtime closed.");
|
|
277
|
+
let wire;
|
|
278
|
+
try {
|
|
279
|
+
wire = JSON.parse(original);
|
|
280
|
+
} catch {}
|
|
281
|
+
if (!record(wire)) {
|
|
282
|
+
const text = original.trim();
|
|
283
|
+
const fallback = "Provider request failed with HTTP 429";
|
|
284
|
+
const url = new URL(requestURL);
|
|
285
|
+
const message = !text || /^<(?:!doctype|html)/i.test(text) ? `${fallback} (POST ${url.origin}${url.pathname})` : `${fallback}: ${text.length > 2000 ? text.slice(0, 2000) + "\u2026" : text}`;
|
|
286
|
+
wire = { message, [ORIGINAL]: original };
|
|
287
|
+
} else if (CONTROL in wire || ORIGINAL in wire) {
|
|
288
|
+
throw new Error("Reserved local diagnostic field collision.");
|
|
289
|
+
}
|
|
290
|
+
const context = {
|
|
291
|
+
sessionID: failure.sessionID,
|
|
292
|
+
model: { providerID: failure.model.providerID, id: failure.model.id, variant: failure.model.variant },
|
|
293
|
+
kind: failure.kind,
|
|
294
|
+
handle: failure.handle
|
|
295
|
+
};
|
|
296
|
+
const claims = {
|
|
297
|
+
version: 1,
|
|
298
|
+
runtimeID: this.runtimeID,
|
|
299
|
+
...context,
|
|
300
|
+
finalNativeLimit: true,
|
|
301
|
+
original: Buffer.from(original, "utf16le").toString("base64"),
|
|
302
|
+
digest: digest(JSON.stringify(wire))
|
|
303
|
+
};
|
|
304
|
+
const value = Buffer.from(JSON.stringify(claims)).toString("hex");
|
|
305
|
+
if (!record(wire))
|
|
306
|
+
throw new Error("Invalid native diagnostic.");
|
|
307
|
+
return JSON.stringify({ ...wire, [CONTROL]: `${value}.${this.mac(value).toString("hex")}` });
|
|
308
|
+
}
|
|
309
|
+
verify(context) {
|
|
310
|
+
if (this.#closed)
|
|
311
|
+
return;
|
|
312
|
+
try {
|
|
313
|
+
const wire = JSON.parse(context.error.response?.body ?? "");
|
|
314
|
+
if (!record(wire) || typeof wire[CONTROL] !== "string")
|
|
315
|
+
return;
|
|
316
|
+
const match = /^([0-9a-f]+)\.([0-9a-f]{64})$/.exec(wire[CONTROL]);
|
|
317
|
+
if (!match || match[1].length % 2)
|
|
318
|
+
return;
|
|
319
|
+
const value = match[1];
|
|
320
|
+
if (!timingSafeEqual(Buffer.from(match[2], "hex"), this.mac(value)))
|
|
321
|
+
return;
|
|
322
|
+
const claims = JSON.parse(Buffer.from(value, "hex").toString());
|
|
323
|
+
if (claims.version !== 1 || claims.runtimeID !== this.runtimeID || claims.finalNativeLimit !== true || !["primary", "compaction"].includes(claims.kind) || typeof claims.handle !== "string" || claims.sessionID !== context.sessionID || claims.model?.providerID !== context.model.providerID || claims.model.id !== context.model.id || claims.model.variant !== context.model.variant || typeof claims.original !== "string")
|
|
324
|
+
return;
|
|
325
|
+
delete wire[CONTROL];
|
|
326
|
+
if (digest(JSON.stringify(wire)) !== claims.digest)
|
|
327
|
+
return;
|
|
328
|
+
return { originalBody: Buffer.from(claims.original, "base64").toString("utf16le"), failure: claims };
|
|
329
|
+
} catch {
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
dispose() {
|
|
334
|
+
this.#closed = true;
|
|
335
|
+
this.#key.fill(0);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// src/runtime.ts
|
|
340
|
+
class RouterRuntime {
|
|
341
|
+
capacity;
|
|
342
|
+
router = new SessionRouter([]);
|
|
343
|
+
accounts = [];
|
|
344
|
+
nativeOrder = [];
|
|
345
|
+
calls = new Map;
|
|
346
|
+
primary = new Map;
|
|
347
|
+
listeners = new Set;
|
|
348
|
+
durableListeners = new Set;
|
|
349
|
+
durableText = "";
|
|
350
|
+
current = { instanceID: crypto.randomUUID(), revision: 0, enabled: true, assignments: [] };
|
|
351
|
+
enabledValue = true;
|
|
352
|
+
disposed = false;
|
|
353
|
+
sequence = 0;
|
|
354
|
+
retryControl = new RetryControl(this.current.instanceID);
|
|
355
|
+
constructor(capacity = 2048) {
|
|
356
|
+
this.capacity = capacity;
|
|
357
|
+
if (!Number.isInteger(capacity) || capacity < 1)
|
|
358
|
+
throw new Error("Invalid call capacity.");
|
|
359
|
+
}
|
|
360
|
+
get enabled() {
|
|
361
|
+
return this.enabledValue;
|
|
362
|
+
}
|
|
363
|
+
setEnabled(enabled) {
|
|
364
|
+
this.assertOpen();
|
|
365
|
+
this.enabledValue = enabled;
|
|
366
|
+
this.publish();
|
|
367
|
+
return this.snapshot();
|
|
368
|
+
}
|
|
369
|
+
setAccounts(accounts, nativeOrder = accounts) {
|
|
370
|
+
this.assertOpen();
|
|
371
|
+
this.validateOrder(nativeOrder);
|
|
372
|
+
this.validateOrder(accounts);
|
|
373
|
+
if (accounts.some(({ id }) => !nativeOrder.some((account) => account.id === id))) {
|
|
374
|
+
throw new Error("Eligible accounts must belong to the native credential order.");
|
|
375
|
+
}
|
|
376
|
+
this.router.setAccounts(accounts.map(({ id }) => id));
|
|
377
|
+
this.accounts = accounts.map((account) => ({ ...account }));
|
|
378
|
+
this.nativeOrder = nativeOrder.map((account) => ({ ...account }));
|
|
379
|
+
this.publish();
|
|
380
|
+
}
|
|
381
|
+
validateOrder(accounts) {
|
|
382
|
+
if (accounts.some(({ index }) => !Number.isInteger(index) || index < 0) || new Set(accounts.map(({ index }) => index)).size !== accounts.length || accounts.some(({ id }) => !id) || new Set(accounts.map(({ id }) => id)).size !== accounts.length) {
|
|
383
|
+
throw new Error("Native account indices must be distinct nonnegative integers.");
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
setNativeOrder(nativeOrder) {
|
|
387
|
+
this.assertOpen();
|
|
388
|
+
this.validateOrder(nativeOrder);
|
|
389
|
+
this.nativeOrder = nativeOrder.map((account) => ({ ...account }));
|
|
390
|
+
this.accounts = this.accounts.filter(({ id }) => nativeOrder.some((account) => account.id === id));
|
|
391
|
+
this.router.setAccounts(this.accounts.map(({ id }) => id));
|
|
392
|
+
this.publish();
|
|
393
|
+
}
|
|
394
|
+
restore(state) {
|
|
395
|
+
this.assertOpen();
|
|
396
|
+
if (this.calls.size || this.primary.size)
|
|
397
|
+
throw new Error("Routing restore requires an unused runtime.");
|
|
398
|
+
this.router.restore({
|
|
399
|
+
assignments: state.sessions.flatMap((row) => row.accountID === null ? [] : [[row.sessionID, row.accountID]]),
|
|
400
|
+
cursor: state.cursor
|
|
401
|
+
});
|
|
402
|
+
for (const row of state.sessions)
|
|
403
|
+
if (row.primary !== null)
|
|
404
|
+
this.primary.set(row.sessionID, row.primary);
|
|
405
|
+
this.publish();
|
|
406
|
+
}
|
|
407
|
+
durableSnapshot() {
|
|
408
|
+
const routing = this.router.state();
|
|
409
|
+
return {
|
|
410
|
+
version: 1,
|
|
411
|
+
sessions: [...new Set([...this.primary.keys(), ...routing.assignments.map(([id]) => id)])].sort().map((sessionID) => ({
|
|
412
|
+
sessionID,
|
|
413
|
+
accountID: this.router.getAssignedAccount(sessionID) ?? null,
|
|
414
|
+
primary: this.primary.get(sessionID) ?? null
|
|
415
|
+
})),
|
|
416
|
+
cursor: routing.cursor
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
subscribeDurable(listener) {
|
|
420
|
+
this.assertOpen();
|
|
421
|
+
this.durableListeners.add(listener);
|
|
422
|
+
return () => {
|
|
423
|
+
this.durableListeners.delete(listener);
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
setPrimaryProvider(sessionID, nativeOpenAI) {
|
|
427
|
+
this.assertOpen();
|
|
428
|
+
this.primary.set(sessionID, nativeOpenAI);
|
|
429
|
+
this.publish();
|
|
430
|
+
}
|
|
431
|
+
begin(sessionID, kind, model) {
|
|
432
|
+
this.assertOpen();
|
|
433
|
+
if (this.calls.size >= this.capacity) {
|
|
434
|
+
const idle = [...this.calls.values()].filter((call2) => call2.inFlight === 0).sort((a, b) => Number(a.outcome !== "success") - Number(b.outcome !== "success") || a.recency - b.recency);
|
|
435
|
+
if (!idle[0])
|
|
436
|
+
throw new Error("Routing call capacity reached: all entries are executing.");
|
|
437
|
+
this.calls.delete(idle[0].handle);
|
|
438
|
+
}
|
|
439
|
+
const call = {
|
|
440
|
+
handle: crypto.randomUUID(),
|
|
441
|
+
sessionID,
|
|
442
|
+
kind,
|
|
443
|
+
model: model && { providerID: model.providerID, id: model.id, variant: model.variant },
|
|
444
|
+
routing: this.router.begin(sessionID),
|
|
445
|
+
tried: new Set,
|
|
446
|
+
limited: new Set,
|
|
447
|
+
inFlight: 0,
|
|
448
|
+
outcome: "new",
|
|
449
|
+
recency: ++this.sequence,
|
|
450
|
+
aborts: new Set
|
|
451
|
+
};
|
|
452
|
+
this.calls.set(call.handle, call);
|
|
453
|
+
this.publish();
|
|
454
|
+
return call;
|
|
455
|
+
}
|
|
456
|
+
lookup(handle) {
|
|
457
|
+
const call = this.calls.get(handle);
|
|
458
|
+
if (call)
|
|
459
|
+
call.recency = ++this.sequence;
|
|
460
|
+
return call;
|
|
461
|
+
}
|
|
462
|
+
contains(call) {
|
|
463
|
+
return this.calls.get(call.handle) === call;
|
|
464
|
+
}
|
|
465
|
+
enter(call) {
|
|
466
|
+
this.assertOpen();
|
|
467
|
+
if (this.calls.get(call.handle) !== call)
|
|
468
|
+
throw new Error("Routing state expired.");
|
|
469
|
+
if (call.cancelled)
|
|
470
|
+
throw new Error("Routing request cancelled.");
|
|
471
|
+
if (call.inFlight)
|
|
472
|
+
throw new Error("Routing exchange already executing.");
|
|
473
|
+
const fresh = !call.exhaustion && (call.outcome === "new" || call.outcome === "success");
|
|
474
|
+
const routing = fresh ? this.router.begin(call.sessionID) : call.routing;
|
|
475
|
+
const tried = fresh ? new Set : call.tried;
|
|
476
|
+
const limited = fresh ? new Set : call.limited;
|
|
477
|
+
call.routing = routing;
|
|
478
|
+
call.tried = tried;
|
|
479
|
+
call.limited = limited;
|
|
480
|
+
if (fresh)
|
|
481
|
+
call.sentWebSocket = false;
|
|
482
|
+
call.inFlight++;
|
|
483
|
+
call.recency = ++this.sequence;
|
|
484
|
+
return { call, routing, tried, limited, retainedError: call.exhaustion?.error, succeeded: false };
|
|
485
|
+
}
|
|
486
|
+
complete(operation, accountID) {
|
|
487
|
+
const { call } = operation;
|
|
488
|
+
if (this.disposed || call.cancelled || this.calls.get(call.handle) !== call || !this.available(accountID))
|
|
489
|
+
return;
|
|
490
|
+
operation.succeeded = true;
|
|
491
|
+
call.exhaustion = undefined;
|
|
492
|
+
this.router.commit(operation.routing, accountID);
|
|
493
|
+
this.publish();
|
|
494
|
+
}
|
|
495
|
+
retain(operation, error) {
|
|
496
|
+
operation.terminalError = error;
|
|
497
|
+
if (this.calls.get(operation.call.handle) === operation.call)
|
|
498
|
+
operation.call.exhaustion = { error };
|
|
499
|
+
}
|
|
500
|
+
end(operation) {
|
|
501
|
+
const { call } = operation;
|
|
502
|
+
call.inFlight--;
|
|
503
|
+
call.outcome = operation.succeeded ? "success" : "failure";
|
|
504
|
+
call.recency = ++this.sequence;
|
|
505
|
+
}
|
|
506
|
+
available(accountID) {
|
|
507
|
+
return this.accounts.some(({ id }) => id === accountID);
|
|
508
|
+
}
|
|
509
|
+
commit(call, accountID) {
|
|
510
|
+
if (this.disposed || this.calls.get(call.handle) !== call || call.exhaustion || !this.available(accountID))
|
|
511
|
+
return false;
|
|
512
|
+
const accepted = this.router.commit(call.routing, accountID);
|
|
513
|
+
this.publish();
|
|
514
|
+
return accepted;
|
|
515
|
+
}
|
|
516
|
+
release(handle) {
|
|
517
|
+
if (this.calls.get(handle)?.inFlight === 0)
|
|
518
|
+
this.calls.delete(handle);
|
|
519
|
+
}
|
|
520
|
+
releaseSessionCalls(sessionID, primaryOnly = false) {
|
|
521
|
+
for (const [handle, call] of this.calls) {
|
|
522
|
+
if (call.sessionID === sessionID && call.inFlight === 0 && (!primaryOnly || call.kind === "primary"))
|
|
523
|
+
this.calls.delete(handle);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
removeSession(sessionID) {
|
|
527
|
+
this.router.removeSession(sessionID);
|
|
528
|
+
this.primary.delete(sessionID);
|
|
529
|
+
for (const [handle, call] of this.calls) {
|
|
530
|
+
if (call.sessionID === sessionID) {
|
|
531
|
+
this.cancel(call);
|
|
532
|
+
this.calls.delete(handle);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
this.publish();
|
|
536
|
+
}
|
|
537
|
+
snapshot() {
|
|
538
|
+
return structuredClone(this.current);
|
|
539
|
+
}
|
|
540
|
+
subscribe(listener) {
|
|
541
|
+
this.assertOpen();
|
|
542
|
+
this.listeners.add(listener);
|
|
543
|
+
return () => {
|
|
544
|
+
this.listeners.delete(listener);
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
stop() {
|
|
548
|
+
this.disposed = true;
|
|
549
|
+
for (const call of this.calls.values())
|
|
550
|
+
this.cancel(call);
|
|
551
|
+
}
|
|
552
|
+
dispose() {
|
|
553
|
+
this.stop();
|
|
554
|
+
this.retryControl.dispose();
|
|
555
|
+
this.calls.clear();
|
|
556
|
+
this.listeners.clear();
|
|
557
|
+
this.durableListeners.clear();
|
|
558
|
+
for (const [id] of this.router.entries())
|
|
559
|
+
this.router.removeSession(id);
|
|
560
|
+
this.primary.clear();
|
|
561
|
+
this.accounts = [];
|
|
562
|
+
this.nativeOrder = [];
|
|
563
|
+
}
|
|
564
|
+
cancel(call) {
|
|
565
|
+
call.cancelled = true;
|
|
566
|
+
for (const abort of call.aborts)
|
|
567
|
+
abort.abort();
|
|
568
|
+
}
|
|
569
|
+
cancelPrimary(sessionID) {
|
|
570
|
+
for (const call of this.calls.values()) {
|
|
571
|
+
if (call.sessionID === sessionID && call.kind === "primary")
|
|
572
|
+
this.cancel(call);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
assertOpen() {
|
|
576
|
+
if (this.disposed)
|
|
577
|
+
throw new Error("Routing runtime is disposed.");
|
|
578
|
+
}
|
|
579
|
+
publish() {
|
|
580
|
+
const durable = this.durableSnapshot();
|
|
581
|
+
const text = JSON.stringify(durable);
|
|
582
|
+
if (text !== this.durableText) {
|
|
583
|
+
this.durableText = text;
|
|
584
|
+
for (const listener of this.durableListeners)
|
|
585
|
+
listener(durable);
|
|
586
|
+
}
|
|
587
|
+
const assignments = [...new Set([
|
|
588
|
+
...this.primary.keys(),
|
|
589
|
+
...this.router.entries().map(([id]) => id)
|
|
590
|
+
])].sort().map((sessionID) => ({
|
|
591
|
+
sessionID,
|
|
592
|
+
accountIndex: this.primary.get(sessionID) === true ? this.nativeOrder.find(({ id }) => id === this.router.getAssignedAccount(sessionID))?.index ?? null : null
|
|
593
|
+
}));
|
|
594
|
+
if (this.current.enabled === this.enabledValue && JSON.stringify(assignments) === JSON.stringify(this.current.assignments))
|
|
595
|
+
return;
|
|
596
|
+
this.current = {
|
|
597
|
+
instanceID: this.current.instanceID,
|
|
598
|
+
revision: this.current.revision + 1,
|
|
599
|
+
enabled: this.enabledValue,
|
|
600
|
+
assignments
|
|
601
|
+
};
|
|
602
|
+
for (const listener of this.listeners)
|
|
603
|
+
listener(this.snapshot());
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// src/relay.ts
|
|
608
|
+
import { randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
609
|
+
|
|
610
|
+
// src/relay-protocol.ts
|
|
611
|
+
import { protocol, route } from "@opencode/ai/protocols/openai-responses";
|
|
612
|
+
import { Effect, Schema } from "effect";
|
|
613
|
+
import { ai } from "@opencode/ai/effect";
|
|
614
|
+
import { HttpClientResponse } from "effect/http";
|
|
615
|
+
var decode = Schema.decodeUnknownSync(protocol.stream.event);
|
|
616
|
+
function wireEvent(raw) {
|
|
617
|
+
const original = JSON.parse(raw);
|
|
618
|
+
if (record(original) && ((CONTROL in original) || (ORIGINAL in original))) {
|
|
619
|
+
throw new Error("Reserved local diagnostic field collision.");
|
|
620
|
+
}
|
|
621
|
+
const event = decode(raw);
|
|
622
|
+
if (!record(event))
|
|
623
|
+
throw new Error("Invalid native event.");
|
|
624
|
+
if (CONTROL in event || ORIGINAL in event)
|
|
625
|
+
throw new Error("Reserved local diagnostic field collision.");
|
|
626
|
+
return event;
|
|
627
|
+
}
|
|
628
|
+
var terminal = (event) => ["error", "response.failed", "response.incomplete", "response.completed"].includes(event.type);
|
|
629
|
+
function wire429(event) {
|
|
630
|
+
return ["error", "response.failed"].includes(event.type) && !(typeof event.status === "number" && typeof event.status_code === "number" && event.status !== event.status_code) && (event.status === 429 || event.status_code === 429);
|
|
631
|
+
}
|
|
632
|
+
var nativeLimitCodes = new Set([
|
|
633
|
+
"rate_limit_exceeded",
|
|
634
|
+
"rate_limit_error",
|
|
635
|
+
"too_many_requests",
|
|
636
|
+
"insufficient_quota"
|
|
637
|
+
]);
|
|
638
|
+
function wsLimit(event) {
|
|
639
|
+
if (!["error", "response.failed"].includes(event.type))
|
|
640
|
+
return false;
|
|
641
|
+
const statuses = [event.status, event.status_code].filter((status) => status !== undefined);
|
|
642
|
+
if (statuses.some((status) => typeof status !== "number" || !Number.isInteger(status)) || statuses.length === 2 && statuses[0] !== statuses[1])
|
|
643
|
+
throw new Error("Conflicting or malformed native status.");
|
|
644
|
+
if (statuses.length)
|
|
645
|
+
return statuses[0] === 429;
|
|
646
|
+
const nested = event.error ?? event.response?.error;
|
|
647
|
+
if (event.code !== undefined && typeof event.code !== "string" || nested !== undefined && nested !== null && !record(nested) && typeof nested !== "string" || record(nested) && nested.code !== undefined && typeof nested.code !== "string") {
|
|
648
|
+
throw new Error("Malformed native error code.");
|
|
649
|
+
}
|
|
650
|
+
const code = event.code ?? (record(nested) ? nested.code : undefined);
|
|
651
|
+
return typeof code === "string" && nativeLimitCodes.has(code);
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
class ResponseLifecycle {
|
|
655
|
+
id;
|
|
656
|
+
ended = false;
|
|
657
|
+
invalid = false;
|
|
658
|
+
visible = false;
|
|
659
|
+
success = false;
|
|
660
|
+
parser = protocol.stream.initial({
|
|
661
|
+
model: { id: "relay-validation", provider: "openai", route: {
|
|
662
|
+
id: "openai.responses",
|
|
663
|
+
providerMetadataKey: "openai"
|
|
664
|
+
} },
|
|
665
|
+
messages: [],
|
|
666
|
+
tools: []
|
|
667
|
+
});
|
|
668
|
+
observe(event) {
|
|
669
|
+
if (this.ended) {
|
|
670
|
+
this.invalid = true;
|
|
671
|
+
this.success = false;
|
|
672
|
+
throw new Error("Native event after terminal.");
|
|
673
|
+
}
|
|
674
|
+
if (event.type === "response.created") {
|
|
675
|
+
if (this.id || typeof event.response?.id !== "string" || !event.response.id)
|
|
676
|
+
this.invalid = true;
|
|
677
|
+
else
|
|
678
|
+
this.id = event.response.id;
|
|
679
|
+
} else if (event.type.startsWith("response.") && !this.id)
|
|
680
|
+
this.invalid = true;
|
|
681
|
+
if (event.response?.id && event.response.id !== this.id)
|
|
682
|
+
this.invalid = true;
|
|
683
|
+
if (!["error", "response.failed", "response.incomplete"].includes(event.type) && !this.invalid) {
|
|
684
|
+
try {
|
|
685
|
+
const [next, output] = Effect.runSync(protocol.stream.step(this.parser, event));
|
|
686
|
+
this.parser = next;
|
|
687
|
+
if (output.some((item) => item.type === "tool-input-error"))
|
|
688
|
+
this.invalid = true;
|
|
689
|
+
} catch {
|
|
690
|
+
this.invalid = true;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
if (!["response.created", "response.in_progress", "ping", "keepalive"].includes(event.type) && !terminal(event))
|
|
694
|
+
this.visible = true;
|
|
695
|
+
if (terminal(event)) {
|
|
696
|
+
this.ended = true;
|
|
697
|
+
this.success = !this.invalid && !!this.id && event.type === "response.completed" && event.response?.id === this.id && event.response?.status === "completed" && Array.isArray(event.response.output);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
var compactRequest = ai.request({ model: route.model({ id: "relay-validation" }), prompt: "Local response validation only." });
|
|
702
|
+
async function compactSuccess(raw, signal) {
|
|
703
|
+
try {
|
|
704
|
+
const value = JSON.parse(raw);
|
|
705
|
+
if (!record(value) || CONTROL in value || ORIGINAL in value)
|
|
706
|
+
return false;
|
|
707
|
+
await Effect.runPromise(Effect.scoped(route.compact.endpoint(compactRequest, {
|
|
708
|
+
execute: (request) => Effect.succeed(HttpClientResponse.fromWeb(request, new Response(raw, {
|
|
709
|
+
status: 200,
|
|
710
|
+
headers: { "content-type": "application/json" }
|
|
711
|
+
})))
|
|
712
|
+
})), { signal });
|
|
713
|
+
return true;
|
|
714
|
+
} catch {
|
|
715
|
+
return false;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
var sseFrame = (raw) => raw.split(`
|
|
719
|
+
`).map((line) => `data: ${line}`).join(`
|
|
720
|
+
`) + `
|
|
721
|
+
|
|
722
|
+
`;
|
|
723
|
+
async function* sseData(body, signal, maxFrame = 8 * 1024 * 1024) {
|
|
724
|
+
const reader = body.getReader();
|
|
725
|
+
const decoder = new TextDecoder;
|
|
726
|
+
let buffer = "";
|
|
727
|
+
let pendingCR = false;
|
|
728
|
+
const cancel = () => {
|
|
729
|
+
reader.cancel().catch(() => {});
|
|
730
|
+
};
|
|
731
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
732
|
+
try {
|
|
733
|
+
for (;; ) {
|
|
734
|
+
if (signal.aborted)
|
|
735
|
+
throw new Error("Relay request cancelled.");
|
|
736
|
+
const next = await reader.read();
|
|
737
|
+
let text = decoder.decode(next.value, { stream: !next.done });
|
|
738
|
+
if (pendingCR)
|
|
739
|
+
text = "\r" + text;
|
|
740
|
+
pendingCR = !next.done && text.endsWith("\r");
|
|
741
|
+
if (pendingCR)
|
|
742
|
+
text = text.slice(0, -1);
|
|
743
|
+
buffer += text.replace(/\r\n/g, `
|
|
744
|
+
`).replace(/\r/g, `
|
|
745
|
+
`);
|
|
746
|
+
let end;
|
|
747
|
+
while ((end = buffer.indexOf(`
|
|
748
|
+
|
|
749
|
+
`)) >= 0) {
|
|
750
|
+
const frame = buffer.slice(0, end);
|
|
751
|
+
if (frame.length > maxFrame)
|
|
752
|
+
throw new Error("Native SSE frame too large.");
|
|
753
|
+
buffer = buffer.slice(end + 2);
|
|
754
|
+
const data = frame.split(`
|
|
755
|
+
`).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join(`
|
|
756
|
+
`);
|
|
757
|
+
if (data && data !== "[DONE]")
|
|
758
|
+
yield data;
|
|
759
|
+
}
|
|
760
|
+
if (buffer.length > maxFrame)
|
|
761
|
+
throw new Error("Native SSE frame too large.");
|
|
762
|
+
if (next.done) {
|
|
763
|
+
if (buffer.trim())
|
|
764
|
+
throw new Error("Truncated native SSE frame.");
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
} finally {
|
|
769
|
+
signal.removeEventListener("abort", cancel);
|
|
770
|
+
await reader.cancel().catch(() => {});
|
|
771
|
+
reader.releaseLock();
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// src/network.ts
|
|
776
|
+
var value = (environment, name) => environment[name] ?? environment[name.toLowerCase()];
|
|
777
|
+
function webSocketProxy(input, environment = process.env) {
|
|
778
|
+
const url = new URL(input);
|
|
779
|
+
if (["127.0.0.1", "localhost", "::1"].includes(url.hostname))
|
|
780
|
+
return;
|
|
781
|
+
const noProxy = value(environment, "NO_PROXY");
|
|
782
|
+
const port = url.port || (url.protocol === "wss:" ? "443" : "80");
|
|
783
|
+
const hostname = url.hostname.toLowerCase();
|
|
784
|
+
if (noProxy?.split(/[\s,]+/).some((entry) => {
|
|
785
|
+
if (!entry)
|
|
786
|
+
return false;
|
|
787
|
+
if (entry === "*")
|
|
788
|
+
return true;
|
|
789
|
+
const match = /^(.+?):(\d+)$/.exec(entry);
|
|
790
|
+
if (match?.[2] && match[2] !== port)
|
|
791
|
+
return false;
|
|
792
|
+
const host = (match?.[1] ?? entry).toLowerCase().replace(/^\*/, "");
|
|
793
|
+
return host.startsWith(".") ? hostname.endsWith(host) : hostname === host;
|
|
794
|
+
}))
|
|
795
|
+
return;
|
|
796
|
+
return value(environment, url.protocol === "wss:" ? "WSS_PROXY" : "WS_PROXY") ?? value(environment, url.protocol === "wss:" ? "HTTPS_PROXY" : "HTTP_PROXY") ?? value(environment, "ALL_PROXY");
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// src/relay.ts
|
|
800
|
+
var maxBody = 32 * 1024 * 1024;
|
|
801
|
+
var maxPrefix = 256 * 1024;
|
|
802
|
+
var connectLeaseMs = 1e4;
|
|
803
|
+
var BunWebSocket = globalThis.WebSocket;
|
|
804
|
+
var localError = (message, status = 409) => new Response(JSON.stringify({ error: { message } }), {
|
|
805
|
+
status,
|
|
806
|
+
headers: { "content-type": "application/json" }
|
|
807
|
+
});
|
|
808
|
+
var cleanResponseHeaders = (input) => {
|
|
809
|
+
const headers = new Headers(input);
|
|
810
|
+
for (const name of (headers.get("connection") ?? "").split(","))
|
|
811
|
+
if (name.trim())
|
|
812
|
+
headers.delete(name.trim());
|
|
813
|
+
for (const name of [
|
|
814
|
+
"content-encoding",
|
|
815
|
+
"content-length",
|
|
816
|
+
"transfer-encoding",
|
|
817
|
+
"connection",
|
|
818
|
+
"set-cookie",
|
|
819
|
+
"upgrade",
|
|
820
|
+
"proxy-connection",
|
|
821
|
+
"trailer",
|
|
822
|
+
"te"
|
|
823
|
+
])
|
|
824
|
+
headers.delete(name);
|
|
825
|
+
return headers;
|
|
826
|
+
};
|
|
827
|
+
async function boundedBytes(body, signal) {
|
|
828
|
+
if (!body)
|
|
829
|
+
return new Uint8Array;
|
|
830
|
+
const reader = body.getReader();
|
|
831
|
+
const chunks = [];
|
|
832
|
+
let size = 0;
|
|
833
|
+
const cancel = () => {
|
|
834
|
+
reader.cancel().catch(() => {});
|
|
835
|
+
};
|
|
836
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
837
|
+
try {
|
|
838
|
+
for (;; ) {
|
|
839
|
+
if (signal.aborted)
|
|
840
|
+
throw new Error("Native response cancelled.");
|
|
841
|
+
const next = await reader.read();
|
|
842
|
+
if (signal.aborted)
|
|
843
|
+
throw new Error("Native response cancelled.");
|
|
844
|
+
if (next.done) {
|
|
845
|
+
const bytes = new Uint8Array(size);
|
|
846
|
+
let offset = 0;
|
|
847
|
+
for (const chunk of chunks) {
|
|
848
|
+
bytes.set(chunk, offset);
|
|
849
|
+
offset += chunk.byteLength;
|
|
850
|
+
}
|
|
851
|
+
return bytes;
|
|
852
|
+
}
|
|
853
|
+
size += next.value.byteLength;
|
|
854
|
+
if (size > maxBody)
|
|
855
|
+
throw new Error("Native response diagnostic exceeds local limit.");
|
|
856
|
+
chunks.push(next.value);
|
|
857
|
+
}
|
|
858
|
+
} finally {
|
|
859
|
+
signal.removeEventListener("abort", cancel);
|
|
860
|
+
await reader.cancel().catch(() => {});
|
|
861
|
+
reader.releaseLock();
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
async function boundedText(response, signal) {
|
|
865
|
+
return new TextDecoder().decode(await boundedBytes(response.body, signal));
|
|
866
|
+
}
|
|
867
|
+
var failureResponse = (failure) => new Response(failure.status === 200 && new Headers(failure.headers).get("content-type")?.includes("text/event-stream") ? sseFrame(failure.body) : failure.body, { status: failure.status, headers: failure.headers });
|
|
868
|
+
function checkDiagnostic(raw) {
|
|
869
|
+
let value2;
|
|
870
|
+
try {
|
|
871
|
+
value2 = JSON.parse(raw);
|
|
872
|
+
} catch {
|
|
873
|
+
return;
|
|
874
|
+
}
|
|
875
|
+
if (record(value2) && ((CONTROL in value2) || (ORIGINAL in value2)))
|
|
876
|
+
throw new Error("Reserved diagnostic collision.");
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
class SessionRelay {
|
|
880
|
+
runtime;
|
|
881
|
+
dependencies;
|
|
882
|
+
auth = randomBytes2(32).toString("hex");
|
|
883
|
+
owned = new Map;
|
|
884
|
+
sockets = new Set;
|
|
885
|
+
server;
|
|
886
|
+
closed = false;
|
|
887
|
+
sendHTTP;
|
|
888
|
+
connect;
|
|
889
|
+
constructor(runtime, dependencies) {
|
|
890
|
+
this.runtime = runtime;
|
|
891
|
+
this.dependencies = dependencies;
|
|
892
|
+
this.sendHTTP = dependencies.fetch ?? fetch;
|
|
893
|
+
this.connect = dependencies.connect ?? ((url, headers) => {
|
|
894
|
+
const proxy = webSocketProxy(url);
|
|
895
|
+
return new BunWebSocket(url, { headers: Object.fromEntries(headers), ...proxy ? { proxy } : {} });
|
|
896
|
+
});
|
|
897
|
+
this.server = Bun.serve({
|
|
898
|
+
hostname: "127.0.0.1",
|
|
899
|
+
port: 0,
|
|
900
|
+
maxRequestBodySize: maxBody,
|
|
901
|
+
fetch: (request, server) => this.accept(request, server),
|
|
902
|
+
websocket: {
|
|
903
|
+
maxPayloadLength: maxBody,
|
|
904
|
+
backpressureLimit: maxBody,
|
|
905
|
+
closeOnBackpressureLimit: true,
|
|
906
|
+
idleTimeout: 60,
|
|
907
|
+
open: (socket) => {
|
|
908
|
+
this.sockets.add(socket);
|
|
909
|
+
if (socket.data.first)
|
|
910
|
+
socket.data.unusedLease = setTimeout(() => {
|
|
911
|
+
this.runtime.cancel(socket.data.binding.call);
|
|
912
|
+
socket.close(1001, "Unused native transport lease expired");
|
|
913
|
+
}, connectLeaseMs);
|
|
914
|
+
},
|
|
915
|
+
message: (socket, data) => {
|
|
916
|
+
clearTimeout(socket.data.unusedLease);
|
|
917
|
+
if (typeof data !== "string") {
|
|
918
|
+
socket.close(1008, "Text native frames required");
|
|
919
|
+
return;
|
|
920
|
+
}
|
|
921
|
+
this.wsExchange(socket, data).catch(() => socket.close(1011, "Local relay exchange failed"));
|
|
922
|
+
},
|
|
923
|
+
close: (socket) => {
|
|
924
|
+
clearTimeout(socket.data.unusedLease);
|
|
925
|
+
this.sockets.delete(socket);
|
|
926
|
+
socket.data.first?.socket.close();
|
|
927
|
+
socket.data.first = undefined;
|
|
928
|
+
if (socket.data.abort)
|
|
929
|
+
this.runtime.cancel(socket.data.binding.call);
|
|
930
|
+
if (socket.data.pending) {
|
|
931
|
+
this.runtime.cancel(socket.data.binding.call);
|
|
932
|
+
socket.data.pending.end();
|
|
933
|
+
socket.data.pending = undefined;
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
});
|
|
938
|
+
}
|
|
939
|
+
get origin() {
|
|
940
|
+
return this.server.url.origin;
|
|
941
|
+
}
|
|
942
|
+
bind(call, selected) {
|
|
943
|
+
this.prune();
|
|
944
|
+
this.owned.set(call.handle, { call, family: selected });
|
|
945
|
+
return `${this.origin}/op/${call.handle}`;
|
|
946
|
+
}
|
|
947
|
+
localHeaders(headers) {
|
|
948
|
+
const copy = new Headers(headers);
|
|
949
|
+
for (const key of [...copy.keys()]) {
|
|
950
|
+
if (key === "authorization" || key === "chatgpt-account-id" || key === "cookie" || key === "api-key" || key === "x-api-key" || key.startsWith("x-opencode-local-"))
|
|
951
|
+
copy.delete(key);
|
|
952
|
+
}
|
|
953
|
+
copy.set(LOCAL_AUTH, this.auth);
|
|
954
|
+
return copy;
|
|
955
|
+
}
|
|
956
|
+
binding(url, sessionID, model, kind) {
|
|
957
|
+
let parsed;
|
|
958
|
+
try {
|
|
959
|
+
parsed = new URL(url);
|
|
960
|
+
} catch {
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
const httpOrigin = parsed.origin.replace(/^ws:/, "http:");
|
|
964
|
+
if (httpOrigin !== this.origin)
|
|
965
|
+
return;
|
|
966
|
+
const match = /^\/op\/([0-9a-f-]{36})\/responses(?:\/compact)?$/.exec(parsed.pathname);
|
|
967
|
+
if (!match || parsed.search || parsed.hash || parsed.username || parsed.password)
|
|
968
|
+
return;
|
|
969
|
+
const binding = this.owned.get(match[1]);
|
|
970
|
+
const call = binding?.call;
|
|
971
|
+
if (!call || this.runtime.lookup(call.handle) !== call || call.sessionID !== sessionID || call.kind !== kind || call.model?.providerID !== model.providerID || call.model.id !== model.id || call.model.variant !== model.variant)
|
|
972
|
+
return;
|
|
973
|
+
return binding;
|
|
974
|
+
}
|
|
975
|
+
prune() {
|
|
976
|
+
for (const [handle, binding] of this.owned)
|
|
977
|
+
if (!this.runtime.contains(binding.call))
|
|
978
|
+
this.owned.delete(handle);
|
|
979
|
+
}
|
|
980
|
+
authenticated(request) {
|
|
981
|
+
if (this.closed)
|
|
982
|
+
return;
|
|
983
|
+
const url = new URL(request.url);
|
|
984
|
+
if (url.origin !== this.origin || url.search || url.hash)
|
|
985
|
+
return;
|
|
986
|
+
const value2 = request.headers.get(LOCAL_AUTH) ?? "";
|
|
987
|
+
const supplied = Buffer.from(value2);
|
|
988
|
+
const expected = Buffer.from(this.auth);
|
|
989
|
+
if (supplied.length !== expected.length || !timingSafeEqual2(supplied, expected))
|
|
990
|
+
return;
|
|
991
|
+
const match = /^\/op\/([0-9a-f-]{36})\/responses(?:\/compact)?$/.exec(url.pathname);
|
|
992
|
+
if (!match)
|
|
993
|
+
return;
|
|
994
|
+
const binding = this.owned.get(match[1]);
|
|
995
|
+
if (!binding || this.runtime.lookup(binding.call.handle) !== binding.call)
|
|
996
|
+
return;
|
|
997
|
+
return binding;
|
|
998
|
+
}
|
|
999
|
+
target(binding, compact = false, ws = false) {
|
|
1000
|
+
return `${nativeBase(binding.family).replace(/^https:/, ws ? "wss:" : "https:")}/responses${compact ? "/compact" : ""}`;
|
|
1001
|
+
}
|
|
1002
|
+
async open(url, headers, signal) {
|
|
1003
|
+
if (signal.aborted)
|
|
1004
|
+
throw new Error("Cancelled.");
|
|
1005
|
+
const socket = this.connect(url, headers);
|
|
1006
|
+
return new Promise((resolve, reject) => {
|
|
1007
|
+
let settled = false;
|
|
1008
|
+
const close = () => {
|
|
1009
|
+
try {
|
|
1010
|
+
socket.close();
|
|
1011
|
+
} catch {}
|
|
1012
|
+
};
|
|
1013
|
+
const cleanup = () => {
|
|
1014
|
+
clearTimeout(timer);
|
|
1015
|
+
signal.removeEventListener("abort", abort);
|
|
1016
|
+
};
|
|
1017
|
+
const fail = (message) => {
|
|
1018
|
+
if (settled)
|
|
1019
|
+
return;
|
|
1020
|
+
settled = true;
|
|
1021
|
+
cleanup();
|
|
1022
|
+
close();
|
|
1023
|
+
reject(new Error(message));
|
|
1024
|
+
};
|
|
1025
|
+
const abort = () => fail("Cancelled.");
|
|
1026
|
+
const timer = setTimeout(() => fail("Native upstream WebSocket connection lease expired."), connectLeaseMs);
|
|
1027
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
1028
|
+
socket.onopen = () => {
|
|
1029
|
+
if (signal.aborted || settled) {
|
|
1030
|
+
close();
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
settled = true;
|
|
1034
|
+
cleanup();
|
|
1035
|
+
resolve(socket);
|
|
1036
|
+
};
|
|
1037
|
+
socket.onerror = () => fail("Native upstream WebSocket unavailable.");
|
|
1038
|
+
socket.onclose = () => fail("Native upstream WebSocket closed before opening.");
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
async accept(request, server) {
|
|
1042
|
+
if (request.headers.get("upgrade")?.toLowerCase() !== "websocket")
|
|
1043
|
+
return this.respondHTTP(request);
|
|
1044
|
+
const binding = this.authenticated(request);
|
|
1045
|
+
if (!binding)
|
|
1046
|
+
return localError("Local routing state expired or access denied.", 403);
|
|
1047
|
+
if (binding.call.cancelled)
|
|
1048
|
+
return localError("Local routing operation cancelled.");
|
|
1049
|
+
if (request.headers.get("upgrade")?.toLowerCase() === "websocket") {
|
|
1050
|
+
if (request.method !== "GET" || new URL(request.url).pathname.endsWith("/compact") || binding.family !== "codex")
|
|
1051
|
+
return localError("Invalid native WebSocket route.", 400);
|
|
1052
|
+
if (binding.call.exhaustion) {
|
|
1053
|
+
if (server.upgrade(request, { data: { binding, headers: request.headers } }))
|
|
1054
|
+
return;
|
|
1055
|
+
return localError("Local upgrade failed.", 400);
|
|
1056
|
+
}
|
|
1057
|
+
let pending;
|
|
1058
|
+
try {
|
|
1059
|
+
pending = this.start(binding);
|
|
1060
|
+
} catch {
|
|
1061
|
+
return localError("Local native exchange busy or expired.");
|
|
1062
|
+
}
|
|
1063
|
+
const abort = pending.abort;
|
|
1064
|
+
const onAbort = () => this.runtime.cancel(binding.call);
|
|
1065
|
+
request.signal.addEventListener("abort", onAbort, { once: true });
|
|
1066
|
+
let first;
|
|
1067
|
+
let upgraded = false;
|
|
1068
|
+
try {
|
|
1069
|
+
const id = pending.state.routing.candidates.find((id2) => !pending.state.limited.has(id2) && this.runtime.available(id2));
|
|
1070
|
+
if (!id)
|
|
1071
|
+
throw new Error("No native candidate remains.");
|
|
1072
|
+
const headers = await this.dependencies.headers(id, binding.family, request.headers, abort.signal);
|
|
1073
|
+
const socket = await this.open(this.target(binding, false, true), headers, abort.signal);
|
|
1074
|
+
first = { socket, id };
|
|
1075
|
+
if (this.closed || binding.call.cancelled || abort.signal.aborted)
|
|
1076
|
+
throw new Error("Cancelled.");
|
|
1077
|
+
if (server.upgrade(request, { data: { binding, headers: request.headers, first, pending } })) {
|
|
1078
|
+
upgraded = true;
|
|
1079
|
+
return;
|
|
1080
|
+
}
|
|
1081
|
+
socket.close();
|
|
1082
|
+
} catch {
|
|
1083
|
+
first?.socket.close();
|
|
1084
|
+
return localError("Native WebSocket unavailable; native fallback may proceed.", 502);
|
|
1085
|
+
} finally {
|
|
1086
|
+
if (!upgraded)
|
|
1087
|
+
pending.end();
|
|
1088
|
+
request.signal.removeEventListener("abort", onAbort);
|
|
1089
|
+
}
|
|
1090
|
+
return localError("Local upgrade failed.", 400);
|
|
1091
|
+
}
|
|
1092
|
+
return localError("Invalid native transport.", 400);
|
|
1093
|
+
}
|
|
1094
|
+
async respondHTTP(request, invocationSignal) {
|
|
1095
|
+
const binding = this.authenticated(request);
|
|
1096
|
+
if (!binding)
|
|
1097
|
+
return localError("Local routing state expired or access denied.", 403);
|
|
1098
|
+
if (request.method !== "POST" || request.headers.has("upgrade"))
|
|
1099
|
+
return localError("Method not allowed.", 405);
|
|
1100
|
+
if (binding.call.cancelled)
|
|
1101
|
+
return localError("Local routing operation cancelled.");
|
|
1102
|
+
return this.httpExchange(binding, request, invocationSignal);
|
|
1103
|
+
}
|
|
1104
|
+
start(binding) {
|
|
1105
|
+
const state = this.runtime.enter(binding.call);
|
|
1106
|
+
const abort = new AbortController;
|
|
1107
|
+
binding.call.aborts.add(abort);
|
|
1108
|
+
return { state, abort, end: () => {
|
|
1109
|
+
binding.call.aborts.delete(abort);
|
|
1110
|
+
this.runtime.end(state);
|
|
1111
|
+
} };
|
|
1112
|
+
}
|
|
1113
|
+
seal(binding, raw, url) {
|
|
1114
|
+
const call = binding.call;
|
|
1115
|
+
if (!call.model)
|
|
1116
|
+
throw new Error("Missing native model context.");
|
|
1117
|
+
return this.runtime.retryControl.seal(raw, {
|
|
1118
|
+
sessionID: call.sessionID,
|
|
1119
|
+
model: call.model,
|
|
1120
|
+
kind: call.kind,
|
|
1121
|
+
handle: call.handle
|
|
1122
|
+
}, url);
|
|
1123
|
+
}
|
|
1124
|
+
cached(binding, state) {
|
|
1125
|
+
return state.retainedError;
|
|
1126
|
+
}
|
|
1127
|
+
failure(binding, state, failure, requestURL = this.target(binding)) {
|
|
1128
|
+
const body = this.seal(binding, failure.body, requestURL);
|
|
1129
|
+
const final = { ...failure, body };
|
|
1130
|
+
this.runtime.retain(state, final);
|
|
1131
|
+
return final;
|
|
1132
|
+
}
|
|
1133
|
+
async httpExchange(binding, request, invocationSignal) {
|
|
1134
|
+
if (binding.call.sentWebSocket && binding.call.outcome !== "success") {
|
|
1135
|
+
return localError("Native post-send transport handoff cannot be safely replayed.");
|
|
1136
|
+
}
|
|
1137
|
+
let exchange;
|
|
1138
|
+
try {
|
|
1139
|
+
exchange = this.start(binding);
|
|
1140
|
+
} catch {
|
|
1141
|
+
return localError("Local routing state expired, cancelled or busy.");
|
|
1142
|
+
}
|
|
1143
|
+
const { state, abort } = exchange;
|
|
1144
|
+
const signal = invocationSignal ? AbortSignal.any([request.signal, invocationSignal]) : request.signal;
|
|
1145
|
+
const cancel = () => {
|
|
1146
|
+
this.runtime.cancel(binding.call);
|
|
1147
|
+
};
|
|
1148
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
1149
|
+
let streaming = false;
|
|
1150
|
+
let preHandoff;
|
|
1151
|
+
let released = false;
|
|
1152
|
+
const release = () => {
|
|
1153
|
+
if (released)
|
|
1154
|
+
return;
|
|
1155
|
+
released = true;
|
|
1156
|
+
signal.removeEventListener("abort", cancel);
|
|
1157
|
+
exchange.end();
|
|
1158
|
+
};
|
|
1159
|
+
try {
|
|
1160
|
+
const cached = this.cached(binding, state);
|
|
1161
|
+
if (cached)
|
|
1162
|
+
return cached.transport === "http" ? failureResponse(cached) : localError("Native exchange already terminated on WebSocket.");
|
|
1163
|
+
if (signal.aborted) {
|
|
1164
|
+
cancel();
|
|
1165
|
+
throw new Error("Cancelled.");
|
|
1166
|
+
}
|
|
1167
|
+
const body = (await boundedBytes(request.body, abort.signal)).buffer;
|
|
1168
|
+
if (body.byteLength > maxBody)
|
|
1169
|
+
return localError("Native request too large.", 413);
|
|
1170
|
+
const encoding = request.headers.get("content-encoding");
|
|
1171
|
+
const plain = encoding === "zstd" ? Bun.zstdDecompressSync(body) : encoding === "gzip" ? Bun.gunzipSync(new Uint8Array(body)) : encoding === "deflate" ? Bun.inflateSync(new Uint8Array(body)) : !encoding || encoding === "identity" ? new Uint8Array(body) : undefined;
|
|
1172
|
+
if (!plain || plain.byteLength > maxBody)
|
|
1173
|
+
return localError("Unsupported or oversized native request encoding.", 413);
|
|
1174
|
+
const canonical = JSON.parse(new TextDecoder().decode(plain));
|
|
1175
|
+
if (!record(canonical) || typeof canonical.model !== "string" || !Array.isArray(canonical.input) || canonical.previous_response_id != null || CONTROL in canonical || ORIGINAL in canonical) {
|
|
1176
|
+
return localError("Full native canonical history is required.");
|
|
1177
|
+
}
|
|
1178
|
+
const compact = new URL(request.url).pathname.endsWith("/compact");
|
|
1179
|
+
let last;
|
|
1180
|
+
for (const id of state.routing.candidates) {
|
|
1181
|
+
if (abort.signal.aborted || binding.call.cancelled)
|
|
1182
|
+
throw new Error("Cancelled.");
|
|
1183
|
+
if (state.limited.has(id) || !this.runtime.available(id))
|
|
1184
|
+
continue;
|
|
1185
|
+
const headers = await this.dependencies.headers(id, binding.family, request.headers, abort.signal);
|
|
1186
|
+
state.tried.add(id);
|
|
1187
|
+
const response = await this.sendHTTP(this.target(binding, compact), {
|
|
1188
|
+
method: "POST",
|
|
1189
|
+
headers,
|
|
1190
|
+
body,
|
|
1191
|
+
signal: abort.signal,
|
|
1192
|
+
redirect: "manual"
|
|
1193
|
+
});
|
|
1194
|
+
if (response.status >= 300 && response.status < 400) {
|
|
1195
|
+
await response.body?.cancel();
|
|
1196
|
+
return localError("Native upstream redirect refused.", 502);
|
|
1197
|
+
}
|
|
1198
|
+
if (response.status === 429) {
|
|
1199
|
+
const raw = await boundedText(response, abort.signal);
|
|
1200
|
+
checkDiagnostic(raw);
|
|
1201
|
+
state.limited.add(id);
|
|
1202
|
+
last = { transport: "http", status: response.status, headers: [...cleanResponseHeaders(response.headers)], body: raw };
|
|
1203
|
+
continue;
|
|
1204
|
+
}
|
|
1205
|
+
if (!response.ok || compact) {
|
|
1206
|
+
const raw = await boundedText(response, abort.signal);
|
|
1207
|
+
checkDiagnostic(raw);
|
|
1208
|
+
if (response.ok && await compactSuccess(raw, abort.signal) && !abort.signal.aborted)
|
|
1209
|
+
this.runtime.complete(state, id);
|
|
1210
|
+
return new Response(raw, { status: response.status, headers: cleanResponseHeaders(response.headers) });
|
|
1211
|
+
}
|
|
1212
|
+
if (!response.body || !response.headers.get("content-type")?.includes("text/event-stream")) {
|
|
1213
|
+
const bytes = response.body ? await boundedBytes(response.body, abort.signal) : null;
|
|
1214
|
+
return new Response(bytes, { status: response.status, headers: cleanResponseHeaders(response.headers) });
|
|
1215
|
+
}
|
|
1216
|
+
const iterator = sseData(response.body, abort.signal)[Symbol.asyncIterator]();
|
|
1217
|
+
preHandoff = iterator;
|
|
1218
|
+
const lifecycle = new ResponseLifecycle;
|
|
1219
|
+
const prefix = [];
|
|
1220
|
+
let invalidFrame;
|
|
1221
|
+
let size = 0;
|
|
1222
|
+
let nextAccount = false;
|
|
1223
|
+
for (;; ) {
|
|
1224
|
+
const next = await iterator.next();
|
|
1225
|
+
if (next.done)
|
|
1226
|
+
break;
|
|
1227
|
+
checkDiagnostic(next.value);
|
|
1228
|
+
let event;
|
|
1229
|
+
try {
|
|
1230
|
+
event = wireEvent(next.value);
|
|
1231
|
+
} catch {
|
|
1232
|
+
invalidFrame = next.value;
|
|
1233
|
+
prefix.push(next.value);
|
|
1234
|
+
break;
|
|
1235
|
+
}
|
|
1236
|
+
lifecycle.observe(event);
|
|
1237
|
+
if (wire429(event) && !lifecycle.visible) {
|
|
1238
|
+
state.limited.add(id);
|
|
1239
|
+
last = { transport: "http", status: response.status, headers: [...cleanResponseHeaders(response.headers)], body: next.value };
|
|
1240
|
+
nextAccount = true;
|
|
1241
|
+
await iterator.return?.(undefined);
|
|
1242
|
+
preHandoff = undefined;
|
|
1243
|
+
break;
|
|
1244
|
+
}
|
|
1245
|
+
prefix.push(next.value);
|
|
1246
|
+
if (!lifecycle.visible && !terminal(event)) {
|
|
1247
|
+
size += next.value.length;
|
|
1248
|
+
if (size > maxPrefix)
|
|
1249
|
+
throw new Error("Native setup prefix exceeds local limit.");
|
|
1250
|
+
}
|
|
1251
|
+
if (lifecycle.visible || terminal(event))
|
|
1252
|
+
break;
|
|
1253
|
+
}
|
|
1254
|
+
if (nextAccount)
|
|
1255
|
+
continue;
|
|
1256
|
+
if (abort.signal.aborted || binding.call.cancelled)
|
|
1257
|
+
throw new Error("Cancelled.");
|
|
1258
|
+
const encoder = new TextEncoder;
|
|
1259
|
+
const encode = (raw) => encoder.encode(sseFrame(raw));
|
|
1260
|
+
let endPromise;
|
|
1261
|
+
let unusedLease;
|
|
1262
|
+
const end = () => endPromise ??= (async () => {
|
|
1263
|
+
clearTimeout(unusedLease);
|
|
1264
|
+
abort.signal.removeEventListener("abort", onAbort);
|
|
1265
|
+
try {
|
|
1266
|
+
await iterator.return?.(undefined);
|
|
1267
|
+
} finally {
|
|
1268
|
+
release();
|
|
1269
|
+
}
|
|
1270
|
+
})();
|
|
1271
|
+
const onAbort = () => {
|
|
1272
|
+
end();
|
|
1273
|
+
};
|
|
1274
|
+
abort.signal.addEventListener("abort", onAbort, { once: true });
|
|
1275
|
+
unusedLease = setTimeout(() => {
|
|
1276
|
+
cancel();
|
|
1277
|
+
end();
|
|
1278
|
+
}, 60000);
|
|
1279
|
+
const stream = new ReadableStream({
|
|
1280
|
+
pull: async (controller) => {
|
|
1281
|
+
clearTimeout(unusedLease);
|
|
1282
|
+
try {
|
|
1283
|
+
if (abort.signal.aborted || binding.call.cancelled)
|
|
1284
|
+
throw new Error("Cancelled.");
|
|
1285
|
+
let raw = prefix.shift();
|
|
1286
|
+
if (raw === undefined) {
|
|
1287
|
+
const next = await iterator.next();
|
|
1288
|
+
if (next.done) {
|
|
1289
|
+
controller.close();
|
|
1290
|
+
await end();
|
|
1291
|
+
return;
|
|
1292
|
+
}
|
|
1293
|
+
raw = next.value;
|
|
1294
|
+
checkDiagnostic(raw);
|
|
1295
|
+
try {
|
|
1296
|
+
lifecycle.observe(wireEvent(raw));
|
|
1297
|
+
} catch {
|
|
1298
|
+
invalidFrame = raw;
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
if (raw === invalidFrame) {
|
|
1302
|
+
controller.enqueue(encode(raw));
|
|
1303
|
+
controller.close();
|
|
1304
|
+
await end();
|
|
1305
|
+
return;
|
|
1306
|
+
}
|
|
1307
|
+
const event = wireEvent(raw);
|
|
1308
|
+
if (wire429(event)) {
|
|
1309
|
+
raw = this.failure(binding, state, {
|
|
1310
|
+
transport: "http",
|
|
1311
|
+
status: response.status,
|
|
1312
|
+
headers: [...cleanResponseHeaders(response.headers)],
|
|
1313
|
+
body: raw
|
|
1314
|
+
}).body;
|
|
1315
|
+
}
|
|
1316
|
+
if (terminal(event) && lifecycle.success && !abort.signal.aborted && !binding.call.cancelled) {
|
|
1317
|
+
this.runtime.complete(state, id);
|
|
1318
|
+
}
|
|
1319
|
+
controller.enqueue(encode(raw));
|
|
1320
|
+
if (terminal(event)) {
|
|
1321
|
+
controller.close();
|
|
1322
|
+
await end();
|
|
1323
|
+
}
|
|
1324
|
+
} catch (error) {
|
|
1325
|
+
controller.error(error);
|
|
1326
|
+
await end();
|
|
1327
|
+
}
|
|
1328
|
+
},
|
|
1329
|
+
cancel: async () => {
|
|
1330
|
+
cancel();
|
|
1331
|
+
abort.abort();
|
|
1332
|
+
await end();
|
|
1333
|
+
}
|
|
1334
|
+
}, { highWaterMark: 0 });
|
|
1335
|
+
const result = new Response(stream, { status: response.status, headers: cleanResponseHeaders(response.headers) });
|
|
1336
|
+
streaming = true;
|
|
1337
|
+
preHandoff = undefined;
|
|
1338
|
+
return result;
|
|
1339
|
+
}
|
|
1340
|
+
if (!last)
|
|
1341
|
+
return localError("No native accounts remain available.");
|
|
1342
|
+
const final = this.failure(binding, state, last, this.target(binding, compact));
|
|
1343
|
+
return failureResponse(final);
|
|
1344
|
+
} catch {
|
|
1345
|
+
return localError("Local native exchange failed or was cancelled.", 502);
|
|
1346
|
+
} finally {
|
|
1347
|
+
if (!streaming) {
|
|
1348
|
+
abort.abort();
|
|
1349
|
+
try {
|
|
1350
|
+
await preHandoff?.return?.(undefined);
|
|
1351
|
+
} catch {} finally {
|
|
1352
|
+
release();
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
async wsExchange(host, frame) {
|
|
1358
|
+
const { binding } = host.data;
|
|
1359
|
+
const request = JSON.parse(frame);
|
|
1360
|
+
if (!record(request) || request.type !== "response.create" || request.previous_response_id !== undefined || CONTROL in request || ORIGINAL in request)
|
|
1361
|
+
throw new Error("Full native history required.");
|
|
1362
|
+
const exchange = host.data.pending ?? this.start(binding);
|
|
1363
|
+
host.data.pending = undefined;
|
|
1364
|
+
host.data.abort = exchange.abort;
|
|
1365
|
+
const { state, abort } = exchange;
|
|
1366
|
+
try {
|
|
1367
|
+
const cached = this.cached(binding, state);
|
|
1368
|
+
if (cached) {
|
|
1369
|
+
if (cached.transport !== "ws")
|
|
1370
|
+
throw new Error("Native exchange already terminated on HTTP.");
|
|
1371
|
+
host.send(cached.body);
|
|
1372
|
+
return;
|
|
1373
|
+
}
|
|
1374
|
+
let last;
|
|
1375
|
+
for (const id of state.routing.candidates) {
|
|
1376
|
+
if (abort.signal.aborted || binding.call.cancelled)
|
|
1377
|
+
throw new Error("Cancelled.");
|
|
1378
|
+
if (state.limited.has(id) || !this.runtime.available(id))
|
|
1379
|
+
continue;
|
|
1380
|
+
const first = host.data.first;
|
|
1381
|
+
host.data.first = undefined;
|
|
1382
|
+
let socket;
|
|
1383
|
+
if (first?.id === id && first.socket.readyState === WebSocket.OPEN)
|
|
1384
|
+
socket = first.socket;
|
|
1385
|
+
else {
|
|
1386
|
+
first?.socket.close();
|
|
1387
|
+
socket = await this.open(this.target(binding, false, true), await this.dependencies.headers(id, binding.family, host.data.headers, abort.signal), abort.signal);
|
|
1388
|
+
}
|
|
1389
|
+
state.tried.add(id);
|
|
1390
|
+
const result = await this.wsAttempt(socket, host, binding, state, id, frame, abort.signal);
|
|
1391
|
+
if (result.retry) {
|
|
1392
|
+
state.limited.add(id);
|
|
1393
|
+
last = result.retry;
|
|
1394
|
+
continue;
|
|
1395
|
+
}
|
|
1396
|
+
return;
|
|
1397
|
+
}
|
|
1398
|
+
if (!last)
|
|
1399
|
+
throw new Error("No native accounts available.");
|
|
1400
|
+
const final = this.failure(binding, state, { transport: "ws", status: 0, headers: [], body: last });
|
|
1401
|
+
host.send(final.body);
|
|
1402
|
+
} finally {
|
|
1403
|
+
host.data.abort = undefined;
|
|
1404
|
+
exchange.end();
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
wsAttempt(socket, host, binding, state, accountID, frame, signal) {
|
|
1408
|
+
return new Promise((resolve, reject) => {
|
|
1409
|
+
const lifecycle = new ResponseLifecycle;
|
|
1410
|
+
const prefix = [];
|
|
1411
|
+
let size = 0, settled = false;
|
|
1412
|
+
const finish = (value2, error) => {
|
|
1413
|
+
if (settled)
|
|
1414
|
+
return;
|
|
1415
|
+
settled = true;
|
|
1416
|
+
signal.removeEventListener("abort", cancel);
|
|
1417
|
+
socket.onmessage = socket.onerror = socket.onclose = null;
|
|
1418
|
+
socket.close();
|
|
1419
|
+
if (error)
|
|
1420
|
+
reject(error);
|
|
1421
|
+
else
|
|
1422
|
+
resolve(value2);
|
|
1423
|
+
};
|
|
1424
|
+
const cancel = () => finish(undefined, new Error("Cancelled."));
|
|
1425
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
1426
|
+
socket.onerror = () => finish(undefined, new Error("Native WebSocket failed."));
|
|
1427
|
+
socket.onclose = () => finish(undefined, new Error("Truncated native WebSocket response."));
|
|
1428
|
+
socket.onmessage = (message) => {
|
|
1429
|
+
try {
|
|
1430
|
+
if (signal.aborted)
|
|
1431
|
+
throw new Error("Cancelled.");
|
|
1432
|
+
if (typeof message.data !== "string" || message.data.length > maxBody)
|
|
1433
|
+
throw new Error("Invalid native frame.");
|
|
1434
|
+
const raw = message.data;
|
|
1435
|
+
checkDiagnostic(raw);
|
|
1436
|
+
let event;
|
|
1437
|
+
try {
|
|
1438
|
+
event = wireEvent(raw);
|
|
1439
|
+
} catch {
|
|
1440
|
+
host.send(raw);
|
|
1441
|
+
finish({});
|
|
1442
|
+
return;
|
|
1443
|
+
}
|
|
1444
|
+
lifecycle.observe(event);
|
|
1445
|
+
if (wsLimit(event)) {
|
|
1446
|
+
if (!lifecycle.visible) {
|
|
1447
|
+
finish({ retry: raw });
|
|
1448
|
+
return;
|
|
1449
|
+
}
|
|
1450
|
+
const final = this.failure(binding, state, { transport: "ws", status: 0, headers: [], body: raw });
|
|
1451
|
+
host.send(final.body);
|
|
1452
|
+
finish({});
|
|
1453
|
+
return;
|
|
1454
|
+
}
|
|
1455
|
+
if (!lifecycle.visible && !terminal(event)) {
|
|
1456
|
+
size += raw.length;
|
|
1457
|
+
if (size > maxPrefix)
|
|
1458
|
+
throw new Error("Native setup prefix too large.");
|
|
1459
|
+
prefix.push(raw);
|
|
1460
|
+
} else {
|
|
1461
|
+
for (const pending of prefix.splice(0))
|
|
1462
|
+
host.send(pending);
|
|
1463
|
+
if (terminal(event) && lifecycle.success && !signal.aborted && !binding.call.cancelled) {
|
|
1464
|
+
this.runtime.complete(state, accountID);
|
|
1465
|
+
}
|
|
1466
|
+
host.send(raw);
|
|
1467
|
+
}
|
|
1468
|
+
if (terminal(event))
|
|
1469
|
+
finish({ success: lifecycle.success });
|
|
1470
|
+
} catch {
|
|
1471
|
+
finish(undefined, new Error("Invalid native lifecycle."));
|
|
1472
|
+
}
|
|
1473
|
+
};
|
|
1474
|
+
if (signal.aborted) {
|
|
1475
|
+
cancel();
|
|
1476
|
+
return;
|
|
1477
|
+
}
|
|
1478
|
+
binding.call.sentWebSocket = true;
|
|
1479
|
+
socket.send(frame);
|
|
1480
|
+
});
|
|
1481
|
+
}
|
|
1482
|
+
close() {
|
|
1483
|
+
if (this.closed)
|
|
1484
|
+
return;
|
|
1485
|
+
this.closed = true;
|
|
1486
|
+
for (const binding of this.owned.values())
|
|
1487
|
+
this.runtime.cancel(binding.call);
|
|
1488
|
+
for (const socket of this.sockets)
|
|
1489
|
+
socket.close(1001, "Local relay closed");
|
|
1490
|
+
this.owned.clear();
|
|
1491
|
+
this.server.stop(true);
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
// src/persistence.ts
|
|
1496
|
+
function routingStorageKey(location) {
|
|
1497
|
+
return "routing/v1/" + encodeURIComponent(JSON.stringify([location.directory, location.workspaceID ?? null]));
|
|
1498
|
+
}
|
|
1499
|
+
var record2 = (value2) => !!value2 && typeof value2 === "object" && !Array.isArray(value2);
|
|
1500
|
+
var keys = (value2, expected) => Object.keys(value2).length === expected.length && expected.every((key) => Object.hasOwn(value2, key));
|
|
1501
|
+
var id = (value2) => typeof value2 === "string" && value2.length > 0;
|
|
1502
|
+
function decodeRouting(value2) {
|
|
1503
|
+
const invalid = () => {
|
|
1504
|
+
throw new Error("Saved routing state is invalid or has an unsupported version.");
|
|
1505
|
+
};
|
|
1506
|
+
if (!record2(value2) || !keys(value2, ["version", "sessions", "cursor"]) || value2.version !== 1 || !Array.isArray(value2.sessions) || !record2(value2.cursor) || !keys(value2.cursor, ["nextAccountID", "order"]) || !Array.isArray(value2.cursor.order))
|
|
1507
|
+
return invalid();
|
|
1508
|
+
const { cursor, sessions } = value2;
|
|
1509
|
+
const order = cursor.order;
|
|
1510
|
+
if (order.some((entry) => !id(entry)) || new Set(order).size !== order.length || !(cursor.nextAccountID === null || id(cursor.nextAccountID)) || cursor.nextAccountID !== null && !order.includes(cursor.nextAccountID))
|
|
1511
|
+
return invalid();
|
|
1512
|
+
const seen = new Set;
|
|
1513
|
+
for (const row of sessions) {
|
|
1514
|
+
if (!record2(row) || !keys(row, ["sessionID", "accountID", "primary"]) || !id(row.sessionID) || !(row.accountID === null || id(row.accountID)) || !(row.primary === null || typeof row.primary === "boolean") || seen.has(row.sessionID))
|
|
1515
|
+
return invalid();
|
|
1516
|
+
seen.add(row.sessionID);
|
|
1517
|
+
}
|
|
1518
|
+
return structuredClone(value2);
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
class RoutingPersistence {
|
|
1522
|
+
storage;
|
|
1523
|
+
key;
|
|
1524
|
+
tail = Promise.resolve();
|
|
1525
|
+
saved;
|
|
1526
|
+
closed = false;
|
|
1527
|
+
hydrated = false;
|
|
1528
|
+
failed = false;
|
|
1529
|
+
constructor(storage, key) {
|
|
1530
|
+
this.storage = storage;
|
|
1531
|
+
this.key = key;
|
|
1532
|
+
}
|
|
1533
|
+
async hydrate() {
|
|
1534
|
+
if (this.closed || this.hydrated)
|
|
1535
|
+
throw new Error("Routing storage is not available for hydration.");
|
|
1536
|
+
let raw;
|
|
1537
|
+
try {
|
|
1538
|
+
raw = await this.storage.get(this.key);
|
|
1539
|
+
} catch {
|
|
1540
|
+
throw new Error("Saved routing state could not be read.");
|
|
1541
|
+
}
|
|
1542
|
+
if (raw === undefined) {
|
|
1543
|
+
this.hydrated = true;
|
|
1544
|
+
return;
|
|
1545
|
+
}
|
|
1546
|
+
const state = decodeRouting(raw);
|
|
1547
|
+
this.saved = JSON.stringify(state);
|
|
1548
|
+
this.hydrated = true;
|
|
1549
|
+
return state;
|
|
1550
|
+
}
|
|
1551
|
+
save(state) {
|
|
1552
|
+
if (this.closed)
|
|
1553
|
+
return;
|
|
1554
|
+
if (!this.hydrated)
|
|
1555
|
+
throw new Error("Routing storage has not been hydrated.");
|
|
1556
|
+
const text = JSON.stringify(state);
|
|
1557
|
+
if (text === this.saved)
|
|
1558
|
+
return;
|
|
1559
|
+
this.saved = text;
|
|
1560
|
+
const snapshot = structuredClone(state);
|
|
1561
|
+
this.tail = this.tail.then(async () => {
|
|
1562
|
+
try {
|
|
1563
|
+
await this.storage.set(this.key, snapshot);
|
|
1564
|
+
} catch {
|
|
1565
|
+
this.failed = true;
|
|
1566
|
+
}
|
|
1567
|
+
});
|
|
1568
|
+
}
|
|
1569
|
+
async close() {
|
|
1570
|
+
this.closed = true;
|
|
1571
|
+
await this.tail;
|
|
1572
|
+
if (this.failed)
|
|
1573
|
+
throw new Error("Routing state could not be saved.");
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
// src/settings.ts
|
|
1578
|
+
var settingsStorageKey = (location) => routingStorageKey(location).replace(/^routing\/v1\//, "settings/v1/");
|
|
1579
|
+
|
|
1580
|
+
class SettingsPersistence {
|
|
1581
|
+
storage;
|
|
1582
|
+
key;
|
|
1583
|
+
hydrated = false;
|
|
1584
|
+
closed = false;
|
|
1585
|
+
desired = true;
|
|
1586
|
+
failed = false;
|
|
1587
|
+
tail = Promise.resolve();
|
|
1588
|
+
lastWrite = Promise.resolve();
|
|
1589
|
+
constructor(storage, key) {
|
|
1590
|
+
this.storage = storage;
|
|
1591
|
+
this.key = key;
|
|
1592
|
+
}
|
|
1593
|
+
async hydrate() {
|
|
1594
|
+
if (this.closed || this.hydrated)
|
|
1595
|
+
throw new Error("Routing settings are not available for hydration.");
|
|
1596
|
+
let raw;
|
|
1597
|
+
try {
|
|
1598
|
+
raw = await this.storage.get(this.key);
|
|
1599
|
+
} catch {
|
|
1600
|
+
throw new Error("Routing settings could not be read.");
|
|
1601
|
+
}
|
|
1602
|
+
if (raw !== undefined) {
|
|
1603
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(raw).length !== 2 || !("version" in raw) || raw.version !== 1 || !("enabled" in raw) || typeof raw.enabled !== "boolean") {
|
|
1604
|
+
throw new Error("Saved routing settings are invalid or have an unsupported version.");
|
|
1605
|
+
}
|
|
1606
|
+
this.desired = raw.enabled;
|
|
1607
|
+
}
|
|
1608
|
+
this.hydrated = true;
|
|
1609
|
+
return this.desired;
|
|
1610
|
+
}
|
|
1611
|
+
save(enabled) {
|
|
1612
|
+
if (this.closed)
|
|
1613
|
+
return Promise.reject(new Error("Routing settings are closed."));
|
|
1614
|
+
if (!this.hydrated)
|
|
1615
|
+
return Promise.reject(new Error("Routing settings have not been hydrated."));
|
|
1616
|
+
if (enabled === this.desired)
|
|
1617
|
+
return this.lastWrite;
|
|
1618
|
+
this.desired = enabled;
|
|
1619
|
+
const write = this.tail.then(async () => {
|
|
1620
|
+
try {
|
|
1621
|
+
await this.storage.set(this.key, { version: 1, enabled });
|
|
1622
|
+
this.failed = false;
|
|
1623
|
+
} catch {
|
|
1624
|
+
this.failed = true;
|
|
1625
|
+
throw new Error("Routing settings could not be saved.");
|
|
1626
|
+
}
|
|
1627
|
+
});
|
|
1628
|
+
this.lastWrite = write;
|
|
1629
|
+
this.tail = write.catch(() => {});
|
|
1630
|
+
return write;
|
|
1631
|
+
}
|
|
1632
|
+
async close() {
|
|
1633
|
+
this.closed = true;
|
|
1634
|
+
await this.tail;
|
|
1635
|
+
if (this.failed)
|
|
1636
|
+
throw new Error("Routing settings could not be saved.");
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
// src/index.ts
|
|
1641
|
+
var NATIVE_PACKAGES = new Set([
|
|
1642
|
+
"@opencode/ai/providers/openai",
|
|
1643
|
+
"@opencode/ai/providers/openai/responses"
|
|
1644
|
+
]);
|
|
1645
|
+
function privateHeaders(input) {
|
|
1646
|
+
const headers = new Headers(input);
|
|
1647
|
+
for (const key of [...headers.keys()])
|
|
1648
|
+
if (key.startsWith("x-opencode-local-"))
|
|
1649
|
+
headers.delete(key);
|
|
1650
|
+
return headers;
|
|
1651
|
+
}
|
|
1652
|
+
function withHeaders(request, headers) {
|
|
1653
|
+
const copy = new Request(request);
|
|
1654
|
+
for (const key of [...copy.headers.keys()])
|
|
1655
|
+
copy.headers.delete(key);
|
|
1656
|
+
for (const [key, value2] of headers)
|
|
1657
|
+
copy.headers.set(key, value2);
|
|
1658
|
+
return copy;
|
|
1659
|
+
}
|
|
1660
|
+
var src_default = Plugin.define({
|
|
1661
|
+
id: "opencode-openai-session-router",
|
|
1662
|
+
effect: (context) => Effect2.gen(function* () {
|
|
1663
|
+
let runtime, accounts, relay;
|
|
1664
|
+
let closed = false;
|
|
1665
|
+
let unsubscribe = () => {};
|
|
1666
|
+
let unsubscribeDurable = () => {};
|
|
1667
|
+
let persistence;
|
|
1668
|
+
let settings;
|
|
1669
|
+
let emitTail = Promise.resolve();
|
|
1670
|
+
const close = async () => {
|
|
1671
|
+
if (closed)
|
|
1672
|
+
return;
|
|
1673
|
+
closed = true;
|
|
1674
|
+
unsubscribe();
|
|
1675
|
+
unsubscribeDurable();
|
|
1676
|
+
accounts?.stop();
|
|
1677
|
+
runtime?.stop();
|
|
1678
|
+
try {
|
|
1679
|
+
const drained = await Promise.allSettled([persistence?.close(), settings?.close()]);
|
|
1680
|
+
const failure = drained.find((result) => result.status === "rejected");
|
|
1681
|
+
if (failure?.status === "rejected")
|
|
1682
|
+
throw failure.reason;
|
|
1683
|
+
} finally {
|
|
1684
|
+
accounts?.dispose();
|
|
1685
|
+
relay?.close();
|
|
1686
|
+
runtime?.dispose();
|
|
1687
|
+
await emitTail;
|
|
1688
|
+
}
|
|
1689
|
+
};
|
|
1690
|
+
yield* Effect2.addFinalizer(() => Effect2.promise(close));
|
|
1691
|
+
const captured = yield* Effect2.context();
|
|
1692
|
+
const run = Effect2.runPromiseWith(captured);
|
|
1693
|
+
const store = runtime = new RouterRuntime;
|
|
1694
|
+
const pool = accounts = new NativeAccounts({
|
|
1695
|
+
active: (signal) => run(context.integration.connection.active("openai"), { signal }),
|
|
1696
|
+
connections: (signal) => run(context.integration.get({ integrationID: Integration.ID.make("openai") }), { signal }).then(({ data }) => data.connections),
|
|
1697
|
+
resolve: (connection, signal) => run(context.integration.connection.resolve(connection), { signal })
|
|
1698
|
+
}, store);
|
|
1699
|
+
persistence = new RoutingPersistence({
|
|
1700
|
+
get: (key) => run(context.storage.get(key)),
|
|
1701
|
+
set: (key, value2) => run(context.storage.set(key, JSON.parse(JSON.stringify(value2))))
|
|
1702
|
+
}, routingStorageKey(context.location));
|
|
1703
|
+
const restored = yield* Effect2.promise(() => persistence.hydrate());
|
|
1704
|
+
if (restored)
|
|
1705
|
+
store.restore(restored);
|
|
1706
|
+
settings = new SettingsPersistence({
|
|
1707
|
+
get: (key) => run(context.storage.get(key)),
|
|
1708
|
+
set: (key, value2) => run(context.storage.set(key, { version: value2.version, enabled: value2.enabled }))
|
|
1709
|
+
}, settingsStorageKey(context.location));
|
|
1710
|
+
store.setEnabled(yield* Effect2.promise(() => settings.hydrate()));
|
|
1711
|
+
yield* Effect2.promise((signal) => pool.refreshMetadata(signal));
|
|
1712
|
+
unsubscribeDurable = store.subscribeDurable((state) => persistence.save(state));
|
|
1713
|
+
const transport = relay = new SessionRelay(store, pool);
|
|
1714
|
+
const rpc = yield* context.rpc.register(RouterRpc, {
|
|
1715
|
+
snapshot: () => Effect2.sync(() => store.snapshot()),
|
|
1716
|
+
setEnabled: ({ enabled }) => Effect2.promise(async () => {
|
|
1717
|
+
if (closed)
|
|
1718
|
+
throw new Error("Routing runtime is closed.");
|
|
1719
|
+
store.setEnabled(enabled);
|
|
1720
|
+
await settings.save(enabled);
|
|
1721
|
+
return store.snapshot();
|
|
1722
|
+
})
|
|
1723
|
+
}).pipe(Effect2.orDie);
|
|
1724
|
+
unsubscribe = store.subscribe((snapshot) => {
|
|
1725
|
+
emitTail = emitTail.then(() => run(rpc.events.emit("changed", snapshot))).catch(() => {});
|
|
1726
|
+
});
|
|
1727
|
+
yield* context.session.hook("model.request", (request) => Effect2.promise(async (signal) => {
|
|
1728
|
+
if (closed || signal.aborted || !store.enabled)
|
|
1729
|
+
return;
|
|
1730
|
+
let eligible = false;
|
|
1731
|
+
if (request.model.providerID === "openai") {
|
|
1732
|
+
const [provider, models] = await Promise.all([
|
|
1733
|
+
run(context.provider.get({ providerID: Provider.ID.make("openai") }), { signal }),
|
|
1734
|
+
run(context.model.list(), { signal })
|
|
1735
|
+
]);
|
|
1736
|
+
const model = models.data.find((item) => item.providerID === request.model.providerID && item.id === request.model.id);
|
|
1737
|
+
eligible = !!model && (model.type === undefined || model.type === "chat") && provider.data.integrationID === "openai" && NATIVE_PACKAGES.has(model.package ?? provider.data.package ?? "");
|
|
1738
|
+
const configuredNative = request.baseURL ?? model?.settings?.baseURL ?? provider.data.settings?.baseURL;
|
|
1739
|
+
if (configuredNative !== undefined && (typeof configuredNative !== "string" || ![nativeBase("codex"), nativeBase("token-sharing")].includes(configuredNative.replace(/\/$/, ""))))
|
|
1740
|
+
eligible = false;
|
|
1741
|
+
if (eligible) {
|
|
1742
|
+
if (closed || signal.aborted || !store.enabled)
|
|
1743
|
+
return;
|
|
1744
|
+
const selected = await pool.pool(signal);
|
|
1745
|
+
const configured = configuredNative ?? (selected && nativeBase(selected));
|
|
1746
|
+
if (!selected || typeof configured !== "string" || configured.replace(/\/$/, "") !== nativeBase(selected))
|
|
1747
|
+
eligible = false;
|
|
1748
|
+
else {
|
|
1749
|
+
if (signal.aborted || closed || !store.enabled)
|
|
1750
|
+
return;
|
|
1751
|
+
const call = store.begin(request.sessionID, request.kind, request.model);
|
|
1752
|
+
request.baseURL = transport.bind(call, selected);
|
|
1753
|
+
request.headers = Object.fromEntries(transport.localHeaders(new Headers(request.headers)));
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
if (signal.aborted || closed || !store.enabled)
|
|
1758
|
+
return;
|
|
1759
|
+
if (!eligible)
|
|
1760
|
+
request.headers = Object.fromEntries(privateHeaders(new Headers(request.headers)));
|
|
1761
|
+
if (request.kind === "primary")
|
|
1762
|
+
store.setPrimaryProvider(request.sessionID, eligible);
|
|
1763
|
+
}));
|
|
1764
|
+
yield* context.session.hook("http.request", (event) => Effect2.promise(async (signal) => {
|
|
1765
|
+
const url = new URL(event.request.url);
|
|
1766
|
+
const binding = transport.binding(event.request.url, event.sessionID, event.model, event.kind);
|
|
1767
|
+
if (url.origin === transport.origin && !binding)
|
|
1768
|
+
throw new Error("Local routing state expired or transport context mismatch.");
|
|
1769
|
+
const headers = binding ? transport.localHeaders(event.request.headers) : privateHeaders(event.request.headers);
|
|
1770
|
+
if (!binding && event.request.headers.has(LOCAL_AUTH)) {
|
|
1771
|
+
headers.delete("authorization");
|
|
1772
|
+
headers.delete("chatgpt-account-id");
|
|
1773
|
+
event.request = withHeaders(event.request, headers);
|
|
1774
|
+
throw new Error("Managed native destination changed before transport.");
|
|
1775
|
+
}
|
|
1776
|
+
event.request = withHeaders(event.request, headers);
|
|
1777
|
+
if (!binding)
|
|
1778
|
+
return;
|
|
1779
|
+
const response = await transport.respondHTTP(event.request, signal);
|
|
1780
|
+
if (signal.aborted) {
|
|
1781
|
+
await response.body?.cancel().catch(() => {});
|
|
1782
|
+
return;
|
|
1783
|
+
}
|
|
1784
|
+
return response;
|
|
1785
|
+
}).pipe(Effect2.map((response) => {
|
|
1786
|
+
if (response)
|
|
1787
|
+
event.response = response;
|
|
1788
|
+
})));
|
|
1789
|
+
yield* context.session.hook("experimental.ws.handshake", (event) => Effect2.sync(() => {
|
|
1790
|
+
const origin = new URL(event.url).origin.replace(/^ws:/, "http:");
|
|
1791
|
+
const binding = transport.binding(event.url, event.sessionID, event.model, event.kind);
|
|
1792
|
+
if (origin === transport.origin && !binding)
|
|
1793
|
+
throw new Error("Local routing state expired or WebSocket context mismatch.");
|
|
1794
|
+
const original = new Headers(event.headers);
|
|
1795
|
+
if (!binding) {
|
|
1796
|
+
event.headers = Object.fromEntries(privateHeaders(original));
|
|
1797
|
+
if (original.has(LOCAL_AUTH))
|
|
1798
|
+
throw new Error("Managed native WebSocket destination changed.");
|
|
1799
|
+
return;
|
|
1800
|
+
}
|
|
1801
|
+
const headers = transport.localHeaders(original);
|
|
1802
|
+
headers.set("x-opencode-local-affinity", randomBytes3(24).toString("hex"));
|
|
1803
|
+
event.headers = Object.fromEntries(headers);
|
|
1804
|
+
}));
|
|
1805
|
+
yield* context.session.hook("retry", (retry) => Effect2.sync(() => {
|
|
1806
|
+
if (store.retryControl.verify(retry))
|
|
1807
|
+
retry.decision = { retry: false };
|
|
1808
|
+
}));
|
|
1809
|
+
yield* context.event.subscribe({
|
|
1810
|
+
types: [
|
|
1811
|
+
"credential.updated",
|
|
1812
|
+
"credential.switched",
|
|
1813
|
+
"integration.updated",
|
|
1814
|
+
"session.deleted",
|
|
1815
|
+
"session.execution.succeeded",
|
|
1816
|
+
"session.execution.failed",
|
|
1817
|
+
"session.execution.interrupted"
|
|
1818
|
+
]
|
|
1819
|
+
}).pipe(Stream.runForEach((event) => Effect2.promise(async (signal) => {
|
|
1820
|
+
if (closed)
|
|
1821
|
+
return;
|
|
1822
|
+
if (event.type === "credential.updated" || event.type === "credential.switched" || event.type === "integration.updated") {
|
|
1823
|
+
if ("integrationID" in event.data && event.data.integrationID !== "openai")
|
|
1824
|
+
return;
|
|
1825
|
+
pool.invalidate();
|
|
1826
|
+
await pool.refreshMetadata(signal);
|
|
1827
|
+
return;
|
|
1828
|
+
}
|
|
1829
|
+
if (event.type === "session.deleted")
|
|
1830
|
+
store.removeSession(event.data.sessionID);
|
|
1831
|
+
else if ("sessionID" in event.data && typeof event.data.sessionID === "string") {
|
|
1832
|
+
if (event.type === "session.execution.interrupted")
|
|
1833
|
+
store.cancelPrimary(event.data.sessionID);
|
|
1834
|
+
store.releaseSessionCalls(event.data.sessionID, true);
|
|
1835
|
+
}
|
|
1836
|
+
}).pipe(Effect2.catchCause(() => Effect2.void))), Effect2.catchCause(() => Effect2.void), Effect2.forkScoped);
|
|
1837
|
+
yield* Effect2.addFinalizer(() => Effect2.promise(close));
|
|
1838
|
+
})
|
|
1839
|
+
});
|
|
1840
|
+
export {
|
|
1841
|
+
src_default as default
|
|
1842
|
+
};
|