@r-33/opencode 0.0.0-stage → 0.4.7-rc.20

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/dist/index.js ADDED
@@ -0,0 +1,4545 @@
1
+ // src/auth/auth-error/auth-error.ts
2
+ var AuthError = class extends Error {
3
+ constructor(code, options) {
4
+ super(
5
+ "Route 33 authorization failed",
6
+ options?.cause === void 0 ? void 0 : { cause: options.cause }
7
+ );
8
+ this.code = code;
9
+ this.name = "AuthError";
10
+ this.statusCode = options?.statusCode;
11
+ }
12
+ code;
13
+ statusCode;
14
+ };
15
+
16
+ // src/auth/build-authorize-url/build-authorize-url.ts
17
+ var buildAuthorizeUrl = (issuerUrl2, request) => {
18
+ const url = new URL("/authorize", issuerUrl2);
19
+ url.search = new URLSearchParams({
20
+ client_id: request.clientId,
21
+ code_challenge: request.codeChallenge,
22
+ code_challenge_method: "S256",
23
+ redirect_uri: request.redirectUri,
24
+ response_type: "code",
25
+ scope: request.scope,
26
+ state: request.state
27
+ }).toString();
28
+ return url;
29
+ };
30
+
31
+ // src/contract/adapters/contract-parse-error/contract-parse-error.ts
32
+ var ContractParseError = class extends Error {
33
+ };
34
+
35
+ // src/contract/adapters/gateway-api-key/gateway-api-key.ts
36
+ var GatewayApiKey = class {
37
+ value;
38
+ constructor(value) {
39
+ this.value = value;
40
+ }
41
+ };
42
+
43
+ // src/contract/adapters/management-jwt/management-jwt.ts
44
+ var ManagementJwt = class {
45
+ value;
46
+ constructor(value) {
47
+ this.value = value;
48
+ }
49
+ };
50
+
51
+ // src/contract/adapters/parse-gateway-key/parse-gateway-key.ts
52
+ var parseGatewayKey = (value) => {
53
+ if (typeof value !== "string" || value.length === 0) {
54
+ throw new Error("gateway key must be non-empty");
55
+ }
56
+ return new GatewayApiKey(value);
57
+ };
58
+
59
+ // src/contract/adapters/parse-management-jwt/parse-management-jwt.ts
60
+ var parseManagementJwt = (value) => {
61
+ if (typeof value !== "string" || value.length === 0) {
62
+ throw new Error("management token must be non-empty");
63
+ }
64
+ return new ManagementJwt(value);
65
+ };
66
+
67
+ // src/contract/predicates/has-string-fields/has-string-fields.ts
68
+ var hasStringFields = (record, fields) => fields.every((field) => typeof record[field] === "string");
69
+
70
+ // src/contract/predicates/is-nullable-string/is-nullable-string.ts
71
+ var isNullableString = (value) => typeof value === "string" || value === null;
72
+
73
+ // src/contract/predicates/is-owner-type/is-owner-type.ts
74
+ var isOwnerType = (value) => value === "project" || value === "user_personal" || value === "user_project";
75
+
76
+ // src/contract/predicates/is-record/is-record.ts
77
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
78
+
79
+ // src/contract/adapters/parse-management-subject/parse-management-subject.ts
80
+ var parseManagementSubject = (credential) => {
81
+ const encodedPayload = credential.value.split(".")[1];
82
+ if (encodedPayload === void 0 || encodedPayload.length === 0) {
83
+ throw new ContractParseError("management token carries no usable subject");
84
+ }
85
+ let payload;
86
+ try {
87
+ payload = JSON.parse(
88
+ Buffer.from(encodedPayload, "base64url").toString("utf8")
89
+ );
90
+ } catch {
91
+ throw new ContractParseError("management token payload is not JSON");
92
+ }
93
+ if (!isRecord(payload)) {
94
+ throw new ContractParseError("management token payload is not an object");
95
+ }
96
+ const subject = payload["sub"];
97
+ if (typeof subject !== "string" || subject.length === 0) {
98
+ throw new ContractParseError("management token carries no usable subject");
99
+ }
100
+ return subject;
101
+ };
102
+
103
+ // src/contract/auth-session/parse-token-set/parse-token-set.ts
104
+ var parseTokenSet = (value) => {
105
+ if (!isRecord(value)) {
106
+ throw new ContractParseError("invalid token response");
107
+ }
108
+ if (typeof value["access_token"] !== "string" || typeof value["expires_in"] !== "number" || value["token_type"] !== "Bearer") {
109
+ throw new ContractParseError("invalid token response");
110
+ }
111
+ return {
112
+ access_token: value["access_token"],
113
+ expires_in: value["expires_in"],
114
+ token_type: "Bearer",
115
+ ...typeof value["id_token"] === "string" ? { id_token: value["id_token"] } : {},
116
+ ...typeof value["refresh_token"] === "string" ? { refresh_token: value["refresh_token"] } : {},
117
+ ...typeof value["scope"] === "string" ? { scope: value["scope"] } : {}
118
+ };
119
+ };
120
+
121
+ // src/auth/exchange-code-and-parse/exchange-code-and-parse.ts
122
+ var exchangeCodeAndParse = async (options) => {
123
+ const body = new URLSearchParams({
124
+ client_id: options.clientId,
125
+ code: options.input.code,
126
+ code_verifier: options.input.codeVerifier,
127
+ grant_type: "authorization_code",
128
+ redirect_uri: options.input.redirectUri
129
+ });
130
+ let response;
131
+ try {
132
+ response = await (options.fetchImpl ?? fetch)(options.tokenUrl, {
133
+ body,
134
+ headers: { "content-type": "application/x-www-form-urlencoded" },
135
+ method: "POST"
136
+ });
137
+ } catch (cause) {
138
+ throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", { cause });
139
+ }
140
+ if (!response.ok) {
141
+ throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", {
142
+ statusCode: response.status
143
+ });
144
+ }
145
+ let payload;
146
+ try {
147
+ payload = await response.json();
148
+ } catch (cause) {
149
+ throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", { cause });
150
+ }
151
+ try {
152
+ return parseTokenSet(payload);
153
+ } catch (cause) {
154
+ if (cause instanceof ContractParseError) {
155
+ throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", { cause });
156
+ }
157
+ throw cause;
158
+ }
159
+ };
160
+
161
+ // src/auth/refresh-session/refresh-session.ts
162
+ var refreshSession = async (options) => {
163
+ const body = new URLSearchParams({
164
+ client_id: options.clientId,
165
+ grant_type: "refresh_token",
166
+ refresh_token: options.refreshToken
167
+ });
168
+ let response;
169
+ try {
170
+ response = await (options.fetchImpl ?? fetch)(options.tokenUrl, {
171
+ body,
172
+ headers: { "content-type": "application/x-www-form-urlencoded" },
173
+ method: "POST"
174
+ });
175
+ } catch (cause) {
176
+ throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", { cause });
177
+ }
178
+ if (!response.ok) {
179
+ throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", {
180
+ statusCode: response.status
181
+ });
182
+ }
183
+ let payload;
184
+ try {
185
+ payload = await response.json();
186
+ } catch (cause) {
187
+ throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", { cause });
188
+ }
189
+ try {
190
+ return parseTokenSet(payload);
191
+ } catch (cause) {
192
+ if (cause instanceof ContractParseError) {
193
+ throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", { cause });
194
+ }
195
+ throw cause;
196
+ }
197
+ };
198
+
199
+ // src/auth/create-auth-session/create-auth-session.ts
200
+ var createAuthSession = (options) => {
201
+ const tokenUrl = new URL("/oauth/token", options.issuerUrl);
202
+ return {
203
+ authorizationUrl: (request) => buildAuthorizeUrl(options.issuerUrl, request),
204
+ exchangeCode: (input) => exchangeCodeAndParse({
205
+ clientId: options.clientId,
206
+ ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl },
207
+ input,
208
+ tokenUrl
209
+ }),
210
+ refresh: (refreshToken) => refreshSession({
211
+ clientId: options.clientId,
212
+ ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl },
213
+ refreshToken,
214
+ tokenUrl
215
+ })
216
+ };
217
+ };
218
+
219
+ // src/shared/default-auth-issuer-url/default-auth-issuer-url.ts
220
+ var DEFAULT_AUTH_ISSUER_URL = "https://auth.route33.ai";
221
+
222
+ // src/shared/default-base-url/default-base-url.ts
223
+ var DEFAULT_BASE_URL = "https://api.route33.ai/v1";
224
+
225
+ // src/shared/default-management-api-base-url/default-management-api-base-url.ts
226
+ var DEFAULT_MANAGEMENT_API_BASE_URL = "https://mapi.route33.ai/api/v1";
227
+
228
+ // src/shared/default-catalog-ttl-ms/default-catalog-ttl-ms.ts
229
+ var DEFAULT_CATALOG_TTL_MS = 36e5;
230
+
231
+ // src/shared/logger/logger.ts
232
+ var logger = {
233
+ info: (...args) => {
234
+ console.log("[route_33]", ...args);
235
+ },
236
+ warn: (...args) => {
237
+ console.warn("[route_33]", ...args);
238
+ },
239
+ error: (...args) => {
240
+ console.error("[route_33]", ...args);
241
+ }
242
+ };
243
+
244
+ // src/shared/models-dev-ttl-ms/models-dev-ttl-ms.ts
245
+ var MODELS_DEV_TTL_MS = 864e5;
246
+
247
+ // src/shared/native-sdk-api-key-placeholder/native-sdk-api-key-placeholder.ts
248
+ var NATIVE_SDK_API_KEY_PLACEHOLDER = "__route33_fetch_shim_auth__";
249
+
250
+ // src/shared/resolve-cache-dir/resolve-cache-dir.ts
251
+ import * as os from "node:os";
252
+ import * as path from "node:path";
253
+ var resolveCacheDir = (env) => {
254
+ const override = env["ROUTE33_CACHE_DIR"];
255
+ if (override !== void 0 && override !== "") {
256
+ return override;
257
+ }
258
+ return path.join(
259
+ env["XDG_CACHE_HOME"] ?? path.join(os.homedir(), ".cache"),
260
+ "opencode-route33"
261
+ );
262
+ };
263
+
264
+ // src/auth/open-browser-and-capture/open-browser-and-capture.ts
265
+ import { timingSafeEqual } from "node:crypto";
266
+
267
+ // src/auth/loopback-callback/loopback-callback.ts
268
+ import { createServer } from "node:http";
269
+
270
+ // src/auth/loopback-callback/callback-page/callback-page.ts
271
+ var MARK_PATHS = [
272
+ "M310.6,175.8c0-6.1-2.7-11.8-7.2-15.9l-127.6-114.4V7h-43.5v48.3c0,6.2,2.6,12.1,7.2,16.2l92.5,82.9H0v43.5h234.7l-95.6,91.4c-4.3,4.1-6.7,9.8-6.7,15.7v48.3h43.5v-39l128.1-122.4c4.4-4.2,6.8-10,6.7-16.1h0Z",
273
+ "M457.2,175.9v-2.6c18.4-4.9,33-14.1,44-27.7,11-13.6,16.5-30.3,16.5-50.3s-4.5-32.9-13.4-47.5c-9-14.5-21.6-26.1-38-34.9-16.4-8.7-35.8-13.1-58.3-13.1s-41.1,4-58.8,12.1-31.8,19.3-42.4,33.7-16.1,31-16.6,50h51.1c.3-10.8,3.6-20,9.8-27.7,6.2-7.6,14.2-13.5,24.1-17.5,9.9-4.1,20.6-6.1,32-6.1s22.3,2.2,31.1,6.7c8.8,4.5,15.6,10.8,20.5,18.8,4.9,8.1,7.3,17.5,7.3,28.4s-2.8,21.1-8.4,29.4-13.3,14.8-23.2,19.5-21.3,7.1-34.2,7.1h-29.9v43.3h29.9c16.2,0,30,2.5,41.5,7.5,11.5,5,20.2,12,26.1,21.1,6,9,9,19.4,9,31.2s-3,21.2-9.1,29.8-14.4,15.3-25.1,20.1c-10.7,4.9-22.9,7.3-36.7,7.3s-24.2-2.1-34.5-6.2-18.6-10-24.8-17.5c-6.3-7.5-9.8-16.5-10.6-26.8h-53.2c.6,19,6.3,35.7,17,50.2,10.7,14.5,25.2,25.7,43.6,33.8,18.4,8.1,39.4,12.1,63.1,12.1s45.1-4.4,63.7-13.2c18.6-8.8,33.3-20.8,44-36,10.8-15.2,16.1-32.5,16.1-51.8s-6.4-40.7-19.2-55.6c-12.8-14.9-30.8-24.2-54-27.8h0Z",
274
+ "M763,203.7c-12.8-14.9-30.8-24.2-54-27.8v-2.6c18.4-4.9,33-14.1,44-27.7,11-13.6,16.5-30.3,16.5-50.3s-4.5-32.9-13.4-47.5c-8.9-14.5-21.6-26.1-38-34.9-16.4-8.7-35.8-13.1-58.3-13.1s-41.1,4-58.8,12.1-31.8,19.3-42.4,33.7-16.1,31-16.6,50h51.1c.3-10.8,3.6-20,9.8-27.7,6.2-7.6,14.2-13.5,24.1-17.5,9.9-4.1,20.6-6.1,32-6.1s22.3,2.2,31.1,6.7c8.8,4.5,15.6,10.8,20.5,18.8,4.9,8.1,7.3,17.5,7.3,28.4s-2.8,21.1-8.4,29.4c-5.6,8.3-13.3,14.8-23.2,19.5s-21.3,7.1-34.2,7.1h-29.9v43.3h29.9c16.2,0,30,2.5,41.5,7.5,11.5,5,20.2,12,26.1,21.1,6,9,8.9,19.4,8.9,31.2s-3,21.2-9.1,29.8c-6.1,8.6-14.4,15.3-25.1,20.1-10.7,4.9-22.9,7.3-36.7,7.3s-24.2-2.1-34.5-6.2-18.6-10-24.8-17.5c-6.3-7.5-9.8-16.5-10.6-26.8h-53.2c.6,19,6.3,35.7,17,50.2,10.7,14.5,25.2,25.7,43.6,33.8,18.4,8.1,39.4,12.1,63.1,12.1s45.1-4.4,63.7-13.2,33.3-20.8,44-36c10.8-15.2,16.1-32.5,16.1-51.8s-6.4-40.7-19.2-55.6h0Z"
275
+ ];
276
+ var BRAND_MARK = `<svg class="r33-mark" viewBox="0 0 782.2 360.3" fill="currentColor" role="img" aria-label="route33.ai" xmlns="http://www.w3.org/2000/svg"><path d="${MARK_PATHS[0]}"/><path d="${MARK_PATHS[1]}"/><path d="${MARK_PATHS[2]}"/></svg>`;
277
+ var PAGE_STYLE = `:root{color-scheme:dark;--r33-euro-blue:#0000FF;--r33-off-white:#F1F1F1;--r33-off-black:#121212;--r33-grey-300:#C9CBCF;--r33-radius-fillet:4px;--r33-space-2:8px;--r33-space-3:16px;--r33-space-4:24px;--r33-space-6:64px;--r33-font-body:"Geist","Helvetica Neue",Arial,sans-serif;--r33-font-mono:"Geist Mono","SFMono-Regular",Menlo,monospace;--r33-surface:var(--r33-off-black);--r33-text-primary:var(--r33-off-white);--r33-text-secondary:var(--r33-grey-300);--r33-fill-accent:var(--r33-euro-blue);--r33-on-fill-accent:var(--r33-off-white)}
278
+ *{box-sizing:border-box}
279
+ html,body{margin:0}
280
+ .r33-page{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:var(--r33-space-6);background:var(--r33-surface);color:var(--r33-text-primary);font-family:var(--r33-font-body);-webkit-font-smoothing:antialiased}
281
+ .r33-panel{display:grid;gap:var(--r33-space-4);max-width:460px;width:100%}
282
+ .r33-mark{height:40px;width:auto;color:var(--r33-text-primary)}
283
+ .r33-status{display:inline-flex;align-items:center;gap:var(--r33-space-2);font-size:11px;letter-spacing:0.08em;text-transform:uppercase;color:var(--r33-text-secondary)}
284
+ .r33-status__dot{width:8px;height:8px;background:var(--r33-fill-accent)}
285
+ .r33-status__dot--error{background:transparent;border:1px solid var(--r33-text-primary);border-radius:50%}
286
+ .r33-headline{margin:0;font-size:48px;line-height:0.85;letter-spacing:-0.02em;font-weight:600;color:var(--r33-text-primary);text-wrap:balance}
287
+ .r33-subline{margin:0;font-size:16px;line-height:1.45;color:var(--r33-text-secondary);max-width:40ch;text-wrap:pretty}
288
+ .r33-code{margin:0;font-size:13px;letter-spacing:0.04em;color:var(--r33-text-secondary)}
289
+ .r33-code__value{font-family:var(--r33-font-mono);text-transform:uppercase;color:var(--r33-text-primary)}
290
+ @media (prefers-reduced-motion:reduce){*{animation-duration:1ms!important;transition-duration:1ms!important}}`;
291
+ var buildCallbackPage = (state, errorCode) => {
292
+ const isError = state === "error";
293
+ const safeCode = (errorCode ?? "").replace(/[^a-z0-9_-]/gi, "");
294
+ const title = isError ? "Sign-in failed" : "Signed in";
295
+ const headline = isError ? "Sign-in failed" : "Signed in to route33";
296
+ const subline = isError ? "Return to OpenCode and retry." : "Return to OpenCode \u2014 one more step may wait there: if it asks which budget covers usage, pick a project. This window can be closed.";
297
+ const statusLabel = isError ? "Authentication error" : "Authenticated";
298
+ const dotClass = isError ? "r33-status__dot r33-status__dot--error" : "r33-status__dot";
299
+ const codeLine = isError && safeCode.length > 0 ? `<p class="r33-code">Error code: <span class="r33-code__value">${safeCode}</span></p>` : "";
300
+ return `<!doctype html>
301
+ <html lang="en" data-theme="dark">
302
+ <head>
303
+ <meta charset="utf-8">
304
+ <meta name="viewport" content="width=device-width, initial-scale=1">
305
+ <title>${title} \xB7 route33.ai</title>
306
+ <style>${PAGE_STYLE}</style>
307
+ </head>
308
+ <body>
309
+ <main class="r33-page">
310
+ <div class="r33-panel">
311
+ ${BRAND_MARK}
312
+ <span class="r33-status"><span class="${dotClass}"></span>${statusLabel}</span>
313
+ <h1 class="r33-headline">${headline}</h1>
314
+ <p class="r33-subline">${subline}</p>
315
+ ${codeLine}
316
+ </div>
317
+ </main>
318
+ </body>
319
+ </html>`;
320
+ };
321
+
322
+ // src/auth/loopback-callback/loopback-callback.ts
323
+ var createAuthLoopbackCallback = async () => {
324
+ let redirectUri = "http://127.0.0.1/callback";
325
+ let resolveCapture;
326
+ const captured = new Promise((resolve2) => {
327
+ resolveCapture = resolve2;
328
+ });
329
+ const server = createServer((request, response) => {
330
+ const url = new URL(request.url ?? "/", redirectUri);
331
+ if (request.method !== "GET" || url.pathname !== "/callback") {
332
+ response.writeHead(404).end();
333
+ return;
334
+ }
335
+ const resolve2 = resolveCapture;
336
+ resolveCapture = void 0;
337
+ resolve2?.(url);
338
+ const error = url.searchParams.get("error");
339
+ const page = error === null || error.length === 0 ? buildCallbackPage("success") : buildCallbackPage("error", error);
340
+ response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
341
+ response.end(page);
342
+ });
343
+ await new Promise((resolve2, reject) => {
344
+ const onError = (cause) => {
345
+ reject(new AuthError("AUTH_CALLBACK_LISTEN_FAILED", { cause }));
346
+ };
347
+ server.once("error", onError);
348
+ server.listen(0, "127.0.0.1", () => {
349
+ server.off("error", onError);
350
+ resolve2();
351
+ });
352
+ });
353
+ const address = server.address();
354
+ if (address === null || typeof address === "string") {
355
+ server.close();
356
+ throw new AuthError("AUTH_CALLBACK_LISTEN_FAILED");
357
+ }
358
+ redirectUri = `http://127.0.0.1:${String(address.port)}/callback`;
359
+ return {
360
+ redirectUri,
361
+ close: () => {
362
+ if (!server.listening) {
363
+ return Promise.resolve();
364
+ }
365
+ return new Promise((resolve2, reject) => {
366
+ server.close((cause) => {
367
+ if (cause === void 0) {
368
+ resolve2();
369
+ return;
370
+ }
371
+ reject(new AuthError("AUTH_CALLBACK_CLEANUP_FAILED", { cause }));
372
+ });
373
+ });
374
+ },
375
+ wait: () => captured
376
+ };
377
+ };
378
+
379
+ // src/auth/open-system-browser/open-system-browser.ts
380
+ import { spawn } from "node:child_process";
381
+ var openSystemBrowser = async (url, options = {}) => new Promise((resolve2, reject) => {
382
+ let command = "xdg-open";
383
+ let args = [url.href];
384
+ if (process.platform === "darwin") {
385
+ command = "open";
386
+ } else if (process.platform === "win32") {
387
+ command = "cmd";
388
+ args = ["/c", "start", "", url.href];
389
+ }
390
+ if (options.spawnUrl !== void 0) {
391
+ options.spawnUrl(command, args, { detached: true, stdio: "ignore" });
392
+ resolve2();
393
+ return;
394
+ }
395
+ const child = spawn(command, args, {
396
+ detached: true,
397
+ stdio: "ignore"
398
+ });
399
+ child.once("error", reject);
400
+ child.once("spawn", () => {
401
+ child.unref();
402
+ resolve2();
403
+ });
404
+ });
405
+
406
+ // src/auth/open-browser-and-capture/open-browser-and-capture.ts
407
+ var openBrowserAndCapture = async (options) => {
408
+ const callback = await createAuthLoopbackCallback();
409
+ const authorizationUrl = options.authorizationUrl(callback.redirectUri);
410
+ const browserRunner = options.browserRunner ?? ((url) => openSystemBrowser(url));
411
+ let timer;
412
+ const timeout = new Promise((_resolve, reject) => {
413
+ timer = setTimeout(() => {
414
+ reject(new AuthError("AUTH_CALLBACK_TIMEOUT"));
415
+ }, options.timeoutMs ?? 12e4);
416
+ });
417
+ const launch = browserRunner(authorizationUrl).catch((cause) => {
418
+ throw new AuthError("AUTH_BROWSER_LAUNCH_FAILED", { cause });
419
+ });
420
+ try {
421
+ const completed = await Promise.race([
422
+ Promise.all([launch, callback.wait()]),
423
+ timeout
424
+ ]);
425
+ const callbackUrl = completed[1];
426
+ const actualState = callbackUrl.searchParams.get("state");
427
+ if (actualState === null) {
428
+ throw new AuthError("AUTH_CALLBACK_RESPONSE_INVALID");
429
+ }
430
+ const expectedState = Buffer.from(options.expectedState);
431
+ const receivedState = Buffer.from(actualState);
432
+ if (expectedState.length !== receivedState.length || !timingSafeEqual(expectedState, receivedState)) {
433
+ throw new AuthError("AUTH_CALLBACK_STATE_MISMATCH");
434
+ }
435
+ const code = callbackUrl.searchParams.get("code");
436
+ if (code === null || code.length === 0) {
437
+ throw new AuthError("AUTH_CALLBACK_RESPONSE_INVALID");
438
+ }
439
+ return { code, redirectUri: callback.redirectUri };
440
+ } finally {
441
+ if (timer !== void 0) {
442
+ clearTimeout(timer);
443
+ }
444
+ await callback.close();
445
+ }
446
+ };
447
+
448
+ // src/auth/pkce-verifier-and-challenge/pkce-verifier-and-challenge.ts
449
+ import { randomBytes } from "node:crypto";
450
+
451
+ // src/auth/pkce-challenge/pkce-challenge.ts
452
+ import { createHash } from "node:crypto";
453
+ var pkceChallenge = (verifier) => createHash("sha256").update(verifier).digest("base64url");
454
+
455
+ // src/auth/pkce-verifier-and-challenge/pkce-verifier-and-challenge.ts
456
+ var createPkceVerifierAndChallenge = () => {
457
+ const codeVerifier = randomBytes(32).toString("base64url");
458
+ return {
459
+ codeChallenge: pkceChallenge(codeVerifier),
460
+ codeVerifier,
461
+ state: randomBytes(32).toString("base64url")
462
+ };
463
+ };
464
+
465
+ // src/auth/requested-scopes/requested-scopes.ts
466
+ var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read projects:read keys:read keys:write";
467
+
468
+ // src/auth/login-flow/login-flow.ts
469
+ var loginFlow = async (options) => {
470
+ const log = options.logger ?? logger;
471
+ log.info("auth.login.started");
472
+ const pkce = createPkceVerifierAndChallenge();
473
+ const captured = await openBrowserAndCapture({
474
+ authorizationUrl: (redirectUri) => options.session.authorizationUrl({
475
+ clientId: options.clientId,
476
+ codeChallenge: pkce.codeChallenge,
477
+ redirectUri,
478
+ scope: REQUESTED_OAUTH_SCOPES,
479
+ state: pkce.state
480
+ }),
481
+ ...options.browserRunner === void 0 ? {} : { browserRunner: options.browserRunner },
482
+ expectedState: pkce.state,
483
+ ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
484
+ });
485
+ const tokenSet = await options.session.exchangeCode({
486
+ code: captured.code,
487
+ codeVerifier: pkce.codeVerifier,
488
+ redirectUri: captured.redirectUri
489
+ });
490
+ let credential;
491
+ try {
492
+ credential = parseManagementJwt(tokenSet.access_token);
493
+ } catch (cause) {
494
+ throw new AuthError("AUTH_TOKEN_RESPONSE_INVALID", { cause });
495
+ }
496
+ log.info("auth.login.completed");
497
+ return { credential, tokenSet };
498
+ };
499
+
500
+ // src/cli/read-env-base-url/read-env-base-url.ts
501
+ var readEnvBaseUrl = (env = process.env) => {
502
+ const value = env["ROUTE33_BASE_URL"]?.trim();
503
+ return value === "" ? void 0 : value;
504
+ };
505
+
506
+ // src/cli/read-env-api-base/read-env-api-base.ts
507
+ var readEnvApiBase = (env = process.env) => {
508
+ const value = env["ROUTE33_API_BASE"]?.trim();
509
+ return value === "" ? void 0 : value;
510
+ };
511
+
512
+ // src/cli/read-env-auth-issuer/read-env-auth-issuer.ts
513
+ var readEnvAuthIssuer = (env = process.env) => {
514
+ const value = env["ROUTE33_AUTH_ISSUER"]?.trim();
515
+ return value === "" ? void 0 : value;
516
+ };
517
+
518
+ // src/cli/read-env-cache-dir/read-env-cache-dir.ts
519
+ var readEnvCacheDir = (env = process.env) => resolveCacheDir(env);
520
+
521
+ // src/cli/read-env-catalog-ttl-ms/read-env-catalog-ttl-ms.ts
522
+ var readEnvCatalogTtlMs = (env = process.env) => {
523
+ const value = Number(env["ROUTE33_CATALOG_TTL_MS"]);
524
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_CATALOG_TTL_MS;
525
+ };
526
+
527
+ // src/cli/read-env-client-id/read-env-client-id.ts
528
+ var readEnvClientId = (env = process.env) => {
529
+ const value = env["ROUTE33_CLIENT_ID"]?.trim();
530
+ return value === "" ? void 0 : value;
531
+ };
532
+
533
+ // src/cli/read-env-direct-api-key/read-env-direct-api-key.ts
534
+ var readEnvDirectApiKey = (env = process.env) => {
535
+ const value = env["ROUTE33_API_KEY"]?.trim();
536
+ return value === "" ? void 0 : value;
537
+ };
538
+
539
+ // src/cli/read-env-disable-id-shim/read-env-disable-id-shim.ts
540
+ var readEnvDisableIdShim = (env = process.env) => env["ROUTE33_DISABLE_ID_SHIM"] === "1";
541
+
542
+ // src/cli/read-env-discovery/read-env-discovery.ts
543
+ var readEnvDiscovery = (env = process.env) => env["ROUTE33_DISCOVERY"] !== "0";
544
+
545
+ // src/cli/read-env-strict/read-env-strict.ts
546
+ var readEnvStrict = (env = process.env) => env["ROUTE33_STRICT"] !== "0";
547
+
548
+ // src/cli/resolve-v1-secret-store-directory/resolve-v1-secret-store-directory.ts
549
+ import * as os2 from "node:os";
550
+ import * as path2 from "node:path";
551
+ var resolveV1SecretStoreDirectory = (options = {}) => {
552
+ const explicit = options.directory?.trim();
553
+ if (explicit !== void 0 && explicit.length > 0) {
554
+ return path2.resolve(explicit);
555
+ }
556
+ const hostConfig = (options.env ?? process.env)["OPENCODE_CONFIG_DIR"]?.trim();
557
+ if (hostConfig !== void 0 && hostConfig.length > 0) {
558
+ return path2.join(path2.resolve(hostConfig), "route33");
559
+ }
560
+ return path2.join(
561
+ options.homeDirectory ?? os2.homedir(),
562
+ ".config",
563
+ "opencode",
564
+ "route33"
565
+ );
566
+ };
567
+
568
+ // src/config/abortable-sleep/abortable-sleep.ts
569
+ var abortableSleep = (milliseconds, signal) => new Promise((resolve2, reject) => {
570
+ if (signal === void 0) {
571
+ setTimeout(resolve2, milliseconds);
572
+ return;
573
+ }
574
+ const abortError = () => {
575
+ const reason = signal.reason;
576
+ if (reason instanceof Error) {
577
+ return reason;
578
+ }
579
+ return new Error(String(reason), { cause: reason });
580
+ };
581
+ if (signal.aborted) {
582
+ reject(abortError());
583
+ return;
584
+ }
585
+ const onAbort = () => {
586
+ clearTimeout(timer);
587
+ reject(abortError());
588
+ };
589
+ const timer = setTimeout(() => {
590
+ signal.removeEventListener("abort", onAbort);
591
+ resolve2();
592
+ }, milliseconds);
593
+ signal.addEventListener("abort", onAbort, { once: true });
594
+ });
595
+
596
+ // src/config/is-resendable-body/is-resendable-body.ts
597
+ var isResendableBody = (body) => body === void 0 || typeof body === "string" || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof Blob || body instanceof URLSearchParams || body instanceof FormData;
598
+
599
+ // src/config/parse-exhaustion-envelope/parse-exhaustion-envelope.ts
600
+ var parseExhaustionEnvelope = async (response) => {
601
+ let body;
602
+ try {
603
+ body = await response.clone().json();
604
+ } catch (error) {
605
+ if (error instanceof Error) {
606
+ return void 0;
607
+ }
608
+ throw error;
609
+ }
610
+ if (!isRecord(body)) {
611
+ return void 0;
612
+ }
613
+ const nestedError = body["error"];
614
+ const nestedCode = isRecord(nestedError) ? nestedError["code"] : void 0;
615
+ if (body["code"] !== "PROVIDER_LANES_EXHAUSTED" && nestedCode !== "PROVIDER_LANES_EXHAUSTED") {
616
+ return void 0;
617
+ }
618
+ const nestedId = isRecord(nestedError) ? nestedError["correlationId"] : void 0;
619
+ const directId = body["correlationId"];
620
+ let correlationId;
621
+ if (typeof directId === "string") {
622
+ correlationId = directId;
623
+ } else if (typeof nestedId === "string") {
624
+ correlationId = nestedId;
625
+ }
626
+ return { correlationId };
627
+ };
628
+
629
+ // src/config/request-model/request-model.ts
630
+ var requestModel = (body) => {
631
+ if (typeof body !== "string") {
632
+ return void 0;
633
+ }
634
+ let parsed;
635
+ try {
636
+ parsed = JSON.parse(body);
637
+ } catch (error) {
638
+ if (error instanceof SyntaxError) {
639
+ return void 0;
640
+ }
641
+ throw error;
642
+ }
643
+ return isRecord(parsed) && typeof parsed["model"] === "string" ? parsed["model"] : void 0;
644
+ };
645
+
646
+ // src/config/retry-wait-seconds/retry-wait-seconds.ts
647
+ var retryWaitSeconds = (options) => {
648
+ const advised = options.retryAfter !== null && /^\d+$/.test(options.retryAfter) ? Number(options.retryAfter) : void 0;
649
+ return advised !== void 0 && advised > 0 ? Math.min(advised, options.maxWaitSeconds) : Math.min(
650
+ options.baseSeconds * 2 ** (options.attempt - 1),
651
+ options.maxWaitSeconds
652
+ );
653
+ };
654
+
655
+ // src/config/exhaustion-retry-fetch/exhaustion-retry-fetch.ts
656
+ var buildExhaustionRetryFetch = (innerFetch, options = {}) => {
657
+ const sleep = options.sleep ?? abortableSleep;
658
+ const maxWaitSeconds = options.maxWaitSeconds ?? 1200;
659
+ const baseSeconds = options.baseSeconds ?? 5;
660
+ const parseRetryableExhaustion = async (response) => {
661
+ if (response.status !== 429) {
662
+ return void 0;
663
+ }
664
+ const contentType = response.headers.get("content-type") ?? "";
665
+ if (!/(?:^|\/)json(?:;|$)|\+json(?:;|$)/i.test(contentType)) {
666
+ return void 0;
667
+ }
668
+ return parseExhaustionEnvelope(response);
669
+ };
670
+ return async (input, init) => {
671
+ const body = init?.body;
672
+ const signal = init?.signal ?? void 0;
673
+ const resendable = isResendableBody(body);
674
+ const model = requestModel(body);
675
+ for (let attempt = 1; ; attempt += 1) {
676
+ const response = await innerFetch(input, init);
677
+ const exhaustion = await parseRetryableExhaustion(response);
678
+ if (exhaustion === void 0 || !resendable) {
679
+ return response;
680
+ }
681
+ const seconds = retryWaitSeconds({
682
+ attempt,
683
+ baseSeconds,
684
+ maxWaitSeconds,
685
+ retryAfter: response.headers.get("retry-after")
686
+ });
687
+ logger.warn("provider lanes exhausted; retrying", {
688
+ attempt,
689
+ correlationId: exhaustion.correlationId,
690
+ ...model === void 0 ? {} : { model },
691
+ seconds
692
+ });
693
+ await sleep(seconds * 1e3, signal);
694
+ signal?.throwIfAborted();
695
+ }
696
+ };
697
+ };
698
+
699
+ // src/config/rewrite-openai-body/rewrite-openai-body.ts
700
+ var rewriteOpenAiBody = (body) => {
701
+ const parseOpenAiRecord = () => {
702
+ let value;
703
+ try {
704
+ value = JSON.parse(body);
705
+ } catch (error) {
706
+ if (error instanceof SyntaxError) {
707
+ return void 0;
708
+ }
709
+ throw error;
710
+ }
711
+ if (!isRecord(value)) {
712
+ return void 0;
713
+ }
714
+ const model = value["model"];
715
+ if (typeof model !== "string" || !model.startsWith("openai/")) {
716
+ return void 0;
717
+ }
718
+ return value;
719
+ };
720
+ const parsed = parseOpenAiRecord();
721
+ if (parsed === void 0) {
722
+ return void 0;
723
+ }
724
+ const tools = parsed["tools"];
725
+ const dropsEffort = "reasoning_effort" in parsed && Array.isArray(tools) && tools.length > 0;
726
+ const renamesMaxTokens = "max_tokens" in parsed;
727
+ if (!dropsEffort && !renamesMaxTokens) {
728
+ return void 0;
729
+ }
730
+ const rewritten = { ...parsed };
731
+ if (dropsEffort) {
732
+ delete rewritten["reasoning_effort"];
733
+ }
734
+ if (renamesMaxTokens) {
735
+ rewritten["max_completion_tokens"] ??= rewritten["max_tokens"];
736
+ delete rewritten["max_tokens"];
737
+ }
738
+ return JSON.stringify(rewritten);
739
+ };
740
+
741
+ // src/config/openai-chat-compat-fetch/openai-chat-compat-fetch.ts
742
+ var buildOpenAiChatCompatFetch = (fetchImpl) => (input, init) => {
743
+ const rewritten = typeof init?.body === "string" ? rewriteOpenAiBody(init.body) : void 0;
744
+ const finalInit = rewritten === void 0 ? init : { ...init, body: rewritten };
745
+ return (fetchImpl ?? globalThis.fetch)(input, finalInit);
746
+ };
747
+
748
+ // src/config/build-options/build-options.ts
749
+ var buildOptions = (baseURL) => ({
750
+ apiKey: NATIVE_SDK_API_KEY_PLACEHOLDER,
751
+ baseURL,
752
+ fetch: buildExhaustionRetryFetch(buildOpenAiChatCompatFetch()),
753
+ headerTimeout: 15e5
754
+ });
755
+
756
+ // src/config/native-sdk-by-vendor/native-sdk-by-vendor.ts
757
+ var NATIVE_SDK_BY_VENDOR = {
758
+ anthropic: "@ai-sdk/anthropic",
759
+ mistralai: "@ai-sdk/mistral",
760
+ openai: "@ai-sdk/openai"
761
+ };
762
+
763
+ // src/config/to-model-patch/to-model-patch.ts
764
+ var toModelPatch = (options) => {
765
+ const entry = { name: options.meta.name };
766
+ if (options.routingSlug !== void 0) {
767
+ entry.id = options.routingSlug;
768
+ }
769
+ if (options.nativeNpm !== void 0) {
770
+ entry.provider = { npm: options.nativeNpm };
771
+ }
772
+ const applyMetadata = () => {
773
+ const capabilities = options.meta.capabilities;
774
+ entry.attachment = options.meta.attachment ?? capabilities.attachment;
775
+ if (options.meta.modalities !== void 0) {
776
+ entry.modalities = structuredClone(options.meta.modalities);
777
+ }
778
+ entry.reasoning = options.forceReasoning ? true : capabilities.reasoning;
779
+ entry.temperature = capabilities.temperature;
780
+ entry.tool_call = capabilities.tool_call;
781
+ if (options.meta.cost !== void 0) {
782
+ entry.cost = structuredClone(options.meta.cost);
783
+ }
784
+ if (options.meta.limit !== void 0) {
785
+ entry.limit = {
786
+ context: options.meta.limit.context,
787
+ output: options.meta.limit.output
788
+ };
789
+ }
790
+ if (options.meta.variants !== void 0) {
791
+ entry.variants = structuredClone(options.meta.variants);
792
+ }
793
+ };
794
+ applyMetadata();
795
+ const compactEntry = { name: entry.name };
796
+ for (const [key, value] of Object.entries(entry)) {
797
+ if (value !== void 0) {
798
+ compactEntry[key] = value;
799
+ }
800
+ }
801
+ return compactEntry;
802
+ };
803
+
804
+ // src/config/build-provider-blocks/build-provider-blocks.ts
805
+ var buildProviderBlocks = (enriched, options) => {
806
+ const models = {};
807
+ for (const [slug, meta] of Object.entries(enriched).sort(
808
+ ([left], [right]) => left.localeCompare(right)
809
+ )) {
810
+ const separator = slug.indexOf("/");
811
+ const vendor = separator === -1 ? slug : slug.slice(0, separator);
812
+ models[slug] = toModelPatch({
813
+ forceReasoning: vendor === "anthropic",
814
+ meta,
815
+ ...NATIVE_SDK_BY_VENDOR[vendor] === void 0 ? {} : { nativeNpm: NATIVE_SDK_BY_VENDOR[vendor] }
816
+ });
817
+ }
818
+ return {
819
+ route_33: {
820
+ models,
821
+ name: "route_33",
822
+ npm: "@ai-sdk/openai-compatible",
823
+ options: buildOptions(options.baseURL)
824
+ }
825
+ };
826
+ };
827
+
828
+ // src/config/collected-ref/collected-ref.ts
829
+ var pushRef = (refs, value, source) => {
830
+ if (typeof value !== "string") {
831
+ return;
832
+ }
833
+ const separator = value.indexOf("/");
834
+ if (separator <= 0 || separator >= value.length - 1) {
835
+ return;
836
+ }
837
+ const providerId = value.slice(0, separator);
838
+ const suffix = value.slice(separator + 1);
839
+ if (providerId === "route_33") {
840
+ refs.push({ providerId, modelKey: suffix, ref: value, source });
841
+ return;
842
+ }
843
+ if (providerId === "route_33_anthropic") {
844
+ refs.push({
845
+ providerId: "route_33",
846
+ modelKey: `anthropic/${suffix}`,
847
+ ref: value,
848
+ source,
849
+ legacyReplacement: `route_33/anthropic/${suffix}`
850
+ });
851
+ }
852
+ };
853
+
854
+ // src/config/collect-cfg-refs/collect-cfg-refs.ts
855
+ var collectCfgRefs = (config) => {
856
+ const refs = [];
857
+ pushRef(refs, config.model, 'opencode config "model"');
858
+ pushRef(refs, config.small_model, 'opencode config "small_model"');
859
+ for (const [name, agent] of Object.entries(config.agent ?? {})) {
860
+ pushRef(refs, agent?.model, `opencode agent "${name}"`);
861
+ }
862
+ return refs;
863
+ };
864
+
865
+ // src/catalog/catalog-fetch-error/catalog-fetch-error.ts
866
+ var CatalogFetchError = class extends Error {
867
+ constructor(reason, message, statusCode) {
868
+ super(`catalog fetch failed (${reason}): ${message}`);
869
+ this.reason = reason;
870
+ this.statusCode = statusCode;
871
+ this.name = "CatalogFetchError";
872
+ }
873
+ reason;
874
+ statusCode;
875
+ };
876
+
877
+ // src/catalog/catalog-cache/cache-file-path/cache-file-path.ts
878
+ import * as path3 from "node:path";
879
+ var cacheFilePath = (keyHash, cacheDir) => path3.join(cacheDir, `catalog-${keyHash}.json`);
880
+
881
+ // src/catalog/catalog-cache/cache-state/cache-state.ts
882
+ var catalogMemory = /* @__PURE__ */ new Map();
883
+
884
+ // src/catalog/catalog-cache/cache-version/cache-version.ts
885
+ var CATALOG_CACHE_VERSION = 2;
886
+
887
+ // src/catalog/catalog-cache/hash-key/hash-key.ts
888
+ import { createHash as createHash2 } from "node:crypto";
889
+ var hashKey = (baseURL, gatewayKey) => createHash2("sha256").update(`${baseURL}
890
+ ${gatewayKey.value}`).digest("hex").slice(0, 12);
891
+
892
+ // src/catalog/catalog-cache/is-catalog-model-record/is-catalog-model-record.ts
893
+ var isCatalogModelRecord = (value) => isRecord(value) && Object.values(value).every(
894
+ (model) => isRecord(model) && typeof model["id"] === "string"
895
+ );
896
+
897
+ // src/catalog/catalog-cache/read-disk/read-disk.ts
898
+ import * as fs from "node:fs";
899
+ var readDisk = (keyHash, cacheDir) => {
900
+ try {
901
+ const parsed = JSON.parse(
902
+ fs.readFileSync(cacheFilePath(keyHash, cacheDir), "utf8")
903
+ );
904
+ if (!isRecord(parsed) || parsed["version"] !== CATALOG_CACHE_VERSION || typeof parsed["fetchedAt"] !== "number" || !isCatalogModelRecord(parsed["models"])) {
905
+ return void 0;
906
+ }
907
+ return {
908
+ fetchedAt: parsed["fetchedAt"],
909
+ keyHash,
910
+ models: parsed["models"]
911
+ };
912
+ } catch {
913
+ return void 0;
914
+ }
915
+ };
916
+
917
+ // src/catalog/catalog-cache/read-fresh-catalog/read-fresh-catalog.ts
918
+ var readFreshCatalog = (options) => {
919
+ const keyHash = hashKey(options.baseURL, options.gatewayKey);
920
+ const now = options.now ?? Date.now();
921
+ const requestedTtl = options.catalogTtlMs ?? DEFAULT_CATALOG_TTL_MS;
922
+ const ttl = Number.isFinite(requestedTtl) && requestedTtl > 0 ? requestedTtl : DEFAULT_CATALOG_TTL_MS;
923
+ const inMemory = catalogMemory.get(keyHash);
924
+ if (inMemory !== void 0 && now - inMemory.fetchedAt <= ttl) {
925
+ return inMemory.models;
926
+ }
927
+ const onDisk = readDisk(keyHash, options.cacheDir);
928
+ if (onDisk === void 0 || now - onDisk.fetchedAt > ttl) {
929
+ return void 0;
930
+ }
931
+ catalogMemory.set(keyHash, onDisk);
932
+ return onDisk.models;
933
+ };
934
+
935
+ // src/catalog/catalog-cache/read-stale-catalog/read-stale-catalog.ts
936
+ var readStaleCatalog = (options) => {
937
+ const keyHash = hashKey(options.baseURL, options.gatewayKey);
938
+ return (catalogMemory.get(keyHash) ?? readDisk(keyHash, options.cacheDir))?.models;
939
+ };
940
+
941
+ // src/catalog/catalog-cache/write-catalog/write-catalog.ts
942
+ import * as fs2 from "node:fs";
943
+ var writeCatalog = (options) => {
944
+ const keyHash = hashKey(options.baseURL, options.gatewayKey);
945
+ const record = {
946
+ fetchedAt: options.now ?? Date.now(),
947
+ keyHash,
948
+ models: options.models
949
+ };
950
+ catalogMemory.set(keyHash, record);
951
+ try {
952
+ fs2.mkdirSync(options.cacheDir, { recursive: true });
953
+ fs2.writeFileSync(
954
+ cacheFilePath(keyHash, options.cacheDir),
955
+ JSON.stringify({ version: CATALOG_CACHE_VERSION, ...record })
956
+ );
957
+ } catch (error) {
958
+ logger.warn(
959
+ `could not persist catalog cache: ${error instanceof Error ? error.message : String(error)}`
960
+ );
961
+ }
962
+ };
963
+
964
+ // src/catalog/build-cache-read-options/build-cache-read-options.ts
965
+ var buildCacheReadOptions = (options) => ({
966
+ baseURL: options.baseURL,
967
+ cacheDir: options.cacheDir,
968
+ ...options.catalogTtlMs === void 0 ? {} : { catalogTtlMs: options.catalogTtlMs },
969
+ gatewayKey: options.gatewayKey,
970
+ ...options.now === void 0 ? {} : { now: options.now }
971
+ });
972
+
973
+ // src/catalog/build-fetch-catalog-options/build-fetch-catalog-options.ts
974
+ var buildFetchCatalogOptions = (options) => ({
975
+ baseURL: options.baseURL,
976
+ gatewayKey: options.gatewayKey,
977
+ ...options.disableIdShim === void 0 ? {} : { disableIdShim: options.disableIdShim },
978
+ ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl }
979
+ });
980
+
981
+ // src/catalog/catalog-models-url/catalog-models-url.ts
982
+ var catalogModelsUrl = (baseURL) => {
983
+ let normalizedBaseURL = baseURL;
984
+ while (normalizedBaseURL.endsWith("/")) {
985
+ normalizedBaseURL = normalizedBaseURL.slice(0, -1);
986
+ }
987
+ return `${normalizedBaseURL}/models`;
988
+ };
989
+
990
+ // src/catalog/default-fetch-timeout-ms/default-fetch-timeout-ms.ts
991
+ var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
992
+
993
+ // src/contract/gateway-catalog/parse-catalog-result/parse-catalog-result.ts
994
+ var parseCatalogResult = (value) => {
995
+ if (!isRecord(value) || !Array.isArray(value["data"])) {
996
+ throw new ContractParseError("invalid catalog response");
997
+ }
998
+ return value;
999
+ };
1000
+
1001
+ // src/catalog/parse-catalog-entries/parse-catalog-entries.ts
1002
+ var parseCatalogEntries = (payload) => {
1003
+ if (Array.isArray(payload)) {
1004
+ return payload;
1005
+ }
1006
+ try {
1007
+ return parseCatalogResult(payload).data;
1008
+ } catch (error) {
1009
+ if (error instanceof ContractParseError) {
1010
+ throw new CatalogFetchError("parse", error.message);
1011
+ }
1012
+ throw error;
1013
+ }
1014
+ };
1015
+
1016
+ // src/catalog/parse-model-capabilities/parse-model-capabilities.ts
1017
+ var parseModelCapabilities = (raw) => {
1018
+ if (!isRecord(raw)) {
1019
+ return void 0;
1020
+ }
1021
+ const reasoning = raw["reasoning"] === true;
1022
+ const toolCall = raw["tool_support"] === true;
1023
+ if (!reasoning && !toolCall) {
1024
+ return void 0;
1025
+ }
1026
+ return {
1027
+ ...reasoning ? { reasoning: true } : {},
1028
+ ...toolCall ? { tool_call: true } : {}
1029
+ };
1030
+ };
1031
+
1032
+ // src/catalog/parse-model-limit/parse-model-limit.ts
1033
+ var parseModelLimit = (raw) => {
1034
+ if (!isRecord(raw)) {
1035
+ return void 0;
1036
+ }
1037
+ const context = raw["context"];
1038
+ const output = raw["output"];
1039
+ if (typeof context !== "number" || !Number.isInteger(context) || context <= 0 || typeof output !== "number" || !Number.isInteger(output) || output <= 0) {
1040
+ return void 0;
1041
+ }
1042
+ return { context, output };
1043
+ };
1044
+
1045
+ // src/catalog/parse-model-modalities/parse-model-modalities.ts
1046
+ var MODEL_MODALITIES = /* @__PURE__ */ new Set([
1047
+ "text",
1048
+ "audio",
1049
+ "image",
1050
+ "video",
1051
+ "pdf"
1052
+ ]);
1053
+ var parseModelModalities = (raw) => {
1054
+ if (!isRecord(raw) || !Array.isArray(raw["input"]) || !Array.isArray(raw["output"])) {
1055
+ return void 0;
1056
+ }
1057
+ return {
1058
+ input: raw["input"].filter(
1059
+ (value) => MODEL_MODALITIES.has(value)
1060
+ ),
1061
+ output: raw["output"].filter(
1062
+ (value) => MODEL_MODALITIES.has(value)
1063
+ )
1064
+ };
1065
+ };
1066
+
1067
+ // src/catalog/parse-model-variants/parse-model-variants.ts
1068
+ var parseModelVariants = (raw) => {
1069
+ if (!isRecord(raw)) {
1070
+ return void 0;
1071
+ }
1072
+ const variants = {};
1073
+ for (const [name, value] of Object.entries(raw)) {
1074
+ if (!isRecord(value)) {
1075
+ return void 0;
1076
+ }
1077
+ variants[name] = value;
1078
+ }
1079
+ return variants;
1080
+ };
1081
+
1082
+ // src/catalog/extract-catalog-model-broadcast/extract-catalog-model-broadcast.ts
1083
+ var extractCatalogModelBroadcast = (entry) => {
1084
+ const limit = parseModelLimit(entry["limits"]);
1085
+ const capabilities = parseModelCapabilities(entry["capabilities"]);
1086
+ const variants = parseModelVariants(entry["variants"]);
1087
+ const modalities = parseModelModalities(entry["modalities"]);
1088
+ return {
1089
+ ...limit === void 0 ? {} : { limit },
1090
+ ...capabilities === void 0 ? {} : { capabilities },
1091
+ ...variants === void 0 ? {} : { variants },
1092
+ ...typeof entry["hasZdrLane"] === "boolean" ? { hasZdrLane: entry["hasZdrLane"] } : {},
1093
+ ...modalities === void 0 ? {} : { modalities },
1094
+ ...typeof entry["attachment"] === "boolean" ? { attachment: entry["attachment"] } : {}
1095
+ };
1096
+ };
1097
+
1098
+ // src/catalog/per-million-rate/per-million-rate.ts
1099
+ var perMillionRate = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
1100
+
1101
+ // src/catalog/extract-models-dev-pricing/extract-models-dev-pricing.ts
1102
+ var extractModelsDevPricing = (raw) => {
1103
+ const input = perMillionRate(raw["input"]);
1104
+ const output = perMillionRate(raw["output"]);
1105
+ if (input === void 0 || output === void 0) {
1106
+ return void 0;
1107
+ }
1108
+ const rawCacheRead = raw["cache_read"];
1109
+ const rawCacheWrite = raw["cache_write"];
1110
+ const cacheRead = perMillionRate(rawCacheRead);
1111
+ const cacheWrite = perMillionRate(rawCacheWrite);
1112
+ if (rawCacheRead !== void 0 && cacheRead === void 0 || rawCacheWrite !== void 0 && cacheWrite === void 0) {
1113
+ return void 0;
1114
+ }
1115
+ return {
1116
+ input,
1117
+ output,
1118
+ currency: "USD",
1119
+ ...cacheRead === void 0 ? {} : { cache_read: cacheRead },
1120
+ ...cacheWrite === void 0 ? {} : { cache_write: cacheWrite }
1121
+ };
1122
+ };
1123
+
1124
+ // src/catalog/per-token-rate/per-token-rate.ts
1125
+ var perTokenRate = (value) => {
1126
+ if (typeof value !== "string" || value.trim() === "") {
1127
+ return void 0;
1128
+ }
1129
+ const parsed = Number(value);
1130
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
1131
+ };
1132
+
1133
+ // src/catalog/extract-open-router-pricing/extract-open-router-pricing.ts
1134
+ var extractOpenRouterPricing = (raw) => {
1135
+ const input = perTokenRate(raw["prompt"]);
1136
+ const output = perTokenRate(raw["completion"]);
1137
+ if (input === void 0 || output === void 0) {
1138
+ return void 0;
1139
+ }
1140
+ const rawCacheRead = raw["input_cache_read"];
1141
+ const rawCacheWrite = raw["input_cache_write"];
1142
+ const cacheRead = perTokenRate(rawCacheRead);
1143
+ const cacheWrite = perTokenRate(rawCacheWrite);
1144
+ if (rawCacheRead !== void 0 && cacheRead === void 0 || rawCacheWrite !== void 0 && cacheWrite === void 0) {
1145
+ return void 0;
1146
+ }
1147
+ return {
1148
+ input: Number((input * 1e6).toPrecision(12)),
1149
+ output: Number((output * 1e6).toPrecision(12)),
1150
+ currency: "USD",
1151
+ ...cacheRead === void 0 ? {} : { cache_read: Number((cacheRead * 1e6).toPrecision(12)) },
1152
+ ...cacheWrite === void 0 ? {} : { cache_write: Number((cacheWrite * 1e6).toPrecision(12)) }
1153
+ };
1154
+ };
1155
+
1156
+ // src/catalog/extract-pricing/extract-pricing.ts
1157
+ var OPEN_ROUTER_PRICING_KEYS = [
1158
+ "prompt",
1159
+ "completion",
1160
+ "request",
1161
+ "input_cache_read",
1162
+ "input_cache_write"
1163
+ ];
1164
+ var MODELS_DEV_PRICING_KEYS = [
1165
+ "input",
1166
+ "output",
1167
+ "cache_read",
1168
+ "cache_write"
1169
+ ];
1170
+ var extractPricing = (raw) => {
1171
+ if (!isRecord(raw) || raw["currency"] !== void 0 && raw["currency"] !== "USD") {
1172
+ return void 0;
1173
+ }
1174
+ const hasOpenRouterKeys = OPEN_ROUTER_PRICING_KEYS.some((key) => key in raw);
1175
+ const hasModelsDevKeys = MODELS_DEV_PRICING_KEYS.some((key) => key in raw);
1176
+ if (hasOpenRouterKeys === hasModelsDevKeys) {
1177
+ return void 0;
1178
+ }
1179
+ return hasOpenRouterKeys ? extractOpenRouterPricing(raw) : extractModelsDevPricing(raw);
1180
+ };
1181
+
1182
+ // src/catalog/extract-catalog-model-metadata/extract-catalog-model-metadata.ts
1183
+ var extractCatalogModelMetadata = (entry) => {
1184
+ const displayName = typeof entry["display_name"] === "string" ? entry["display_name"].trim() : "";
1185
+ const pricing = isRecord(entry["pricing"]) && extractPricing(entry["pricing"]) !== void 0 ? entry["pricing"] : void 0;
1186
+ return {
1187
+ ...displayName === "" ? {} : { displayName },
1188
+ ...pricing === void 0 ? {} : { pricing }
1189
+ };
1190
+ };
1191
+
1192
+ // src/catalog/normalize-model-id/normalize-model-id.ts
1193
+ var normalizeId = (raw, disableShim = false) => {
1194
+ const id = raw.trim();
1195
+ if (id === "") {
1196
+ logger.warn("dropping empty model id");
1197
+ return void 0;
1198
+ }
1199
+ if (!id.includes(":")) return id;
1200
+ const match = disableShim ? null : /^([^:/]+):global:global:([^:]+):(.+)$/.exec(id);
1201
+ if (match?.[2] !== void 0 && match[3] !== void 0)
1202
+ return `${match[2]}/${match[3]}`;
1203
+ logger.warn(`dropping colon-form model id ${id}`);
1204
+ return void 0;
1205
+ };
1206
+
1207
+ // src/catalog/parse-catalog-model/parse-catalog-model.ts
1208
+ var parseCatalogModel = (entry, disableIdShim = false) => {
1209
+ if (!isRecord(entry) || typeof entry["id"] !== "string") {
1210
+ return void 0;
1211
+ }
1212
+ const id = normalizeId(entry["id"], disableIdShim);
1213
+ if (id === void 0) {
1214
+ return void 0;
1215
+ }
1216
+ return {
1217
+ id,
1218
+ ...extractCatalogModelMetadata(entry),
1219
+ ...extractCatalogModelBroadcast(entry)
1220
+ };
1221
+ };
1222
+
1223
+ // src/catalog/to-catalog-models/to-catalog-models.ts
1224
+ var toCatalogModels = (entries, disableIdShim = false) => {
1225
+ const models = {};
1226
+ for (const entry of entries) {
1227
+ const model = parseCatalogModel(entry, disableIdShim);
1228
+ if (model === void 0 || models[model.id] !== void 0) {
1229
+ continue;
1230
+ }
1231
+ models[model.id] = model;
1232
+ }
1233
+ return models;
1234
+ };
1235
+
1236
+ // src/catalog/fetch-catalog/fetch-catalog.ts
1237
+ var fetchCatalog = async (options) => {
1238
+ const controller = new AbortController();
1239
+ const timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
1240
+ const timer = setTimeout(() => {
1241
+ controller.abort();
1242
+ }, timeoutMs);
1243
+ const url = catalogModelsUrl(options.baseURL);
1244
+ try {
1245
+ let response;
1246
+ try {
1247
+ response = await (options.fetchImpl ?? fetch)(url, {
1248
+ headers: { Authorization: `Bearer ${options.gatewayKey.value}` },
1249
+ signal: controller.signal
1250
+ });
1251
+ } catch (error) {
1252
+ throw new CatalogFetchError(
1253
+ controller.signal.aborted ? "timeout" : "network",
1254
+ error instanceof Error ? error.message : String(error)
1255
+ );
1256
+ }
1257
+ if (!response.ok) {
1258
+ throw new CatalogFetchError(
1259
+ "http",
1260
+ `${url} responded ${String(response.status)}`,
1261
+ response.status
1262
+ );
1263
+ }
1264
+ let payload;
1265
+ try {
1266
+ payload = await response.json();
1267
+ } catch {
1268
+ throw new CatalogFetchError(
1269
+ controller.signal.aborted ? "timeout" : "parse",
1270
+ controller.signal.aborted ? `body not read within ${String(timeoutMs)}ms` : "response body is not valid JSON"
1271
+ );
1272
+ }
1273
+ const models = toCatalogModels(
1274
+ parseCatalogEntries(payload),
1275
+ options.disableIdShim
1276
+ );
1277
+ logger.info(
1278
+ `fetched ${String(Object.keys(models).length)} model(s) from ${url}`
1279
+ );
1280
+ return models;
1281
+ } finally {
1282
+ clearTimeout(timer);
1283
+ }
1284
+ };
1285
+
1286
+ // src/catalog/none-catalog-result/none-catalog-result.ts
1287
+ var noneCatalogResult = (reason, intentionalOptOut) => {
1288
+ const message = `route33: no model catalog available \u2014 0 models injected (${reason}). route33 is unusable without a catalog: resolve an API key (opencode auth login / ROUTE33_API_KEY) \u2014 the key dictates which models are available.`;
1289
+ if (intentionalOptOut) {
1290
+ logger.info(message);
1291
+ } else {
1292
+ logger.warn(message);
1293
+ }
1294
+ return { models: {}, source: "none" };
1295
+ };
1296
+
1297
+ // src/catalog/catalog-service/catalog-service.ts
1298
+ var getCatalog = async (options) => {
1299
+ try {
1300
+ if (options.discoveryEnabled === false) {
1301
+ return noneCatalogResult(
1302
+ "discovery disabled via ROUTE33_DISCOVERY=0",
1303
+ true
1304
+ );
1305
+ }
1306
+ if (options.gatewayKey === void 0) {
1307
+ return noneCatalogResult("no API key resolved", false);
1308
+ }
1309
+ const cacheOptions = buildCacheReadOptions({
1310
+ baseURL: options.baseURL,
1311
+ cacheDir: options.cacheDir,
1312
+ catalogTtlMs: options.catalogTtlMs,
1313
+ gatewayKey: options.gatewayKey,
1314
+ now: options.now
1315
+ });
1316
+ const fresh = readFreshCatalog(cacheOptions);
1317
+ if (fresh !== void 0) {
1318
+ logger.info(
1319
+ `catalog source: cache (${String(Object.keys(fresh).length)} model(s))`
1320
+ );
1321
+ return { models: fresh, source: "cache" };
1322
+ }
1323
+ try {
1324
+ const live = await fetchCatalog(
1325
+ buildFetchCatalogOptions({
1326
+ baseURL: options.baseURL,
1327
+ disableIdShim: options.disableIdShim,
1328
+ fetchImpl: options.fetchImpl,
1329
+ gatewayKey: options.gatewayKey
1330
+ })
1331
+ );
1332
+ if (Object.keys(live).length === 0) {
1333
+ throw new CatalogFetchError(
1334
+ "parse",
1335
+ "gateway returned an empty catalog"
1336
+ );
1337
+ }
1338
+ writeCatalog({ ...cacheOptions, models: live });
1339
+ logger.info(
1340
+ `catalog source: live (${String(Object.keys(live).length)} model(s))`
1341
+ );
1342
+ return { models: live, source: "live" };
1343
+ } catch (error) {
1344
+ logger.warn(
1345
+ `live catalog fetch failed \u2014 trying stale cache: ${error instanceof Error ? error.message : String(error)}`
1346
+ );
1347
+ }
1348
+ const stale = readStaleCatalog(cacheOptions);
1349
+ if (stale !== void 0) {
1350
+ logger.info(
1351
+ `catalog source: stale-cache (${String(Object.keys(stale).length)} model(s))`
1352
+ );
1353
+ return { models: stale, source: "stale-cache" };
1354
+ }
1355
+ return {
1356
+ ...noneCatalogResult("live fetch failed and no cache available", false),
1357
+ liveFetchFailed: true
1358
+ };
1359
+ } catch (error) {
1360
+ logger.error(
1361
+ `unexpected catalog-service failure \u2014 no catalog available: ${error instanceof Error ? error.message : String(error)}`
1362
+ );
1363
+ return noneCatalogResult("unexpected internal failure", false);
1364
+ }
1365
+ };
1366
+
1367
+ // src/enrich/resolve-capabilities/resolve-capabilities.ts
1368
+ var resolveCapabilities = (catalogModel, modelsDevLookup) => {
1369
+ const catalogCapabilities = catalogModel?.capabilities ?? {};
1370
+ const modelsDevCapabilities = modelsDevLookup ?? {};
1371
+ const candidates = [
1372
+ [
1373
+ "reasoning",
1374
+ catalogCapabilities.reasoning ?? modelsDevCapabilities.reasoning
1375
+ ],
1376
+ [
1377
+ "tool_call",
1378
+ catalogCapabilities.tool_call ?? modelsDevCapabilities.tool_call
1379
+ ],
1380
+ ["attachment", modelsDevCapabilities.attachment],
1381
+ ["temperature", modelsDevCapabilities.temperature]
1382
+ ];
1383
+ const result = {};
1384
+ for (const [key, value] of candidates) {
1385
+ if (value !== void 0) {
1386
+ result[key] = value;
1387
+ }
1388
+ }
1389
+ return result;
1390
+ };
1391
+
1392
+ // src/enrich/resolve-model-name/resolve-model-name.ts
1393
+ var resolveModelName = (slug, catalogModel) => catalogModel?.id === slug && catalogModel.displayName !== void 0 ? catalogModel.displayName : slug;
1394
+
1395
+ // src/enrich/build-model-meta/build-model-meta.ts
1396
+ var buildModelMeta = (options) => {
1397
+ const meta = {
1398
+ name: resolveModelName(options.slug, options.catalogModel),
1399
+ capabilities: resolveCapabilities(
1400
+ options.catalogModel,
1401
+ options.modelsDevLookup
1402
+ )
1403
+ };
1404
+ let attachment = options.modelsDevLookup?.attachment;
1405
+ if (options.catalogModel !== void 0) {
1406
+ if (options.catalogModel.modalities !== void 0) {
1407
+ meta.modalities = options.catalogModel.modalities;
1408
+ }
1409
+ if (options.catalogModel.attachment !== void 0) {
1410
+ attachment = options.catalogModel.attachment;
1411
+ }
1412
+ if (options.catalogModel.variants !== void 0) {
1413
+ meta.variants = options.catalogModel.variants;
1414
+ }
1415
+ }
1416
+ if (attachment !== void 0) {
1417
+ meta.attachment = attachment;
1418
+ }
1419
+ if (options.limit !== void 0) {
1420
+ meta.limit = options.limit;
1421
+ }
1422
+ if (options.cost !== void 0) {
1423
+ meta.cost = options.cost;
1424
+ }
1425
+ return meta;
1426
+ };
1427
+
1428
+ // src/enrich/report-metadata-gaps/report-metadata-gaps.ts
1429
+ var reportMetadataGaps = (report) => {
1430
+ if (report.limit === void 0) {
1431
+ if (report.catalogPresent) {
1432
+ logger.warn(
1433
+ `limit metadata unavailable for ${report.slug} \u2014 no context/output ceiling will be enforced until added`
1434
+ );
1435
+ } else {
1436
+ logger.info(
1437
+ `not in the current gateway catalog \u2014 serving cached metadata for ${report.slug}`
1438
+ );
1439
+ }
1440
+ }
1441
+ if (report.cost === void 0) {
1442
+ logger.warn(
1443
+ `cost metadata unavailable for ${report.slug} \u2014 reported cost will be $0 until added`
1444
+ );
1445
+ }
1446
+ };
1447
+
1448
+ // src/enrich/resolve-cost/resolve-cost.ts
1449
+ var resolveCost = (catalogModel, modelsDevLookup) => {
1450
+ const catalogCost = catalogModel?.pricing === void 0 ? void 0 : extractPricing(catalogModel.pricing);
1451
+ return catalogCost ?? modelsDevLookup?.cost;
1452
+ };
1453
+
1454
+ // src/enrich/resolve-limit/resolve-limit.ts
1455
+ var resolveLimit = (catalogModel, modelsDevLookup) => catalogModel?.limit ?? modelsDevLookup?.limit;
1456
+
1457
+ // src/enrich/enrich-model/enrich-model.ts
1458
+ var enrichModel = (slug, sources) => {
1459
+ const modelsDevLookup = sources.modelsDev.lookup(slug);
1460
+ const catalogModel = sources.catalogModel;
1461
+ const catalogPresent = sources.catalogPresent ?? catalogModel !== void 0;
1462
+ const limit = resolveLimit(catalogModel, modelsDevLookup);
1463
+ const cost = resolveCost(catalogModel, modelsDevLookup);
1464
+ reportMetadataGaps({ slug, catalogPresent, limit, cost });
1465
+ return buildModelMeta({ slug, catalogModel, modelsDevLookup, limit, cost });
1466
+ };
1467
+
1468
+ // src/enrich/models-dev/load-models-dev/load-models-dev.ts
1469
+ import * as path5 from "node:path";
1470
+
1471
+ // src/enrich/models-dev/is-expressible-context-tier/is-expressible-context-tier.ts
1472
+ var EXPRESSIBLE_TIER_SIZE = 2e5;
1473
+ var isExpressibleContextTier = (tier) => {
1474
+ const marker = tier["tier"];
1475
+ return isRecord(marker) && marker["type"] === "context" && marker["size"] === EXPRESSIBLE_TIER_SIZE;
1476
+ };
1477
+
1478
+ // src/enrich/models-dev/num/num.ts
1479
+ var num = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
1480
+
1481
+ // src/enrich/models-dev/max-rate/max-rate.ts
1482
+ var maxRate = (current, candidate) => {
1483
+ const rate = num(candidate);
1484
+ if (rate === void 0) {
1485
+ return current;
1486
+ }
1487
+ return current === void 0 || rate > current ? rate : current;
1488
+ };
1489
+
1490
+ // src/enrich/models-dev/parse-rate-block/parse-rate-block.ts
1491
+ var parseRateBlock = (value) => {
1492
+ if (!isRecord(value)) {
1493
+ return void 0;
1494
+ }
1495
+ const input = num(value["input"]);
1496
+ const output = num(value["output"]);
1497
+ if (input === void 0 || output === void 0) {
1498
+ return void 0;
1499
+ }
1500
+ const cacheRead = num(value["cache_read"]);
1501
+ const cacheWrite = num(value["cache_write"]);
1502
+ return {
1503
+ input,
1504
+ output,
1505
+ ...cacheRead === void 0 ? {} : { cache_read: cacheRead },
1506
+ ...cacheWrite === void 0 ? {} : { cache_write: cacheWrite }
1507
+ };
1508
+ };
1509
+
1510
+ // src/enrich/models-dev/collapse-cost-tiers/collapse-cost-tiers.ts
1511
+ var collapseCostTiers = (cost, tiers) => {
1512
+ const collapsed = { ...cost };
1513
+ for (const tier of tiers) {
1514
+ if (isExpressibleContextTier(tier)) {
1515
+ if (collapsed.context_over_200k === void 0) {
1516
+ const preciseTier = parseRateBlock(tier);
1517
+ if (preciseTier !== void 0) {
1518
+ collapsed.context_over_200k = preciseTier;
1519
+ }
1520
+ }
1521
+ continue;
1522
+ }
1523
+ collapsed.input = maxRate(collapsed.input, tier["input"]) ?? collapsed.input;
1524
+ collapsed.output = maxRate(collapsed.output, tier["output"]) ?? collapsed.output;
1525
+ const cacheRead = maxRate(collapsed.cache_read, tier["cache_read"]);
1526
+ const cacheWrite = maxRate(collapsed.cache_write, tier["cache_write"]);
1527
+ if (cacheRead !== void 0) {
1528
+ collapsed.cache_read = cacheRead;
1529
+ }
1530
+ if (cacheWrite !== void 0) {
1531
+ collapsed.cache_write = cacheWrite;
1532
+ }
1533
+ }
1534
+ return collapsed;
1535
+ };
1536
+
1537
+ // src/enrich/models-dev/normalize-cost/normalize-cost.ts
1538
+ var normalizeCost = (raw) => {
1539
+ if (!isRecord(raw)) {
1540
+ return void 0;
1541
+ }
1542
+ const baseInput = num(raw["input"]);
1543
+ const baseOutput = num(raw["output"]);
1544
+ if (baseInput === void 0 || baseOutput === void 0) {
1545
+ return void 0;
1546
+ }
1547
+ const cacheRead = num(raw["cache_read"]);
1548
+ const cacheWrite = num(raw["cache_write"]);
1549
+ const contextOver200k = parseRateBlock(raw["context_over_200k"]);
1550
+ const cost = {
1551
+ input: baseInput,
1552
+ output: baseOutput,
1553
+ ...cacheRead === void 0 ? {} : { cache_read: cacheRead },
1554
+ ...cacheWrite === void 0 ? {} : { cache_write: cacheWrite },
1555
+ ...contextOver200k === void 0 ? {} : { context_over_200k: contextOver200k }
1556
+ };
1557
+ const tiers = Array.isArray(raw["tiers"]) ? raw["tiers"].filter(isRecord) : [];
1558
+ return collapseCostTiers(cost, tiers);
1559
+ };
1560
+
1561
+ // src/enrich/models-dev/normalize-model-limit/normalize-model-limit.ts
1562
+ var normalizeModelLimit = (raw) => {
1563
+ if (!isRecord(raw)) {
1564
+ return void 0;
1565
+ }
1566
+ const context = num(raw["context"]);
1567
+ const output = num(raw["output"]);
1568
+ if (context === void 0 || output === void 0) {
1569
+ return void 0;
1570
+ }
1571
+ const input = num(raw["input"]);
1572
+ return {
1573
+ context,
1574
+ output,
1575
+ ...input === void 0 ? {} : { input }
1576
+ };
1577
+ };
1578
+
1579
+ // src/enrich/models-dev/build-models-dev-lookup/build-models-dev-lookup.ts
1580
+ var buildModelsDevLookup = (model) => {
1581
+ const cost = normalizeCost(model["cost"]);
1582
+ const limit = normalizeModelLimit(model["limit"]);
1583
+ const reasoning = model["reasoning"];
1584
+ const toolCall = model["tool_call"];
1585
+ const attachment = model["attachment"];
1586
+ const temperature = model["temperature"];
1587
+ return {
1588
+ ...cost === void 0 ? {} : { cost },
1589
+ ...limit === void 0 ? {} : { limit },
1590
+ ...typeof reasoning === "boolean" ? { reasoning } : {},
1591
+ ...typeof toolCall === "boolean" ? { tool_call: toolCall } : {},
1592
+ ...typeof attachment === "boolean" ? { attachment } : {},
1593
+ ...typeof temperature === "boolean" ? { temperature } : {}
1594
+ };
1595
+ };
1596
+
1597
+ // src/enrich/models-dev/swap-last/swap-last.ts
1598
+ var swapLast = (value, from, to) => {
1599
+ const index = value.lastIndexOf(from);
1600
+ return index === -1 ? value : `${value.slice(0, index)}${to}${value.slice(index + from.length)}`;
1601
+ };
1602
+
1603
+ // src/enrich/models-dev/vendor-aliases/vendor-aliases.ts
1604
+ var VENDOR_ALIASES = {
1605
+ "z-ai": "zai"
1606
+ };
1607
+
1608
+ // src/enrich/models-dev/probe-candidates/probe-candidates.ts
1609
+ var probeCandidates = (slug) => {
1610
+ const separatorIndex = slug.indexOf("/");
1611
+ if (separatorIndex <= 0 || separatorIndex >= slug.length - 1) {
1612
+ return [];
1613
+ }
1614
+ const vendor = slug.slice(0, separatorIndex);
1615
+ const model = slug.slice(separatorIndex + 1);
1616
+ const alias = VENDOR_ALIASES[vendor];
1617
+ const vendors = alias === void 0 || alias === vendor ? [vendor] : [vendor, alias];
1618
+ const swaps = [];
1619
+ for (const candidate of [
1620
+ model.replaceAll(".", "-"),
1621
+ model.replaceAll("-", "."),
1622
+ swapLast(model, ".", "-"),
1623
+ swapLast(model, "-", ".")
1624
+ ]) {
1625
+ if (candidate !== model && !swaps.includes(candidate)) {
1626
+ swaps.push(candidate);
1627
+ }
1628
+ }
1629
+ return [
1630
+ ...vendors.map((provider) => [provider, model]),
1631
+ ...vendors.flatMap(
1632
+ (provider) => swaps.map((candidate) => [provider, candidate])
1633
+ )
1634
+ ];
1635
+ };
1636
+
1637
+ // src/enrich/models-dev/lookup/lookup.ts
1638
+ var lookupSlug = (data, slug) => {
1639
+ for (const [providerKey, modelKey] of probeCandidates(slug)) {
1640
+ const provider = data[providerKey];
1641
+ if (!isRecord(provider) || !isRecord(provider["models"])) {
1642
+ continue;
1643
+ }
1644
+ const model = provider["models"][modelKey];
1645
+ if (isRecord(model)) {
1646
+ return buildModelsDevLookup(model);
1647
+ }
1648
+ }
1649
+ return void 0;
1650
+ };
1651
+
1652
+ // src/enrich/models-dev/create-models-dev-source/create-models-dev-source.ts
1653
+ var createModelsDevSource = (source, data) => ({
1654
+ source,
1655
+ lookup: (slug) => lookupSlug(data, slug)
1656
+ });
1657
+
1658
+ // src/enrich/models-dev/fetch-live/fetch-live.ts
1659
+ var MODELS_DEV_API_URL = "https://models.dev/api.json";
1660
+ var FETCH_TIMEOUT_MS = 5e3;
1661
+ var fetchLive = async (fetchImpl) => {
1662
+ const controller = new AbortController();
1663
+ const timer = setTimeout(() => {
1664
+ controller.abort();
1665
+ }, FETCH_TIMEOUT_MS);
1666
+ try {
1667
+ const response = await fetchImpl(MODELS_DEV_API_URL, {
1668
+ signal: controller.signal
1669
+ });
1670
+ if (!response.ok) {
1671
+ logger.warn(`models.dev responded ${String(response.status)}`);
1672
+ return void 0;
1673
+ }
1674
+ const body = await response.json();
1675
+ return isRecord(body) ? body : void 0;
1676
+ } catch (error) {
1677
+ logger.warn(
1678
+ "models.dev fetch failed:",
1679
+ error instanceof Error ? error.message : String(error)
1680
+ );
1681
+ return void 0;
1682
+ } finally {
1683
+ clearTimeout(timer);
1684
+ }
1685
+ };
1686
+
1687
+ // src/enrich/models-dev/read-models-dev-cache/read-models-dev-cache.ts
1688
+ import * as fs3 from "node:fs";
1689
+ var readModelsDevCache = (cachePath) => {
1690
+ try {
1691
+ const parsed = JSON.parse(fs3.readFileSync(cachePath, "utf8"));
1692
+ if (!isRecord(parsed)) {
1693
+ return void 0;
1694
+ }
1695
+ const fetchedAt = num(parsed["fetchedAt"]);
1696
+ const data = parsed["data"];
1697
+ if (fetchedAt === void 0 || !isRecord(data)) {
1698
+ return void 0;
1699
+ }
1700
+ return { fetchedAt, data };
1701
+ } catch {
1702
+ return void 0;
1703
+ }
1704
+ };
1705
+
1706
+ // src/enrich/models-dev/write-models-dev-cache/write-models-dev-cache.ts
1707
+ import * as fs4 from "node:fs";
1708
+ import * as path4 from "node:path";
1709
+ var writeModelsDevCache = (cachePath, envelope) => {
1710
+ try {
1711
+ fs4.mkdirSync(path4.dirname(cachePath), { recursive: true });
1712
+ fs4.writeFileSync(cachePath, JSON.stringify(envelope), "utf8");
1713
+ } catch (error) {
1714
+ logger.warn(
1715
+ "failed to write models.dev cache:",
1716
+ error instanceof Error ? error.message : String(error)
1717
+ );
1718
+ }
1719
+ };
1720
+
1721
+ // src/enrich/models-dev/load-models-dev/load-models-dev.ts
1722
+ var CACHE_FILE = "models-dev.json";
1723
+ var loadModelsDev = async (options = {}) => {
1724
+ const fetchImpl = options.fetchImpl ?? fetch;
1725
+ const cacheDir = options.cacheDir ?? resolveCacheDir({});
1726
+ const ttlMs = options.ttlMs ?? MODELS_DEV_TTL_MS;
1727
+ const now = options.now ?? Date.now;
1728
+ const cachePath = path5.join(cacheDir, CACHE_FILE);
1729
+ const cached = readModelsDevCache(cachePath);
1730
+ if (cached !== void 0 && now() - cached.fetchedAt < ttlMs) {
1731
+ return createModelsDevSource("cache", cached.data);
1732
+ }
1733
+ const live = await fetchLive(fetchImpl);
1734
+ if (live !== void 0) {
1735
+ writeModelsDevCache(cachePath, { fetchedAt: now(), data: live });
1736
+ return createModelsDevSource("live", live);
1737
+ }
1738
+ if (cached !== void 0) {
1739
+ logger.warn("models.dev unreachable \u2014 serving stale cache");
1740
+ return createModelsDevSource("stale-cache", cached.data);
1741
+ }
1742
+ logger.warn(
1743
+ "models.dev unavailable (no network, no cache) \u2014 enrichment source disabled"
1744
+ );
1745
+ return { source: null, lookup: () => void 0 };
1746
+ };
1747
+
1748
+ // src/config/enrich-catalog/enrich-catalog.ts
1749
+ var enrichCatalog = (catalog, modelsDev) => {
1750
+ const enriched = {};
1751
+ for (const catalogModel of Object.values(catalog.models)) {
1752
+ enriched[catalogModel.id] = enrichModel(catalogModel.id, {
1753
+ catalogModel,
1754
+ catalogPresent: true,
1755
+ modelsDev
1756
+ });
1757
+ }
1758
+ return enriched;
1759
+ };
1760
+
1761
+ // src/config/merge-provider/merge-provider.ts
1762
+ var mergeProvider = (target, patch) => {
1763
+ target.npm ??= patch.npm;
1764
+ target.name ??= patch.name;
1765
+ if (target.options === void 0) {
1766
+ target.options = { ...patch.options };
1767
+ return;
1768
+ }
1769
+ for (const [field, value] of Object.entries(patch.options)) {
1770
+ const forced = field === "baseURL" || field === "headers" || field === "apiKey" && value !== NATIVE_SDK_API_KEY_PLACEHOLDER;
1771
+ if (forced || target.options[field] === void 0) {
1772
+ target.options[field] = value;
1773
+ }
1774
+ }
1775
+ };
1776
+
1777
+ // src/config/merge-config/merge-config.ts
1778
+ var mergeConfig = (config, blocks) => {
1779
+ config.provider ??= {};
1780
+ const target = config.provider.route_33 ?? {};
1781
+ config.provider.route_33 = target;
1782
+ mergeProvider(target, blocks.route_33);
1783
+ };
1784
+
1785
+ // src/config/regenerate-models/regenerate-models.ts
1786
+ var regenerateModels = (input) => {
1787
+ if (input.source === "none" && input.failedLiveFetch === true) {
1788
+ const current = Object.fromEntries(
1789
+ Object.entries(input.currentModels ?? {}).filter(
1790
+ (entry) => entry[1] !== void 0
1791
+ ).map(([key, entry]) => [key, structuredClone(entry)])
1792
+ );
1793
+ return { models: current, prunedKeys: [], skipped: true };
1794
+ }
1795
+ const models = Object.fromEntries(
1796
+ Object.entries(input.freshModels).map(([key, entry]) => [
1797
+ key,
1798
+ structuredClone(entry)
1799
+ ])
1800
+ );
1801
+ const prunedKeys = Object.keys(input.currentModels ?? {}).filter((key) => input.freshModels[key] === void 0).sort((left, right) => left.localeCompare(right));
1802
+ return { models, prunedKeys };
1803
+ };
1804
+
1805
+ // src/config/remove-legacy-manifest/remove-legacy-manifest.ts
1806
+ import * as fs5 from "node:fs";
1807
+ import * as path6 from "node:path";
1808
+ var removeLegacyManifest = (root) => {
1809
+ const file = path6.join(root, ".opencode", "route33-generated.json");
1810
+ try {
1811
+ if (!fs5.existsSync(file)) {
1812
+ return;
1813
+ }
1814
+ fs5.rmSync(file);
1815
+ logger.info(
1816
+ "route_33: removed obsolete route33-generated.json (regeneration is stateless since 0.4.4)"
1817
+ );
1818
+ } catch (error) {
1819
+ logger.info(
1820
+ `route_33: unable to remove legacy route33-generated.json: ${error instanceof Error ? error.message : String(error)}`
1821
+ );
1822
+ }
1823
+ };
1824
+
1825
+ // src/config/resolve-provider-base-url/resolve-provider-base-url.ts
1826
+ var resolveProviderBaseUrl = (config, override) => {
1827
+ if (override !== void 0) {
1828
+ return override;
1829
+ }
1830
+ const configured = config.provider?.route_33?.options?.["baseURL"];
1831
+ return typeof configured === "string" && configured.trim() !== "" && !configured.startsWith("{env:") ? configured : DEFAULT_BASE_URL;
1832
+ };
1833
+
1834
+ // src/config/configure-route33/configure-route33.ts
1835
+ var configureRoute33 = async (config, options) => {
1836
+ removeLegacyManifest(options.cwd);
1837
+ const gatewayKey = await options.credentialProvider();
1838
+ const baseURL = resolveProviderBaseUrl(config, options.baseURL);
1839
+ const buildCatalogOptions = () => ({
1840
+ baseURL,
1841
+ cacheDir: options.cacheDir,
1842
+ ...options.catalogTtlMs === void 0 ? {} : { catalogTtlMs: options.catalogTtlMs },
1843
+ ...options.disableIdShim === void 0 ? {} : { disableIdShim: options.disableIdShim },
1844
+ ...options.discoveryEnabled === void 0 ? {} : { discoveryEnabled: options.discoveryEnabled },
1845
+ ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl },
1846
+ ...gatewayKey === void 0 ? {} : { gatewayKey }
1847
+ });
1848
+ const buildModelsDevOptions = () => ({
1849
+ cacheDir: options.cacheDir,
1850
+ ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl }
1851
+ });
1852
+ const catalog = await getCatalog(buildCatalogOptions());
1853
+ const modelsDev = await loadModelsDev(buildModelsDevOptions());
1854
+ const blocks = buildProviderBlocks(enrichCatalog(catalog, modelsDev), {
1855
+ baseURL
1856
+ });
1857
+ const mergeableConfig = config;
1858
+ mergeConfig(mergeableConfig, blocks);
1859
+ const provider = mergeableConfig.provider?.route_33;
1860
+ if (provider !== void 0) {
1861
+ const regeneration = regenerateModels({
1862
+ currentModels: provider.models,
1863
+ failedLiveFetch: catalog.liveFetchFailed,
1864
+ freshModels: blocks.route_33.models,
1865
+ source: catalog.source
1866
+ });
1867
+ provider.models = regeneration.models;
1868
+ if (regeneration.skipped === true) {
1869
+ logger.info(
1870
+ "route_33: catalog fetch failed without a cache; preserving existing model entries"
1871
+ );
1872
+ } else {
1873
+ for (const key of regeneration.prunedKeys) {
1874
+ logger.info(
1875
+ `route_33: dropped model entry '${key}' (not in the gateway catalog)`
1876
+ );
1877
+ }
1878
+ }
1879
+ }
1880
+ return {
1881
+ catalogAvailable: catalog.source !== "none",
1882
+ keyResolved: gatewayKey !== void 0
1883
+ };
1884
+ };
1885
+
1886
+ // src/config/gateway-credential-error/gateway-credential-error.ts
1887
+ var GatewayCredentialError = class extends Error {
1888
+ constructor(message, options) {
1889
+ super(message, options);
1890
+ this.name = "GatewayCredentialError";
1891
+ }
1892
+ };
1893
+
1894
+ // src/config/describe-missing/describe-missing.ts
1895
+ var describeMissing = (config, missing) => {
1896
+ const sections = missing.map((entry) => {
1897
+ const available = Object.keys(
1898
+ config.provider?.[entry.providerId]?.models ?? {}
1899
+ ).sort((left, right) => left.localeCompare(right)).map((key) => `${entry.providerId}/${key}`).join(", ");
1900
+ return [
1901
+ ` ${entry.ref}`,
1902
+ ` referenced by: ${entry.sources.join(", ")}`,
1903
+ ...entry.legacyReplacement === void 0 ? [] : [` rename to "${entry.legacyReplacement}"`],
1904
+ ` available on ${entry.providerId}: ${available || "(none)"}`
1905
+ ].join("\n");
1906
+ });
1907
+ return `[route_33] ${String(missing.length)} unresolvable model reference(s):
1908
+
1909
+ ${sections.join("\n\n")}`;
1910
+ };
1911
+
1912
+ // src/config/find-missing-refs/find-missing-refs.ts
1913
+ var findMissingRefs = (config, refs) => {
1914
+ const byRef = /* @__PURE__ */ new Map();
1915
+ for (const ref of refs) {
1916
+ const models = config.provider?.[ref.providerId]?.models;
1917
+ if (ref.legacyReplacement === void 0 && models?.[ref.modelKey] !== void 0) {
1918
+ continue;
1919
+ }
1920
+ const existing = byRef.get(ref.ref);
1921
+ if (existing === void 0) {
1922
+ byRef.set(ref.ref, {
1923
+ providerId: ref.providerId,
1924
+ modelKey: ref.modelKey,
1925
+ ref: ref.ref,
1926
+ sources: [ref.source],
1927
+ ...ref.legacyReplacement === void 0 ? {} : { legacyReplacement: ref.legacyReplacement }
1928
+ });
1929
+ } else if (!existing.sources.includes(ref.source)) {
1930
+ byRef.set(ref.ref, {
1931
+ ...existing,
1932
+ sources: [...existing.sources, ref.source]
1933
+ });
1934
+ }
1935
+ }
1936
+ return [...byRef.values()].sort(
1937
+ (left, right) => left.ref.localeCompare(right.ref)
1938
+ );
1939
+ };
1940
+
1941
+ // src/config/inject-stubs/inject-stubs.ts
1942
+ var injectStubs = (config, missing) => {
1943
+ config.provider ??= {};
1944
+ for (const entry of missing) {
1945
+ const provider = config.provider[entry.providerId] ?? {};
1946
+ config.provider[entry.providerId] = provider;
1947
+ provider.models ??= {};
1948
+ provider.models[entry.modelKey] = { name: entry.modelKey };
1949
+ }
1950
+ };
1951
+
1952
+ // src/config/inject-aliased/inject-aliased.ts
1953
+ var injectAliased = (config, missing, servedKey) => {
1954
+ const models = config.provider?.[missing.providerId]?.models;
1955
+ if (models === void 0) {
1956
+ return;
1957
+ }
1958
+ const served = models[servedKey];
1959
+ if (typeof served !== "object" || served === null || Array.isArray(served)) {
1960
+ return;
1961
+ }
1962
+ models[missing.modelKey] = { ...structuredClone(served), id: servedKey };
1963
+ };
1964
+
1965
+ // src/config/swap-at-digit-boundaries/swap-at-digit-boundaries.ts
1966
+ var swapAtDigitBoundaries = (tail, from, to) => {
1967
+ let result = "";
1968
+ for (let index = 0; index < tail.length; index += 1) {
1969
+ const character = tail.charAt(index);
1970
+ const previous = tail[index - 1];
1971
+ const next = tail[index + 1];
1972
+ const previousIsDigit = previous !== void 0 && previous >= "0" && previous <= "9";
1973
+ const nextIsDigit = next !== void 0 && next >= "0" && next <= "9";
1974
+ result += character === from && previousIsDigit && nextIsDigit ? to : character;
1975
+ }
1976
+ return result;
1977
+ };
1978
+
1979
+ // src/config/resolve-spelling/resolve-spelling.ts
1980
+ var resolveSpelling = (modelKey, availableKeys) => {
1981
+ const separator = modelKey.indexOf("/");
1982
+ const vendor = separator === -1 ? "" : modelKey.slice(0, separator);
1983
+ const tail = separator === -1 ? modelKey : modelKey.slice(separator + 1);
1984
+ const candidates = new Set(
1985
+ [
1986
+ swapAtDigitBoundaries(tail, ".", "-"),
1987
+ swapAtDigitBoundaries(tail, "-", ".")
1988
+ ].filter((candidate) => candidate !== tail)
1989
+ );
1990
+ if (candidates.size === 0) {
1991
+ return void 0;
1992
+ }
1993
+ const matches = availableKeys.filter((key) => {
1994
+ const keySeparator = key.indexOf("/");
1995
+ const keyVendor = keySeparator === -1 ? "" : key.slice(0, keySeparator);
1996
+ const keyTail = keySeparator === -1 ? key : key.slice(keySeparator + 1);
1997
+ return keyVendor === vendor && candidates.has(keyTail);
1998
+ });
1999
+ return matches.length === 1 ? matches[0] : void 0;
2000
+ };
2001
+
2002
+ // src/config/resolve-ref-spellings/resolve-ref-spellings.ts
2003
+ var resolveRefSpellings = (config, missing) => {
2004
+ const unresolved = [];
2005
+ for (const entry of missing) {
2006
+ const servedKey = entry.legacyReplacement === void 0 ? resolveSpelling(
2007
+ entry.modelKey,
2008
+ Object.keys(config.provider?.[entry.providerId]?.models ?? {})
2009
+ ) : void 0;
2010
+ if (servedKey === void 0) {
2011
+ unresolved.push(entry);
2012
+ continue;
2013
+ }
2014
+ injectAliased(config, entry, servedKey);
2015
+ logger.info(
2016
+ `${entry.ref} resolved to the served spelling "${entry.providerId}/${servedKey}" via dot\u2194dash tolerance \u2014 injected an aliased model entry routing to the served id`
2017
+ );
2018
+ }
2019
+ return unresolved;
2020
+ };
2021
+
2022
+ // src/config/validation-error/validation-error.ts
2023
+ var Route33ValidationError = class extends Error {
2024
+ name = "Route33ValidationError";
2025
+ missingRefs;
2026
+ constructor(message, missingRefs) {
2027
+ super(message);
2028
+ this.missingRefs = missingRefs;
2029
+ }
2030
+ };
2031
+
2032
+ // src/config/validation-remediation/validation-remediation.ts
2033
+ var VALIDATION_REMEDIATION = [
2034
+ "Remediation:",
2035
+ " 1. Set ROUTE33_STRICT=0 to downgrade this error to a warning (missing models get a name-only stub entry).",
2036
+ ' 2. Declare the model explicitly under "provider" in opencode.jsonc.',
2037
+ " 3. Verify the authenticated Route 33 account can access this model \u2014 the catalog is credential-scoped."
2038
+ ].join("\n");
2039
+
2040
+ // src/config/validate-refs/validate-refs.ts
2041
+ var validateRefs = (config, options = {}) => {
2042
+ const missing = findMissingRefs(config, collectCfgRefs(config));
2043
+ if (missing.length === 0) {
2044
+ return;
2045
+ }
2046
+ const unresolved = resolveRefSpellings(config, missing);
2047
+ if (unresolved.length === 0) {
2048
+ return;
2049
+ }
2050
+ const details = describeMissing(config, unresolved);
2051
+ const missingIds = unresolved.map((entry) => entry.ref);
2052
+ if (unresolved.some((entry) => entry.legacyReplacement !== void 0)) {
2053
+ throw new Route33ValidationError(details, missingIds);
2054
+ }
2055
+ if (options.strict === false) {
2056
+ logger.warn(
2057
+ `${details}
2058
+
2059
+ (ROUTE33_STRICT=0 \u2014 continuing with name-only stub entries)`
2060
+ );
2061
+ injectStubs(config, unresolved);
2062
+ return;
2063
+ }
2064
+ if (options.keyResolved === false) {
2065
+ logger.warn(
2066
+ `no route_33 gateway credential resolved \u2014 no model catalog available; ${String(unresolved.length)} referenced model(s) remain unavailable: ${missingIds.join(", ")}. Authenticate with Route 33, then restart. (Continuing with name-only stub entries.)`
2067
+ );
2068
+ injectStubs(config, unresolved);
2069
+ return;
2070
+ }
2071
+ if (options.catalogAvailable === false) {
2072
+ logger.warn(
2073
+ `route33 model catalog unavailable \u2014 ${String(unresolved.length)} referenced model(s) could not be validated against the credential-scoped catalog: ${missingIds.join(", ")}. Restore gateway connectivity or declare the model explicitly under "provider" in opencode.jsonc, then restart. (Continuing with name-only stub entries.)`
2074
+ );
2075
+ injectStubs(config, unresolved);
2076
+ return;
2077
+ }
2078
+ throw new Route33ValidationError(
2079
+ `${details}
2080
+
2081
+ ${VALIDATION_REMEDIATION}`,
2082
+ missingIds
2083
+ );
2084
+ };
2085
+
2086
+ // src/config/config-hook/config-hook.ts
2087
+ var createConfigHook = (options) => async (config) => {
2088
+ let state = {
2089
+ catalogAvailable: false,
2090
+ keyResolved: false
2091
+ };
2092
+ try {
2093
+ state = await configureRoute33(config, options);
2094
+ } catch (error) {
2095
+ if (error instanceof GatewayCredentialError) {
2096
+ throw error;
2097
+ }
2098
+ logger.error(
2099
+ `model discovery/injection failed unexpectedly \u2014 opencode startup continues without injected models: ${error instanceof Error ? error.message : String(error)}`
2100
+ );
2101
+ }
2102
+ try {
2103
+ validateRefs(config, {
2104
+ catalogAvailable: state.catalogAvailable,
2105
+ keyResolved: state.keyResolved,
2106
+ strict: options.strict
2107
+ });
2108
+ } catch (error) {
2109
+ if (error instanceof Route33ValidationError) {
2110
+ logger.error(error.message);
2111
+ throw error;
2112
+ }
2113
+ logger.error(
2114
+ `ref validation failed unexpectedly \u2014 skipping: ${error instanceof Error ? error.message : String(error)}`
2115
+ );
2116
+ }
2117
+ };
2118
+
2119
+ // src/key-lease/default-gateway-key-renewal-ratio/default-gateway-key-renewal-ratio.ts
2120
+ var DEFAULT_GATEWAY_KEY_RENEWAL_RATIO = 0.8;
2121
+
2122
+ // src/key-lease/default-gateway-key-ttl-ms/default-gateway-key-ttl-ms.ts
2123
+ var DEFAULT_GATEWAY_KEY_TTL_MS = 15 * 60 * 1e3;
2124
+
2125
+ // src/key-lease/file-secret-store/file-secret-store.ts
2126
+ import { randomUUID } from "node:crypto";
2127
+ import * as fs6 from "node:fs/promises";
2128
+ import * as path7 from "node:path";
2129
+ var FileSecretStore = class {
2130
+ #directory;
2131
+ #file;
2132
+ constructor(options) {
2133
+ if (options.directory.length === 0) {
2134
+ throw new TypeError("File secret store requires a directory");
2135
+ }
2136
+ if (!/^[a-zA-Z0-9._-]+$/u.test(options.scopeId)) {
2137
+ throw new TypeError("File secret store scope is not portable");
2138
+ }
2139
+ this.#directory = options.directory;
2140
+ this.#file = path7.join(options.directory, `lease-${options.scopeId}.json`);
2141
+ }
2142
+ /** Reads and parses the scoped gateway credential.
2143
+ * @returns The persisted credential, when present.
2144
+ */
2145
+ async get() {
2146
+ let contents;
2147
+ try {
2148
+ contents = await fs6.readFile(this.#file, "utf8");
2149
+ } catch (cause) {
2150
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
2151
+ return void 0;
2152
+ }
2153
+ throw cause;
2154
+ }
2155
+ const value = JSON.parse(contents);
2156
+ return parseGatewayKey(value);
2157
+ }
2158
+ /** Writes the scoped gateway credential through an atomic private file.
2159
+ * @param key - The credential to persist, or undefined to remove it.
2160
+ * @returns A promise that settles after the file write or removal.
2161
+ */
2162
+ async set(key) {
2163
+ if (key === void 0) {
2164
+ await fs6.rm(this.#file, { force: true });
2165
+ return;
2166
+ }
2167
+ await fs6.mkdir(this.#directory, { mode: 448, recursive: true });
2168
+ await fs6.chmod(this.#directory, 448);
2169
+ const temporary = path7.join(this.#directory, `.lease-${randomUUID()}.tmp`);
2170
+ try {
2171
+ await fs6.writeFile(temporary, `${JSON.stringify(key.value)}
2172
+ `, {
2173
+ encoding: "utf8",
2174
+ flag: "wx",
2175
+ mode: 384
2176
+ });
2177
+ await fs6.rename(temporary, this.#file);
2178
+ } finally {
2179
+ await fs6.rm(temporary, { force: true });
2180
+ }
2181
+ }
2182
+ };
2183
+
2184
+ // src/key-lease/host-storage-secret-store/host-storage-secret-store.ts
2185
+ var HostStorageSecretStore = class {
2186
+ #key;
2187
+ #storage;
2188
+ constructor(options) {
2189
+ this.#key = options.key;
2190
+ this.#storage = options.storage;
2191
+ }
2192
+ /** Reads and parses the scoped gateway credential.
2193
+ * @returns The persisted credential, when present.
2194
+ */
2195
+ async get() {
2196
+ const value = await this.#storage.get(this.#key);
2197
+ return value === void 0 ? void 0 : parseGatewayKey(value);
2198
+ }
2199
+ /** Writes the scoped gateway credential only through host-owned storage.
2200
+ * @param key - The credential to persist, or undefined to remove it.
2201
+ * @returns A promise that settles after the host write or removal.
2202
+ */
2203
+ set(key) {
2204
+ return key === void 0 ? this.#storage.remove(this.#key) : this.#storage.set(this.#key, key.value);
2205
+ }
2206
+ };
2207
+
2208
+ // src/key-lease/key-lease-error/key-lease-error.ts
2209
+ var REDACTED_CAUSE = "Route 33 gateway key lease dependency failed";
2210
+ var KeyLeaseError = class extends Error {
2211
+ constructor(code, options) {
2212
+ super(
2213
+ "Route 33 gateway key lease failed",
2214
+ options?.cause === void 0 ? void 0 : { cause: REDACTED_CAUSE }
2215
+ );
2216
+ this.code = code;
2217
+ this.name = "KeyLeaseError";
2218
+ }
2219
+ code;
2220
+ };
2221
+
2222
+ // src/key-lease/is-management-unauthorized/is-management-unauthorized.ts
2223
+ var isManagementUnauthorized = (cause) => {
2224
+ if (cause instanceof Response) {
2225
+ return cause.status === 401;
2226
+ }
2227
+ if (typeof cause !== "object") {
2228
+ return false;
2229
+ }
2230
+ if (cause === null) {
2231
+ return false;
2232
+ }
2233
+ if ("status" in cause && cause.status === 401) {
2234
+ return true;
2235
+ }
2236
+ if ("statusCode" in cause && cause.statusCode === 401) {
2237
+ return true;
2238
+ }
2239
+ return "response" in cause && cause.response instanceof Response && cause.response.status === 401;
2240
+ };
2241
+
2242
+ // src/key-lease/recover-lease-state/recover-lease-state.ts
2243
+ var recoverLeaseState = async (options) => {
2244
+ let keys;
2245
+ try {
2246
+ keys = (await options.managementClient.list(options.managementCredential)).data;
2247
+ } catch (cause) {
2248
+ throw new KeyLeaseError(
2249
+ isManagementUnauthorized(cause) ? "KEY_LEASE_UNAUTHORIZED" : "KEY_LEASE_MINT_FAILED",
2250
+ { cause }
2251
+ );
2252
+ }
2253
+ const matches = keys.filter((key2) => {
2254
+ if (key2.name !== options.keyName || key2.revoked || key2.status !== "active" || !Number.isFinite(Date.parse(key2.expires_at))) {
2255
+ return false;
2256
+ }
2257
+ switch (options.attribution.kind) {
2258
+ case "personal":
2259
+ return key2.ownership_type === "user_personal" && key2.project_id === null;
2260
+ case "project":
2261
+ return key2.ownership_type === "project" && key2.project_id === options.attribution.projectId;
2262
+ default: {
2263
+ const unexpected = options.attribution;
2264
+ throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
2265
+ }
2266
+ }
2267
+ });
2268
+ const key = matches.length === 1 ? matches[0] : void 0;
2269
+ if (key === void 0) {
2270
+ return void 0;
2271
+ }
2272
+ const recovered = {
2273
+ attribution: options.attribution,
2274
+ expiresAt: key.expires_at,
2275
+ keyId: key.id
2276
+ };
2277
+ return options.state.compareAndSwap(void 0, recovered) ? recovered : options.state.snapshot();
2278
+ };
2279
+
2280
+ // src/key-lease/current-lease-state/current-lease-state.ts
2281
+ var currentLeaseState = async (deps) => {
2282
+ let current = deps.state.snapshot();
2283
+ let storedKey;
2284
+ try {
2285
+ storedKey = await deps.secretStore.get();
2286
+ } catch (cause) {
2287
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
2288
+ }
2289
+ if (current === void 0 && storedKey !== void 0) {
2290
+ current = await recoverLeaseState({
2291
+ attribution: deps.attribution,
2292
+ keyName: deps.keyName,
2293
+ managementClient: deps.managementClient,
2294
+ managementCredential: deps.credential,
2295
+ state: deps.state
2296
+ });
2297
+ }
2298
+ return { current, storedKey };
2299
+ };
2300
+
2301
+ // src/key-lease/map-renewal-failure/map-renewal-failure.ts
2302
+ var mapRenewalFailure = (options) => {
2303
+ if (options.current === void 0) {
2304
+ throw options.cause;
2305
+ }
2306
+ if (options.now < Date.parse(options.current.expiresAt)) {
2307
+ throw options.cause;
2308
+ }
2309
+ if (!(options.cause instanceof KeyLeaseError)) {
2310
+ throw options.cause;
2311
+ }
2312
+ if (options.cause.code !== "KEY_LEASE_MINT_FAILED") {
2313
+ throw options.cause;
2314
+ }
2315
+ throw new KeyLeaseError("KEY_LEASE_EXPIRED", { cause: options.cause });
2316
+ };
2317
+
2318
+ // src/key-lease/expiry-ttl-ms/expiry-ttl-ms.ts
2319
+ var DAY_MS = 864e5;
2320
+ var expiryTtlMs = (ttlMs, expiryDays) => {
2321
+ const explicit = (expiryDays ?? 0) * DAY_MS;
2322
+ return explicit > 0 ? explicit : ttlMs;
2323
+ };
2324
+
2325
+ // src/key-lease/resolve-key-ownership/resolve-key-ownership.ts
2326
+ var resolveKeyOwnership = (options) => {
2327
+ switch (options.attribution.kind) {
2328
+ case "personal":
2329
+ if (options.managementSubject.length === 0) {
2330
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2331
+ }
2332
+ return {
2333
+ ownerId: options.managementSubject,
2334
+ ownerType: "user_personal",
2335
+ projectId: null
2336
+ };
2337
+ case "project":
2338
+ return {
2339
+ ownerId: options.managementSubject,
2340
+ ownerType: "user_project",
2341
+ projectId: options.attribution.projectId
2342
+ };
2343
+ default: {
2344
+ const unexpected = options.attribution;
2345
+ throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
2346
+ }
2347
+ }
2348
+ };
2349
+
2350
+ // src/key-lease/build-mint-input/build-mint-input.ts
2351
+ var buildMintInput = (deps) => {
2352
+ const ownership = resolveKeyOwnership({
2353
+ attribution: deps.attribution,
2354
+ managementSubject: deps.managementSubject
2355
+ });
2356
+ return {
2357
+ allowedModels: deps.extras?.allowedModels,
2358
+ description: deps.extras?.description,
2359
+ expiresAt: new Date(
2360
+ deps.now + expiryTtlMs(deps.ttlMs, deps.extras?.expiryDays)
2361
+ ).toISOString(),
2362
+ maxBudgetAmount: deps.extras?.maxBudgetAmount ?? null,
2363
+ name: deps.extras?.name ?? deps.keyName,
2364
+ ...ownership
2365
+ };
2366
+ };
2367
+
2368
+ // src/key-lease/mint-fresh-lease/mint-fresh-lease.ts
2369
+ var mintFreshLease = async (deps) => {
2370
+ const now = deps.clock();
2371
+ const input = buildMintInput({
2372
+ attribution: deps.attribution,
2373
+ extras: deps.extras,
2374
+ keyName: deps.keyName,
2375
+ managementSubject: deps.managementSubject,
2376
+ now,
2377
+ ttlMs: deps.ttlMs
2378
+ });
2379
+ let material;
2380
+ try {
2381
+ material = await deps.managementClient.create(
2382
+ deps.managementCredential,
2383
+ input
2384
+ );
2385
+ } catch (cause) {
2386
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", { cause });
2387
+ }
2388
+ const minted = {
2389
+ key: material.key,
2390
+ lease: {
2391
+ attribution: deps.attribution,
2392
+ expiresAt: material.expires_at,
2393
+ keyId: material.id
2394
+ }
2395
+ };
2396
+ try {
2397
+ await deps.secretStore.set(minted.key);
2398
+ } catch (cause) {
2399
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
2400
+ }
2401
+ deps.state.compareAndSwap(deps.state.snapshot(), minted.lease);
2402
+ return minted;
2403
+ };
2404
+
2405
+ // src/key-lease/orphan-control/orphan-control.ts
2406
+ var controlOrphans = async (options) => {
2407
+ const now = options.clock();
2408
+ if (!Number.isFinite(now) || !Number.isInteger(options.retentionCycles) || options.retentionCycles <= 0 || !Number.isFinite(options.ttlMs) || options.ttlMs <= 0) {
2409
+ return { kind: "unavailable" };
2410
+ }
2411
+ let keys;
2412
+ try {
2413
+ keys = await options.managementClient.list(options.managementCredential);
2414
+ } catch {
2415
+ return { kind: "unavailable" };
2416
+ }
2417
+ const staleKeys = keys.data.filter(
2418
+ (key) => key.name === options.keyName && key.id !== options.currentKeyId && Date.parse(key.expires_at) <= now
2419
+ );
2420
+ const deletions = await Promise.allSettled(
2421
+ staleKeys.map(
2422
+ (key) => Promise.resolve().then(
2423
+ () => options.managementClient.delete(options.managementCredential, key.id)
2424
+ )
2425
+ )
2426
+ );
2427
+ return {
2428
+ attempted: deletions.length,
2429
+ deleted: deletions.filter(({ status }) => status === "fulfilled").length,
2430
+ kind: "completed"
2431
+ };
2432
+ };
2433
+
2434
+ // src/key-lease/reject-lease/reject-lease.ts
2435
+ var rejectLease = async (options) => {
2436
+ const shouldClear = options.storedKey === void 0 || options.storedKey.value === options.rejection.key.value;
2437
+ if (shouldClear) {
2438
+ try {
2439
+ await options.secretStore.set(void 0);
2440
+ } catch (cause) {
2441
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
2442
+ }
2443
+ if (!options.state.clear(options.current)) {
2444
+ throw new KeyLeaseError("KEY_LEASE_RENEWAL_RACE");
2445
+ }
2446
+ }
2447
+ switch (options.rejection.kind) {
2448
+ case "expired":
2449
+ throw new KeyLeaseError("KEY_LEASE_EXPIRED");
2450
+ case "unauthorized":
2451
+ throw new KeyLeaseError("KEY_LEASE_UNAUTHORIZED");
2452
+ default: {
2453
+ const unexpected = options.rejection;
2454
+ throw new TypeError(`Unexpected lease rejection: ${String(unexpected)}`);
2455
+ }
2456
+ }
2457
+ };
2458
+
2459
+ // src/key-lease/mint-key/mint-key.ts
2460
+ var mintKey = async (options) => {
2461
+ const now = options.clock();
2462
+ if (!Number.isFinite(now)) {
2463
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2464
+ }
2465
+ if (!Number.isFinite(options.installation.ttlMs)) {
2466
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2467
+ }
2468
+ if (options.installation.ttlMs <= 0) {
2469
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2470
+ }
2471
+ if (options.installation.keyName.length === 0) {
2472
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2473
+ }
2474
+ const input = buildMintInput({
2475
+ attribution: options.attribution,
2476
+ extras: options.extras,
2477
+ keyName: options.installation.keyName,
2478
+ managementSubject: options.identity.subject,
2479
+ now,
2480
+ ttlMs: options.installation.ttlMs
2481
+ });
2482
+ let material;
2483
+ try {
2484
+ material = await options.managementClient.create(
2485
+ options.identity.credential,
2486
+ input
2487
+ );
2488
+ } catch (cause) {
2489
+ if (isManagementUnauthorized(cause)) {
2490
+ throw new KeyLeaseError("KEY_LEASE_UNAUTHORIZED", { cause });
2491
+ }
2492
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", { cause });
2493
+ }
2494
+ return {
2495
+ key: material.key,
2496
+ lease: {
2497
+ attribution: options.attribution,
2498
+ expiresAt: material.expires_at,
2499
+ keyId: material.id
2500
+ }
2501
+ };
2502
+ };
2503
+
2504
+ // src/key-lease/renew-key/renew-key.ts
2505
+ var renewals = /* @__PURE__ */ new WeakMap();
2506
+ var renewKey = async (options) => {
2507
+ const inFlight = renewals.get(options.leaseState);
2508
+ if (inFlight !== void 0) {
2509
+ return inFlight;
2510
+ }
2511
+ const expected = options.leaseState.snapshot();
2512
+ const renewal = (async () => {
2513
+ const discard = async (keyId) => {
2514
+ const cleared = options.leaseState.clear(expected);
2515
+ await Promise.allSettled([
2516
+ Promise.resolve().then(() => options.secretStore.set(void 0)),
2517
+ Promise.resolve().then(
2518
+ () => options.mint.managementClient.delete(
2519
+ options.mint.identity.credential,
2520
+ keyId
2521
+ )
2522
+ )
2523
+ ]);
2524
+ return cleared;
2525
+ };
2526
+ let renewed;
2527
+ if (expected === void 0) {
2528
+ renewed = await mintKey(options.mint);
2529
+ } else {
2530
+ try {
2531
+ const material = await options.mint.managementClient.regenerate(
2532
+ options.mint.identity.credential,
2533
+ expected.keyId,
2534
+ new Date(
2535
+ options.mint.clock() + options.mint.installation.ttlMs
2536
+ ).toISOString()
2537
+ );
2538
+ renewed = {
2539
+ key: material.key,
2540
+ lease: {
2541
+ attribution: options.mint.attribution,
2542
+ expiresAt: material.expires_at,
2543
+ keyId: expected.keyId
2544
+ }
2545
+ };
2546
+ } catch (cause) {
2547
+ const cleared = await discard(expected.keyId);
2548
+ if (!cleared) {
2549
+ throw new KeyLeaseError("KEY_LEASE_RENEWAL_RACE", { cause });
2550
+ }
2551
+ throw new KeyLeaseError(
2552
+ isManagementUnauthorized(cause) ? "KEY_LEASE_UNAUTHORIZED" : "KEY_LEASE_MINT_FAILED",
2553
+ { cause }
2554
+ );
2555
+ }
2556
+ }
2557
+ try {
2558
+ await options.secretStore.set(renewed.key);
2559
+ } catch (cause) {
2560
+ const cleared = await discard(renewed.lease.keyId);
2561
+ if (!cleared) {
2562
+ throw new KeyLeaseError("KEY_LEASE_RENEWAL_RACE", { cause });
2563
+ }
2564
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
2565
+ }
2566
+ if (!options.leaseState.compareAndSwap(expected, renewed.lease)) {
2567
+ await discard(renewed.lease.keyId);
2568
+ throw new KeyLeaseError("KEY_LEASE_RENEWAL_RACE");
2569
+ }
2570
+ return renewed;
2571
+ })();
2572
+ renewals.set(options.leaseState, renewal);
2573
+ try {
2574
+ return await renewal;
2575
+ } finally {
2576
+ if (renewals.get(options.leaseState) === renewal) {
2577
+ renewals.delete(options.leaseState);
2578
+ }
2579
+ }
2580
+ };
2581
+
2582
+ // src/key-lease/resolve-lease-policy/resolve-lease-policy.ts
2583
+ var resolveLeasePolicy = (policy) => {
2584
+ const resolved = {
2585
+ deletePreviousKey: false,
2586
+ renewalRatio: DEFAULT_GATEWAY_KEY_RENEWAL_RATIO,
2587
+ ttlMs: DEFAULT_GATEWAY_KEY_TTL_MS,
2588
+ ...policy
2589
+ };
2590
+ if (!Number.isFinite(resolved.ttlMs)) {
2591
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2592
+ }
2593
+ if (resolved.ttlMs <= 0) {
2594
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2595
+ }
2596
+ if (!Number.isFinite(resolved.renewalRatio)) {
2597
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2598
+ }
2599
+ if (resolved.renewalRatio <= 0) {
2600
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2601
+ }
2602
+ if (resolved.renewalRatio >= 1) {
2603
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2604
+ }
2605
+ if (resolved.orphanRetentionCycles === void 0) {
2606
+ return resolved;
2607
+ }
2608
+ if (!Number.isInteger(resolved.orphanRetentionCycles)) {
2609
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2610
+ }
2611
+ if (resolved.orphanRetentionCycles <= 0) {
2612
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2613
+ }
2614
+ return resolved;
2615
+ };
2616
+
2617
+ // src/key-lease/resolve-seam-value/resolve-seam-value.ts
2618
+ var resolveSeamValue = async (value) => typeof value === "function" ? value() : value;
2619
+
2620
+ // src/key-lease/reusable-lease/reusable-lease.ts
2621
+ var reusableLease = (options) => {
2622
+ if (options.current === void 0) {
2623
+ return void 0;
2624
+ }
2625
+ if (options.storedKey === void 0) {
2626
+ return void 0;
2627
+ }
2628
+ if (!options.state.matchesAttribution(options.attribution)) {
2629
+ return void 0;
2630
+ }
2631
+ const renewalAt = Date.parse(options.current.expiresAt) - options.policy.ttlMs * (1 - options.policy.renewalRatio);
2632
+ if (options.now >= renewalAt) {
2633
+ return void 0;
2634
+ }
2635
+ return { key: options.storedKey, lease: options.current };
2636
+ };
2637
+
2638
+ // src/key-lease/lease-for-attribution/lease-for-attribution.ts
2639
+ var leaseForAttribution = async (options) => {
2640
+ const policy = resolveLeasePolicy(options.policy);
2641
+ const clock = options.clock ?? Date.now;
2642
+ const now = clock();
2643
+ if (!Number.isFinite(now)) {
2644
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2645
+ }
2646
+ const { current, storedKey } = await currentLeaseState({
2647
+ attribution: options.attribution,
2648
+ credential: await resolveSeamValue(options.management.credential),
2649
+ keyName: options.installation.keyName,
2650
+ managementClient: options.management.client,
2651
+ secretStore: options.installation.secretStore,
2652
+ state: options.installation.state,
2653
+ stateStore: options.installation.stateStore
2654
+ });
2655
+ if (options.rejection !== void 0) {
2656
+ return rejectLease({
2657
+ current,
2658
+ rejection: options.rejection,
2659
+ secretStore: options.installation.secretStore,
2660
+ state: options.installation.state,
2661
+ storedKey
2662
+ });
2663
+ }
2664
+ if (options.request?.forceMint === true) {
2665
+ return mintFreshLease({
2666
+ attribution: options.attribution,
2667
+ clock,
2668
+ extras: options.request.extras,
2669
+ keyName: options.installation.keyName,
2670
+ managementClient: options.management.client,
2671
+ managementCredential: await resolveSeamValue(
2672
+ options.management.credential
2673
+ ),
2674
+ managementSubject: await resolveSeamValue(options.management.subject),
2675
+ secretStore: options.installation.secretStore,
2676
+ state: options.installation.state,
2677
+ stateStore: options.installation.stateStore,
2678
+ ttlMs: policy.ttlMs
2679
+ });
2680
+ }
2681
+ const reusable = reusableLease({
2682
+ attribution: options.attribution,
2683
+ current,
2684
+ now,
2685
+ policy,
2686
+ state: options.installation.state,
2687
+ storedKey
2688
+ });
2689
+ if (reusable !== void 0) {
2690
+ return reusable;
2691
+ }
2692
+ try {
2693
+ const renewed = await renewKey({
2694
+ leaseState: options.installation.state,
2695
+ mint: {
2696
+ attribution: options.attribution,
2697
+ clock,
2698
+ identity: {
2699
+ credential: await resolveSeamValue(options.management.credential),
2700
+ subject: await resolveSeamValue(options.management.subject)
2701
+ },
2702
+ installation: {
2703
+ keyName: options.installation.keyName,
2704
+ ttlMs: policy.ttlMs
2705
+ },
2706
+ managementClient: options.management.client
2707
+ },
2708
+ secretStore: options.installation.secretStore
2709
+ });
2710
+ if (policy.orphanRetentionCycles !== void 0) {
2711
+ await controlOrphans({
2712
+ clock,
2713
+ currentKeyId: renewed.lease.keyId,
2714
+ keyName: options.installation.keyName,
2715
+ managementClient: options.management.client,
2716
+ managementCredential: await resolveSeamValue(
2717
+ options.management.credential
2718
+ ),
2719
+ retentionCycles: policy.orphanRetentionCycles,
2720
+ ttlMs: policy.ttlMs
2721
+ });
2722
+ }
2723
+ return renewed;
2724
+ } catch (cause) {
2725
+ return mapRenewalFailure({ cause, current, now });
2726
+ }
2727
+ };
2728
+
2729
+ // src/attribution/clear-attribution/clear-attribution.ts
2730
+ import * as fs9 from "node:fs";
2731
+
2732
+ // src/attribution/resolve-attribution-file/resolve-attribution-file.ts
2733
+ import * as fs8 from "node:fs";
2734
+ import * as path9 from "node:path";
2735
+
2736
+ // src/attribution/detect-worktree-root/detect-worktree-root.ts
2737
+ import * as fs7 from "node:fs";
2738
+ import * as path8 from "node:path";
2739
+ var detectWorktreeRoot = (startDirectory) => {
2740
+ let directory = fs7.realpathSync(startDirectory);
2741
+ for (; ; ) {
2742
+ const gitEntry = path8.join(directory, ".git");
2743
+ if (fs7.existsSync(gitEntry)) {
2744
+ const entry = fs7.statSync(gitEntry);
2745
+ if (entry.isDirectory() || entry.isFile()) {
2746
+ return directory;
2747
+ }
2748
+ }
2749
+ const parent = path8.dirname(directory);
2750
+ if (parent === directory) {
2751
+ return void 0;
2752
+ }
2753
+ directory = parent;
2754
+ }
2755
+ };
2756
+
2757
+ // src/attribution/resolve-attribution-file/resolve-attribution-file.ts
2758
+ var resolveAttributionFile = (options) => {
2759
+ const worktreeRoot = detectWorktreeRoot(options.directory);
2760
+ if (worktreeRoot !== void 0) {
2761
+ return path9.join(worktreeRoot, ".opencode", "route33.attribution.json");
2762
+ }
2763
+ const fallbackRoots = {
2764
+ "return-undefined": void 0,
2765
+ "use-directory": fs8.realpathSync(options.directory)
2766
+ };
2767
+ const fallbackRoot = fallbackRoots[options.outsideWorktree];
2768
+ return fallbackRoot === void 0 ? void 0 : path9.join(fallbackRoot, ".opencode", "route33.attribution.json");
2769
+ };
2770
+
2771
+ // src/attribution/clear-attribution/clear-attribution.ts
2772
+ var clearAttribution = (options) => {
2773
+ const file = resolveAttributionFile(options);
2774
+ if (file === void 0) {
2775
+ return false;
2776
+ }
2777
+ fs9.rmSync(file, { force: true });
2778
+ return true;
2779
+ };
2780
+
2781
+ // src/attribution/read-legacy-key/read-legacy-key.ts
2782
+ import * as fs10 from "node:fs";
2783
+ import * as path10 from "node:path";
2784
+ var LEGACY_KEY_RELATIVE_PATH = path10.join(".opencode", "route33.key");
2785
+ var readLegacyKey = (worktree) => {
2786
+ if (worktree.trim() === "") return void 0;
2787
+ let raw;
2788
+ try {
2789
+ raw = fs10.readFileSync(
2790
+ path10.join(worktree, LEGACY_KEY_RELATIVE_PATH),
2791
+ "utf8"
2792
+ );
2793
+ } catch {
2794
+ return void 0;
2795
+ }
2796
+ try {
2797
+ const parsed = JSON.parse(raw);
2798
+ if (typeof parsed !== "object" || parsed === null || parsed.type !== "api") {
2799
+ return void 0;
2800
+ }
2801
+ const key = parsed.key;
2802
+ if (typeof key !== "string" || key.trim() === "") {
2803
+ return void 0;
2804
+ }
2805
+ return { value: key };
2806
+ } catch {
2807
+ return void 0;
2808
+ }
2809
+ };
2810
+
2811
+ // src/attribution/parse-attribution/parse-attribution.ts
2812
+ var parseAttribution = (value) => {
2813
+ if (!isRecord(value)) {
2814
+ throw new ContractParseError("invalid attribution");
2815
+ }
2816
+ if (value["kind"] === "personal") {
2817
+ return { kind: "personal" };
2818
+ }
2819
+ if (value["kind"] === "project" && typeof value["projectId"] === "string") {
2820
+ return { kind: "project", projectId: value["projectId"] };
2821
+ }
2822
+ throw new ContractParseError("invalid attribution");
2823
+ };
2824
+
2825
+ // src/attribution/read-attribution/read-attribution.ts
2826
+ import * as fs11 from "node:fs";
2827
+ var readAttribution = (options) => {
2828
+ const file = resolveAttributionFile(options);
2829
+ if (file === void 0) {
2830
+ return void 0;
2831
+ }
2832
+ try {
2833
+ const parsed = JSON.parse(fs11.readFileSync(file, "utf8"));
2834
+ return parseAttribution(parsed);
2835
+ } catch {
2836
+ return void 0;
2837
+ }
2838
+ };
2839
+
2840
+ // src/attribution/remove-legacy-key/remove-legacy-key.ts
2841
+ import * as fs12 from "node:fs";
2842
+ import * as path11 from "node:path";
2843
+ var LEGACY_KEY_RELATIVE_PATH2 = path11.join(".opencode", "route33.key");
2844
+ var removeLegacyKey = (worktree) => {
2845
+ try {
2846
+ fs12.rmSync(path11.join(worktree, LEGACY_KEY_RELATIVE_PATH2), { force: true });
2847
+ return true;
2848
+ } catch {
2849
+ return false;
2850
+ }
2851
+ };
2852
+
2853
+ // src/attribution/write-attribution/write-attribution.ts
2854
+ import { randomUUID as randomUUID2 } from "node:crypto";
2855
+ import * as fs13 from "node:fs";
2856
+ import * as path12 from "node:path";
2857
+ var writeAttribution = (options, attribution) => {
2858
+ const file = resolveAttributionFile(options);
2859
+ if (file === void 0) {
2860
+ return false;
2861
+ }
2862
+ fs13.mkdirSync(path12.dirname(file), { recursive: true });
2863
+ const temporaryFile = `${file}.${String(process.pid)}.${randomUUID2()}.tmp`;
2864
+ try {
2865
+ fs13.writeFileSync(temporaryFile, `${JSON.stringify(attribution)}
2866
+ `, "utf8");
2867
+ fs13.renameSync(temporaryFile, file);
2868
+ } catch (error) {
2869
+ fs13.rmSync(temporaryFile, { force: true });
2870
+ throw error;
2871
+ }
2872
+ return true;
2873
+ };
2874
+
2875
+ // src/key-lease/lease-state/lease-state.ts
2876
+ var LeaseState = class _LeaseState {
2877
+ /** Current committed snapshot; mutation is limited to compare-and-swap transitions. */
2878
+ #current;
2879
+ constructor(current) {
2880
+ this.#current = current;
2881
+ }
2882
+ /** Restores untrusted persisted metadata or an empty lease.
2883
+ * @param value - Persisted metadata, or undefined for a new installation.
2884
+ * @returns A lease-state coordinator.
2885
+ */
2886
+ static restore(value) {
2887
+ if (value === void 0) {
2888
+ return new _LeaseState(void 0);
2889
+ }
2890
+ if (!isRecord(value)) {
2891
+ throw new ContractParseError("invalid gateway key lease state");
2892
+ }
2893
+ const fields = Object.keys(value);
2894
+ if (fields.length !== 3 || fields.some(
2895
+ (field) => field !== "attribution" && field !== "expiresAt" && field !== "keyId"
2896
+ )) {
2897
+ throw new ContractParseError("invalid gateway key lease state");
2898
+ }
2899
+ const expiresAt = value["expiresAt"];
2900
+ const keyId = value["keyId"];
2901
+ if (typeof expiresAt !== "string" || !Number.isFinite(Date.parse(expiresAt)) || typeof keyId !== "string" || keyId.length === 0) {
2902
+ throw new ContractParseError("invalid gateway key lease state");
2903
+ }
2904
+ return new _LeaseState({
2905
+ attribution: parseAttribution(value["attribution"]),
2906
+ expiresAt,
2907
+ keyId
2908
+ });
2909
+ }
2910
+ /** Reads the current non-secret metadata.
2911
+ * @returns The current lease metadata, if one is committed.
2912
+ */
2913
+ snapshot() {
2914
+ return this.#current;
2915
+ }
2916
+ /** Checks whether current metadata belongs to an attribution.
2917
+ * @param attribution - The requested ownership choice.
2918
+ * @returns Whether the current lease has the same attribution.
2919
+ */
2920
+ matchesAttribution(attribution) {
2921
+ if (this.#current === void 0) {
2922
+ return false;
2923
+ }
2924
+ switch (this.#current.attribution.kind) {
2925
+ case "personal":
2926
+ return attribution.kind === "personal";
2927
+ case "project":
2928
+ return attribution.kind === "project" && attribution.projectId === this.#current.attribution.projectId;
2929
+ default:
2930
+ return _LeaseState.#unexpectedAttribution(this.#current.attribution);
2931
+ }
2932
+ }
2933
+ /** Atomically swaps metadata when the expected snapshot is still current.
2934
+ * @param expected - Snapshot observed before asynchronous renewal.
2935
+ * @param next - Fresh metadata to commit.
2936
+ * @returns Whether the swap committed.
2937
+ */
2938
+ compareAndSwap(expected, next) {
2939
+ if (this.#current !== expected) {
2940
+ return false;
2941
+ }
2942
+ this.#current = next;
2943
+ return true;
2944
+ }
2945
+ /** Clears metadata only while the expected snapshot remains current.
2946
+ * @param expected - Snapshot whose lease is being invalidated.
2947
+ * @returns Whether the state was cleared.
2948
+ */
2949
+ clear(expected) {
2950
+ if (this.#current !== expected) {
2951
+ return false;
2952
+ }
2953
+ this.#current = void 0;
2954
+ return true;
2955
+ }
2956
+ static #unexpectedAttribution(value) {
2957
+ throw new TypeError(`Unexpected attribution: ${String(value)}`);
2958
+ }
2959
+ };
2960
+
2961
+ // src/key-lease/lease-installation-factory/lease-installation-factory.ts
2962
+ var createLeaseInstallationFactory = (options) => {
2963
+ const installations = /* @__PURE__ */ new Map();
2964
+ return (scopeId) => {
2965
+ const existing = installations.get(scopeId);
2966
+ if (existing !== void 0) {
2967
+ return existing;
2968
+ }
2969
+ const installation = {
2970
+ keyName: `route33:lease:${scopeId}`,
2971
+ secretStore: options.createSecretStore(scopeId),
2972
+ ...options.createStateStore === void 0 ? {} : { stateStore: options.createStateStore(scopeId) },
2973
+ state: LeaseState.restore(void 0)
2974
+ };
2975
+ installations.set(scopeId, installation);
2976
+ return installation;
2977
+ };
2978
+ };
2979
+
2980
+ // src/key-lease/scope-id/scope-id.ts
2981
+ import { createHash as createHash3 } from "node:crypto";
2982
+ var deriveScopeId = (input) => {
2983
+ let identity;
2984
+ switch (input.attribution.kind) {
2985
+ case "personal":
2986
+ identity = ["route33-lease", "personal"];
2987
+ break;
2988
+ case "project":
2989
+ if (input.folderRealpath === void 0 || input.folderRealpath.length === 0) {
2990
+ throw new TypeError("Project lease scope requires a real folder path");
2991
+ }
2992
+ identity = [
2993
+ "route33-lease",
2994
+ "project",
2995
+ input.attribution.projectId,
2996
+ input.folderRealpath
2997
+ ];
2998
+ break;
2999
+ default: {
3000
+ const unexpected = input.attribution;
3001
+ throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
3002
+ }
3003
+ }
3004
+ return createHash3("sha256").update(JSON.stringify(identity)).digest("hex");
3005
+ };
3006
+
3007
+ // src/requested-client-id/requested-client-id.ts
3008
+ var DEFAULT_ROUTE33_CLIENT_ID = false ? "" : "";
3009
+
3010
+ // src/catalog/gateway-model-ids/gateway-model-ids.ts
3011
+ var gatewayModelIds = async (deps) => {
3012
+ const { baseURL, gatewayKey, ...rest } = deps;
3013
+ const catalog = await getCatalog({
3014
+ ...rest,
3015
+ baseURL,
3016
+ gatewayKey: { value: gatewayKey.value }
3017
+ });
3018
+ return Object.keys(catalog.models).sort((a, b) => a.localeCompare(b));
3019
+ };
3020
+
3021
+ // src/commands/change-attribution/change-attribution.ts
3022
+ var changeAttribution = async (options) => {
3023
+ await options.clear();
3024
+ return options.prompt();
3025
+ };
3026
+
3027
+ // src/commands/inspect-session/inspect-session.ts
3028
+ var inspectSession = (options) => {
3029
+ const attribution = options.readAttribution();
3030
+ const lease = options.readLease();
3031
+ return {
3032
+ attribution,
3033
+ ...lease === void 0 ? {} : { lease: { expiresAt: lease.expiresAt, keyId: lease.keyId } }
3034
+ };
3035
+ };
3036
+
3037
+ // src/commands/reset-attribution/reset-attribution.ts
3038
+ var resetAttribution = async (options) => {
3039
+ await options.clear();
3040
+ };
3041
+
3042
+ // src/commands/rotate-now/rotate-now.ts
3043
+ var rotateNow = async (options) => {
3044
+ const rotated = await options.lease({ renewalRatio: Number.EPSILON });
3045
+ return rotated.lease;
3046
+ };
3047
+
3048
+ // src/ux/attribution-prompt/attribution-prompt.ts
3049
+ var PERSONAL_KEY_ACTIVE_MARKER = "machine key active";
3050
+ var createAttributionPrompt = (projects, options = {}) => {
3051
+ const choicesBySelection = {
3052
+ personal: { kind: "personal" }
3053
+ };
3054
+ const projectOptions = projects.map((project) => {
3055
+ const selection = `project:${project.id}`;
3056
+ choicesBySelection[selection] = {
3057
+ kind: "project",
3058
+ projectId: project.id
3059
+ };
3060
+ const budget = project.effective_budget ?? project.max_budget;
3061
+ const allowance = budget === null ? "no cap set" : `cap ${budget.amount} ${budget.currency}`;
3062
+ return {
3063
+ label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${allowance}`,
3064
+ selection
3065
+ };
3066
+ });
3067
+ return {
3068
+ choicesBySelection,
3069
+ options: [
3070
+ {
3071
+ label: options.personalKeyActive === true ? `Personal \u2014 your own key (${PERSONAL_KEY_ACTIVE_MARKER})` : "Personal \u2014 your own key",
3072
+ selection: "personal"
3073
+ },
3074
+ ...projectOptions
3075
+ ],
3076
+ title: "Choose where Route 33 should manage this key"
3077
+ };
3078
+ };
3079
+
3080
+ // src/ux/attribution-prompt-error/attribution-prompt-error.ts
3081
+ var MESSAGES = {
3082
+ ATTRIBUTION_PRESENTER_UNAVAILABLE: "Route 33 needs OpenCode v2 to assign a budget for this folder. Update to OpenCode v2, run /connect, choose Route 33, and follow the steps.",
3083
+ ATTRIBUTION_SELECTION_INVALID: "That Route 33 option is no longer available. Connect again and pick another."
3084
+ };
3085
+ var AttributionPromptError = class extends GatewayCredentialError {
3086
+ code;
3087
+ constructor(code) {
3088
+ super(MESSAGES[code]);
3089
+ this.name = "AttributionPromptError";
3090
+ this.code = code;
3091
+ }
3092
+ };
3093
+
3094
+ // src/ux/prompt-flow/prompt-flow.ts
3095
+ var resolveAttribution = async (options) => {
3096
+ const remembered = readAttribution(options.state);
3097
+ if (remembered !== void 0) {
3098
+ return remembered;
3099
+ }
3100
+ if (options.presenter === void 0) {
3101
+ throw new AttributionPromptError("ATTRIBUTION_PRESENTER_UNAVAILABLE");
3102
+ }
3103
+ const plan = createAttributionPrompt(await options.loadProjects());
3104
+ const selection = await options.presenter.pick(plan);
3105
+ const attribution = plan.choicesBySelection[selection];
3106
+ if (attribution === void 0) {
3107
+ throw new AttributionPromptError("ATTRIBUTION_SELECTION_INVALID");
3108
+ }
3109
+ writeAttribution(options.state, attribution);
3110
+ return attribution;
3111
+ };
3112
+
3113
+ // src/ux/trusted-party-copy/trusted-party-copy.ts
3114
+ var TRUSTED_PARTY_COPY = {
3115
+ message: "Route 33 wants to manage your keys for this OpenCode installation.",
3116
+ title: "Connect Route 33"
3117
+ };
3118
+
3119
+ // src/route33-runtime/login-session/login-session.ts
3120
+ var EXPIRY_SKEW_MS = 6e4;
3121
+ var LoginSession = class {
3122
+ #options;
3123
+ #result;
3124
+ #expiresAt;
3125
+ constructor(options) {
3126
+ this.#options = options;
3127
+ }
3128
+ /**
3129
+ * Resolves the login once per process, sharing in-flight attempts.
3130
+ * @param policy - Whether this attempt may start a browser login; an in-flight attempt is always shared.
3131
+ * @returns The token set plus its typed management credential.
3132
+ */
3133
+ /**
3134
+ * Clears the session: the cached login result and the stored refresh
3135
+ * token. The next login starts from scratch — /r33 logout and the
3136
+ * auto-reconnect path both land here.
3137
+ */
3138
+ async clear() {
3139
+ this.#result = void 0;
3140
+ this.#expiresAt = void 0;
3141
+ await this.#options.tokenStore?.set(void 0);
3142
+ }
3143
+ /**
3144
+ *
3145
+ * @param policy
3146
+ */
3147
+ result(policy = {}) {
3148
+ if (this.#result !== void 0 && this.#expiresAt !== void 0 && Date.now() >= this.#expiresAt - EXPIRY_SKEW_MS) {
3149
+ this.#result = void 0;
3150
+ }
3151
+ this.#result ??= this.#start(policy).catch((cause) => {
3152
+ this.#result = void 0;
3153
+ throw cause;
3154
+ });
3155
+ return this.#result;
3156
+ }
3157
+ /**
3158
+ * Resolves only the management credential for lazy management clients.
3159
+ * @param policy - Whether this attempt may start a browser login.
3160
+ * @returns The current login's typed management credential.
3161
+ */
3162
+ async credential(policy = {}) {
3163
+ return (await this.result(policy)).credential;
3164
+ }
3165
+ async #start(policy) {
3166
+ const viaRefresh = await this.#tryRefresh();
3167
+ if (viaRefresh !== void 0) {
3168
+ return viaRefresh;
3169
+ }
3170
+ if (policy.allowBrowser === false) {
3171
+ throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED");
3172
+ }
3173
+ await this.#options.presenter?.present(TRUSTED_PARTY_COPY);
3174
+ const result = await loginFlow(this.#options.auth);
3175
+ this.#trackExpiry(result.tokenSet.expires_in);
3176
+ await this.#persist(result.tokenSet.refresh_token);
3177
+ return result;
3178
+ }
3179
+ async #tryRefresh() {
3180
+ const tokenStore = this.#options.tokenStore;
3181
+ if (tokenStore === void 0) {
3182
+ return void 0;
3183
+ }
3184
+ const stored = await tokenStore.get();
3185
+ if (stored === void 0 || stored === "") {
3186
+ return void 0;
3187
+ }
3188
+ let tokenSet;
3189
+ try {
3190
+ tokenSet = await this.#options.auth.session.refresh(stored);
3191
+ } catch {
3192
+ logger.info("auth.refresh.fell-back-to-browser");
3193
+ return void 0;
3194
+ }
3195
+ let credential;
3196
+ try {
3197
+ credential = parseManagementJwt(tokenSet.access_token);
3198
+ } catch (cause) {
3199
+ throw new AuthError("AUTH_TOKEN_RESPONSE_INVALID", { cause });
3200
+ }
3201
+ this.#trackExpiry(tokenSet.expires_in);
3202
+ await this.#persist(tokenSet.refresh_token);
3203
+ return { credential, tokenSet };
3204
+ }
3205
+ #trackExpiry(expiresIn) {
3206
+ this.#expiresAt = Date.now() + expiresIn * 1e3;
3207
+ }
3208
+ async #persist(token) {
3209
+ try {
3210
+ await this.#options.tokenStore?.set(token);
3211
+ } catch {
3212
+ logger.warn("auth.token.persist-failed");
3213
+ }
3214
+ }
3215
+ };
3216
+
3217
+ // src/route33-runtime/route33-runtime.ts
3218
+ var Route33Runtime = class {
3219
+ #options;
3220
+ #session;
3221
+ #managementClient;
3222
+ constructor(options) {
3223
+ this.#options = options;
3224
+ this.#session = new LoginSession({
3225
+ auth: options.auth,
3226
+ ...options.presenter === void 0 ? {} : { presenter: options.presenter },
3227
+ ...options.tokenStore === void 0 ? {} : { tokenStore: options.tokenStore }
3228
+ });
3229
+ }
3230
+ /**
3231
+ * Runs the browser or refresh-token login once for this process.
3232
+ * @param policy - Whether this attempt may start a browser login.
3233
+ * @returns The token set plus its typed management credential.
3234
+ */
3235
+ login(policy = {}) {
3236
+ return this.#session.result(policy);
3237
+ }
3238
+ /**
3239
+ * Lists projects visible to the current management login.
3240
+ * @returns Projects with their listing organisation stitched in.
3241
+ */
3242
+ async listProjects() {
3243
+ const credential = await this.#session.credential();
3244
+ const client = this.#client();
3245
+ const organizations = await client.listOrganizations(credential);
3246
+ const projects = await Promise.all(
3247
+ organizations.data.map(async (organization) => {
3248
+ const collection = await client.listProjects(
3249
+ credential,
3250
+ organization.id
3251
+ );
3252
+ return collection.data.map((project) => ({
3253
+ ...project,
3254
+ organisation: { id: organization.id, name: organization.name }
3255
+ }));
3256
+ })
3257
+ );
3258
+ return projects.flat();
3259
+ }
3260
+ /**
3261
+ * Reads the stored key for a saved attribution without any login.
3262
+ * @returns The reusable key and lease when the stored lease is still valid.
3263
+ */
3264
+ async storedReusableKey() {
3265
+ const attribution = readAttribution(this.#options.state);
3266
+ if (attribution === void 0) {
3267
+ return void 0;
3268
+ }
3269
+ const installation = this.#installation(attribution);
3270
+ await this.#hydrateState(installation);
3271
+ const storedKey = await installation.secretStore.get();
3272
+ return reusableLease({
3273
+ attribution,
3274
+ current: installation.state.snapshot(),
3275
+ now: this.#now(),
3276
+ policy: resolveLeasePolicy(this.#options.policy),
3277
+ state: installation.state,
3278
+ storedKey
3279
+ });
3280
+ }
3281
+ /**
3282
+ * Resolves the current gateway credential for the config hook.
3283
+ * @returns A leased inference key.
3284
+ */
3285
+ async resolveCredential() {
3286
+ return (await this.#lease(this.#options.policy)).key;
3287
+ }
3288
+ /**
3289
+ * Reports whether the machine-global personal key exists — the silent
3290
+ * fallback for folders that never attributed.
3291
+ * @returns True when a stored personal lease is still valid.
3292
+ */
3293
+ async hasPersonalLease() {
3294
+ const installation = this.#installation({ kind: "personal" });
3295
+ const storedKey = await installation.secretStore.get();
3296
+ return storedKey !== void 0;
3297
+ }
3298
+ async #storedPersonalKey() {
3299
+ const installation = this.#installation({ kind: "personal" });
3300
+ return installation.secretStore.get();
3301
+ }
3302
+ /**
3303
+ * Resolves the workspace-owned key for any directory without prompting:
3304
+ * the folder's own attribution first, the machine-global personal key
3305
+ * as the fallback for folders that never attributed.
3306
+ * @param directory - Session directory whose worktree attribution decides the key.
3307
+ * @returns That workspace's leased key, the global personal key, or undefined.
3308
+ */
3309
+ async resolveWorkspaceCredential(directory) {
3310
+ const attribution = readAttribution({
3311
+ directory,
3312
+ outsideWorktree: "return-undefined"
3313
+ });
3314
+ if (attribution === void 0) {
3315
+ const installation = this.#installation({ kind: "personal" });
3316
+ const storedKey = await installation.secretStore.get();
3317
+ return storedKey;
3318
+ }
3319
+ return (await this.#leaseAttribution(attribution, void 0, directory)).key;
3320
+ }
3321
+ /**
3322
+ * Builds injectable handlers for the host's command surface.
3323
+ * @returns Change, reset, rotate, and safe inspection handlers.
3324
+ */
3325
+ commandHandlers() {
3326
+ return {
3327
+ "change-attribution": () => changeAttribution({
3328
+ clear: () => {
3329
+ clearAttribution(this.#options.state);
3330
+ },
3331
+ prompt: () => this.#resolveAttribution()
3332
+ }),
3333
+ "inspect-session": async () => {
3334
+ try {
3335
+ return await this.#inspectSession();
3336
+ } catch {
3337
+ return inspectSession({
3338
+ readAttribution: () => readAttribution(this.#options.state),
3339
+ readLease: () => {
3340
+ const attribution = readAttribution(this.#options.state);
3341
+ return attribution === void 0 ? void 0 : this.#installation(attribution).state.snapshot();
3342
+ }
3343
+ });
3344
+ }
3345
+ },
3346
+ "reset-attribution": () => resetAttribution({
3347
+ clear: () => {
3348
+ clearAttribution(this.#options.state);
3349
+ }
3350
+ }),
3351
+ logout: () => this.#session.clear(),
3352
+ "rotate-now": () => rotateNow({
3353
+ lease: (policy) => this.#lease({ ...this.#options.policy, ...policy })
3354
+ })
3355
+ };
3356
+ }
3357
+ /** Enriched session inspection: the plain report plus the key's name and organisation/project.
3358
+ * @returns A safe session report that cannot carry gateway plaintext.
3359
+ */
3360
+ async #inspectSession() {
3361
+ const base = inspectSession({
3362
+ readAttribution: () => readAttribution(this.#options.state),
3363
+ readLease: () => {
3364
+ const attribution = readAttribution(this.#options.state);
3365
+ return attribution === void 0 ? void 0 : this.#installation(attribution).state.snapshot();
3366
+ }
3367
+ });
3368
+ const keyId = base.lease?.keyId;
3369
+ if (keyId === void 0) {
3370
+ return base;
3371
+ }
3372
+ const credential = await this.#session.credential();
3373
+ const client = this.#client();
3374
+ const [keys, projects] = await Promise.all([
3375
+ client.list(credential).then((collection) => collection.data).catch(() => []),
3376
+ this.listProjects().catch(() => [])
3377
+ ]);
3378
+ const key = keys.find((item) => item.id === keyId);
3379
+ if (key === void 0) {
3380
+ return base;
3381
+ }
3382
+ const projectId = key.project_id ?? null;
3383
+ const project = projectId === null ? void 0 : projects.find((item) => item.id === projectId);
3384
+ return {
3385
+ ...base,
3386
+ key: {
3387
+ name: key.name,
3388
+ organisationName: project?.organisation.name ?? null,
3389
+ projectName: project?.name ?? null
3390
+ }
3391
+ };
3392
+ }
3393
+ /**
3394
+ * Lists the gateway catalog's model ids under the current stored key —
3395
+ * the connect form's allowed-models picker offers exactly these.
3396
+ * @returns Catalog model ids, empty while no key or catalog exists.
3397
+ */
3398
+ async catalogModelIds() {
3399
+ const workspace = await this.storedReusableKey();
3400
+ const personal = workspace === void 0 ? await this.#storedPersonalKey() : void 0;
3401
+ const value = workspace?.key.value ?? personal?.value;
3402
+ if (value === void 0) {
3403
+ return [];
3404
+ }
3405
+ return gatewayModelIds({
3406
+ baseURL: readEnvBaseUrl() ?? DEFAULT_BASE_URL,
3407
+ cacheDir: readEnvCacheDir(),
3408
+ catalogTtlMs: readEnvCatalogTtlMs(),
3409
+ disableIdShim: readEnvDisableIdShim(),
3410
+ discoveryEnabled: readEnvDiscovery(),
3411
+ gatewayKey: { value }
3412
+ });
3413
+ }
3414
+ /**
3415
+ * Mints a fresh key for one attribution with the wizard's answers —
3416
+ * name, cap, description, and allowed models — and persists it as the
3417
+ * workspace lease. Never reuses an existing key: the plugin rotates by
3418
+ * default, so every wizard completion mints anew.
3419
+ * @param attribution - The budget the wizard selected.
3420
+ * @param extras - The wizard's key-creation answers.
3421
+ * @param directory - Optional worktree override for project leases.
3422
+ * @returns The fresh key material with its lease metadata.
3423
+ */
3424
+ async mintWorkspaceKey(attribution, extras, directory = this.#options.state.directory) {
3425
+ return this.#leaseAttribution(attribution, void 0, directory, {
3426
+ extras,
3427
+ forceMint: true
3428
+ });
3429
+ }
3430
+ /**
3431
+ * Reads the active key's allowance for one attribution: the leased
3432
+ * key looked up by id, its allowed-models list returned — null or
3433
+ * undefined when the key allows every model.
3434
+ * @param directory - The workspace folder whose lease owns the key.
3435
+ * @returns The key's allowance, or undefined when it cannot be read.
3436
+ */
3437
+ async workspaceKeyAllowance(directory) {
3438
+ const attribution = readAttribution({
3439
+ directory,
3440
+ outsideWorktree: "return-undefined"
3441
+ });
3442
+ if (attribution === void 0) {
3443
+ return void 0;
3444
+ }
3445
+ const lease = this.#installation(attribution).state.snapshot();
3446
+ const keyId = lease?.keyId;
3447
+ if (keyId === void 0) {
3448
+ return void 0;
3449
+ }
3450
+ const credential = await this.#session.credential();
3451
+ const keys = await this.#client().list(credential).then((collection) => collection.data).catch(() => []);
3452
+ const key = keys.find((item) => item.id === keyId);
3453
+ return key === void 0 ? void 0 : { allowedModels: key.allowed_models };
3454
+ }
3455
+ #client() {
3456
+ const client = this.#options.management.client;
3457
+ if (typeof client !== "function") {
3458
+ return client;
3459
+ }
3460
+ this.#managementClient ??= client();
3461
+ return this.#managementClient;
3462
+ }
3463
+ #subject(credential) {
3464
+ const subject = this.#options.management.subject;
3465
+ if (subject === void 0) {
3466
+ return parseManagementSubject(credential);
3467
+ }
3468
+ return typeof subject === "string" ? subject : subject(credential);
3469
+ }
3470
+ #now() {
3471
+ return (this.#options.clock ?? Date.now)();
3472
+ }
3473
+ async #resolveAttribution() {
3474
+ return resolveAttribution({
3475
+ loadProjects: async () => {
3476
+ await this.#session.credential();
3477
+ return this.listProjects();
3478
+ },
3479
+ ...this.#options.presenter === void 0 ? {} : { presenter: this.#options.presenter },
3480
+ state: this.#options.state
3481
+ });
3482
+ }
3483
+ async #lease(policy) {
3484
+ const attribution = await this.#resolveAttribution();
3485
+ return this.#leaseAttribution(attribution, policy);
3486
+ }
3487
+ async #leaseAttribution(attribution, policy, directory = this.#options.state.directory, request) {
3488
+ const installation = this.#installation(attribution, directory);
3489
+ await this.#hydrateState(installation);
3490
+ const minted = await leaseForAttribution({
3491
+ attribution,
3492
+ ...this.#options.clock === void 0 ? {} : { clock: this.#options.clock },
3493
+ installation,
3494
+ management: {
3495
+ client: this.#client(),
3496
+ credential: () => this.#session.credential(),
3497
+ subject: async () => this.#subject(await this.#session.credential())
3498
+ },
3499
+ ...policy === void 0 ? {} : { policy },
3500
+ ...request === void 0 ? {} : { request }
3501
+ });
3502
+ await this.#persistState(installation, minted.lease);
3503
+ return minted;
3504
+ }
3505
+ async #hydrateState(installation) {
3506
+ const store = installation.stateStore;
3507
+ if (store === void 0 || installation.state.snapshot() !== void 0) {
3508
+ return;
3509
+ }
3510
+ try {
3511
+ const persisted = await store.get();
3512
+ if (persisted !== void 0) {
3513
+ installation.state.compareAndSwap(void 0, persisted);
3514
+ }
3515
+ } catch {
3516
+ }
3517
+ }
3518
+ async #persistState(installation, lease) {
3519
+ try {
3520
+ await installation.stateStore?.set(lease);
3521
+ } catch {
3522
+ }
3523
+ }
3524
+ #installation(attribution, directory = this.#options.state.directory) {
3525
+ switch (attribution.kind) {
3526
+ case "personal":
3527
+ return this.#options.installation(deriveScopeId({ attribution }));
3528
+ case "project": {
3529
+ const folderRealpath = detectWorktreeRoot(directory);
3530
+ if (folderRealpath === void 0) {
3531
+ throw new TypeError("Project lease scope requires a worktree root");
3532
+ }
3533
+ return this.#options.installation(
3534
+ deriveScopeId({ attribution, folderRealpath })
3535
+ );
3536
+ }
3537
+ default: {
3538
+ const unexpected = attribution;
3539
+ throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
3540
+ }
3541
+ }
3542
+ }
3543
+ };
3544
+
3545
+ // src/v1-entry/unattributed-prompt-gate/unattributed-prompt-gate.ts
3546
+ var createUnattributedPromptGate = ({ directory, outsideWorktree }) => (input) => {
3547
+ if (input.model?.providerID !== "route_33") return Promise.resolve();
3548
+ const attribution = readAttribution({ directory, outsideWorktree });
3549
+ if (attribution !== void 0) return Promise.resolve();
3550
+ return Promise.reject(
3551
+ new Error(
3552
+ "Route 33 needs a budget for this folder first \u2014 run /r33 in OpenCode, choose Route 33, and assign a budget."
3553
+ )
3554
+ );
3555
+ };
3556
+
3557
+ // src/v1-entry/workspace-key-headers/workspace-key-headers.ts
3558
+ var createWorkspaceKeyHeaders = ({ resolveKey, session }) => async (input, output) => {
3559
+ const workspace = await session.get({ sessionID: input.sessionID });
3560
+ const key = await resolveKey(workspace.location.directory);
3561
+ if (key === void 0) return;
3562
+ output.headers["Authorization"] = `Bearer ${key.value}`;
3563
+ };
3564
+
3565
+ // src/create-route33-plugin/create-route33-plugin.ts
3566
+ var createRoute33Plugin = (options = {}) => {
3567
+ const baseURL = readEnvBaseUrl();
3568
+ const clientId2 = options.clientId ?? readEnvClientId() ?? DEFAULT_ROUTE33_CLIENT_ID;
3569
+ const directKey = readEnvDirectApiKey();
3570
+ const resolvedConfig = {
3571
+ ...baseURL === void 0 ? {} : { baseURL },
3572
+ cacheDir: readEnvCacheDir(),
3573
+ catalogTtlMs: readEnvCatalogTtlMs(),
3574
+ disableIdShim: readEnvDisableIdShim(),
3575
+ discoveryEnabled: readEnvDiscovery(),
3576
+ strict: readEnvStrict(),
3577
+ ...options.config
3578
+ };
3579
+ const runtimeOptions = options.runtime;
3580
+ const installation = runtimeOptions === void 0 ? void 0 : runtimeOptions.installation ?? createLeaseInstallationFactory({
3581
+ createSecretStore: (scopeId) => new FileSecretStore({
3582
+ directory: resolveV1SecretStoreDirectory({
3583
+ ...options.secretStoreDirectory === void 0 ? {} : { directory: options.secretStoreDirectory }
3584
+ }),
3585
+ scopeId
3586
+ })
3587
+ });
3588
+ return (input) => {
3589
+ const runtime2 = runtimeOptions === void 0 || installation === void 0 ? void 0 : new Route33Runtime({
3590
+ ...runtimeOptions,
3591
+ auth: { ...runtimeOptions.auth, clientId: clientId2 },
3592
+ installation,
3593
+ state: {
3594
+ directory: input.worktree,
3595
+ outsideWorktree: "return-undefined"
3596
+ }
3597
+ });
3598
+ if (runtime2 !== void 0) {
3599
+ options.bindRuntime?.(runtime2);
3600
+ if (options.registerCommands !== void 0) {
3601
+ options.registerCommands(runtime2.commandHandlers());
3602
+ }
3603
+ }
3604
+ let credentialProvider;
3605
+ let workspaceHeaders;
3606
+ let promptGate;
3607
+ if (directKey !== void 0) {
3608
+ credentialProvider = () => Promise.resolve(parseGatewayKey(directKey));
3609
+ } else if (runtime2 === void 0) {
3610
+ credentialProvider = () => Promise.reject(
3611
+ new AttributionPromptError("ATTRIBUTION_PRESENTER_UNAVAILABLE")
3612
+ );
3613
+ } else {
3614
+ credentialProvider = () => runtime2.resolveCredential();
3615
+ workspaceHeaders = createWorkspaceKeyHeaders({
3616
+ resolveKey: (directory) => runtime2.resolveWorkspaceCredential(directory),
3617
+ session: {
3618
+ get: async ({ sessionID }) => {
3619
+ const session = await options.readSession?.(sessionID);
3620
+ return session ?? { location: { directory: input.worktree } };
3621
+ }
3622
+ }
3623
+ });
3624
+ promptGate = createUnattributedPromptGate({
3625
+ directory: input.worktree,
3626
+ outsideWorktree: "return-undefined"
3627
+ });
3628
+ }
3629
+ return Promise.resolve({
3630
+ config: createConfigHook({
3631
+ ...resolvedConfig,
3632
+ credentialProvider,
3633
+ cwd: input.worktree
3634
+ }),
3635
+ ...workspaceHeaders === void 0 ? {} : { "chat.headers": workspaceHeaders },
3636
+ ...promptGate === void 0 ? {} : { "chat.message": promptGate }
3637
+ });
3638
+ };
3639
+ };
3640
+
3641
+ // src/contract/management-keys/parse-api-key/parse-api-key.ts
3642
+ var parseApiKey = (value) => {
3643
+ if (!isRecord(value) || !isOwnerType(value["ownership_type"]) || !isNullableString(value["project_id"])) {
3644
+ throw new ContractParseError("invalid API key");
3645
+ }
3646
+ const field = (name) => {
3647
+ const text = value[name];
3648
+ if (typeof text !== "string") {
3649
+ throw new ContractParseError("invalid API key");
3650
+ }
3651
+ return text;
3652
+ };
3653
+ const status = value["status"];
3654
+ if (status !== "active" && status !== "revoked") {
3655
+ throw new ContractParseError("invalid API key");
3656
+ }
3657
+ const rawModels = value["allowed_models"];
3658
+ const allowedModels = Array.isArray(rawModels) ? rawModels.filter((item) => typeof item === "string") : null;
3659
+ return {
3660
+ allowed_models: allowedModels,
3661
+ expires_at: field("expires_at"),
3662
+ id: field("id"),
3663
+ name: field("name"),
3664
+ org_id: field("org_id"),
3665
+ ownership_type: value["ownership_type"],
3666
+ project_id: value["project_id"],
3667
+ revoked: value["revoked"] === true,
3668
+ status
3669
+ };
3670
+ };
3671
+
3672
+ // src/contract/management-keys/parse-collection/parse-collection.ts
3673
+ var parseCollection = (value, parseItem) => {
3674
+ if (!isRecord(value)) {
3675
+ throw new ContractParseError("invalid management collection");
3676
+ }
3677
+ const data = value["data"];
3678
+ if (!Array.isArray(data)) {
3679
+ throw new ContractParseError("invalid management collection");
3680
+ }
3681
+ const page = value["page"];
3682
+ if (!isRecord(page)) {
3683
+ throw new ContractParseError("invalid management collection");
3684
+ }
3685
+ const limit = page["limit"];
3686
+ if (typeof limit !== "number") {
3687
+ throw new ContractParseError("invalid management collection");
3688
+ }
3689
+ if (![Number.isInteger(limit), limit >= 1, limit <= 500].every(Boolean)) {
3690
+ throw new ContractParseError("invalid management collection");
3691
+ }
3692
+ const nextCursor = page["next_cursor"];
3693
+ if (!isNullableString(nextCursor)) {
3694
+ throw new ContractParseError("invalid management collection");
3695
+ }
3696
+ const hasMore = page["has_more"];
3697
+ if (typeof hasMore !== "boolean") {
3698
+ throw new ContractParseError("invalid management collection");
3699
+ }
3700
+ const collection = {
3701
+ data: data.map(parseItem),
3702
+ page: {
3703
+ has_more: hasMore,
3704
+ limit,
3705
+ next_cursor: nextCursor
3706
+ }
3707
+ };
3708
+ const meta = value["meta"];
3709
+ if (meta === void 0) {
3710
+ return collection;
3711
+ }
3712
+ if (!isRecord(meta)) {
3713
+ throw new ContractParseError("invalid management collection");
3714
+ }
3715
+ return { ...collection, meta };
3716
+ };
3717
+
3718
+ // src/contract/management-keys/parse-key-material/parse-key-material.ts
3719
+ var parseKeyMaterial = (value) => {
3720
+ if (!isRecord(value) || typeof value["key"] !== "string") {
3721
+ throw new ContractParseError("invalid key material");
3722
+ }
3723
+ return { ...parseApiKey(value), key: new GatewayApiKey(value["key"]) };
3724
+ };
3725
+
3726
+ // src/contract/management-keys/parse-organization/parse-organization.ts
3727
+ var parseOrganization = (value) => {
3728
+ if (!isRecord(value)) {
3729
+ throw new ContractParseError("invalid organization");
3730
+ }
3731
+ const stringField = (name) => {
3732
+ const field = value[name];
3733
+ if (typeof field !== "string") {
3734
+ throw new ContractParseError("invalid organization");
3735
+ }
3736
+ return field;
3737
+ };
3738
+ const nullableStringField = (name) => {
3739
+ const field = value[name];
3740
+ if (!isNullableString(field)) {
3741
+ throw new ContractParseError("invalid organization");
3742
+ }
3743
+ return field;
3744
+ };
3745
+ const numberField = (name) => {
3746
+ const field = value[name];
3747
+ if (typeof field !== "number") {
3748
+ throw new ContractParseError("invalid organization");
3749
+ }
3750
+ return field;
3751
+ };
3752
+ const nullableNumberField = (name) => {
3753
+ const field = value[name];
3754
+ if (typeof field !== "number" && field !== null) {
3755
+ throw new ContractParseError("invalid organization");
3756
+ }
3757
+ return field;
3758
+ };
3759
+ const booleanField = (name) => {
3760
+ const field = value[name];
3761
+ if (typeof field !== "boolean") {
3762
+ throw new ContractParseError("invalid organization");
3763
+ }
3764
+ return field;
3765
+ };
3766
+ const budgetField = (name) => {
3767
+ const field = value[name];
3768
+ if (field === null) {
3769
+ return null;
3770
+ }
3771
+ if (!isRecord(field) || typeof field["amount"] !== "string" || typeof field["currency"] !== "string") {
3772
+ throw new ContractParseError("invalid organization");
3773
+ }
3774
+ return { amount: field["amount"], currency: field["currency"] };
3775
+ };
3776
+ const setupStatus = value["setup_status"];
3777
+ if (setupStatus !== "broken" && setupStatus !== "ok" && setupStatus !== "partial" && setupStatus !== "unvalidated") {
3778
+ throw new ContractParseError("invalid organization");
3779
+ }
3780
+ return {
3781
+ alert_active: booleanField("alert_active"),
3782
+ alert_percentage: numberField("alert_percentage"),
3783
+ azure_group_id: nullableStringField("azure_group_id"),
3784
+ azure_owners_group_id: nullableStringField("azure_owners_group_id"),
3785
+ created_at: nullableStringField("created_at"),
3786
+ deactivated_at: nullableStringField("deactivated_at"),
3787
+ default_project_budget: budgetField("default_project_budget"),
3788
+ default_user_budget: budgetField("default_user_budget"),
3789
+ domain: nullableStringField("domain"),
3790
+ id: stringField("id"),
3791
+ idp_connection: nullableStringField("idp_connection"),
3792
+ member_count: nullableNumberField("member_count"),
3793
+ name: stringField("name"),
3794
+ scim_sync: nullableStringField("scim_sync"),
3795
+ setup_status: setupStatus,
3796
+ slug: nullableStringField("slug"),
3797
+ tenant_id: nullableStringField("tenant_id"),
3798
+ updated_at: nullableStringField("updated_at")
3799
+ };
3800
+ };
3801
+
3802
+ // src/contract/management-keys/parse-wire-money/parse-wire-money.ts
3803
+ var parseWireMoney = (value) => {
3804
+ if (!isRecord(value)) return null;
3805
+ const amount = value["amount"];
3806
+ const currency = value["currency"];
3807
+ return typeof amount === "string" && typeof currency === "string" ? { amount, currency } : null;
3808
+ };
3809
+
3810
+ // src/contract/management-keys/parse-project/parse-project.ts
3811
+ var parseProject = (value) => {
3812
+ if (!isRecord(value) || !hasStringFields(value, ["id", "name"]) || !hasStringFields(value, ["id", "name", "org_id"])) {
3813
+ throw new ContractParseError("invalid project");
3814
+ }
3815
+ return {
3816
+ effective_budget: parseWireMoney(value["effective_budget"]),
3817
+ id: value["id"] ?? "",
3818
+ max_budget: parseWireMoney(value["max_budget"]),
3819
+ name: value["name"] ?? "",
3820
+ org_id: value["org_id"] ?? ""
3821
+ };
3822
+ };
3823
+
3824
+ // src/management/management-error/management-error.ts
3825
+ var ManagementError = class extends Error {
3826
+ constructor(code, options) {
3827
+ super(
3828
+ "Route 33 management request failed",
3829
+ options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
3830
+ );
3831
+ this.code = code;
3832
+ this.name = "ManagementError";
3833
+ this.statusCode = options?.statusCode;
3834
+ }
3835
+ code;
3836
+ statusCode;
3837
+ };
3838
+
3839
+ // src/management/management-http-transport/management-http-transport.ts
3840
+ var ManagementHttpTransport = class {
3841
+ #baseUrl;
3842
+ #credential;
3843
+ #fetchImpl;
3844
+ #onUnauthorized;
3845
+ #timeoutMs;
3846
+ constructor(options) {
3847
+ const baseUrl = options.baseUrl ?? "https://api.route33.ai/v1";
3848
+ this.#baseUrl = new URL(baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`);
3849
+ this.#credential = options.credential;
3850
+ this.#fetchImpl = options.fetchImpl ?? fetch;
3851
+ this.#onUnauthorized = options.onUnauthorized;
3852
+ this.#timeoutMs = options.timeoutMs ?? 1e4;
3853
+ }
3854
+ /** Sends a request and reads one JSON value under the request timeout.
3855
+ * @param request - Management path, method, and optional JSON body.
3856
+ * @returns The untrusted response value.
3857
+ */
3858
+ json(request) {
3859
+ return this.#perform(request, async (response) => {
3860
+ try {
3861
+ return await response.json();
3862
+ } catch (cause) {
3863
+ throw new ContractParseError("invalid management response", { cause });
3864
+ }
3865
+ });
3866
+ }
3867
+ /** Sends a request whose successful response has no body.
3868
+ * @param request - Management path and method.
3869
+ */
3870
+ empty(request) {
3871
+ return this.#perform(request, () => Promise.resolve());
3872
+ }
3873
+ async #perform(request, consume) {
3874
+ const controller = new AbortController();
3875
+ const timer = setTimeout(() => {
3876
+ controller.abort();
3877
+ }, this.#timeoutMs);
3878
+ const headers = new Headers({
3879
+ accept: "application/json",
3880
+ authorization: `Bearer ${this.#credential.value}`
3881
+ });
3882
+ if (request.body !== void 0) {
3883
+ headers.set("content-type", "application/json");
3884
+ }
3885
+ try {
3886
+ const send = () => this.#fetchImpl(new URL(request.path, this.#baseUrl), {
3887
+ ...request.body === void 0 ? {} : { body: JSON.stringify(request.body) },
3888
+ headers,
3889
+ method: request.method,
3890
+ signal: controller.signal
3891
+ });
3892
+ let response = await send();
3893
+ if (response.status === 401 && this.#onUnauthorized !== void 0) {
3894
+ await this.#onUnauthorized();
3895
+ response = await send();
3896
+ }
3897
+ if (!response.ok) {
3898
+ throw new ManagementError(
3899
+ response.status === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
3900
+ { statusCode: response.status }
3901
+ );
3902
+ }
3903
+ return await consume(response);
3904
+ } catch (cause) {
3905
+ if (cause instanceof ManagementError) {
3906
+ throw cause;
3907
+ }
3908
+ if (controller.signal.aborted) {
3909
+ throw new ManagementError("MANAGEMENT_TIMEOUT", { cause });
3910
+ }
3911
+ if (cause instanceof ContractParseError) {
3912
+ throw cause;
3913
+ }
3914
+ throw new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
3915
+ } finally {
3916
+ clearTimeout(timer);
3917
+ }
3918
+ }
3919
+ };
3920
+
3921
+ // src/management/http-management-keys/http-management-keys.ts
3922
+ var HttpManagementKeys = class {
3923
+ #credential;
3924
+ #transport;
3925
+ constructor(options) {
3926
+ this.#credential = options.credential;
3927
+ this.#transport = new ManagementHttpTransport(options);
3928
+ }
3929
+ /** Creates a future-expiring ownership-scoped key.
3930
+ * @param accessToken - Credential required by the frozen contract.
3931
+ * @param input - Key name, expiry, and ownership.
3932
+ * @returns One-time key material.
3933
+ */
3934
+ async create(accessToken, input) {
3935
+ this.#authorize(accessToken);
3936
+ return parseKeyMaterial(
3937
+ await this.#transport.json({
3938
+ body: {
3939
+ ...input.allowedModels === void 0 ? {} : { allowed_models: input.allowedModels },
3940
+ ...input.description === void 0 ? {} : { description: input.description },
3941
+ expires_at: input.expiresAt,
3942
+ ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
3943
+ name: input.name,
3944
+ ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
3945
+ owner_type: input.ownerType,
3946
+ ...input.projectId === null ? {} : { project_id: input.projectId }
3947
+ },
3948
+ method: "POST",
3949
+ path: "api-keys"
3950
+ })
3951
+ );
3952
+ }
3953
+ /** Treats a successful empty response as confirmation of permanent removal.
3954
+ * @param accessToken - Credential required by the frozen contract.
3955
+ * @param id - Key identifier.
3956
+ */
3957
+ async delete(accessToken, id) {
3958
+ this.#authorize(accessToken);
3959
+ await this.#transport.empty({
3960
+ method: "DELETE",
3961
+ path: `api-keys/${encodeURIComponent(id)}`
3962
+ });
3963
+ }
3964
+ /** Gets a safe key DTO.
3965
+ * @param accessToken - Credential required by the frozen contract.
3966
+ * @param id - Key identifier.
3967
+ * @returns The secret-free key DTO.
3968
+ */
3969
+ async get(accessToken, id) {
3970
+ this.#authorize(accessToken);
3971
+ return parseApiKey(
3972
+ await this.#transport.json({
3973
+ method: "GET",
3974
+ path: `api-keys/${encodeURIComponent(id)}`
3975
+ })
3976
+ );
3977
+ }
3978
+ /** Lists safe key DTOs.
3979
+ * @param accessToken - Credential required by the frozen contract.
3980
+ * @returns The parsed key collection.
3981
+ */
3982
+ async list(accessToken) {
3983
+ this.#authorize(accessToken);
3984
+ return parseCollection(
3985
+ await this.#transport.json({ method: "GET", path: "api-keys" }),
3986
+ parseApiKey
3987
+ );
3988
+ }
3989
+ /** Lists organizations visible to the authenticated management subject.
3990
+ * @param accessToken - Credential required by the frozen contract.
3991
+ * @returns The parsed organization collection.
3992
+ */
3993
+ async listOrganizations(accessToken) {
3994
+ this.#authorize(accessToken);
3995
+ return parseCollection(
3996
+ await this.#transport.json({ method: "GET", path: "orgs" }),
3997
+ parseOrganization
3998
+ );
3999
+ }
4000
+ /** Lists projects visible within an organisation filter.
4001
+ * @param accessToken - Credential required by the frozen contract.
4002
+ * @param organisationId - Required backend organisation filter.
4003
+ * @returns The parsed project collection.
4004
+ */
4005
+ async listProjects(accessToken, organisationId) {
4006
+ this.#authorize(accessToken);
4007
+ if (organisationId.trim().length === 0) {
4008
+ throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
4009
+ statusCode: 400
4010
+ });
4011
+ }
4012
+ const query = new URLSearchParams({
4013
+ member_user_id: parseManagementSubject(accessToken),
4014
+ org_id: organisationId
4015
+ });
4016
+ return parseCollection(
4017
+ await this.#transport.json({
4018
+ method: "GET",
4019
+ path: `projects?${query.toString()}`
4020
+ }),
4021
+ parseProject
4022
+ );
4023
+ }
4024
+ /** Regenerates one-time key material while preserving expiry when omitted.
4025
+ * @param accessToken - Credential required by the frozen contract.
4026
+ * @param id - Key identifier.
4027
+ * @param expiresAt - Optional replacement expiry.
4028
+ * @returns Regenerated one-time key material.
4029
+ */
4030
+ async regenerate(accessToken, id, expiresAt) {
4031
+ this.#authorize(accessToken);
4032
+ return parseKeyMaterial(
4033
+ await this.#transport.json({
4034
+ body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
4035
+ method: "POST",
4036
+ path: `api-keys/${encodeURIComponent(id)}/secrets`
4037
+ })
4038
+ );
4039
+ }
4040
+ /** Updates mutable key metadata.
4041
+ * @param accessToken - Credential required by the frozen contract.
4042
+ * @param id - Key identifier.
4043
+ * @param input - Optional name and expiry replacements.
4044
+ * @returns The updated safe key DTO.
4045
+ */
4046
+ async update(accessToken, id, input) {
4047
+ this.#authorize(accessToken);
4048
+ return parseApiKey(
4049
+ await this.#transport.json({
4050
+ body: {
4051
+ ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
4052
+ ...input.name === void 0 ? {} : { name: input.name }
4053
+ },
4054
+ method: "PATCH",
4055
+ path: `api-keys/${encodeURIComponent(id)}`
4056
+ })
4057
+ );
4058
+ }
4059
+ #authorize(accessToken) {
4060
+ if (accessToken.value !== this.#credential.value) {
4061
+ throw new ManagementError("MANAGEMENT_UNAUTHORIZED", {
4062
+ statusCode: 401
4063
+ });
4064
+ }
4065
+ }
4066
+ };
4067
+
4068
+ // src/lazy-management-keys/lazy-management-keys.ts
4069
+ var lazyManagementKeys = (options) => {
4070
+ const client = (accessToken) => new HttpManagementKeys({
4071
+ baseUrl: options.apiBaseUrl,
4072
+ credential: accessToken,
4073
+ ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl }
4074
+ });
4075
+ return {
4076
+ create: async (accessToken, input) => client(accessToken).create(accessToken, input),
4077
+ delete: async (accessToken, id) => client(accessToken).delete(accessToken, id),
4078
+ get: async (accessToken, id) => client(accessToken).get(accessToken, id),
4079
+ list: async (accessToken) => client(accessToken).list(accessToken),
4080
+ listOrganizations: async (accessToken) => client(accessToken).listOrganizations(accessToken),
4081
+ listProjects: async (accessToken, organisationId) => client(accessToken).listProjects(accessToken, organisationId),
4082
+ regenerate: async (accessToken, id, expiresAt) => client(accessToken).regenerate(accessToken, id, expiresAt),
4083
+ update: async (accessToken, id, input) => client(accessToken).update(accessToken, id, input)
4084
+ };
4085
+ };
4086
+
4087
+ // src/production-runtime-options/production-runtime-options.ts
4088
+ var LOGIN_BUDGET_MS = 8.5 * 60 * 1e3;
4089
+ var buildProductionRuntimeOptions = (input) => ({
4090
+ auth: {
4091
+ ...input.browserRunner === void 0 ? {} : { browserRunner: input.browserRunner },
4092
+ session: createAuthSession({
4093
+ clientId: input.clientId,
4094
+ issuerUrl: input.issuerUrl
4095
+ }),
4096
+ timeoutMs: LOGIN_BUDGET_MS
4097
+ },
4098
+ management: {
4099
+ client: () => lazyManagementKeys({ apiBaseUrl: input.apiBaseUrl })
4100
+ },
4101
+ ...input.tokenStore === void 0 ? {} : { tokenStore: input.tokenStore }
4102
+ });
4103
+
4104
+ // src/v1-entry/host-auth-bridge/host-auth-bridge.ts
4105
+ var createHostAuthBridge = () => {
4106
+ let refresh;
4107
+ return {
4108
+ hydrate: (auth) => {
4109
+ if (typeof auth.refresh === "string" && auth.refresh !== "") {
4110
+ refresh = auth.refresh;
4111
+ }
4112
+ },
4113
+ tokenStore: {
4114
+ get: () => Promise.resolve(refresh),
4115
+ set: (token) => {
4116
+ refresh = token;
4117
+ return Promise.resolve();
4118
+ }
4119
+ }
4120
+ };
4121
+ };
4122
+
4123
+ // src/auth/authorization-url-stash/loopback-origin/loopback-origin.ts
4124
+ var loopbackOrigin = (url) => {
4125
+ const redirect = url.searchParams.get("redirect_uri");
4126
+ if (redirect === null) return void 0;
4127
+ let parsed;
4128
+ try {
4129
+ parsed = new URL(redirect);
4130
+ } catch {
4131
+ return void 0;
4132
+ }
4133
+ return parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost" ? parsed.origin : void 0;
4134
+ };
4135
+
4136
+ // src/auth/authorization-url-stash/authorization-url-stash.ts
4137
+ var FALLBACK_URL = "https://route33.ai";
4138
+ var SIGN_IN_INSTRUCTIONS = "Open the Route 33 sign-in link \u2014 your browser will finish at a confirmation page.";
4139
+ var FINISHING_INSTRUCTIONS = "Finishing Route 33 setup\u2026";
4140
+ var URL_WAIT_BUDGET_MS = 3e4;
4141
+ var LISTENER_PROBE_TIMEOUT_MS = 750;
4142
+ var createAuthorizationUrlStash = (options = {}) => {
4143
+ let latest;
4144
+ let waiters = [];
4145
+ const browserRunner = (url) => {
4146
+ latest = url;
4147
+ const publish = waiters;
4148
+ waiters = [];
4149
+ for (const resolve2 of publish) resolve2(url);
4150
+ return Promise.resolve();
4151
+ };
4152
+ const usableCandidate = async (url) => {
4153
+ const origin = loopbackOrigin(url);
4154
+ if (origin === void 0) return url;
4155
+ const controller = new AbortController();
4156
+ const timer = setTimeout(() => {
4157
+ controller.abort();
4158
+ }, options.listenerProbeTimeoutMs ?? LISTENER_PROBE_TIMEOUT_MS);
4159
+ try {
4160
+ const response = await (options.fetchImpl ?? fetch)(`${origin}/`, {
4161
+ signal: controller.signal
4162
+ });
4163
+ return response.status >= 200 ? url : void 0;
4164
+ } catch {
4165
+ return void 0;
4166
+ } finally {
4167
+ clearTimeout(timer);
4168
+ }
4169
+ };
4170
+ const urlForConnect = async (callback) => {
4171
+ let decide;
4172
+ const decided = new Promise((resolve2) => {
4173
+ decide = resolve2;
4174
+ });
4175
+ const settle = (decision) => {
4176
+ clearTimeout(timer);
4177
+ decide(decision);
4178
+ };
4179
+ const timer = setTimeout(() => {
4180
+ settle({ instructions: SIGN_IN_INSTRUCTIONS, url: FALLBACK_URL });
4181
+ }, options.urlWaitBudgetMs ?? URL_WAIT_BUDGET_MS);
4182
+ void Promise.resolve(callback).catch(() => void 0).then(() => {
4183
+ settle({ instructions: FINISHING_INSTRUCTIONS, url: FALLBACK_URL });
4184
+ });
4185
+ const serve = (url) => {
4186
+ settle({ instructions: SIGN_IN_INSTRUCTIONS, url: url.toString() });
4187
+ };
4188
+ const awaitPublish = () => {
4189
+ const publish = new Promise((resolve2) => {
4190
+ waiters.push(resolve2);
4191
+ });
4192
+ void publish.then(serve);
4193
+ };
4194
+ const candidate = latest;
4195
+ if (candidate === void 0) {
4196
+ awaitPublish();
4197
+ } else {
4198
+ void usableCandidate(candidate).then((usable) => {
4199
+ if (usable !== void 0) {
4200
+ serve(usable);
4201
+ } else if (latest !== void 0 && latest !== candidate) {
4202
+ serve(latest);
4203
+ } else {
4204
+ awaitPublish();
4205
+ }
4206
+ });
4207
+ }
4208
+ return decided;
4209
+ };
4210
+ return { browserRunner, urlForConnect };
4211
+ };
4212
+
4213
+ // src/v1-entry/route33-auth-hook/route33-auth-hook.ts
4214
+ var createRoute33AuthHook = (deps) => ({
4215
+ loader: async (auth) => {
4216
+ deps.bridge.hydrate(await auth());
4217
+ return buildOptions(deps.providerBaseURL);
4218
+ },
4219
+ methods: [
4220
+ {
4221
+ authorize: async () => {
4222
+ const stash = createAuthorizationUrlStash();
4223
+ const login = deps.startLogin(stash.browserRunner);
4224
+ const decision = await stash.urlForConnect(login.then(() => void 0));
4225
+ return {
4226
+ callback: async () => {
4227
+ try {
4228
+ const { tokenSet } = await login;
4229
+ deps.bridge.hydrate({
4230
+ refresh: tokenSet.refresh_token,
4231
+ type: "oauth"
4232
+ });
4233
+ return {
4234
+ access: tokenSet.access_token,
4235
+ expires: Date.now() + tokenSet.expires_in * 1e3,
4236
+ provider: "route_33",
4237
+ refresh: tokenSet.refresh_token ?? "",
4238
+ type: "success"
4239
+ };
4240
+ } catch {
4241
+ return { type: "failed" };
4242
+ }
4243
+ },
4244
+ instructions: decision.instructions,
4245
+ method: "auto",
4246
+ url: decision.url
4247
+ };
4248
+ },
4249
+ label: "Route 33 (browser sign-in)",
4250
+ type: "oauth"
4251
+ }
4252
+ ],
4253
+ provider: "route_33"
4254
+ });
4255
+
4256
+ // src/v1-entry/host-modality-flags/host-modality-flags.ts
4257
+ var hostModalityFlags = (modalities) => ({
4258
+ audio: modalities.includes("audio"),
4259
+ image: modalities.includes("image"),
4260
+ pdf: modalities.includes("pdf"),
4261
+ text: modalities.includes("text"),
4262
+ video: modalities.includes("video")
4263
+ });
4264
+
4265
+ // src/v1-entry/host-model-capabilities/host-model-capabilities.ts
4266
+ var hostModelCapabilities = (meta, forceReasoning) => {
4267
+ const modalities = meta.modalities;
4268
+ const capabilities = meta.capabilities;
4269
+ const attachment = meta.attachment ?? capabilities.attachment ?? false;
4270
+ return {
4271
+ attachment,
4272
+ input: hostModalityFlags(modalities?.input ?? ["text"]),
4273
+ interleaved: false,
4274
+ output: hostModalityFlags(modalities?.output ?? ["text"]),
4275
+ reasoning: capabilities.reasoning === true || forceReasoning,
4276
+ temperature: capabilities.temperature === true,
4277
+ toolcall: capabilities.tool_call === true
4278
+ };
4279
+ };
4280
+
4281
+ // src/v1-entry/host-model-quantities/host-model-quantities.ts
4282
+ var ZERO_COST = {
4283
+ cache: { read: 0, write: 0 },
4284
+ input: 0,
4285
+ output: 0
4286
+ };
4287
+ var DEFAULT_LIMIT = { context: 2e5, output: 64e3 };
4288
+ var hostModelQuantities = (meta) => {
4289
+ const cost = meta.cost;
4290
+ const limit = meta.limit;
4291
+ return {
4292
+ cost: cost === void 0 ? ZERO_COST : {
4293
+ cache: {
4294
+ read: cost.cache_read ?? 0,
4295
+ write: cost.cache_write ?? 0
4296
+ },
4297
+ input: cost.input,
4298
+ output: cost.output
4299
+ },
4300
+ limit: limit === void 0 ? DEFAULT_LIMIT : {
4301
+ context: limit.context,
4302
+ output: limit.output
4303
+ }
4304
+ };
4305
+ };
4306
+
4307
+ // src/v1-entry/host-model-vendor/host-model-vendor.ts
4308
+ var hostModelVendor = (slug) => {
4309
+ const separator = slug.indexOf("/");
4310
+ const vendor = separator === -1 ? slug : slug.slice(0, separator);
4311
+ return {
4312
+ forceReasoning: vendor === "anthropic",
4313
+ npm: NATIVE_SDK_BY_VENDOR[vendor] ?? "@ai-sdk/openai-compatible"
4314
+ };
4315
+ };
4316
+
4317
+ // src/v1-entry/host-models/host-models.ts
4318
+ var toHostModels = (input) => {
4319
+ const models = {};
4320
+ for (const [slug, meta] of Object.entries(input.enriched)) {
4321
+ const vendor = hostModelVendor(slug);
4322
+ const capabilities = hostModelCapabilities(meta, vendor.forceReasoning);
4323
+ const quantities = hostModelQuantities(meta);
4324
+ models[slug] = {
4325
+ api: { id: slug, npm: vendor.npm, url: input.baseURL },
4326
+ attachment: capabilities.attachment,
4327
+ capabilities,
4328
+ cost: quantities.cost,
4329
+ headers: {},
4330
+ id: slug,
4331
+ limit: quantities.limit,
4332
+ name: meta.name,
4333
+ options: {},
4334
+ providerID: "route_33",
4335
+ release_date: "",
4336
+ status: "active",
4337
+ ...meta.variants === void 0 ? {} : { variants: structuredClone(meta.variants) }
4338
+ };
4339
+ }
4340
+ return models;
4341
+ };
4342
+
4343
+ // src/v1-entry/route33-provider-models/route33-provider-models.ts
4344
+ var createRoute33ProviderModels = (deps) => async (provider) => {
4345
+ const fallback = provider.models;
4346
+ const key = await deps.resolveKey();
4347
+ if (key === void 0) return fallback;
4348
+ const [catalog, modelsDev] = await Promise.all([
4349
+ (deps.loadCatalog ?? getCatalog)({
4350
+ ...deps.catalog,
4351
+ cacheDir: deps.cacheDir,
4352
+ gatewayKey: key
4353
+ }),
4354
+ deps.loadModelsDev()
4355
+ ]);
4356
+ const enriched = enrichCatalog(catalog, modelsDev);
4357
+ const models = toHostModels({
4358
+ baseURL: deps.catalog.baseURL,
4359
+ enriched
4360
+ });
4361
+ return Object.keys(models).length === 0 ? fallback : models;
4362
+ };
4363
+
4364
+ // src/contract/fixtures/fixtures.ts
4365
+ var contractFixtures = {
4366
+ apiKey: {
4367
+ allowed_models: null,
4368
+ expires_at: "2030-02-01T00:00:00.000Z",
4369
+ id: "key_1",
4370
+ name: "OpenCode",
4371
+ effective_budget: null,
4372
+ max_budget: null,
4373
+ org_id: "org_1",
4374
+ ownership_type: "project",
4375
+ project_id: "project_1",
4376
+ revoked: false,
4377
+ status: "active"
4378
+ },
4379
+ keyMaterial: {
4380
+ allowed_models: null,
4381
+ expires_at: "2030-02-01T00:00:00.000Z",
4382
+ id: "key_1",
4383
+ key: "r33_sk_plaintext",
4384
+ name: "OpenCode",
4385
+ org_id: "org_1",
4386
+ ownership_type: "project",
4387
+ project_id: "project_1",
4388
+ revoked: false,
4389
+ status: "active"
4390
+ },
4391
+ project: {
4392
+ effective_budget: null,
4393
+ id: "project_1",
4394
+ max_budget: null,
4395
+ name: "Inference",
4396
+ org_id: "org_1"
4397
+ },
4398
+ tokenSet: {
4399
+ access_token: "access_1",
4400
+ expires_in: 3600,
4401
+ id_token: "id_1",
4402
+ refresh_token: "refresh_1",
4403
+ refresh_token_expires_in: 2592e3,
4404
+ scope: "openid profile email",
4405
+ token_type: "Bearer"
4406
+ }
4407
+ };
4408
+
4409
+ // src/contract/fixtures/fixture-to-wire/fixture-to-wire.ts
4410
+ var fixtureToWire = (value) => structuredClone(value);
4411
+
4412
+ // src/contract/fixtures/parse-contract-fixtures/parse-contract-fixtures.ts
4413
+ var parseContractFixtures = (fixtures) => ({
4414
+ apiKey: parseApiKey(fixtureToWire(fixtures.apiKey)),
4415
+ keyMaterial: parseKeyMaterial(fixtureToWire(fixtures.keyMaterial)),
4416
+ project: parseProject(fixtureToWire(fixtures.project)),
4417
+ tokenSet: parseTokenSet(fixtureToWire(fixtures.tokenSet))
4418
+ });
4419
+
4420
+ // src/index.ts
4421
+ var clientId = readEnvClientId() ?? DEFAULT_ROUTE33_CLIENT_ID;
4422
+ var issuerUrl = readEnvAuthIssuer() ?? DEFAULT_AUTH_ISSUER_URL;
4423
+ var authBridge = createHostAuthBridge();
4424
+ var startNativeLogin = (browserRunner) => loginFlow({
4425
+ browserRunner,
4426
+ clientId,
4427
+ session: createAuthSession({ clientId, issuerUrl }),
4428
+ timeoutMs: LOGIN_BUDGET_MS
4429
+ });
4430
+ var route33Plugin = createRoute33Plugin({
4431
+ bindRuntime: (instance) => {
4432
+ runtime = instance;
4433
+ },
4434
+ runtime: buildProductionRuntimeOptions({
4435
+ apiBaseUrl: readEnvApiBase() ?? DEFAULT_MANAGEMENT_API_BASE_URL,
4436
+ clientId,
4437
+ issuerUrl,
4438
+ tokenStore: authBridge.tokenStore
4439
+ })
4440
+ });
4441
+ var runtime;
4442
+ var modelsDevOnce;
4443
+ var Route33Plugin = async (input) => {
4444
+ const hooks = await route33Plugin(input);
4445
+ const native = readEnvDirectApiKey();
4446
+ return {
4447
+ ...hooks,
4448
+ ...native !== void 0 ? {} : {
4449
+ auth: createRoute33AuthHook({
4450
+ bridge: authBridge,
4451
+ providerBaseURL: readEnvBaseUrl() ?? DEFAULT_BASE_URL,
4452
+ startLogin: startNativeLogin
4453
+ }),
4454
+ provider: {
4455
+ id: "route_33",
4456
+ models: createRoute33ProviderModels({
4457
+ cacheDir: readEnvCacheDir(),
4458
+ catalog: {
4459
+ baseURL: readEnvBaseUrl() ?? DEFAULT_BASE_URL,
4460
+ catalogTtlMs: readEnvCatalogTtlMs(),
4461
+ disableIdShim: readEnvDisableIdShim(),
4462
+ discoveryEnabled: readEnvDiscovery()
4463
+ },
4464
+ loadModelsDev: () => {
4465
+ modelsDevOnce ??= loadModelsDev({
4466
+ cacheDir: readEnvCacheDir()
4467
+ });
4468
+ return modelsDevOnce;
4469
+ },
4470
+ resolveKey: () => {
4471
+ const active = runtime;
4472
+ return active === void 0 ? Promise.resolve(void 0) : active.resolveWorkspaceCredential(input.worktree);
4473
+ }
4474
+ })
4475
+ }
4476
+ }
4477
+ };
4478
+ };
4479
+ export {
4480
+ AttributionPromptError,
4481
+ AuthError,
4482
+ ContractParseError,
4483
+ DEFAULT_GATEWAY_KEY_RENEWAL_RATIO,
4484
+ DEFAULT_GATEWAY_KEY_TTL_MS,
4485
+ FileSecretStore,
4486
+ GatewayApiKey,
4487
+ HostStorageSecretStore,
4488
+ HttpManagementKeys,
4489
+ KeyLeaseError,
4490
+ LeaseState,
4491
+ ManagementError,
4492
+ ManagementJwt,
4493
+ PERSONAL_KEY_ACTIVE_MARKER,
4494
+ REQUESTED_OAUTH_SCOPES,
4495
+ Route33Plugin,
4496
+ Route33Runtime,
4497
+ TRUSTED_PARTY_COPY,
4498
+ buildAuthorizeUrl,
4499
+ changeAttribution,
4500
+ clearAttribution,
4501
+ contractFixtures,
4502
+ controlOrphans,
4503
+ createAttributionPrompt,
4504
+ createAuthLoopbackCallback,
4505
+ createAuthSession,
4506
+ createLeaseInstallationFactory,
4507
+ createPkceVerifierAndChallenge,
4508
+ createRoute33Plugin,
4509
+ deriveScopeId,
4510
+ detectWorktreeRoot,
4511
+ exchangeCodeAndParse,
4512
+ fixtureToWire,
4513
+ inspectSession,
4514
+ leaseForAttribution,
4515
+ loginFlow,
4516
+ mintKey,
4517
+ openBrowserAndCapture,
4518
+ parseApiKey,
4519
+ parseAttribution,
4520
+ parseCatalogResult,
4521
+ parseCollection,
4522
+ parseContractFixtures,
4523
+ parseGatewayKey,
4524
+ parseKeyMaterial,
4525
+ parseManagementJwt,
4526
+ parseManagementSubject,
4527
+ parseOrganization,
4528
+ parseProject,
4529
+ parseTokenSet,
4530
+ pkceChallenge,
4531
+ readAttribution,
4532
+ readLegacyKey,
4533
+ recoverLeaseState,
4534
+ refreshSession,
4535
+ removeLegacyKey,
4536
+ renewKey,
4537
+ resetAttribution,
4538
+ resolveAttribution,
4539
+ resolveAttributionFile,
4540
+ resolveLeasePolicy,
4541
+ resolveSeamValue,
4542
+ reusableLease,
4543
+ rotateNow,
4544
+ writeAttribution
4545
+ };