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.
Files changed (45) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +217 -2
  3. package/dist/accounts.d.ts +31 -0
  4. package/dist/bun.lock.txt +671 -0
  5. package/dist/chunks/index-85yd61pa.js +29 -0
  6. package/dist/chunks/index-n7sr1hee.js +803 -0
  7. package/dist/index.d.ts +4 -0
  8. package/dist/index.js +1842 -0
  9. package/dist/network.d.ts +8 -0
  10. package/dist/panel-contract.d.ts +14 -0
  11. package/dist/persistence.d.ts +40 -0
  12. package/dist/relay-protocol.d.ts +86 -0
  13. package/dist/relay.d.ts +50 -0
  14. package/dist/retry-control.d.ts +41 -0
  15. package/dist/router.d.ts +55 -0
  16. package/dist/rpc.d.ts +98 -0
  17. package/dist/rpc.js +7 -0
  18. package/dist/runtime.d.ts +94 -0
  19. package/dist/settings.d.ts +32 -0
  20. package/dist/sidebar-colors.d.ts +10 -0
  21. package/dist/sidebar-model.d.ts +82 -0
  22. package/dist/sidebar.d.ts +33 -0
  23. package/dist/sidebar.js +12 -0
  24. package/dist/tui.d.ts +3 -0
  25. package/dist/tui.js +25 -0
  26. package/package.json +52 -4
  27. package/scripts/build.ts +39 -0
  28. package/src/accounts.ts +130 -0
  29. package/src/index.ts +203 -0
  30. package/src/network.ts +25 -0
  31. package/src/panel-contract.ts +15 -0
  32. package/src/persistence.ts +96 -0
  33. package/src/relay-protocol.ts +157 -0
  34. package/src/relay.ts +593 -0
  35. package/src/retry-control.ts +92 -0
  36. package/src/router.ts +156 -0
  37. package/src/rpc.ts +28 -0
  38. package/src/runtime.ts +319 -0
  39. package/src/settings.ts +68 -0
  40. package/src/sidebar-colors.ts +132 -0
  41. package/src/sidebar-model.ts +257 -0
  42. package/src/sidebar.tsx +438 -0
  43. package/src/tui.tsx +12 -0
  44. package/tsconfig.build.json +12 -0
  45. package/tsconfig.json +16 -0
