@r-33/opencode 0.4.7-rc.22 → 0.4.7-rc.24

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.
@@ -1,219 +1,22 @@
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
- };
1
+ // src/index.ts
2
+ import { createAuthSession as createAuthSession2 } from "@r-33/auth-browser";
120
3
 
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
- }
4
+ // src/cli/read-env-base-url/read-env-base-url.ts
5
+ var readEnvBaseUrl = (env = process.env) => {
6
+ const value = env["ROUTE33_BASE_URL"]?.trim();
7
+ return value === "" ? void 0 : value;
159
8
  };
160
9
 
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
- }
10
+ // src/cli/read-env-api-base/read-env-api-base.ts
11
+ var readEnvApiBase = (env = process.env) => {
12
+ const value = env["ROUTE33_API_BASE"]?.trim();
13
+ return value === "" ? void 0 : value;
197
14
  };
198
15
 
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
- };
16
+ // src/cli/read-env-auth-issuer/read-env-auth-issuer.ts
17
+ var readEnvAuthIssuer = (env = process.env) => {
18
+ const value = env["ROUTE33_AUTH_ISSUER"]?.trim();
19
+ return value === "" ? void 0 : value;
217
20
  };
218
21
 
219
22
  // src/shared/default-auth-issuer-url/default-auth-issuer-url.ts
@@ -261,260 +64,6 @@ var resolveCacheDir = (env) => {
261
64
  );
262
65
  };
263
66
 
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
67
  // src/cli/read-env-cache-dir/read-env-cache-dir.ts
519
68
  var readEnvCacheDir = (env = process.env) => resolveCacheDir(env);
520
69
 
