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/tui.d.ts
ADDED
package/dist/tui.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
SessionSidebar
|
|
4
|
+
} from "./chunks/index-n7sr1hee.js";
|
|
5
|
+
import"./chunks/index-85yd61pa.js";
|
|
6
|
+
|
|
7
|
+
// src/tui.tsx
|
|
8
|
+
import { createComponent as _$createComponent } from "@opentui/solid";
|
|
9
|
+
import { Plugin } from "@opencode/plugin/tui";
|
|
10
|
+
var tui_default = Plugin.define({
|
|
11
|
+
id: "opencode-openai-session-router",
|
|
12
|
+
setup(ctx) {
|
|
13
|
+
return ctx.ui.slot({
|
|
14
|
+
append: "sidebar.content",
|
|
15
|
+
render: ({
|
|
16
|
+
sessionID
|
|
17
|
+
}) => _$createComponent(SessionSidebar, {
|
|
18
|
+
sessionID
|
|
19
|
+
})
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
export {
|
|
24
|
+
tui_default as default
|
|
25
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-openai-session-router",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Session-scoped routing across native OpenCode OpenAI accounts.",
|
|
6
|
+
"license": "GPL-3.0-only",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/iiNothh/opencode-openai-session-router.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/iiNothh/opencode-openai-session-router#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/iiNothh/opencode-openai-session-router/issues"
|
|
14
|
+
},
|
|
15
|
+
"packageManager": "bun@1.3.14",
|
|
16
|
+
"engines": { "bun": ">=1.3.14" },
|
|
17
|
+
"publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" },
|
|
18
|
+
"exports": {
|
|
19
|
+
".": "./src/index.ts",
|
|
20
|
+
"./tui": "./src/tui.tsx",
|
|
21
|
+
"./rpc": "./src/rpc.ts"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"src", "dist", "README.md", "LICENSE",
|
|
25
|
+
"scripts/build.ts", "tsconfig.json", "tsconfig.build.json"
|
|
26
|
+
],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"test": "bun test --preload @opentui/solid/preload --conditions=browser",
|
|
29
|
+
"typecheck": "tsc --noEmit",
|
|
30
|
+
"build": "bun scripts/build.ts",
|
|
31
|
+
"prepack": "bun run build",
|
|
32
|
+
"verify:package": "bun --preload @opentui/solid/preload --conditions=browser scripts/verify-package.ts",
|
|
33
|
+
"test:packaging": "bun test test/packaging.test.ts"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@opencode/ai": "2.4.4",
|
|
37
|
+
"@opencode/plugin": "2.4.4",
|
|
38
|
+
"@opencode/protocol": "2.4.4",
|
|
39
|
+
"@opencode/schema": "2.4.4",
|
|
40
|
+
"effect": "4.1.0"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@types/bun": "1.4.5",
|
|
44
|
+
"@opentui/core": "0.9.12",
|
|
45
|
+
"@opentui/solid": "0.9.12",
|
|
46
|
+
"solid-js": "1.9.17",
|
|
47
|
+
"typescript": "5.9.3"
|
|
48
|
+
},
|
|
49
|
+
"peerDependencies": {
|
|
50
|
+
"@opentui/core": ">=0.8.0",
|
|
51
|
+
"@opentui/solid": ">=0.8.0",
|
|
52
|
+
"solid-js": ">=1.9.0"
|
|
53
|
+
}
|
|
54
|
+
}
|
package/scripts/build.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { createSolidTransformPlugin } from "@opentui/solid/bun-plugin";
|
|
2
|
+
import { copyFile, lstat, rm } from "node:fs/promises";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
|
|
6
|
+
const root = fileURLToPath(new URL("../", import.meta.url));
|
|
7
|
+
const outdir = join(root, "dist");
|
|
8
|
+
// Sidebar is an internal compiled entry used by the artifact's reactive-render
|
|
9
|
+
// check, not an additional public package export.
|
|
10
|
+
const entrypoints = ["index.ts", "tui.tsx", "rpc.ts", "sidebar.tsx"].map((name) => join(root, "src", name));
|
|
11
|
+
if (process.argv.includes("--dry-run")) {
|
|
12
|
+
console.log(JSON.stringify({ generatedDirectory: outdir, entrypoints, packages: "external", solidCompiler: true }));
|
|
13
|
+
} else {
|
|
14
|
+
const previous = await lstat(outdir).catch((error: NodeJS.ErrnoException) => {
|
|
15
|
+
if (error.code !== "ENOENT") throw error;
|
|
16
|
+
});
|
|
17
|
+
if (previous && (!previous.isDirectory() || previous.isSymbolicLink())) {
|
|
18
|
+
throw new Error("Refusing to replace a non-directory or linked dist target.");
|
|
19
|
+
}
|
|
20
|
+
// Only the fixed generated child directory above can be removed.
|
|
21
|
+
await rm(outdir, { recursive: true, force: true });
|
|
22
|
+
const result = await Bun.build({
|
|
23
|
+
entrypoints, root: join(root, "src"), outdir,
|
|
24
|
+
target: "bun", format: "esm", packages: "external", splitting: true,
|
|
25
|
+
naming: { entry: "[dir]/[name].[ext]", chunk: "chunks/[name]-[hash].[ext]" },
|
|
26
|
+
sourcemap: "none", minify: false,
|
|
27
|
+
plugins: [createSolidTransformPlugin()],
|
|
28
|
+
});
|
|
29
|
+
if (!result.success) throw new AggregateError(result.logs, "Distribution build failed.");
|
|
30
|
+
// npm always excludes bun.lock, even an explicit files entry. Ship an exact
|
|
31
|
+
// Corresponding Source copy under a non-reserved name; restore to bun.lock
|
|
32
|
+
// before installing dependencies when reproducing a build from the tarball.
|
|
33
|
+
await copyFile(join(root, "bun.lock"), join(outdir, "bun.lock.txt"));
|
|
34
|
+
const declarations = Bun.spawn([process.execPath, join(root, "node_modules/typescript/bin/tsc"), "-p", "tsconfig.build.json"], {
|
|
35
|
+
cwd: root, stdout: "inherit", stderr: "inherit",
|
|
36
|
+
});
|
|
37
|
+
if (await declarations.exited !== 0) throw new Error("Declaration build failed.");
|
|
38
|
+
console.log(`Built ${result.outputs.length} externalized JS outputs and source declarations.`);
|
|
39
|
+
}
|
package/src/accounts.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import type { ConnectionInfo } from "@opencode/client";
|
|
2
|
+
import type { Credential } from "@opencode/schema/credential";
|
|
3
|
+
import type { RouterRuntime } from "./runtime";
|
|
4
|
+
|
|
5
|
+
export type OAuthFamily = "codex" | "token-sharing";
|
|
6
|
+
export function family(methodID: string): OAuthFamily | undefined {
|
|
7
|
+
if (methodID === "chatgpt-browser" || methodID === "chatgpt-headless") return "codex";
|
|
8
|
+
if (methodID === "chatgpt-token-sharing") return "token-sharing";
|
|
9
|
+
}
|
|
10
|
+
export const nativeBase = (value: OAuthFamily) =>
|
|
11
|
+
value === "codex" ? "https://chatgpt.com/backend-api/codex" : "https://api.openai.com/v1";
|
|
12
|
+
export interface NativeAccountPort {
|
|
13
|
+
active(signal?: AbortSignal): Promise<ConnectionInfo | undefined>;
|
|
14
|
+
connections(signal?: AbortSignal): Promise<readonly ConnectionInfo[]>;
|
|
15
|
+
resolve(connection: ConnectionInfo, signal?: AbortSignal): Promise<Credential.Value | undefined>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// v2.4.4 dialog-integration.tsx manageConnections: Connected accounts are
|
|
19
|
+
// label/id sorted, whereas integration.connections is active-first priority.
|
|
20
|
+
// filter() creates a copy: never reorder the native resolver's input array.
|
|
21
|
+
const nativeMenu = (connections: readonly ConnectionInfo[]) =>
|
|
22
|
+
connections.filter((connection) => connection.type === "credential")
|
|
23
|
+
.sort((a, b) => a.label.localeCompare(b.label) || a.id.localeCompare(b.id));
|
|
24
|
+
|
|
25
|
+
/** Only identity/family metadata is retained; native resolution owns refresh. */
|
|
26
|
+
export class NativeAccounts {
|
|
27
|
+
private connections = new Map<string, ConnectionInfo>();
|
|
28
|
+
private families = new Map<string, OAuthFamily | undefined>();
|
|
29
|
+
private tail: Promise<unknown> = Promise.resolve();
|
|
30
|
+
private closed = false;
|
|
31
|
+
constructor(private readonly port: NativeAccountPort, private readonly runtime: RouterRuntime) {}
|
|
32
|
+
invalidate(): void { this.families.clear(); }
|
|
33
|
+
|
|
34
|
+
/** Startup/idle display uses connection metadata, never OAuth resolution. */
|
|
35
|
+
refreshMetadata(signal?: AbortSignal): Promise<void> {
|
|
36
|
+
const next = this.tail.then(async () => {
|
|
37
|
+
if (this.closed || signal?.aborted) return;
|
|
38
|
+
const connections = await this.port.connections(signal);
|
|
39
|
+
if (this.closed || signal?.aborted) return;
|
|
40
|
+
const native = nativeMenu(connections);
|
|
41
|
+
const ids = new Set(native.map(({ id }) => id));
|
|
42
|
+
for (const id of this.families.keys()) if (!ids.has(id)) this.families.delete(id);
|
|
43
|
+
// Do not insert unclassified entries or expose an incremental lookup.
|
|
44
|
+
this.connections = new Map([...this.connections].filter(([id]) => ids.has(id)));
|
|
45
|
+
this.runtime.setNativeOrder(native.map(({ id }, index) => ({ id, index })));
|
|
46
|
+
});
|
|
47
|
+
this.tail = next.catch(() => {});
|
|
48
|
+
return next;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
pool(signal?: AbortSignal): Promise<OAuthFamily | undefined> {
|
|
52
|
+
const next = this.tail.then(async () => {
|
|
53
|
+
if (this.closed || signal?.aborted) return;
|
|
54
|
+
const active = await this.port.active(signal);
|
|
55
|
+
if (this.closed || signal?.aborted) return;
|
|
56
|
+
if (active?.type !== "credential" || active.method !== "oauth" || active.status) return;
|
|
57
|
+
const credential = await this.port.resolve(active, signal);
|
|
58
|
+
if (this.closed || signal?.aborted) return;
|
|
59
|
+
if (credential?.type !== "oauth") return;
|
|
60
|
+
const selected = family(credential.methodID);
|
|
61
|
+
if (!selected) return;
|
|
62
|
+
this.families.set(active.id, selected);
|
|
63
|
+
const connections = await this.port.connections(signal);
|
|
64
|
+
if (this.closed || signal?.aborted) return;
|
|
65
|
+
const native = nativeMenu(connections);
|
|
66
|
+
const identities = new Set(native.map(({ id }) => id));
|
|
67
|
+
for (const id of this.families.keys()) if (!identities.has(id)) this.families.delete(id);
|
|
68
|
+
const available: { id: string; index: number }[] = [];
|
|
69
|
+
// Classification awaits native refresh. Existing exchanges must keep the
|
|
70
|
+
// last COMPLETE published lookup throughout those awaits (and on abort).
|
|
71
|
+
const nextConnections = new Map<string, ConnectionInfo>();
|
|
72
|
+
for (const [index, connection] of native.entries()) {
|
|
73
|
+
if (this.closed || signal?.aborted) return;
|
|
74
|
+
if (connection.method !== "oauth" || connection.status) continue;
|
|
75
|
+
nextConnections.set(connection.id, connection);
|
|
76
|
+
if (!this.families.has(connection.id)) {
|
|
77
|
+
try {
|
|
78
|
+
const resolved = connection.id === active.id ? credential :
|
|
79
|
+
await this.port.resolve(connection, signal);
|
|
80
|
+
this.families.set(connection.id, resolved?.type === "oauth" ? family(resolved.methodID) : undefined);
|
|
81
|
+
} catch { continue; }
|
|
82
|
+
}
|
|
83
|
+
if (this.families.get(connection.id) === selected) available.push({ id: connection.id, index });
|
|
84
|
+
}
|
|
85
|
+
if (this.closed || signal?.aborted) return;
|
|
86
|
+
// No await between the corresponding lookup/pool publication. Install the
|
|
87
|
+
// lookup first so synchronous runtime snapshot observers see the same set.
|
|
88
|
+
this.connections = nextConnections;
|
|
89
|
+
this.runtime.setAccounts(available, native.map(({ id }, index) => ({ id, index })));
|
|
90
|
+
return selected;
|
|
91
|
+
});
|
|
92
|
+
this.tail = next.catch(() => {});
|
|
93
|
+
return next;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async headers(id: string, selected: OAuthFamily, source: Headers, signal?: AbortSignal): Promise<Headers> {
|
|
97
|
+
if (this.closed || signal?.aborted) throw new Error("Native account resolver closed or cancelled.");
|
|
98
|
+
const connection = this.connections.get(id);
|
|
99
|
+
if (!connection) throw new Error("Native account no longer available.");
|
|
100
|
+
const credential = await this.port.resolve(connection, signal);
|
|
101
|
+
if (this.closed || signal?.aborted) throw new Error("Native account resolver closed or cancelled.");
|
|
102
|
+
if (credential?.type !== "oauth" || family(credential.methodID) !== selected) {
|
|
103
|
+
throw new Error("Native account is no longer compatible.");
|
|
104
|
+
}
|
|
105
|
+
const headers = upstreamHeaders(source);
|
|
106
|
+
headers.set("authorization", `Bearer ${credential.access}`);
|
|
107
|
+
if (selected === "codex" && typeof credential.metadata?.accountID === "string") {
|
|
108
|
+
headers.set("chatgpt-account-id", credential.metadata.accountID);
|
|
109
|
+
}
|
|
110
|
+
return headers;
|
|
111
|
+
}
|
|
112
|
+
stop(): void { this.closed = true; }
|
|
113
|
+
dispose(): void { this.stop(); this.connections.clear(); this.families.clear(); }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export const LOCAL_AUTH = "x-opencode-local-router-auth";
|
|
117
|
+
/** Native nonsensitive headers/encoding survive; credentials and hop headers do not. */
|
|
118
|
+
export function upstreamHeaders(source: Headers): Headers {
|
|
119
|
+
const headers = new Headers(source);
|
|
120
|
+
const connectionFields = new Set((headers.get("connection") ?? "").toLowerCase().split(",").map((value) => value.trim()));
|
|
121
|
+
for (const key of [...headers.keys()]) {
|
|
122
|
+
if (key.startsWith("x-opencode-local-") || key === "authorization" || key === "proxy-authorization" ||
|
|
123
|
+
key === "chatgpt-account-id" || key === "cookie" || key === "x-api-key" || key === "api-key" || key === "host" || key === "origin" ||
|
|
124
|
+
key === "connection" || key === "upgrade" || key === "content-length" ||
|
|
125
|
+
key.startsWith("sec-websocket-") || key === "transfer-encoding" || key === "proxy-connection" ||
|
|
126
|
+
key === "forwarded" || key.startsWith("x-forwarded-") || key === "x-real-ip" ||
|
|
127
|
+
key === "te" || key === "trailer" || connectionFields.has(key)) headers.delete(key);
|
|
128
|
+
}
|
|
129
|
+
return headers;
|
|
130
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { Plugin, Integration, Provider } from "@opencode/plugin/effect";
|
|
2
|
+
import { Effect, Stream, type Scope } from "effect";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { LOCAL_AUTH, NativeAccounts, nativeBase } from "./accounts";
|
|
5
|
+
import { RouterRuntime } from "./runtime";
|
|
6
|
+
import { RouterRpc } from "./rpc";
|
|
7
|
+
import { SessionRelay } from "./relay";
|
|
8
|
+
import { RoutingPersistence, routingStorageKey } from "./persistence";
|
|
9
|
+
import { SettingsPersistence, settingsStorageKey } from "./settings";
|
|
10
|
+
|
|
11
|
+
// The public Responses entrypoint re-exports the native root model factory.
|
|
12
|
+
// Exact identities only: compatible/custom routes must not enter OAuth routing.
|
|
13
|
+
const NATIVE_PACKAGES = new Set([
|
|
14
|
+
"@opencode/ai/providers/openai",
|
|
15
|
+
"@opencode/ai/providers/openai/responses",
|
|
16
|
+
]);
|
|
17
|
+
function privateHeaders(input: Headers): Headers {
|
|
18
|
+
const headers = new Headers(input);
|
|
19
|
+
for (const key of [...headers.keys()]) if (key.startsWith("x-opencode-local-")) headers.delete(key);
|
|
20
|
+
return headers;
|
|
21
|
+
}
|
|
22
|
+
function withHeaders(request: Request, headers: Headers): Request {
|
|
23
|
+
const copy = new Request(request);
|
|
24
|
+
// Empty Headers in Bun's Request(input,{headers}) can inherit source headers.
|
|
25
|
+
for (const key of [...copy.headers.keys()]) copy.headers.delete(key);
|
|
26
|
+
for (const [key, value] of headers) copy.headers.set(key, value);
|
|
27
|
+
return copy;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export default Plugin.define({
|
|
31
|
+
id: "opencode-openai-session-router",
|
|
32
|
+
effect: (context) => Effect.gen(function* () {
|
|
33
|
+
let runtime: RouterRuntime | undefined, accounts: NativeAccounts | undefined, relay: SessionRelay | undefined;
|
|
34
|
+
let closed = false;
|
|
35
|
+
let unsubscribe = () => {};
|
|
36
|
+
let unsubscribeDurable = () => {};
|
|
37
|
+
let persistence: RoutingPersistence | undefined;
|
|
38
|
+
let settings: SettingsPersistence | undefined;
|
|
39
|
+
let emitTail = Promise.resolve();
|
|
40
|
+
const close = async () => {
|
|
41
|
+
if (closed) return;
|
|
42
|
+
closed = true; // stop admission before cancellation/cleanup
|
|
43
|
+
unsubscribe();
|
|
44
|
+
unsubscribeDurable();
|
|
45
|
+
accounts?.stop();
|
|
46
|
+
runtime?.stop();
|
|
47
|
+
// Public loader awaits this finalizer before the replacement hydrates.
|
|
48
|
+
// Drain desired saved state BEFORE clearing any live runtime values.
|
|
49
|
+
try {
|
|
50
|
+
// Drain both independent documents even if either storage write failed.
|
|
51
|
+
const drained = await Promise.allSettled([persistence?.close(), settings?.close()]);
|
|
52
|
+
const failure = drained.find((result) => result.status === "rejected");
|
|
53
|
+
if (failure?.status === "rejected") throw failure.reason;
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
accounts?.dispose();
|
|
57
|
+
relay?.close();
|
|
58
|
+
runtime?.dispose();
|
|
59
|
+
await emitTail;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
// Partial initialization safe; native registrations also belong to this scope.
|
|
63
|
+
yield* Effect.addFinalizer(() => Effect.promise(close));
|
|
64
|
+
const captured = yield* Effect.context<Scope.Scope>();
|
|
65
|
+
const run = Effect.runPromiseWith(captured);
|
|
66
|
+
const store = runtime = new RouterRuntime();
|
|
67
|
+
const pool = accounts = new NativeAccounts({
|
|
68
|
+
active: (signal) => run(context.integration.connection.active("openai"), { signal }),
|
|
69
|
+
connections: (signal) => run(context.integration.get({ integrationID: Integration.ID.make("openai") }), { signal }).then(({ data }) => data.connections),
|
|
70
|
+
resolve: (connection, signal) => run(context.integration.connection.resolve(connection), { signal }),
|
|
71
|
+
}, store);
|
|
72
|
+
persistence = new RoutingPersistence({
|
|
73
|
+
get: (key) => run(context.storage.get(key)),
|
|
74
|
+
set: (key, value) => run(context.storage.set(key, JSON.parse(JSON.stringify(value)))),
|
|
75
|
+
}, routingStorageKey(context.location));
|
|
76
|
+
const restored = yield* Effect.promise(() => persistence!.hydrate());
|
|
77
|
+
if (restored) store.restore(restored);
|
|
78
|
+
settings = new SettingsPersistence({
|
|
79
|
+
get: (key) => run(context.storage.get(key)),
|
|
80
|
+
set: (key, value) => run(context.storage.set(key, { version: value.version, enabled: value.enabled })),
|
|
81
|
+
}, settingsStorageKey(context.location));
|
|
82
|
+
store.setEnabled(yield* Effect.promise(() => settings!.hydrate()));
|
|
83
|
+
// Metadata-only, before RPC/hooks: completed children display restored IDs
|
|
84
|
+
// projected onto today's FULL native credential order without model traffic.
|
|
85
|
+
yield* Effect.promise((signal) => pool.refreshMetadata(signal));
|
|
86
|
+
unsubscribeDurable = store.subscribeDurable((state) => persistence!.save(state));
|
|
87
|
+
const transport = relay = new SessionRelay(store, pool);
|
|
88
|
+
const rpc = yield* context.rpc.register(RouterRpc, {
|
|
89
|
+
snapshot: () => Effect.sync(() => store.snapshot()),
|
|
90
|
+
setEnabled: ({ enabled }) => Effect.promise(async () => {
|
|
91
|
+
if (closed) throw new Error("Routing runtime is closed.");
|
|
92
|
+
store.setEnabled(enabled); // desired policy applies before any storage await
|
|
93
|
+
await settings!.save(enabled);
|
|
94
|
+
return store.snapshot(); // current authoritative full state, including concurrent changes
|
|
95
|
+
}),
|
|
96
|
+
}).pipe(Effect.orDie);
|
|
97
|
+
unsubscribe = store.subscribe((snapshot) => {
|
|
98
|
+
emitTail = emitTail.then(() => run(rpc.events.emit("changed", snapshot))).catch(() => {});
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
yield* context.session.hook("model.request", (request) => Effect.promise(async (signal) => {
|
|
102
|
+
if (closed || signal.aborted || !store.enabled) return;
|
|
103
|
+
let eligible = false;
|
|
104
|
+
if (request.model.providerID === "openai") {
|
|
105
|
+
const [provider, models] = await Promise.all([
|
|
106
|
+
run(context.provider.get({ providerID: Provider.ID.make("openai") }), { signal }),
|
|
107
|
+
run(context.model.list(), { signal }),
|
|
108
|
+
]);
|
|
109
|
+
const model = models.data.find((item) => item.providerID === request.model.providerID && item.id === request.model.id);
|
|
110
|
+
eligible = !!model && (model.type === undefined || model.type === "chat") &&
|
|
111
|
+
provider.data.integrationID === "openai" &&
|
|
112
|
+
NATIVE_PACKAGES.has(model.package ?? provider.data.package ?? "");
|
|
113
|
+
const configuredNative = request.baseURL ?? model?.settings?.baseURL ?? provider.data.settings?.baseURL;
|
|
114
|
+
if (configuredNative !== undefined && (typeof configuredNative !== "string" ||
|
|
115
|
+
![nativeBase("codex"), nativeBase("token-sharing")].includes(configuredNative.replace(/\/$/, "")))) eligible = false;
|
|
116
|
+
if (eligible) {
|
|
117
|
+
if (closed || signal.aborted || !store.enabled) return;
|
|
118
|
+
const selected = await pool.pool(signal);
|
|
119
|
+
const configured = configuredNative ?? (selected && nativeBase(selected));
|
|
120
|
+
if (!selected || typeof configured !== "string" || configured.replace(/\/$/, "") !== nativeBase(selected)) eligible = false;
|
|
121
|
+
else {
|
|
122
|
+
if (signal.aborted || closed || !store.enabled) return;
|
|
123
|
+
const call = store.begin(request.sessionID, request.kind, request.model);
|
|
124
|
+
request.baseURL = transport.bind(call, selected);
|
|
125
|
+
request.headers = Object.fromEntries(transport.localHeaders(new Headers(request.headers)));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (signal.aborted || closed || !store.enabled) return;
|
|
130
|
+
if (!eligible) request.headers = Object.fromEntries(privateHeaders(new Headers(request.headers)));
|
|
131
|
+
if (request.kind === "primary") store.setPrimaryProvider(request.sessionID, eligible);
|
|
132
|
+
}));
|
|
133
|
+
|
|
134
|
+
// DIRECT public Effect hook: its signal is native per-invocation cancellation.
|
|
135
|
+
// Do not run this callback via Promise-plugin adapter or detached runPromise.
|
|
136
|
+
yield* context.session.hook("http.request", (event) => Effect.promise(async (signal) => {
|
|
137
|
+
const url = new URL(event.request.url);
|
|
138
|
+
const binding = transport.binding(event.request.url, event.sessionID, event.model, event.kind);
|
|
139
|
+
if (url.origin === transport.origin && !binding) throw new Error("Local routing state expired or transport context mismatch.");
|
|
140
|
+
const headers = binding ? transport.localHeaders(event.request.headers) : privateHeaders(event.request.headers);
|
|
141
|
+
if (!binding && event.request.headers.has(LOCAL_AUTH)) {
|
|
142
|
+
headers.delete("authorization");
|
|
143
|
+
headers.delete("chatgpt-account-id");
|
|
144
|
+
event.request = withHeaders(event.request, headers);
|
|
145
|
+
throw new Error("Managed native destination changed before transport.");
|
|
146
|
+
}
|
|
147
|
+
event.request = withHeaders(event.request, headers);
|
|
148
|
+
if (!binding) return;
|
|
149
|
+
// SAME authenticated relay handler, no native HTTP executor/proxy hop.
|
|
150
|
+
const response = await transport.respondHTTP(event.request, signal);
|
|
151
|
+
if (signal.aborted) {
|
|
152
|
+
await response.body?.cancel().catch(() => {});
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
return response;
|
|
156
|
+
}).pipe(Effect.map((response) => { if (response) event.response = response; })));
|
|
157
|
+
|
|
158
|
+
yield* context.session.hook("experimental.ws.handshake", (event) => Effect.sync(() => {
|
|
159
|
+
const origin = new URL(event.url).origin.replace(/^ws:/, "http:");
|
|
160
|
+
const binding = transport.binding(event.url, event.sessionID, event.model, event.kind);
|
|
161
|
+
if (origin === transport.origin && !binding) throw new Error("Local routing state expired or WebSocket context mismatch.");
|
|
162
|
+
const original = new Headers(event.headers);
|
|
163
|
+
if (!binding) {
|
|
164
|
+
event.headers = Object.fromEntries(privateHeaders(original));
|
|
165
|
+
if (original.has(LOCAL_AUTH)) throw new Error("Managed native WebSocket destination changed.");
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
const headers = transport.localHeaders(original);
|
|
169
|
+
// EACH handshake precedes native affinity/checkpoint/driver compilation.
|
|
170
|
+
headers.set("x-opencode-local-affinity", randomBytes(24).toString("hex"));
|
|
171
|
+
event.headers = Object.fromEntries(headers);
|
|
172
|
+
}));
|
|
173
|
+
|
|
174
|
+
yield* context.session.hook("retry", (retry) => Effect.sync(() => {
|
|
175
|
+
// Category/status can be native quota or WS-without-status: HMAC ownership
|
|
176
|
+
// is independent of current credentials/catalog/cache or sibling failures.
|
|
177
|
+
if (store.retryControl.verify(retry)) retry.decision = { retry: false };
|
|
178
|
+
}));
|
|
179
|
+
|
|
180
|
+
yield* context.event.subscribe({
|
|
181
|
+
types: ["credential.updated", "credential.switched", "integration.updated", "session.deleted",
|
|
182
|
+
"session.execution.succeeded", "session.execution.failed", "session.execution.interrupted"],
|
|
183
|
+
}).pipe(Stream.runForEach((event) => Effect.promise(async (signal) => {
|
|
184
|
+
if (closed) return;
|
|
185
|
+
if (event.type === "credential.updated" || event.type === "credential.switched" || event.type === "integration.updated") {
|
|
186
|
+
if ("integrationID" in event.data && event.data.integrationID !== "openai") return;
|
|
187
|
+
pool.invalidate();
|
|
188
|
+
// Native list updates must reproject idle history too. Reclassification
|
|
189
|
+
// and native refresh remain owned by the next genuine model request.
|
|
190
|
+
await pool.refreshMetadata(signal);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
if (event.type === "session.deleted") store.removeSession(event.data.sessionID);
|
|
194
|
+
else if ("sessionID" in event.data && typeof event.data.sessionID === "string") {
|
|
195
|
+
if (event.type === "session.execution.interrupted") store.cancelPrimary(event.data.sessionID);
|
|
196
|
+
store.releaseSessionCalls(event.data.sessionID, true);
|
|
197
|
+
}
|
|
198
|
+
}).pipe(Effect.catchCause(() => Effect.void))), Effect.catchCause(() => Effect.void), Effect.forkScoped);
|
|
199
|
+
// Run before registration finalizers on ordinary teardown, while the first
|
|
200
|
+
// finalizer above remains the partial-init safety net (close is idempotent).
|
|
201
|
+
yield* Effect.addFinalizer(() => Effect.promise(close));
|
|
202
|
+
}),
|
|
203
|
+
});
|
package/src/network.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
type Environment = Readonly<Record<string, string | undefined>>;
|
|
2
|
+
const value = (environment: Environment, name: string) => environment[name] ?? environment[name.toLowerCase()];
|
|
3
|
+
/**
|
|
4
|
+
* Source-aligned with v2.4.4 core/effect/websocket-constructor/options.ts.
|
|
5
|
+
* Public server-owned policy projection, no private import or global env edits.
|
|
6
|
+
* This specifies intended selection, NOT a claim about Bun implicit proxy IO.
|
|
7
|
+
*/
|
|
8
|
+
export function webSocketProxy(input: string, environment: Environment = process.env): string | undefined {
|
|
9
|
+
const url = new URL(input);
|
|
10
|
+
if (["127.0.0.1", "localhost", "::1"].includes(url.hostname)) return;
|
|
11
|
+
const noProxy = value(environment, "NO_PROXY");
|
|
12
|
+
const port = url.port || (url.protocol === "wss:" ? "443" : "80");
|
|
13
|
+
const hostname = url.hostname.toLowerCase();
|
|
14
|
+
if (noProxy?.split(/[\s,]+/).some((entry) => {
|
|
15
|
+
if (!entry) return false;
|
|
16
|
+
if (entry === "*") return true;
|
|
17
|
+
const match = /^(.+?):(\d+)$/.exec(entry);
|
|
18
|
+
if (match?.[2] && match[2] !== port) return false;
|
|
19
|
+
const host = (match?.[1] ?? entry).toLowerCase().replace(/^\*/, "");
|
|
20
|
+
return host.startsWith(".") ? hostname.endsWith(host) : hostname === host;
|
|
21
|
+
})) return;
|
|
22
|
+
return value(environment, url.protocol === "wss:" ? "WSS_PROXY" : "WS_PROXY") ??
|
|
23
|
+
value(environment, url.protocol === "wss:" ? "HTTPS_PROXY" : "HTTP_PROXY") ??
|
|
24
|
+
value(environment, "ALL_PROXY");
|
|
25
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Public, non-secret UI state. Account indices follow native OpenAI list order. */
|
|
2
|
+
export interface SessionAccountView {
|
|
3
|
+
readonly sessionID: string;
|
|
4
|
+
/** The sticky assignment, not an unconfirmed failover candidate. */
|
|
5
|
+
readonly accountIndex: number | null;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface RouterSnapshot {
|
|
9
|
+
/** OFF delegates new requests to native OpenCode; assignments remain history. */
|
|
10
|
+
readonly enabled: boolean;
|
|
11
|
+
/** Distinguishes runtime reloads, whose revision counters restart at zero. */
|
|
12
|
+
readonly instanceID: string;
|
|
13
|
+
readonly revision: number;
|
|
14
|
+
readonly assignments: readonly SessionAccountView[];
|
|
15
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { RoutingState } from "./router";
|
|
2
|
+
|
|
3
|
+
/** Only nonsecret identity/primary metadata and the round-robin cursor persist. */
|
|
4
|
+
export interface DurableRouting {
|
|
5
|
+
readonly version: 1;
|
|
6
|
+
readonly sessions: readonly {
|
|
7
|
+
readonly sessionID: string;
|
|
8
|
+
readonly accountID: string | null;
|
|
9
|
+
readonly primary: boolean | null;
|
|
10
|
+
}[];
|
|
11
|
+
readonly cursor: RoutingState["cursor"];
|
|
12
|
+
}
|
|
13
|
+
export interface RoutingStorage {
|
|
14
|
+
get(key: string): Promise<unknown>;
|
|
15
|
+
set(key: string, value: DurableRouting): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Host storage already namespaces by plugin ID, but is global across Locations.
|
|
19
|
+
// Use the normalized public Location ref, not process IDs or a new identity.
|
|
20
|
+
export function routingStorageKey(location: { directory: string; workspaceID?: string }): string {
|
|
21
|
+
return "routing/v1/" + encodeURIComponent(JSON.stringify([location.directory, location.workspaceID ?? null]));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const record = (value: unknown): value is Record<string, unknown> =>
|
|
25
|
+
!!value && typeof value === "object" && !Array.isArray(value);
|
|
26
|
+
const keys = (value: Record<string, unknown>, expected: string[]) =>
|
|
27
|
+
Object.keys(value).length === expected.length && expected.every((key) => Object.hasOwn(value, key));
|
|
28
|
+
const id = (value: unknown): value is string => typeof value === "string" && value.length > 0;
|
|
29
|
+
|
|
30
|
+
export function decodeRouting(value: unknown): DurableRouting {
|
|
31
|
+
const invalid = () => { throw new Error("Saved routing state is invalid or has an unsupported version."); };
|
|
32
|
+
if (!record(value) || !keys(value, ["version", "sessions", "cursor"]) || value.version !== 1 ||
|
|
33
|
+
!Array.isArray(value.sessions) || !record(value.cursor) ||
|
|
34
|
+
!keys(value.cursor, ["nextAccountID", "order"]) || !Array.isArray(value.cursor.order)) return invalid();
|
|
35
|
+
const { cursor, sessions } = value;
|
|
36
|
+
const order = cursor.order as unknown[];
|
|
37
|
+
if (order.some((entry) => !id(entry)) || new Set(order).size !== order.length ||
|
|
38
|
+
!(cursor.nextAccountID === null || id(cursor.nextAccountID)) ||
|
|
39
|
+
(cursor.nextAccountID !== null && !order.includes(cursor.nextAccountID))) return invalid();
|
|
40
|
+
const seen = new Set<string>();
|
|
41
|
+
for (const row of sessions) {
|
|
42
|
+
if (!record(row) || !keys(row, ["sessionID", "accountID", "primary"]) || !id(row.sessionID) ||
|
|
43
|
+
!(row.accountID === null || id(row.accountID)) ||
|
|
44
|
+
!(row.primary === null || typeof row.primary === "boolean") || seen.has(row.sessionID)) return invalid();
|
|
45
|
+
seen.add(row.sessionID);
|
|
46
|
+
}
|
|
47
|
+
// Whitelisted/validated JSON only; caller never retains unvalidated payloads.
|
|
48
|
+
return structuredClone(value) as unknown as DurableRouting;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* One atomic KV document, serialized writes per Location activation. Native
|
|
53
|
+
* v2.4.4 loader awaits old scope close before loading its replacement. close()
|
|
54
|
+
* drains BEFORE runtime disposal; no late write survives that handoff.
|
|
55
|
+
* Public storage has no CAS: independent processes for the SAME Location are
|
|
56
|
+
* not fenced. Different Locations have different keys, not a global history.
|
|
57
|
+
*/
|
|
58
|
+
export class RoutingPersistence {
|
|
59
|
+
private tail: Promise<void> = Promise.resolve();
|
|
60
|
+
private saved: string | undefined;
|
|
61
|
+
private closed = false;
|
|
62
|
+
private hydrated = false;
|
|
63
|
+
private failed = false;
|
|
64
|
+
constructor(private readonly storage: RoutingStorage, private readonly key: string) {}
|
|
65
|
+
|
|
66
|
+
async hydrate(): Promise<DurableRouting | undefined> {
|
|
67
|
+
if (this.closed || this.hydrated) throw new Error("Routing storage is not available for hydration.");
|
|
68
|
+
let raw: unknown;
|
|
69
|
+
try { raw = await this.storage.get(this.key); }
|
|
70
|
+
catch { throw new Error("Saved routing state could not be read."); }
|
|
71
|
+
if (raw === undefined) { this.hydrated = true; return; }
|
|
72
|
+
const state = decodeRouting(raw);
|
|
73
|
+
this.saved = JSON.stringify(state);
|
|
74
|
+
this.hydrated = true;
|
|
75
|
+
return state;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
save(state: DurableRouting): void {
|
|
79
|
+
if (this.closed) return;
|
|
80
|
+
if (!this.hydrated) throw new Error("Routing storage has not been hydrated.");
|
|
81
|
+
const text = JSON.stringify(state);
|
|
82
|
+
if (text === this.saved) return;
|
|
83
|
+
this.saved = text;
|
|
84
|
+
const snapshot = structuredClone(state);
|
|
85
|
+
this.tail = this.tail.then(async () => {
|
|
86
|
+
try { await this.storage.set(this.key, snapshot); }
|
|
87
|
+
catch { this.failed = true; } // no credential/backend payload in errors
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async close(): Promise<void> {
|
|
92
|
+
this.closed = true;
|
|
93
|
+
await this.tail;
|
|
94
|
+
if (this.failed) throw new Error("Routing state could not be saved.");
|
|
95
|
+
}
|
|
96
|
+
}
|