@@ -0,0 +1,92 @@
1
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
+
3
+ export interface ModelRef {
4
+ readonly providerID: string;
5
+ readonly id: string;
6
+ readonly variant?: string;
7
+ }
8
+ export interface ManagedFailure {
9
+ readonly sessionID: string;
10
+ readonly model: ModelRef;
11
+ readonly kind: "primary" | "compaction" | "generate" | "title";
12
+ readonly handle: string;
13
+ }
14
+ export interface RetryContext {
15
+ readonly sessionID: string;
16
+ readonly model: ModelRef;
17
+ readonly error: { readonly response?: { readonly body: string } };
18
+ }
19
+ export const CONTROL = "_opencode_local_router";
20
+ export const ORIGINAL = "_opencode_local_original";
21
+ const digest = (value: string) => createHash("sha256").update(value).digest("hex");
22
+ export const record = (value: unknown): value is Record<string, any> =>
23
+ typeof value === "object" && value !== null && !Array.isArray(value);
24
+
25
+ /**
26
+ * LOCAL wire diagnostics, inserted only on confirmed native limit termination
27
+ * (HTTP/wire429 or the exact WS-only affirmative code admission predicate).
28
+ * HOST's bundled provider constructs/parses its own errors. No SDK AIError
29
+ * instance or model implementation crosses the host module-identity boundary.
30
+ */
31
+ export class RetryControl {
32
+ #key = randomBytes(32);
33
+ #closed = false;
34
+ constructor(private readonly runtimeID: string) {}
35
+ private mac(value: string): Buffer {
36
+ return createHmac("sha256", this.#key).update(value).digest();
37
+ }
38
+
39
+ seal(original: string, failure: ManagedFailure, requestURL: string): string {
40
+ if (this.#closed) throw new Error("Routing runtime closed.");
41
+ let wire: unknown;
42
+ try { wire = JSON.parse(original); } catch {}
43
+ if (!record(wire)) {
44
+ const text = original.trim();
45
+ const fallback = "Provider request failed with HTTP 429";
46
+ const url = new URL(requestURL);
47
+ const message = !text || /^<(?:!doctype|html)/i.test(text)
48
+ ? `${fallback} (POST ${url.origin}${url.pathname})`
49
+ : `${fallback}: ${text.length > 2000 ? text.slice(0, 2000) + "…" : text}`;
50
+ // Known accepted limitation: escaping non-JSON text (especially a newline
51
+ // after native message truncation) can change native quota classification.
52
+ wire = { message, [ORIGINAL]: original };
53
+ } else if (CONTROL in wire || ORIGINAL in wire) {
54
+ throw new Error("Reserved local diagnostic field collision.");
55
+ }
56
+ const context: ManagedFailure = {
57
+ sessionID: failure.sessionID,
58
+ model: { providerID: failure.model.providerID, id: failure.model.id, variant: failure.model.variant },
59
+ kind: failure.kind, handle: failure.handle,
60
+ };
61
+ const claims = {
62
+ version: 1, runtimeID: this.runtimeID, ...context, finalNativeLimit: true,
63
+ original: Buffer.from(original, "utf16le").toString("base64"),
64
+ digest: digest(JSON.stringify(wire)),
65
+ };
66
+ const value = Buffer.from(JSON.stringify(claims)).toString("hex");
67
+ if (!record(wire)) throw new Error("Invalid native diagnostic.");
68
+ return JSON.stringify({ ...wire, [CONTROL]: `${value}.${this.mac(value).toString("hex")}` });
69
+ }
70
+
71
+ verify(context: RetryContext): { originalBody: string; failure: ManagedFailure } | undefined {
72
+ if (this.#closed) return;
73
+ try {
74
+ const wire: unknown = JSON.parse(context.error.response?.body ?? "");
75
+ if (!record(wire) || typeof wire[CONTROL] !== "string") return;
76
+ const match = /^([0-9a-f]+)\.([0-9a-f]{64})$/.exec(wire[CONTROL]);
77
+ if (!match || match[1]!.length % 2) return;
78
+ const value = match[1]!;
79
+ if (!timingSafeEqual(Buffer.from(match[2]!, "hex"), this.mac(value))) return;
80
+ const claims = JSON.parse(Buffer.from(value, "hex").toString());
81
+ if (claims.version !== 1 || claims.runtimeID !== this.runtimeID || claims.finalNativeLimit !== true ||
82
+ !["primary", "compaction"].includes(claims.kind) || typeof claims.handle !== "string" ||
83
+ claims.sessionID !== context.sessionID || claims.model?.providerID !== context.model.providerID ||
84
+ claims.model.id !== context.model.id || claims.model.variant !== context.model.variant ||
85
+ typeof claims.original !== "string") return;
86
+ delete wire[CONTROL];
87
+ if (digest(JSON.stringify(wire)) !== claims.digest) return;
88
+ return { originalBody: Buffer.from(claims.original, "base64").toString("utf16le"), failure: claims };
89
+ } catch { return; }
90
+ }
91
+ dispose(): void { this.#closed = true; this.#key.fill(0); }
92
+ }
package/src/router.ts ADDED
@@ -0,0 +1,156 @@
1
+ /** API-independent routing core for opencode-openai-session-router. */
2
+ export class NoAccountsError extends Error {
3
+ constructor() {
4
+ super("No accounts are available.");
5
+ this.name = "NoAccountsError";
6
+ }
7
+ }
8
+
9
+ export interface RoutingRequest {
10
+ readonly sessionId: string;
11
+ readonly revision: number;
12
+ readonly candidates: readonly string[];
13
+ }
14
+ export interface RoutingState {
15
+ readonly assignments: readonly (readonly [string, string])[];
16
+ readonly cursor: { readonly nextAccountID: string | null; readonly order: readonly string[] };
17
+ }
18
+
19
+ export class SessionRouter {
20
+ private accounts: string[] = [];
21
+ private nextAccountId: string | undefined;
22
+ private cursorOrder: string[] = [];
23
+ private readonly assignments = new Map<string, string>();
24
+ private readonly revisions = new Map<string, number>();
25
+ private revision = 0;
26
+
27
+ constructor(accountIds: readonly string[]) {
28
+ this.setAccounts(accountIds);
29
+ }
30
+
31
+ /**
32
+ * Account IDs must be stable identities, not positions in an external list.
33
+ * Retain the next round-robin account if possible; otherwise use its next
34
+ * surviving successor in the old order, or the first new account.
35
+ * Historical assignments survive pool changes; unavailable accounts allocate
36
+ * again only on the next request, never merely on metadata refresh.
37
+ */
38
+ setAccounts(accountIds: readonly string[]): void {
39
+ if (accountIds.some((id) => !id) || new Set(accountIds).size !== accountIds.length) {
40
+ throw new Error("Account IDs must be nonempty and unique.");
41
+ }
42
+
43
+ const available = new Set(accountIds);
44
+ if (!accountIds.length) {
45
+ this.accounts = [];
46
+ return;
47
+ }
48
+ const nextIndex = this.cursorOrder.indexOf(this.nextAccountId ?? "");
49
+ let next: string | undefined;
50
+ for (let offset = 0; nextIndex >= 0 && offset < this.cursorOrder.length; offset++) {
51
+ const id = this.cursorOrder[(nextIndex + offset) % this.cursorOrder.length]!;
52
+ if (available.has(id)) {
53
+ next = id;
54
+ break;
55
+ }
56
+ }
57
+ this.accounts = [...accountIds];
58
+ this.nextAccountId = next ?? this.accounts[0];
59
+ this.cursorOrder = [...accountIds];
60
+ }
61
+
62
+ state(): RoutingState {
63
+ return { assignments: this.entries(), cursor: { nextAccountID: this.nextAccountId ?? null, order: [...this.cursorOrder] } };
64
+ }
65
+
66
+ /** Startup only: no calls/capabilities or CAS revisions survive a generation. */
67
+ restore(state: RoutingState): void {
68
+ if (this.assignments.size || this.accounts.length) throw new Error("Routing restore requires an unused router.");
69
+ for (const [sessionID, accountID] of state.assignments) {
70
+ this.assignments.set(sessionID, accountID);
71
+ this.revisions.set(sessionID, ++this.revision);
72
+ }
73
+ this.nextAccountId = state.cursor.nextAccountID ?? undefined;
74
+ this.cursorOrder = [...state.cursor.order];
75
+ }
76
+
77
+ getAssignedAccount(sessionId: string): string | undefined {
78
+ return this.assignments.get(sessionId);
79
+ }
80
+
81
+ entries(): readonly (readonly [string, string])[] {
82
+ return [...this.assignments];
83
+ }
84
+
85
+ removeSession(sessionId: string): void {
86
+ this.assignments.delete(sessionId);
87
+ this.revisions.delete(sessionId);
88
+ }
89
+
90
+ begin(sessionId: string): RoutingRequest {
91
+ const candidates = this.getCandidates(sessionId);
92
+ return { sessionId, candidates, revision: this.revisions.get(sessionId)! };
93
+ }
94
+
95
+ /** An accepted completion invalidates every older overlapping request. */
96
+ commit(request: RoutingRequest, accountId: string): boolean {
97
+ if (
98
+ this.revisions.get(request.sessionId) !== request.revision ||
99
+ !request.candidates.includes(accountId) ||
100
+ !this.accounts.includes(accountId)
101
+ ) return false;
102
+ this.assignments.set(request.sessionId, accountId);
103
+ this.revisions.set(request.sessionId, ++this.revision);
104
+ return true;
105
+ }
106
+
107
+ /** A fresh logical request gets a fresh, bounded candidate snapshot. */
108
+ getCandidates(sessionId: string): readonly string[] {
109
+ if (this.accounts.length === 0) throw new NoAccountsError();
110
+
111
+ let assigned = this.assignments.get(sessionId);
112
+ if (assigned === undefined || !this.accounts.includes(assigned)) {
113
+ assigned = this.nextAccountId!;
114
+ this.assignments.set(sessionId, assigned);
115
+ this.revisions.set(sessionId, ++this.revision);
116
+ const index = this.accounts.indexOf(assigned);
117
+ this.nextAccountId = this.accounts[(index + 1) % this.accounts.length];
118
+ }
119
+ const start = this.accounts.indexOf(assigned);
120
+ return [...this.accounts.slice(start), ...this.accounts.slice(0, start)];
121
+ }
122
+
123
+ /**
124
+ * The adapter classifies rate-limit errors (e.g. HTTP 429); all other errors
125
+ * stop immediately. Exhaustion throws the last rate-limit error unchanged.
126
+ * No clocks, cooldowns, or cross-request failure state are maintained.
127
+ *
128
+ * Changes during an attempt: new accounts wait until the next request;
129
+ * removed accounts are skipped and cannot become assigned on success.
130
+ * Concurrent requests are independent; stale completions cannot overwrite
131
+ * an assignment accepted since their request began.
132
+ */
133
+ async run<T>(
134
+ sessionId: string,
135
+ attempt: (accountId: string) => T | Promise<T>,
136
+ isRateLimit: (error: unknown) => boolean,
137
+ ): Promise<T> {
138
+ const request = this.begin(sessionId);
139
+ const candidates = request.candidates;
140
+ let lastError: unknown = new NoAccountsError();
141
+ for (const accountId of candidates) {
142
+ if (!this.accounts.includes(accountId)) continue;
143
+ let result: T;
144
+ try {
145
+ result = await attempt(accountId);
146
+ } catch (error) {
147
+ if (!isRateLimit(error)) throw error;
148
+ lastError = error;
149
+ continue;
150
+ }
151
+ this.commit(request, accountId);
152
+ return result;
153
+ }
154
+ throw lastError;
155
+ }
156
+ }
package/src/rpc.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { Rpc } from "@opencode/schema/rpc";
2
+ import { Schema } from "effect";
3
+
4
+ const snapshot = Schema.toStandardSchemaV1(Schema.Struct({
5
+ enabled: Schema.Boolean,
6
+ instanceID: Schema.String,
7
+ revision: Schema.Number,
8
+ assignments: Schema.Array(Schema.Struct({
9
+ sessionID: Schema.String,
10
+ accountIndex: Schema.NullOr(Schema.Number),
11
+ })),
12
+ }));
13
+
14
+ /** Public payloads deliberately contain no native connection IDs or labels. */
15
+ export const RouterRpc = Rpc.define({
16
+ id: "opencode-openai-session-router",
17
+ methods: {
18
+ snapshot: {
19
+ input: Schema.toStandardSchemaV1(Schema.Struct({})),
20
+ output: snapshot,
21
+ },
22
+ setEnabled: {
23
+ input: Schema.toStandardSchemaV1(Schema.Struct({ enabled: Schema.Boolean })),
24
+ output: snapshot,
25
+ },
26
+ },
27
+ events: { changed: { schema: snapshot } },
28
+ });
package/src/runtime.ts ADDED
@@ -0,0 +1,319 @@
1
+ import { SessionRouter, type RoutingRequest } from "./router";
2
+ import type { RouterSnapshot } from "./panel-contract";
3
+ import { RetryControl, type ModelRef } from "./retry-control";
4
+ import type { DurableRouting } from "./persistence";
5
+
6
+ /** Only pre-verified compatible IDs enter this store; never credentials. */
7
+ export interface AccountView {
8
+ readonly id: string;
9
+ /** Position in the FULL native credential order, not the compatible pool. */
10
+ readonly index: number;
11
+ }
12
+
13
+ export interface LogicalCall {
14
+ readonly handle: string;
15
+ readonly sessionID: string;
16
+ readonly kind: "primary" | "compaction" | "title" | "generate";
17
+ readonly model?: ModelRef;
18
+ routing: RoutingRequest;
19
+ tried: Set<string>;
20
+ limited: Set<string>;
21
+ inFlight: number;
22
+ outcome: "new" | "success" | "failure";
23
+ recency: number;
24
+ cancelled?: boolean;
25
+ sentWebSocket?: boolean;
26
+ readonly aborts: Set<AbortController>;
27
+ /** Retained until explicit host lifecycle cleanup, including native re-entry. */
28
+ exhaustion?: { readonly error: unknown };
29
+ }
30
+
31
+ export interface RoutingOperation {
32
+ readonly call: LogicalCall;
33
+ readonly routing: RoutingRequest;
34
+ readonly tried: Set<string>;
35
+ readonly limited: Set<string>;
36
+ readonly retainedError?: unknown;
37
+ terminalError?: unknown;
38
+ succeeded: boolean;
39
+ }
40
+
41
+ /**
42
+ * Only executing entries are protected. Eviction never recreates an operation:
43
+ * an evicted handle fails locally before provider traffic. Success is retained
44
+ * for native compaction's same-prepared-request nudge; that nudge is a NEW bounded
45
+ * operation, starting at the current sticky assignment and CAS revision.
46
+ */
47
+ export class RouterRuntime {
48
+ readonly router = new SessionRouter([]);
49
+ private accounts: readonly AccountView[] = [];
50
+ private nativeOrder: readonly AccountView[] = [];
51
+ private readonly calls = new Map<string, LogicalCall>();
52
+ private readonly primary = new Map<string, boolean>();
53
+ private readonly listeners = new Set<(snapshot: RouterSnapshot) => void>();
54
+ private readonly durableListeners = new Set<(state: DurableRouting) => void>();
55
+ private durableText = "";
56
+ private current: RouterSnapshot = { instanceID: crypto.randomUUID(), revision: 0, enabled: true, assignments: [] };
57
+ private enabledValue = true;
58
+ private disposed = false;
59
+ private sequence = 0;
60
+ readonly retryControl = new RetryControl(this.current.instanceID);
61
+
62
+ constructor(private readonly capacity = 2048) {
63
+ if (!Number.isInteger(capacity) || capacity < 1) throw new Error("Invalid call capacity.");
64
+ }
65
+
66
+ get enabled(): boolean { return this.enabledValue; }
67
+
68
+ /** Admission policy only: never cancel calls, reset the cursor or erase history. */
69
+ setEnabled(enabled: boolean): RouterSnapshot {
70
+ this.assertOpen();
71
+ this.enabledValue = enabled;
72
+ this.publish();
73
+ return this.snapshot();
74
+ }
75
+
76
+ setAccounts(accounts: readonly AccountView[], nativeOrder: readonly AccountView[] = accounts): void {
77
+ this.assertOpen();
78
+ this.validateOrder(nativeOrder);
79
+ this.validateOrder(accounts);
80
+ if (accounts.some(({ id }) => !nativeOrder.some((account) => account.id === id))) {
81
+ throw new Error("Eligible accounts must belong to the native credential order.");
82
+ }
83
+ this.router.setAccounts(accounts.map(({ id }) => id));
84
+ this.accounts = accounts.map((account) => ({ ...account }));
85
+ this.nativeOrder = nativeOrder.map((account) => ({ ...account }));
86
+ this.publish();
87
+ }
88
+
89
+ private validateOrder(accounts: readonly AccountView[]): void {
90
+ if (accounts.some(({ index }) => !Number.isInteger(index) || index < 0) ||
91
+ new Set(accounts.map(({ index }) => index)).size !== accounts.length ||
92
+ accounts.some(({ id }) => !id) || new Set(accounts.map(({ id }) => id)).size !== accounts.length) {
93
+ throw new Error("Native account indices must be distinct nonnegative integers.");
94
+ }
95
+ }
96
+
97
+ /** Metadata-only display refresh; never resolve OAuth just to show history. */
98
+ setNativeOrder(nativeOrder: readonly AccountView[]): void {
99
+ this.assertOpen();
100
+ this.validateOrder(nativeOrder);
101
+ this.nativeOrder = nativeOrder.map((account) => ({ ...account }));
102
+ this.accounts = this.accounts.filter(({ id }) => nativeOrder.some((account) => account.id === id));
103
+ this.router.setAccounts(this.accounts.map(({ id }) => id));
104
+ this.publish();
105
+ }
106
+
107
+ restore(state: DurableRouting): void {
108
+ this.assertOpen();
109
+ if (this.calls.size || this.primary.size) throw new Error("Routing restore requires an unused runtime.");
110
+ this.router.restore({
111
+ assignments: state.sessions.flatMap((row) => row.accountID === null ? [] : [[row.sessionID, row.accountID] as const]),
112
+ cursor: state.cursor,
113
+ });
114
+ for (const row of state.sessions) if (row.primary !== null) this.primary.set(row.sessionID, row.primary);
115
+ this.publish();
116
+ }
117
+
118
+ durableSnapshot(): DurableRouting {
119
+ const routing = this.router.state();
120
+ return {
121
+ version: 1,
122
+ sessions: [...new Set([...this.primary.keys(), ...routing.assignments.map(([id]) => id)])].sort().map((sessionID) => ({
123
+ sessionID,
124
+ accountID: this.router.getAssignedAccount(sessionID) ?? null,
125
+ primary: this.primary.get(sessionID) ?? null,
126
+ })),
127
+ cursor: routing.cursor,
128
+ };
129
+ }
130
+
131
+ subscribeDurable(listener: (state: DurableRouting) => void): () => void {
132
+ this.assertOpen();
133
+ this.durableListeners.add(listener);
134
+ return () => { this.durableListeners.delete(listener); };
135
+ }
136
+
137
+ /** Auxiliary requests do not change which account the primary UI displays. */
138
+ setPrimaryProvider(sessionID: string, nativeOpenAI: boolean): void {
139
+ this.assertOpen();
140
+ this.primary.set(sessionID, nativeOpenAI);
141
+ this.publish();
142
+ }
143
+
144
+ begin(sessionID: string, kind: LogicalCall["kind"], model?: ModelRef): LogicalCall {
145
+ this.assertOpen();
146
+ if (this.calls.size >= this.capacity) {
147
+ const idle = [...this.calls.values()].filter((call) => call.inFlight === 0).sort((a, b) =>
148
+ Number(a.outcome !== "success") - Number(b.outcome !== "success") || a.recency - b.recency);
149
+ if (!idle[0]) throw new Error("Routing call capacity reached: all entries are executing.");
150
+ this.calls.delete(idle[0].handle);
151
+ }
152
+ const call: LogicalCall = {
153
+ handle: crypto.randomUUID(),
154
+ sessionID,
155
+ kind,
156
+ model: model && { providerID: model.providerID, id: model.id, variant: model.variant },
157
+ routing: this.router.begin(sessionID),
158
+ tried: new Set(),
159
+ limited: new Set(),
160
+ inFlight: 0,
161
+ outcome: "new",
162
+ recency: ++this.sequence,
163
+ aborts: new Set(),
164
+ };
165
+ this.calls.set(call.handle, call);
166
+ this.publish();
167
+ return call;
168
+ }
169
+
170
+ lookup(handle: string): LogicalCall | undefined {
171
+ const call = this.calls.get(handle);
172
+ if (call) call.recency = ++this.sequence;
173
+ return call;
174
+ }
175
+
176
+ contains(call: LogicalCall): boolean { return this.calls.get(call.handle) === call; }
177
+
178
+ enter(call: LogicalCall): RoutingOperation {
179
+ this.assertOpen();
180
+ if (this.calls.get(call.handle) !== call) throw new Error("Routing state expired.");
181
+ if (call.cancelled) throw new Error("Routing request cancelled.");
182
+ if (call.inFlight) throw new Error("Routing exchange already executing.");
183
+ // Native nonrate retry is still the SAME operation: do not forget accounts
184
+ // already rejected by a rate limit. Only a successful auxiliary/nudge starts
185
+ // a fresh bounded operation/current sticky CAS revision.
186
+ const fresh = !call.exhaustion && (call.outcome === "new" || call.outcome === "success");
187
+ const routing = fresh ? this.router.begin(call.sessionID) : call.routing;
188
+ const tried = fresh ? new Set<string>() : call.tried;
189
+ const limited = fresh ? new Set<string>() : call.limited;
190
+ call.routing = routing;
191
+ call.tried = tried;
192
+ call.limited = limited;
193
+ if (fresh) call.sentWebSocket = false;
194
+ call.inFlight++;
195
+ call.recency = ++this.sequence;
196
+ return { call, routing, tried, limited, retainedError: call.exhaustion?.error, succeeded: false };
197
+ }
198
+
199
+ complete(operation: RoutingOperation, accountID: string): void {
200
+ const { call } = operation;
201
+ if (this.disposed || call.cancelled || this.calls.get(call.handle) !== call || !this.available(accountID)) return;
202
+ operation.succeeded = true;
203
+ call.exhaustion = undefined;
204
+ this.router.commit(operation.routing, accountID);
205
+ this.publish();
206
+ }
207
+
208
+ retain(operation: RoutingOperation, error: unknown): void {
209
+ operation.terminalError = error;
210
+ if (this.calls.get(operation.call.handle) === operation.call) operation.call.exhaustion = { error };
211
+ }
212
+
213
+ end(operation: RoutingOperation): void {
214
+ const { call } = operation;
215
+ call.inFlight--;
216
+ call.outcome = operation.succeeded ? "success" : "failure";
217
+ call.recency = ++this.sequence;
218
+ }
219
+
220
+ available(accountID: string): boolean {
221
+ return this.accounts.some(({ id }) => id === accountID);
222
+ }
223
+
224
+ commit(call: LogicalCall, accountID: string): boolean {
225
+ if (this.disposed || this.calls.get(call.handle) !== call || call.exhaustion || !this.available(accountID)) return false;
226
+ const accepted = this.router.commit(call.routing, accountID);
227
+ this.publish();
228
+ return accepted;
229
+ }
230
+
231
+ release(handle: string): void {
232
+ if (this.calls.get(handle)?.inFlight === 0) this.calls.delete(handle);
233
+ }
234
+
235
+ releaseSessionCalls(sessionID: string, primaryOnly = false): void {
236
+ for (const [handle, call] of this.calls) {
237
+ if (call.sessionID === sessionID && call.inFlight === 0 &&
238
+ (!primaryOnly || call.kind === "primary")) this.calls.delete(handle);
239
+ }
240
+ }
241
+
242
+ removeSession(sessionID: string): void {
243
+ this.router.removeSession(sessionID);
244
+ this.primary.delete(sessionID);
245
+ for (const [handle, call] of this.calls) {
246
+ if (call.sessionID === sessionID) {
247
+ this.cancel(call);
248
+ this.calls.delete(handle);
249
+ }
250
+ }
251
+ this.publish();
252
+ }
253
+
254
+ snapshot(): RouterSnapshot {
255
+ return structuredClone(this.current);
256
+ }
257
+
258
+ subscribe(listener: (snapshot: RouterSnapshot) => void): () => void {
259
+ this.assertOpen();
260
+ this.listeners.add(listener);
261
+ return () => { this.listeners.delete(listener); };
262
+ }
263
+
264
+ /** Stop admission/completions without destroying values still being saved. */
265
+ stop(): void {
266
+ this.disposed = true;
267
+ for (const call of this.calls.values()) this.cancel(call);
268
+ }
269
+
270
+ dispose(): void {
271
+ this.stop();
272
+ this.retryControl.dispose();
273
+ this.calls.clear();
274
+ this.listeners.clear();
275
+ this.durableListeners.clear();
276
+ for (const [id] of this.router.entries()) this.router.removeSession(id);
277
+ this.primary.clear();
278
+ this.accounts = [];
279
+ this.nativeOrder = [];
280
+ }
281
+
282
+ cancel(call: LogicalCall): void {
283
+ call.cancelled = true;
284
+ for (const abort of call.aborts) abort.abort();
285
+ }
286
+
287
+ cancelPrimary(sessionID: string): void {
288
+ for (const call of this.calls.values()) {
289
+ if (call.sessionID === sessionID && call.kind === "primary") this.cancel(call);
290
+ }
291
+ }
292
+
293
+ private assertOpen(): void {
294
+ if (this.disposed) throw new Error("Routing runtime is disposed.");
295
+ }
296
+
297
+ private publish(): void {
298
+ const durable = this.durableSnapshot();
299
+ const text = JSON.stringify(durable);
300
+ if (text !== this.durableText) {
301
+ this.durableText = text;
302
+ for (const listener of this.durableListeners) listener(durable);
303
+ }
304
+ const assignments = [...new Set([
305
+ ...this.primary.keys(),
306
+ ...this.router.entries().map(([id]) => id),
307
+ ])].sort().map((sessionID) => ({
308
+ sessionID,
309
+ accountIndex: this.primary.get(sessionID) === true
310
+ ? this.nativeOrder.find(({ id }) => id === this.router.getAssignedAccount(sessionID))?.index ?? null
311
+ : null,
312
+ }));
313
+ if (this.current.enabled === this.enabledValue &&
314
+ JSON.stringify(assignments) === JSON.stringify(this.current.assignments)) return;
315
+ this.current = { instanceID: this.current.instanceID, revision: this.current.revision + 1,
316
+ enabled: this.enabledValue, assignments };
317
+ for (const listener of this.listeners) listener(this.snapshot());
318
+ }
319
+ }
@@ -0,0 +1,68 @@
1
+ import { routingStorageKey } from "./persistence";
2
+
3
+ export interface RoutingSettings { readonly version: 1; readonly enabled: boolean }
4
+ export interface SettingsStorage {
5
+ get(key: string): Promise<unknown>;
6
+ set(key: string, value: RoutingSettings): Promise<void>;
7
+ }
8
+
9
+ /** Separate document: existing strict routing/v1 mapping bytes/schema stay valid. */
10
+ export const settingsStorageKey = (location: { directory: string; workspaceID?: string }) =>
11
+ routingStorageKey(location).replace(/^routing\/v1\//, "settings/v1/");
12
+
13
+ /**
14
+ * Same Location/native-loader boundary as RoutingPersistence: one atomic KV
15
+ * value, ordered writes, drained close before replacement hydration. No public
16
+ * storage CAS exists; independent same-Location processes are not fenced.
17
+ */
18
+ export class SettingsPersistence {
19
+ private hydrated = false;
20
+ private closed = false;
21
+ private desired = true;
22
+ private failed = false;
23
+ private tail: Promise<void> = Promise.resolve();
24
+ private lastWrite: Promise<void> = Promise.resolve();
25
+ constructor(private readonly storage: SettingsStorage, private readonly key: string) {}
26
+
27
+ async hydrate(): Promise<boolean> {
28
+ if (this.closed || this.hydrated) throw new Error("Routing settings are not available for hydration.");
29
+ let raw: unknown;
30
+ try { raw = await this.storage.get(this.key); }
31
+ catch { throw new Error("Routing settings could not be read."); }
32
+ if (raw !== undefined) {
33
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) ||
34
+ Object.keys(raw).length !== 2 || !("version" in raw) || raw.version !== 1 ||
35
+ !("enabled" in raw) || typeof raw.enabled !== "boolean") {
36
+ throw new Error("Saved routing settings are invalid or have an unsupported version.");
37
+ }
38
+ this.desired = raw.enabled;
39
+ }
40
+ this.hydrated = true;
41
+ return this.desired;
42
+ }
43
+
44
+ save(enabled: boolean): Promise<void> {
45
+ if (this.closed) return Promise.reject(new Error("Routing settings are closed."));
46
+ if (!this.hydrated) return Promise.reject(new Error("Routing settings have not been hydrated."));
47
+ if (enabled === this.desired) return this.lastWrite;
48
+ this.desired = enabled;
49
+ const write = this.tail.then(async () => {
50
+ try {
51
+ await this.storage.set(this.key, { version: 1, enabled });
52
+ this.failed = false;
53
+ } catch {
54
+ this.failed = true;
55
+ throw new Error("Routing settings could not be saved.");
56
+ }
57
+ });
58
+ this.lastWrite = write;
59
+ this.tail = write.catch(() => {}); // caller sees failure; subsequent desired writes still serialize
60
+ return write;
61
+ }
62
+
63
+ async close(): Promise<void> {
64
+ this.closed = true;
65
+ await this.tail;
66
+ if (this.failed) throw new Error("Routing settings could not be saved.");
67
+ }
68
+ }