@@ -596,6 +145,18 @@ var abortableSleep = (milliseconds, signal) => new Promise((resolve2, reject) =>
596
145
  // src/config/is-resendable-body/is-resendable-body.ts
597
146
  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
147
 
148
+ // src/contract/predicates/has-string-fields/has-string-fields.ts
149
+ var hasStringFields = (record, fields) => fields.every((field) => typeof record[field] === "string");
150
+
151
+ // src/contract/predicates/is-nullable-string/is-nullable-string.ts
152
+ var isNullableString = (value) => typeof value === "string" || value === null;
153
+
154
+ // src/contract/predicates/is-owner-type/is-owner-type.ts
155
+ var isOwnerType = (value) => value === "project" || value === "user_personal" || value === "user_project";
156
+
157
+ // src/contract/predicates/is-record/is-record.ts
158
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
159
+
599
160
  // src/config/parse-exhaustion-envelope/parse-exhaustion-envelope.ts
600
161
  var parseExhaustionEnvelope = async (response) => {
601
162
  let body;
@@ -885,8 +446,8 @@ var catalogMemory = /* @__PURE__ */ new Map();
885
446
  var CATALOG_CACHE_VERSION = 2;
886
447
 
887
448
  // 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}
449
+ import { createHash } from "node:crypto";
450
+ var hashKey = (baseURL, gatewayKey) => createHash("sha256").update(`${baseURL}
890
451
  ${gatewayKey.value}`).digest("hex").slice(0, 12);
891
452
 
892
453
  // src/catalog/catalog-cache/is-catalog-model-record/is-catalog-model-record.ts
@@ -984,12 +545,72 @@ var catalogModelsUrl = (baseURL) => {
984
545
  while (normalizedBaseURL.endsWith("/")) {
985
546
  normalizedBaseURL = normalizedBaseURL.slice(0, -1);
986
547
  }
987
- return `${normalizedBaseURL}/models`;
548
+ return `${normalizedBaseURL}/models`;
549
+ };
550
+
551
+ // src/catalog/default-fetch-timeout-ms/default-fetch-timeout-ms.ts
552
+ var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
553
+
554
+ // src/contract/adapters/contract-parse-error/contract-parse-error.ts
555
+ var ContractParseError = class extends Error {
556
+ };
557
+
558
+ // src/contract/adapters/gateway-api-key/gateway-api-key.ts
559
+ var GatewayApiKey = class {
560
+ value;
561
+ constructor(value) {
562
+ this.value = value;
563
+ }
564
+ };
565
+
566
+ // src/contract/adapters/management-jwt/management-jwt.ts
567
+ var ManagementJwt = class {
568
+ value;
569
+ constructor(value) {
570
+ this.value = value;
571
+ }
572
+ };
573
+
574
+ // src/contract/adapters/parse-gateway-key/parse-gateway-key.ts
575
+ var parseGatewayKey = (value) => {
576
+ if (typeof value !== "string" || value.length === 0) {
577
+ throw new Error("gateway key must be non-empty");
578
+ }
579
+ return new GatewayApiKey(value);
580
+ };
581
+
582
+ // src/contract/adapters/parse-management-jwt/parse-management-jwt.ts
583
+ var parseManagementJwt = (value) => {
584
+ if (typeof value !== "string" || value.length === 0) {
585
+ throw new Error("management token must be non-empty");
586
+ }
587
+ return new ManagementJwt(value);
588
+ };
589
+
590
+ // src/contract/adapters/parse-management-subject/parse-management-subject.ts
591
+ var parseManagementSubject = (credential) => {
592
+ const encodedPayload = credential.value.split(".")[1];
593
+ if (encodedPayload === void 0 || encodedPayload.length === 0) {
594
+ throw new ContractParseError("management token carries no usable subject");
595
+ }
596
+ let payload;
597
+ try {
598
+ payload = JSON.parse(
599
+ Buffer.from(encodedPayload, "base64url").toString("utf8")
600
+ );
601
+ } catch {
602
+ throw new ContractParseError("management token payload is not JSON");
603
+ }
604
+ if (!isRecord(payload)) {
605
+ throw new ContractParseError("management token payload is not an object");
606
+ }
607
+ const subject = payload["sub"];
608
+ if (typeof subject !== "string" || subject.length === 0) {
609
+ throw new ContractParseError("management token carries no usable subject");
610
+ }
611
+ return subject;
988
612
  };
989
613
 
990
- // src/catalog/default-fetch-timeout-ms/default-fetch-timeout-ms.ts
991
- var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
992
-
993
614
  // src/contract/gateway-catalog/parse-catalog-result/parse-catalog-result.ts
994
615
  var parseCatalogResult = (value) => {
995
616
  if (!isRecord(value) || !Array.isArray(value["data"])) {
@@ -2943,7 +2564,7 @@ var createLeaseInstallationFactory = (options) => {
2943
2564
  };
2944
2565
 
2945
2566
  // src/key-lease/scope-id/scope-id.ts
2946
- import { createHash as createHash3 } from "node:crypto";
2567
+ import { createHash as createHash2 } from "node:crypto";
2947
2568
  var deriveScopeId = (input) => {
2948
2569
  let identity;
2949
2570
  switch (input.attribution.kind) {
@@ -2966,7 +2587,7 @@ var deriveScopeId = (input) => {
2966
2587
  throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
2967
2588
  }
2968
2589
  }
2969
- return createHash3("sha256").update(JSON.stringify(identity)).digest("hex");
2590
+ return createHash2("sha256").update(JSON.stringify(identity)).digest("hex");
2970
2591
  };
2971
2592
 
2972
2593
  // src/requested-client-id/requested-client-id.ts
@@ -3081,6 +2702,47 @@ var TRUSTED_PARTY_COPY = {
3081
2702
  title: "Connect Route 33"
3082
2703
  };
3083
2704
 
2705
+ // src/ux/callback-page-copy/callback-page-copy.ts
2706
+ var CALLBACK_PAGE_COPY = {
2707
+ errorHeadline: "Sign-in failed",
2708
+ errorSubline: "Return to OpenCode and retry.",
2709
+ successHeadline: "Signed in to route33",
2710
+ successSubline: "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."
2711
+ };
2712
+
2713
+ // src/route33-runtime/login-session/login-session.ts
2714
+ import { AuthError as AuthError2 } from "@r-33/auth-browser";
2715
+
2716
+ // src/route33-login/route33-login.ts
2717
+ import {
2718
+ AuthError,
2719
+ loginFlow
2720
+ } from "@r-33/auth-browser";
2721
+
2722
+ // src/requested-scopes/requested-scopes.ts
2723
+ var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read projects:read users:read keys:read keys:write";
2724
+
2725
+ // src/route33-login/route33-login.ts
2726
+ var route33Login = async (options) => {
2727
+ const log = options.logger ?? logger;
2728
+ const tokenSet = await loginFlow({
2729
+ ...options.browserRunner === void 0 ? {} : { browserRunner: options.browserRunner },
2730
+ clientId: options.clientId,
2731
+ logger: log,
2732
+ pageCopy: CALLBACK_PAGE_COPY,
2733
+ scope: REQUESTED_OAUTH_SCOPES,
2734
+ session: options.session,
2735
+ ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
2736
+ });
2737
+ let credential;
2738
+ try {
2739
+ credential = parseManagementJwt(tokenSet.access_token);
2740
+ } catch (cause) {
2741
+ throw new AuthError("AUTH_TOKEN_RESPONSE_INVALID", { cause });
2742
+ }
2743
+ return { credential, tokenSet };
2744
+ };
2745
+
3084
2746
  // src/route33-runtime/login-session/login-session.ts
3085
2747
  var EXPIRY_SKEW_MS = 6e4;
3086
2748
  var LoginSession = class {
@@ -3090,15 +2752,11 @@ var LoginSession = class {
3090
2752
  constructor(options) {
3091
2753
  this.#options = options;
3092
2754
  }
3093
- /**
3094
- * Resolves the login once per process, sharing in-flight attempts.
3095
- * @param policy - Whether this attempt may start a browser login; an in-flight attempt is always shared.
3096
- * @returns The token set plus its typed management credential.
3097
- */
3098
2755
  /**
3099
2756
  * Clears the session: the cached login result and the stored refresh
3100
2757
  * token. The next login starts from scratch — /r33 logout and the
3101
2758
  * auto-reconnect path both land here.
2759
+ * @returns Resolved once the session and the stored refresh token are gone.
3102
2760
  */
3103
2761
  async clear() {
3104
2762
  this.#result = void 0;
@@ -3106,8 +2764,9 @@ var LoginSession = class {
3106
2764
  await this.#options.tokenStore?.set(void 0);
3107
2765
  }
3108
2766
  /**
3109
- *
3110
- * @param policy
2767
+ * Resolves the login once per process, sharing in-flight attempts.
2768
+ * @param policy - Whether this attempt may start a browser login; an in-flight attempt is always shared.
2769
+ * @returns The token set plus its typed management credential.
3111
2770
  */
3112
2771
  result(policy = {}) {
3113
2772
  if (this.#result !== void 0 && this.#expiresAt !== void 0 && Date.now() >= this.#expiresAt - EXPIRY_SKEW_MS) {
@@ -3133,10 +2792,10 @@ var LoginSession = class {
3133
2792
  return viaRefresh;
3134
2793
  }
3135
2794
  if (policy.allowBrowser === false) {
3136
- throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED");
2795
+ throw new AuthError2("AUTH_REAUTHENTICATION_REQUIRED");
3137
2796
  }
3138
2797
  await this.#options.presenter?.present(TRUSTED_PARTY_COPY);
3139
- const result = await loginFlow(this.#options.auth);
2798
+ const result = await route33Login(this.#options.auth);
3140
2799
  this.#trackExpiry(result.tokenSet.expires_in);
3141
2800
  await this.#persist(result.tokenSet.refresh_token);
3142
2801
  return result;
@@ -3150,23 +2809,29 @@ var LoginSession = class {
3150
2809
  if (stored === void 0 || stored === "") {
3151
2810
  return void 0;
3152
2811
  }
3153
- let tokenSet;
3154
- try {
3155
- tokenSet = await this.#options.auth.session.refresh(stored);
3156
- } catch {
3157
- logger.info("auth.refresh.fell-back-to-browser");
2812
+ const tokenSet = await this.#tryRefreshToken(stored);
2813
+ if (tokenSet === void 0) {
3158
2814
  return void 0;
3159
2815
  }
3160
2816
  let credential;
3161
2817
  try {
3162
2818
  credential = parseManagementJwt(tokenSet.access_token);
3163
2819
  } catch (cause) {
3164
- throw new AuthError("AUTH_TOKEN_RESPONSE_INVALID", { cause });
2820
+ throw new AuthError2("AUTH_TOKEN_RESPONSE_INVALID", { cause });
3165
2821
  }
3166
2822
  this.#trackExpiry(tokenSet.expires_in);
3167
2823
  await this.#persist(tokenSet.refresh_token);
3168
2824
  return { credential, tokenSet };
3169
2825
  }
2826
+ async #tryRefreshToken(stored) {
2827
+ const session = this.#options.auth.session;
2828
+ try {
2829
+ return await session.refresh(stored);
2830
+ } catch {
2831
+ logger.info("auth.refresh.fell-back-to-browser");
2832
+ return void 0;
2833
+ }
2834
+ }
3170
2835
  #trackExpiry(expiresIn) {
3171
2836
  this.#expiresAt = Date.now() + expiresIn * 1e3;
3172
2837
  }
@@ -3200,6 +2865,53 @@ var Route33Runtime = class {
3200
2865
  login(policy = {}) {
3201
2866
  return this.#session.result(policy);
3202
2867
  }
2868
+ /**
2869
+ * Lists exactly the projects the current management login can mint keys
2870
+ * on: the login's per-user budget rows intersected with the
2871
+ * member-visible project listing, organisation names stitched from the
2872
+ * login's own memberships. Orgs the login merely administers carry no
2873
+ * budget row and drop out — the picker never offers a project whose
2874
+ * keys the login cannot create.
2875
+ * @returns Mintable projects with organisation context for the picker.
2876
+ */
2877
+ async listMintableProjects() {
2878
+ const credential = await this.#session.credential();
2879
+ const subject = this.#subject(credential);
2880
+ const client = this.#client();
2881
+ const [budgets, memberships] = await Promise.all([
2882
+ client.listProjectBudgets(credential, subject),
2883
+ client.listMemberships(credential, subject)
2884
+ ]);
2885
+ const organisationNames = new Map(
2886
+ memberships.org_memberships.map(({ org_id, org_name }) => [
2887
+ org_id,
2888
+ org_name
2889
+ ])
2890
+ );
2891
+ const listings = await Promise.all(
2892
+ [...new Set(budgets.data.map(({ org_id }) => org_id))].map(
2893
+ (orgId) => client.listProjects(credential, orgId)
2894
+ )
2895
+ );
2896
+ const projectsById = new Map(
2897
+ listings.flatMap(({ data }) => data).map((project) => [project.id, project])
2898
+ );
2899
+ return budgets.data.flatMap(({ org_id, project_id }) => {
2900
+ const project = projectsById.get(project_id);
2901
+ if (project === void 0) {
2902
+ return [];
2903
+ }
2904
+ return [
2905
+ {
2906
+ ...project,
2907
+ organisation: {
2908
+ id: org_id,
2909
+ name: organisationNames.get(org_id) ?? org_id
2910
+ }
2911
+ }
2912
+ ];
2913
+ });
2914
+ }
3203
2915
  /**
3204
2916
  * Lists projects visible to the current management login.
3205
2917
  * @returns Projects with their listing organisation stitched in.
@@ -3439,7 +3151,7 @@ var Route33Runtime = class {
3439
3151
  return resolveAttribution({
3440
3152
  loadProjects: async () => {
3441
3153
  await this.#session.credential();
3442
- return this.listProjects();
3154
+ return this.listMintableProjects();
3443
3155
  },
3444
3156
  ...this.#options.presenter === void 0 ? {} : { presenter: this.#options.presenter },
3445
3157
  state: this.#options.state
@@ -3603,6 +3315,43 @@ var createRoute33Plugin = (options = {}) => {
3603
3315
  };
3604
3316
  };
3605
3317
 
3318
+ // src/production-runtime-options/production-runtime-options.ts
3319
+ import { createAuthSession } from "@r-33/auth-browser";
3320
+
3321
+ // src/management/drain-pages/drain-pages.ts
3322
+ var drainPages = async (fetchPage) => {
3323
+ const first = await fetchPage("");
3324
+ const data = [...first.data];
3325
+ let { page } = first;
3326
+ while (page.has_more && page.next_cursor !== null) {
3327
+ const next = await fetchPage(page.next_cursor);
3328
+ data.push(...next.data);
3329
+ ({ page } = next);
3330
+ }
3331
+ return { data, page: { ...page, has_more: false, next_cursor: null } };
3332
+ };
3333
+
3334
+ // src/management/management-error/management-error.ts
3335
+ var ManagementError = class extends Error {
3336
+ constructor(code, options) {
3337
+ super(
3338
+ "Route 33 management request failed",
3339
+ options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
3340
+ );
3341
+ this.code = code;
3342
+ this.name = "ManagementError";
3343
+ this.statusCode = options?.statusCode;
3344
+ }
3345
+ code;
3346
+ statusCode;
3347
+ };
3348
+
3349
+ // src/management/sdk-management-keys/sdk-management-keys.ts
3350
+ import {
3351
+ createRoute33Client,
3352
+ Route33SdkError
3353
+ } from "@r-33/sdk";
3354
+
3606
3355
  // src/contract/management-keys/parse-api-key/parse-api-key.ts
3607
3356
  var parseApiKey = (value) => {
3608
3357
  if (!isRecord(value) || !isOwnerType(value["ownership_type"]) || !isNullableString(value["project_id"])) {
@@ -3764,6 +3513,39 @@ var parseOrganization = (value) => {
3764
3513
  };
3765
3514
  };
3766
3515
 
3516
+ // src/contract/management-keys/parse-project-budget-state/parse-project-budget-state.ts
3517
+ var parseProjectBudgetState = (value) => {
3518
+ if (!isRecord(value)) {
3519
+ throw new ContractParseError("invalid project budget");
3520
+ }
3521
+ const stringField = (name) => {
3522
+ const field = value[name];
3523
+ if (typeof field !== "string") {
3524
+ throw new ContractParseError("invalid project budget");
3525
+ }
3526
+ return field;
3527
+ };
3528
+ const cap = value["cap"];
3529
+ if (typeof cap !== "number") {
3530
+ throw new ContractParseError("invalid project budget");
3531
+ }
3532
+ const hasUsage = value["has_usage"];
3533
+ if (typeof hasUsage !== "boolean") {
3534
+ throw new ContractParseError("invalid project budget");
3535
+ }
3536
+ const source = value["source"];
3537
+ if (source !== "own_cap" && source !== "project_default" && source !== "org_default" && source !== "tenant_default" && source !== "platform_default") {
3538
+ throw new ContractParseError("invalid project budget");
3539
+ }
3540
+ return {
3541
+ cap,
3542
+ has_usage: hasUsage,
3543
+ org_id: stringField("org_id"),
3544
+ project_id: stringField("project_id"),
3545
+ source
3546
+ };
3547
+ };
3548
+
3767
3549
  // src/contract/management-keys/parse-wire-money/parse-wire-money.ts
3768
3550
  var parseWireMoney = (value) => {
3769
3551
  if (!isRecord(value)) return null;
@@ -3786,266 +3568,185 @@ var parseProject = (value) => {
3786
3568
  };
3787
3569
  };
3788
3570
 
3789
- // src/management/management-error/management-error.ts
3790
- var ManagementError = class extends Error {
3791
- constructor(code, options) {
3792
- super(
3793
- "Route 33 management request failed",
3794
- options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
3795
- );
3796
- this.code = code;
3797
- this.name = "ManagementError";
3798
- this.statusCode = options?.statusCode;
3571
+ // src/contract/management-keys/parse-user-memberships/parse-user-memberships.ts
3572
+ var parseUserMemberships = (value) => {
3573
+ if (!isRecord(value)) {
3574
+ throw new ContractParseError("invalid user memberships");
3799
3575
  }
3800
- code;
3801
- statusCode;
3576
+ const rows = value["org_memberships"];
3577
+ if (!Array.isArray(rows)) {
3578
+ throw new ContractParseError("invalid user memberships");
3579
+ }
3580
+ return {
3581
+ org_memberships: rows.map((row) => {
3582
+ if (!isRecord(row)) {
3583
+ throw new ContractParseError("invalid user memberships");
3584
+ }
3585
+ const orgId = row["org_id"];
3586
+ const orgName = row["org_name"];
3587
+ if (typeof orgId !== "string" || typeof orgName !== "string") {
3588
+ throw new ContractParseError("invalid user memberships");
3589
+ }
3590
+ return { org_id: orgId, org_name: orgName };
3591
+ })
3592
+ };
3802
3593
  };
3803
3594
 
3804
- // src/management/management-http-transport/management-http-transport.ts
3805
- var ManagementHttpTransport = class {
3806
- #baseUrl;
3807
- #credential;
3808
- #fetchImpl;
3809
- #onUnauthorized;
3810
- #timeoutMs;
3811
- constructor(options) {
3812
- const baseUrl = options.baseUrl ?? "https://api.route33.ai/v1";
3813
- this.#baseUrl = new URL(baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`);
3814
- this.#credential = options.credential;
3815
- this.#fetchImpl = options.fetchImpl ?? fetch;
3816
- this.#onUnauthorized = options.onUnauthorized;
3817
- this.#timeoutMs = options.timeoutMs ?? 1e4;
3818
- }
3819
- /** Sends a request and reads one JSON value under the request timeout.
3820
- * @param request - Management path, method, and optional JSON body.
3821
- * @returns The untrusted response value.
3822
- */
3823
- json(request) {
3824
- return this.#perform(request, async (response) => {
3825
- try {
3826
- return await response.json();
3827
- } catch (cause) {
3828
- throw new ContractParseError("invalid management response", { cause });
3829
- }
3830
- });
3831
- }
3832
- /** Sends a request whose successful response has no body.
3833
- * @param request - Management path and method.
3834
- */
3835
- empty(request) {
3836
- return this.#perform(request, () => Promise.resolve());
3837
- }
3838
- async #perform(request, consume) {
3839
- const controller = new AbortController();
3840
- const timer = setTimeout(() => {
3841
- controller.abort();
3842
- }, this.#timeoutMs);
3843
- const headers = new Headers({
3844
- accept: "application/json",
3845
- authorization: `Bearer ${this.#credential.value}`
3595
+ // src/management/sdk-management-keys/sdk-management-keys.ts
3596
+ var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
3597
+ var sdkManagementKeys = (options) => {
3598
+ const baseUrl = options.apiBaseUrl.replace(API_PREFIX_PATTERN, "");
3599
+ const timeoutMs = options.timeoutMs ?? 1e4;
3600
+ const fetchImpl = options.fetchImpl;
3601
+ const observingFetch = (status) => fetchImpl === void 0 ? void 0 : async (input, init) => {
3602
+ const response = await fetchImpl(input, init);
3603
+ status.code = response.status;
3604
+ return response;
3605
+ };
3606
+ const callClient = (accessToken, status) => {
3607
+ const provider = {
3608
+ getToken: () => Promise.resolve(accessToken.value),
3609
+ onUnauthorized: () => Promise.resolve(accessToken.value)
3610
+ };
3611
+ const observedFetch = observingFetch(status);
3612
+ return createRoute33Client({
3613
+ baseUrl,
3614
+ provider,
3615
+ timeoutMs,
3616
+ ...observedFetch === void 0 ? {} : { fetch: observedFetch }
3846
3617
  });
3847
- if (request.body !== void 0) {
3848
- headers.set("content-type", "application/json");
3618
+ };
3619
+ const mapFailure = (cause) => {
3620
+ if (cause instanceof ManagementError || cause instanceof ContractParseError) {
3621
+ return cause;
3622
+ }
3623
+ if (cause instanceof Route33SdkError) {
3624
+ const code = cause.code === "SDK_TIMEOUT" ? "MANAGEMENT_TIMEOUT" : "MANAGEMENT_NETWORK_ERROR";
3625
+ return new ManagementError(code, { cause });
3626
+ }
3627
+ if (cause instanceof SyntaxError) {
3628
+ return new ContractParseError("invalid management response", { cause });
3849
3629
  }
3630
+ return new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
3631
+ };
3632
+ const call = async (accessToken, run) => {
3633
+ const status = { code: void 0 };
3850
3634
  try {
3851
- const send = () => this.#fetchImpl(new URL(request.path, this.#baseUrl), {
3852
- ...request.body === void 0 ? {} : { body: JSON.stringify(request.body) },
3853
- headers,
3854
- method: request.method,
3855
- signal: controller.signal
3856
- });
3857
- let response = await send();
3858
- if (response.status === 401 && this.#onUnauthorized !== void 0) {
3859
- await this.#onUnauthorized();
3860
- response = await send();
3861
- }
3862
- if (!response.ok) {
3635
+ const outcome = await run(callClient(accessToken, status));
3636
+ const code = status.code;
3637
+ if (code === void 0 || code < 200 || code >= 300) {
3863
3638
  throw new ManagementError(
3864
- response.status === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
3865
- { statusCode: response.status }
3639
+ code === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
3640
+ { statusCode: code }
3866
3641
  );
3867
3642
  }
3868
- return await consume(response);
3643
+ return outcome.data;
3869
3644
  } catch (cause) {
3870
- if (cause instanceof ManagementError) {
3871
- throw cause;
3872
- }
3873
- if (controller.signal.aborted) {
3874
- throw new ManagementError("MANAGEMENT_TIMEOUT", { cause });
3875
- }
3876
- if (cause instanceof ContractParseError) {
3877
- throw cause;
3878
- }
3879
- throw new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
3880
- } finally {
3881
- clearTimeout(timer);
3645
+ throw mapFailure(cause);
3882
3646
  }
3883
- }
3884
- };
3885
-
3886
- // src/management/http-management-keys/http-management-keys.ts
3887
- var HttpManagementKeys = class {
3888
- #credential;
3889
- #transport;
3890
- constructor(options) {
3891
- this.#credential = options.credential;
3892
- this.#transport = new ManagementHttpTransport(options);
3893
- }
3894
- /** Creates a future-expiring ownership-scoped key.
3895
- * @param accessToken - Credential required by the frozen contract.
3896
- * @param input - Key name, expiry, and ownership.
3897
- * @returns One-time key material.
3898
- */
3899
- async create(accessToken, input) {
3900
- this.#authorize(accessToken);
3901
- return parseKeyMaterial(
3902
- await this.#transport.json({
3903
- body: {
3904
- ...input.allowedModels === void 0 ? {} : { allowed_models: input.allowedModels },
3905
- ...input.description === void 0 ? {} : { description: input.description },
3906
- expires_at: input.expiresAt,
3907
- ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
3908
- name: input.name,
3909
- ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
3910
- owner_type: input.ownerType,
3911
- ...input.projectId === null ? {} : { project_id: input.projectId }
3912
- },
3913
- method: "POST",
3914
- path: "api-keys"
3915
- })
3916
- );
3917
- }
3918
- /** Treats a successful empty response as confirmation of permanent removal.
3919
- * @param accessToken - Credential required by the frozen contract.
3920
- * @param id - Key identifier.
3921
- */
3922
- async delete(accessToken, id) {
3923
- this.#authorize(accessToken);
3924
- await this.#transport.empty({
3925
- method: "DELETE",
3926
- path: `api-keys/${encodeURIComponent(id)}`
3927
- });
3928
- }
3929
- /** Gets a safe key DTO.
3930
- * @param accessToken - Credential required by the frozen contract.
3931
- * @param id - Key identifier.
3932
- * @returns The secret-free key DTO.
3933
- */
3934
- async get(accessToken, id) {
3935
- this.#authorize(accessToken);
3936
- return parseApiKey(
3937
- await this.#transport.json({
3938
- method: "GET",
3939
- path: `api-keys/${encodeURIComponent(id)}`
3940
- })
3941
- );
3942
- }
3943
- /** Lists safe key DTOs.
3944
- * @param accessToken - Credential required by the frozen contract.
3945
- * @returns The parsed key collection.
3946
- */
3947
- async list(accessToken) {
3948
- this.#authorize(accessToken);
3949
- return parseCollection(
3950
- await this.#transport.json({ method: "GET", path: "api-keys" }),
3647
+ };
3648
+ return {
3649
+ create: async (accessToken, input) => parseKeyMaterial(
3650
+ await call(
3651
+ accessToken,
3652
+ (client) => client.POST("/api/v1/api-keys", {
3653
+ body: {
3654
+ ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
3655
+ budget_currency: "EUR",
3656
+ ...input.description === void 0 ? {} : { description: input.description },
3657
+ expires_at: input.expiresAt,
3658
+ ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
3659
+ name: input.name,
3660
+ ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
3661
+ owner_type: input.ownerType,
3662
+ ...input.projectId === null ? {} : { project_id: input.projectId }
3663
+ }
3664
+ })
3665
+ )
3666
+ ),
3667
+ delete: async (accessToken, id) => {
3668
+ await call(
3669
+ accessToken,
3670
+ (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
3671
+ params: { path: { api_key_id: id } }
3672
+ })
3673
+ );
3674
+ },
3675
+ get: async (accessToken, id) => parseApiKey(
3676
+ await call(
3677
+ accessToken,
3678
+ (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
3679
+ params: { path: { api_key_id: id } }
3680
+ })
3681
+ )
3682
+ ),
3683
+ list: async (accessToken) => parseCollection(
3684
+ await call(accessToken, (client) => client.GET("/api/v1/api-keys", {})),
3951
3685
  parseApiKey
3952
- );
3953
- }
3954
- /** Lists organizations visible to the authenticated management subject.
3955
- * @param accessToken - Credential required by the frozen contract.
3956
- * @returns The parsed organization collection.
3957
- */
3958
- async listOrganizations(accessToken) {
3959
- this.#authorize(accessToken);
3960
- return parseCollection(
3961
- await this.#transport.json({ method: "GET", path: "orgs" }),
3686
+ ),
3687
+ listOrganizations: async (accessToken) => parseCollection(
3688
+ await call(accessToken, (client) => client.GET("/api/v1/orgs", {})),
3962
3689
  parseOrganization
3963
- );
3964
- }
3965
- /** Lists projects visible within an organisation filter.
3966
- * @param accessToken - Credential required by the frozen contract.
3967
- * @param organisationId - Required backend organisation filter.
3968
- * @returns The parsed project collection.
3969
- */
3970
- async listProjects(accessToken, organisationId) {
3971
- this.#authorize(accessToken);
3972
- if (organisationId.trim().length === 0) {
3973
- throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
3974
- statusCode: 400
3975
- });
3976
- }
3977
- const query = new URLSearchParams({
3978
- member_user_id: parseManagementSubject(accessToken),
3979
- org_id: organisationId
3980
- });
3981
- return parseCollection(
3982
- await this.#transport.json({
3983
- method: "GET",
3984
- path: `projects?${query.toString()}`
3985
- }),
3986
- parseProject
3987
- );
3988
- }
3989
- /** Regenerates one-time key material while preserving expiry when omitted.
3990
- * @param accessToken - Credential required by the frozen contract.
3991
- * @param id - Key identifier.
3992
- * @param expiresAt - Optional replacement expiry.
3993
- * @returns Regenerated one-time key material.
3994
- */
3995
- async regenerate(accessToken, id, expiresAt) {
3996
- this.#authorize(accessToken);
3997
- return parseKeyMaterial(
3998
- await this.#transport.json({
3999
- body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
4000
- method: "POST",
4001
- path: `api-keys/${encodeURIComponent(id)}/secrets`
4002
- })
4003
- );
4004
- }
4005
- /** Updates mutable key metadata.
4006
- * @param accessToken - Credential required by the frozen contract.
4007
- * @param id - Key identifier.
4008
- * @param input - Optional name and expiry replacements.
4009
- * @returns The updated safe key DTO.
4010
- */
4011
- async update(accessToken, id, input) {
4012
- this.#authorize(accessToken);
4013
- return parseApiKey(
4014
- await this.#transport.json({
4015
- body: {
4016
- ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
4017
- ...input.name === void 0 ? {} : { name: input.name }
4018
- },
4019
- method: "PATCH",
4020
- path: `api-keys/${encodeURIComponent(id)}`
4021
- })
4022
- );
4023
- }
4024
- #authorize(accessToken) {
4025
- if (accessToken.value !== this.#credential.value) {
4026
- throw new ManagementError("MANAGEMENT_UNAUTHORIZED", {
4027
- statusCode: 401
4028
- });
4029
- }
4030
- }
4031
- };
4032
-
4033
- // src/lazy-management-keys/lazy-management-keys.ts
4034
- var lazyManagementKeys = (options) => {
4035
- const client = (accessToken) => new HttpManagementKeys({
4036
- baseUrl: options.apiBaseUrl,
4037
- credential: accessToken,
4038
- ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl }
4039
- });
4040
- return {
4041
- create: async (accessToken, input) => client(accessToken).create(accessToken, input),
4042
- delete: async (accessToken, id) => client(accessToken).delete(accessToken, id),
4043
- get: async (accessToken, id) => client(accessToken).get(accessToken, id),
4044
- list: async (accessToken) => client(accessToken).list(accessToken),
4045
- listOrganizations: async (accessToken) => client(accessToken).listOrganizations(accessToken),
4046
- listProjects: async (accessToken, organisationId) => client(accessToken).listProjects(accessToken, organisationId),
4047
- regenerate: async (accessToken, id, expiresAt) => client(accessToken).regenerate(accessToken, id, expiresAt),
4048
- update: async (accessToken, id, input) => client(accessToken).update(accessToken, id, input)
3690
+ ),
3691
+ listMemberships: async (accessToken, userId) => parseUserMemberships(
3692
+ await call(
3693
+ accessToken,
3694
+ (client) => client.GET("/api/v1/users/{user_id}/memberships", {
3695
+ params: { path: { user_id: userId } }
3696
+ })
3697
+ )
3698
+ ),
3699
+ listProjectBudgets: async (accessToken, userId) => parseCollection(
3700
+ await call(
3701
+ accessToken,
3702
+ (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
3703
+ params: { path: { user_id: userId } }
3704
+ })
3705
+ ),
3706
+ parseProjectBudgetState
3707
+ ),
3708
+ listProjects: async (accessToken, organisationId) => {
3709
+ if (organisationId.trim().length === 0) {
3710
+ throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
3711
+ statusCode: 400
3712
+ });
3713
+ }
3714
+ const query = {
3715
+ member_user_id: parseManagementSubject(accessToken),
3716
+ org_id: organisationId
3717
+ };
3718
+ const fetchPage = (cursor) => call(
3719
+ accessToken,
3720
+ (client) => client.GET("/api/v1/projects", {
3721
+ params: {
3722
+ query: cursor === "" ? query : { ...query, cursor }
3723
+ }
3724
+ })
3725
+ ).then((page) => parseCollection(page, parseProject));
3726
+ return drainPages(fetchPage);
3727
+ },
3728
+ regenerate: async (accessToken, id, expiresAt) => parseKeyMaterial(
3729
+ await call(
3730
+ accessToken,
3731
+ (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
3732
+ body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
3733
+ params: { path: { api_key_id: id } }
3734
+ })
3735
+ )
3736
+ ),
3737
+ update: async (accessToken, id, input) => parseApiKey(
3738
+ await call(
3739
+ accessToken,
3740
+ (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
3741
+ body: {
3742
+ budget_currency: "EUR",
3743
+ ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
3744
+ ...input.name === void 0 ? {} : { name: input.name }
3745
+ },
3746
+ params: { path: { api_key_id: id } }
3747
+ })
3748
+ )
3749
+ )
4049
3750
  };
