@r-33/opencode 0.4.7-rc.21 → 0.4.7-rc.23

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
@@ -990,6 +551,66 @@ var catalogModelsUrl = (baseURL) => {
990
551
  // src/catalog/default-fetch-timeout-ms/default-fetch-timeout-ms.ts
991
552
  var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
992
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;
612
+ };
613
+
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 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
  }
@@ -3603,6 +3268,15 @@ var createRoute33Plugin = (options = {}) => {
3603
3268
  };
3604
3269
  };
3605
3270
 
3271
+ // src/production-runtime-options/production-runtime-options.ts
3272
+ import { createAuthSession } from "@r-33/auth-browser";
3273
+
3274
+ // src/management/sdk-management-keys/sdk-management-keys.ts
3275
+ import {
3276
+ createRoute33Client,
3277
+ Route33SdkError
3278
+ } from "@r-33/sdk";
3279
+
3606
3280
  // src/contract/management-keys/parse-api-key/parse-api-key.ts
3607
3281
  var parseApiKey = (value) => {
3608
3282
  if (!isRecord(value) || !isOwnerType(value["ownership_type"]) || !isNullableString(value["project_id"])) {
@@ -3801,251 +3475,145 @@ var ManagementError = class extends Error {
3801
3475
  statusCode;
3802
3476
  };
3803
3477
 
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}`
3478
+ // src/management/sdk-management-keys/sdk-management-keys.ts
3479
+ var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
3480
+ var sdkManagementKeys = (options) => {
3481
+ const baseUrl = options.apiBaseUrl.replace(API_PREFIX_PATTERN, "");
3482
+ const timeoutMs = options.timeoutMs ?? 1e4;
3483
+ const fetchImpl = options.fetchImpl;
3484
+ const observingFetch = (status) => fetchImpl === void 0 ? void 0 : async (input, init) => {
3485
+ const response = await fetchImpl(input, init);
3486
+ status.code = response.status;
3487
+ return response;
3488
+ };
3489
+ const callClient = (accessToken, status) => {
3490
+ const provider = {
3491
+ getToken: () => Promise.resolve(accessToken.value),
3492
+ onUnauthorized: () => Promise.resolve(accessToken.value)
3493
+ };
3494
+ const observedFetch = observingFetch(status);
3495
+ return createRoute33Client({
3496
+ baseUrl,
3497
+ provider,
3498
+ timeoutMs,
3499
+ ...observedFetch === void 0 ? {} : { fetch: observedFetch }
3846
3500
  });
3847
- if (request.body !== void 0) {
3848
- headers.set("content-type", "application/json");
3501
+ };
3502
+ const mapFailure = (cause) => {
3503
+ if (cause instanceof ManagementError || cause instanceof ContractParseError) {
3504
+ return cause;
3505
+ }
3506
+ if (cause instanceof Route33SdkError) {
3507
+ const code = cause.code === "SDK_TIMEOUT" ? "MANAGEMENT_TIMEOUT" : "MANAGEMENT_NETWORK_ERROR";
3508
+ return new ManagementError(code, { cause });
3509
+ }
3510
+ if (cause instanceof SyntaxError) {
3511
+ return new ContractParseError("invalid management response", { cause });
3849
3512
  }
3513
+ return new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
3514
+ };
3515
+ const call = async (accessToken, run) => {
3516
+ const status = { code: void 0 };
3850
3517
  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) {
3518
+ const outcome = await run(callClient(accessToken, status));
3519
+ const code = status.code;
3520
+ if (code === void 0 || code < 200 || code >= 300) {
3863
3521
  throw new ManagementError(
3864
- response.status === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
3865
- { statusCode: response.status }
3522
+ code === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
3523
+ { statusCode: code }
3866
3524
  );
3867
3525
  }
3868
- return await consume(response);
3526
+ return outcome.data;
3869
3527
  } 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);
3528
+ throw mapFailure(cause);
3882
3529
  }
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" }),
3530
+ };
3531
+ return {
3532
+ create: async (accessToken, input) => parseKeyMaterial(
3533
+ await call(
3534
+ accessToken,
3535
+ (client) => client.POST("/api/v1/api-keys", {
3536
+ body: {
3537
+ ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
3538
+ budget_currency: "EUR",
3539
+ ...input.description === void 0 ? {} : { description: input.description },
3540
+ expires_at: input.expiresAt,
3541
+ ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
3542
+ name: input.name,
3543
+ ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
3544
+ owner_type: input.ownerType,
3545
+ ...input.projectId === null ? {} : { project_id: input.projectId }
3546
+ }
3547
+ })
3548
+ )
3549
+ ),
3550
+ delete: async (accessToken, id) => {
3551
+ await call(
3552
+ accessToken,
3553
+ (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
3554
+ params: { path: { api_key_id: id } }
3555
+ })
3556
+ );
3557
+ },
3558
+ get: async (accessToken, id) => parseApiKey(
3559
+ await call(
3560
+ accessToken,
3561
+ (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
3562
+ params: { path: { api_key_id: id } }
3563
+ })
3564
+ )
3565
+ ),
3566
+ list: async (accessToken) => parseCollection(
3567
+ await call(accessToken, (client) => client.GET("/api/v1/api-keys", {})),
3951
3568
  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" }),
3569
+ ),
3570
+ listOrganizations: async (accessToken) => parseCollection(
3571
+ await call(accessToken, (client) => client.GET("/api/v1/orgs", {})),
3962
3572
  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)
3573
+ ),
3574
+ listProjects: async (accessToken, organisationId) => {
3575
+ if (organisationId.trim().length === 0) {
3576
+ throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
3577
+ statusCode: 400
3578
+ });
3579
+ }
3580
+ return parseCollection(
3581
+ await call(
3582
+ accessToken,
3583
+ (client) => client.GET("/api/v1/projects", {
3584
+ params: {
3585
+ query: {
3586
+ member_user_id: parseManagementSubject(accessToken),
3587
+ org_id: organisationId
3588
+ }
3589
+ }
3590
+ })
3591
+ ),
3592
+ parseProject
3593
+ );
3594
+ },
3595
+ regenerate: async (accessToken, id, expiresAt) => parseKeyMaterial(
3596
+ await call(
3597
+ accessToken,
3598
+ (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
3599
+ body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
3600
+ params: { path: { api_key_id: id } }
3601
+ })
3602
+ )
3603
+ ),
3604
+ update: async (accessToken, id, input) => parseApiKey(
3605
+ await call(
3606
+ accessToken,
3607
+ (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
3608
+ body: {
3609
+ budget_currency: "EUR",
3610
+ ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
3611
+ ...input.name === void 0 ? {} : { name: input.name }
3612
+ },
3613
+ params: { path: { api_key_id: id } }
3614
+ })
3615
+ )
3616
+ )
4049
3617
  };
4050
3618
  };
4051
3619
 
@@ -4061,7 +3629,7 @@ var buildProductionRuntimeOptions = (input) => ({
4061
3629
  timeoutMs: LOGIN_BUDGET_MS
4062
3630
  },
4063
3631
  management: {
4064
- client: () => lazyManagementKeys({ apiBaseUrl: input.apiBaseUrl })
3632
+ client: () => sdkManagementKeys({ apiBaseUrl: input.apiBaseUrl })
4065
3633
  },
4066
3634
  ...input.tokenStore === void 0 ? {} : { tokenStore: input.tokenStore }
4067
3635
  });
@@ -4085,97 +3653,10 @@ var createHostAuthBridge = () => {
4085
3653
  };
4086
3654
  };
4087
3655
 
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
3656
  // src/v1-entry/route33-auth-hook/route33-auth-hook.ts
3657
+ import {
3658
+ createAuthorizationUrlStash
3659
+ } from "@r-33/auth-browser";
4179
3660
  var createRoute33AuthHook = (deps) => ({
4180
3661
  loader: async (auth) => {
4181
3662
  deps.bridge.hydrate(await auth());
@@ -4326,14 +3807,17 @@ var createRoute33ProviderModels = (deps) => async (provider) => {
4326
3807
  return Object.keys(models).length === 0 ? fallback : models;
4327
3808
  };
4328
3809
 
3810
+ // src/contract/fixtures/parse-contract-fixtures/parse-contract-fixtures.ts
3811
+ import { parseTokenSet } from "@r-33/auth-browser";
3812
+
4329
3813
  // src/index.ts
4330
3814
  var clientId = readEnvClientId() ?? DEFAULT_ROUTE33_CLIENT_ID;
4331
3815
  var issuerUrl = readEnvAuthIssuer() ?? DEFAULT_AUTH_ISSUER_URL;
4332
3816
  var authBridge = createHostAuthBridge();
4333
- var startNativeLogin = (browserRunner) => loginFlow({
3817
+ var startNativeLogin = (browserRunner) => route33Login({
4334
3818
  browserRunner,
4335
3819
  clientId,
4336
- session: createAuthSession({ clientId, issuerUrl }),
3820
+ session: createAuthSession2({ clientId, issuerUrl }),
4337
3821
  timeoutMs: LOGIN_BUDGET_MS
4338
3822
  });
4339
3823
  var route33Plugin = createRoute33Plugin({
@@ -4388,6 +3872,7 @@ var Route33Plugin = async (input) => {
4388
3872
 
4389
3873
  // src/v2-entry/create-route33-v2-plugin/create-route33-v2-plugin.ts
4390
3874
  import { Integration as Integration2, Plugin } from "@opencode/plugin";
3875
+ import { createAuthorizationUrlStash as createAuthorizationUrlStash2 } from "@r-33/auth-browser";
4391
3876
 
4392
3877
  // src/v2-entry/map-route33-v2-provider/map-route33-v2-provider.ts
4393
3878
  import { Integration, Provider } from "@opencode/plugin";
@@ -4951,7 +4436,7 @@ var createRoute33V2Plugin = (options = {}) => {
4951
4436
  return directKeyMode(context, options, createRoute33Plugin);
4952
4437
  }
4953
4438
  const methodID = Integration2.MethodID.make("browser");
4954
- const stash = createAuthorizationUrlStash();
4439
+ const stash = createAuthorizationUrlStash2();
4955
4440
  const state = {
4956
4441
  directory: context.location.directory,
4957
4442
  outsideWorktree: "return-undefined"