4050
3751
  };
4051
3752
 
@@ -4061,7 +3762,7 @@ var buildProductionRuntimeOptions = (input) => ({
4061
3762
  timeoutMs: LOGIN_BUDGET_MS
4062
3763
  },
4063
3764
  management: {
4064
- client: () => lazyManagementKeys({ apiBaseUrl: input.apiBaseUrl })
3765
+ client: () => sdkManagementKeys({ apiBaseUrl: input.apiBaseUrl })
4065
3766
  },
4066
3767
  ...input.tokenStore === void 0 ? {} : { tokenStore: input.tokenStore }
4067
3768
  });
@@ -4085,97 +3786,10 @@ var createHostAuthBridge = () => {
4085
3786
  };
4086
3787
  };
4087
3788
 
4088
- // src/auth/authorization-url-stash/loopback-origin/loopback-origin.ts
4089
- var loopbackOrigin = (url) => {
4090
- const redirect = url.searchParams.get("redirect_uri");
4091
- if (redirect === null) return void 0;
4092
- let parsed;
4093
- try {
4094
- parsed = new URL(redirect);
4095
- } catch {
4096
- return void 0;
4097
- }
4098
- return parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost" ? parsed.origin : void 0;
4099
- };
4100
-
4101
- // src/auth/authorization-url-stash/authorization-url-stash.ts
4102
- var FALLBACK_URL = "https://route33.ai";
4103
- var SIGN_IN_INSTRUCTIONS = "Open the Route 33 sign-in link \u2014 your browser will finish at a confirmation page.";
4104
- var FINISHING_INSTRUCTIONS = "Finishing Route 33 setup\u2026";
4105
- var URL_WAIT_BUDGET_MS = 3e4;
4106
- var LISTENER_PROBE_TIMEOUT_MS = 750;
4107
- var createAuthorizationUrlStash = (options = {}) => {
4108
- let latest;
4109
- let waiters = [];
4110
- const browserRunner = (url) => {
4111
- latest = url;
4112
- const publish = waiters;
4113
- waiters = [];
4114
- for (const resolve2 of publish) resolve2(url);
4115
- return Promise.resolve();
4116
- };
4117
- const usableCandidate = async (url) => {
4118
- const origin = loopbackOrigin(url);
4119
- if (origin === void 0) return url;
4120
- const controller = new AbortController();
4121
- const timer = setTimeout(() => {
4122
- controller.abort();
4123
- }, options.listenerProbeTimeoutMs ?? LISTENER_PROBE_TIMEOUT_MS);
4124
- try {
4125
- const response = await (options.fetchImpl ?? fetch)(`${origin}/`, {
4126
- signal: controller.signal
4127
- });
4128
- return response.status >= 200 ? url : void 0;
4129
- } catch {
4130
- return void 0;
4131
- } finally {
4132
- clearTimeout(timer);
4133
- }
4134
- };
4135
- const urlForConnect = async (callback) => {
4136
- let decide;
4137
- const decided = new Promise((resolve2) => {
4138
- decide = resolve2;
4139
- });
4140
- const settle = (decision) => {
4141
- clearTimeout(timer);
4142
- decide(decision);
4143
- };
4144
- const timer = setTimeout(() => {
4145
- settle({ instructions: SIGN_IN_INSTRUCTIONS, url: FALLBACK_URL });
4146
- }, options.urlWaitBudgetMs ?? URL_WAIT_BUDGET_MS);
4147
- void Promise.resolve(callback).catch(() => void 0).then(() => {
4148
- settle({ instructions: FINISHING_INSTRUCTIONS, url: FALLBACK_URL });
4149
- });
4150
- const serve = (url) => {
4151
- settle({ instructions: SIGN_IN_INSTRUCTIONS, url: url.toString() });
4152
- };
4153
- const awaitPublish = () => {
4154
- const publish = new Promise((resolve2) => {
4155
- waiters.push(resolve2);
4156
- });
4157
- void publish.then(serve);
4158
- };
4159
- const candidate = latest;
4160
- if (candidate === void 0) {
4161
- awaitPublish();
4162
- } else {
4163
- void usableCandidate(candidate).then((usable) => {
4164
- if (usable !== void 0) {
4165
- serve(usable);
4166
- } else if (latest !== void 0 && latest !== candidate) {
4167
- serve(latest);
4168
- } else {
4169
- awaitPublish();
4170
- }
4171
- });
4172
- }
4173
- return decided;
4174
- };
4175
- return { browserRunner, urlForConnect };
4176
- };
4177
-
4178
3789
  // src/v1-entry/route33-auth-hook/route33-auth-hook.ts
3790
+ import {
3791
+ createAuthorizationUrlStash
3792
+ } from "@r-33/auth-browser";
4179
3793
  var createRoute33AuthHook = (deps) => ({
4180
3794
  loader: async (auth) => {
4181
3795
  deps.bridge.hydrate(await auth());
@@ -4326,14 +3940,17 @@ var createRoute33ProviderModels = (deps) => async (provider) => {
4326
3940
  return Object.keys(models).length === 0 ? fallback : models;
4327
3941
  };
4328
3942
 
3943
+ // src/contract/fixtures/parse-contract-fixtures/parse-contract-fixtures.ts
3944
+ import { parseTokenSet } from "@r-33/auth-browser";
3945
+
4329
3946
  // src/index.ts
4330
3947
  var clientId = readEnvClientId() ?? DEFAULT_ROUTE33_CLIENT_ID;
4331
3948
  var issuerUrl = readEnvAuthIssuer() ?? DEFAULT_AUTH_ISSUER_URL;
4332
3949
  var authBridge = createHostAuthBridge();
4333
- var startNativeLogin = (browserRunner) => loginFlow({
3950
+ var startNativeLogin = (browserRunner) => route33Login({
4334
3951
  browserRunner,
4335
3952
  clientId,
4336
- session: createAuthSession({ clientId, issuerUrl }),
3953
+ session: createAuthSession2({ clientId, issuerUrl }),
4337
3954
  timeoutMs: LOGIN_BUDGET_MS
4338
3955
  });
4339
3956
  var route33Plugin = createRoute33Plugin({
@@ -4388,6 +4005,7 @@ var Route33Plugin = async (input) => {
4388
4005
 
4389
4006
  // src/v2-entry/create-route33-v2-plugin/create-route33-v2-plugin.ts
4390
4007
  import { Integration as Integration2, Plugin } from "@opencode/plugin";
4008
+ import { createAuthorizationUrlStash as createAuthorizationUrlStash2 } from "@r-33/auth-browser";
4391
4009
 
4392
4010
  // src/v2-entry/map-route33-v2-provider/map-route33-v2-provider.ts
4393
4011
  import { Integration, Provider } from "@opencode/plugin";
@@ -4951,7 +4569,7 @@ var createRoute33V2Plugin = (options = {}) => {
4951
4569
  return directKeyMode(context, options, createRoute33Plugin);
4952
4570
  }
4953
4571
  const methodID = Integration2.MethodID.make("browser");
4954
- const stash = createAuthorizationUrlStash();
4572
+ const stash = createAuthorizationUrlStash2();
4955
4573
  const state = {
4956
4574
  directory: context.location.directory,
4957
4575
  outsideWorktree: "return-undefined"
@@ -5008,7 +4626,7 @@ var createRoute33V2Plugin = (options = {}) => {
5008
4626
  return;
5009
4627
  }
5010
4628
  const [projects, modelIds, personalKeyActive] = await Promise.all([
5011
- activeRuntime.listProjects(),
4629
+ activeRuntime.listMintableProjects(),
5012
4630
  activeRuntime.catalogModelIds(),
5013
4631
  activeRuntime.hasPersonalLease().catch(() => false)
5014
4632
  ]);