@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.
@@ -17,35 +17,14 @@ var logger = {
17
17
  }
18
18
  };
19
19
 
20
- // src/auth/auth-error/auth-error.ts
21
- var AuthError = class extends Error {
22
- constructor(code, options) {
23
- super(
24
- "Route 33 authorization failed",
25
- options?.cause === void 0 ? void 0 : { cause: options.cause }
26
- );
27
- this.code = code;
28
- this.name = "AuthError";
29
- this.statusCode = options?.statusCode;
30
- }
31
- code;
32
- statusCode;
33
- };
20
+ // src/cli/create-live-production-smoke-plan/create-live-production-smoke-plan.ts
21
+ import { createAuthSession } from "@r-33/auth-browser";
34
22
 
35
- // src/auth/build-authorize-url/build-authorize-url.ts
36
- var buildAuthorizeUrl = (issuerUrl, request) => {
37
- const url = new URL("/authorize", issuerUrl);
38
- url.search = new URLSearchParams({
39
- client_id: request.clientId,
40
- code_challenge: request.codeChallenge,
41
- code_challenge_method: "S256",
42
- redirect_uri: request.redirectUri,
43
- response_type: "code",
44
- scope: request.scope,
45
- state: request.state
46
- }).toString();
47
- return url;
48
- };
23
+ // src/key-lease/default-gateway-key-renewal-ratio/default-gateway-key-renewal-ratio.ts
24
+ var DEFAULT_GATEWAY_KEY_RENEWAL_RATIO = 0.8;
25
+
26
+ // src/key-lease/default-gateway-key-ttl-ms/default-gateway-key-ttl-ms.ts
27
+ var DEFAULT_GATEWAY_KEY_TTL_MS = 15 * 60 * 1e3;
49
28
 
50
29
  // src/contract/adapters/contract-parse-error/contract-parse-error.ts
51
30
  var ContractParseError = class extends Error {
@@ -111,364 +90,6 @@ var parseManagementSubject = (credential) => {
111
90
  return subject;
112
91
  };
113
92
 
114
- // src/contract/auth-session/parse-token-set/parse-token-set.ts
115
- var parseTokenSet = (value) => {
116
- if (!isRecord(value)) {
117
- throw new ContractParseError("invalid token response");
118
- }
119
- if (typeof value["access_token"] !== "string" || typeof value["expires_in"] !== "number" || value["token_type"] !== "Bearer") {
120
- throw new ContractParseError("invalid token response");
121
- }
122
- return {
123
- access_token: value["access_token"],
124
- expires_in: value["expires_in"],
125
- token_type: "Bearer",
126
- ...typeof value["id_token"] === "string" ? { id_token: value["id_token"] } : {},
127
- ...typeof value["refresh_token"] === "string" ? { refresh_token: value["refresh_token"] } : {},
128
- ...typeof value["scope"] === "string" ? { scope: value["scope"] } : {}
129
- };
130
- };
131
-
132
- // src/auth/exchange-code-and-parse/exchange-code-and-parse.ts
133
- var exchangeCodeAndParse = async (options) => {
134
- const body = new URLSearchParams({
135
- client_id: options.clientId,
136
- code: options.input.code,
137
- code_verifier: options.input.codeVerifier,
138
- grant_type: "authorization_code",
139
- redirect_uri: options.input.redirectUri
140
- });
141
- let response;
142
- try {
143
- response = await (options.fetchImpl ?? fetch)(options.tokenUrl, {
144
- body,
145
- headers: { "content-type": "application/x-www-form-urlencoded" },
146
- method: "POST"
147
- });
148
- } catch (cause) {
149
- throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", { cause });
150
- }
151
- if (!response.ok) {
152
- throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", {
153
- statusCode: response.status
154
- });
155
- }
156
- let payload;
157
- try {
158
- payload = await response.json();
159
- } catch (cause) {
160
- throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", { cause });
161
- }
162
- try {
163
- return parseTokenSet(payload);
164
- } catch (cause) {
165
- if (cause instanceof ContractParseError) {
166
- throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", { cause });
167
- }
168
- throw cause;
169
- }
170
- };
171
-
172
- // src/auth/refresh-session/refresh-session.ts
173
- var refreshSession = async (options) => {
174
- const body = new URLSearchParams({
175
- client_id: options.clientId,
176
- grant_type: "refresh_token",
177
- refresh_token: options.refreshToken
178
- });
179
- let response;
180
- try {
181
- response = await (options.fetchImpl ?? fetch)(options.tokenUrl, {
182
- body,
183
- headers: { "content-type": "application/x-www-form-urlencoded" },
184
- method: "POST"
185
- });
186
- } catch (cause) {
187
- throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", { cause });
188
- }
189
- if (!response.ok) {
190
- throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", {
191
- statusCode: response.status
192
- });
193
- }
194
- let payload;
195
- try {
196
- payload = await response.json();
197
- } catch (cause) {
198
- throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", { cause });
199
- }
200
- try {
201
- return parseTokenSet(payload);
202
- } catch (cause) {
203
- if (cause instanceof ContractParseError) {
204
- throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", { cause });
205
- }
206
- throw cause;
207
- }
208
- };
209
-
210
- // src/auth/create-auth-session/create-auth-session.ts
211
- var createAuthSession = (options) => {
212
- const tokenUrl = new URL("/oauth/token", options.issuerUrl);
213
- return {
214
- authorizationUrl: (request) => buildAuthorizeUrl(options.issuerUrl, request),
215
- exchangeCode: (input) => exchangeCodeAndParse({
216
- clientId: options.clientId,
217
- ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl },
218
- input,
219
- tokenUrl
220
- }),
221
- refresh: (refreshToken) => refreshSession({
222
- clientId: options.clientId,
223
- ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl },
224
- refreshToken,
225
- tokenUrl
226
- })
227
- };
228
- };
229
-
230
- // src/auth/open-browser-and-capture/open-browser-and-capture.ts
231
- import { timingSafeEqual } from "node:crypto";
232
-
233
- // src/auth/loopback-callback/loopback-callback.ts
234
- import { createServer } from "node:http";
235
-
236
- // src/auth/loopback-callback/callback-page/callback-page.ts
237
- var MARK_PATHS = [
238
- "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",
239
- "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",
240
- "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"
241
- ];
242
- 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>`;
243
- 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)}
244
- *{box-sizing:border-box}
245
- html,body{margin:0}
246
- .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}
247
- .r33-panel{display:grid;gap:var(--r33-space-4);max-width:460px;width:100%}
248
- .r33-mark{height:40px;width:auto;color:var(--r33-text-primary)}
249
- .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)}
250
- .r33-status__dot{width:8px;height:8px;background:var(--r33-fill-accent)}
251
- .r33-status__dot--error{background:transparent;border:1px solid var(--r33-text-primary);border-radius:50%}
252
- .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}
253
- .r33-subline{margin:0;font-size:16px;line-height:1.45;color:var(--r33-text-secondary);max-width:40ch;text-wrap:pretty}
254
- .r33-code{margin:0;font-size:13px;letter-spacing:0.04em;color:var(--r33-text-secondary)}
255
- .r33-code__value{font-family:var(--r33-font-mono);text-transform:uppercase;color:var(--r33-text-primary)}
256
- @media (prefers-reduced-motion:reduce){*{animation-duration:1ms!important;transition-duration:1ms!important}}`;
257
- var buildCallbackPage = (state, errorCode) => {
258
- const isError = state === "error";
259
- const safeCode = (errorCode ?? "").replace(/[^a-z0-9_-]/gi, "");
260
- const title = isError ? "Sign-in failed" : "Signed in";
261
- const headline = isError ? "Sign-in failed" : "Signed in to route33";
262
- 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.";
263
- const statusLabel = isError ? "Authentication error" : "Authenticated";
264
- const dotClass = isError ? "r33-status__dot r33-status__dot--error" : "r33-status__dot";
265
- const codeLine = isError && safeCode.length > 0 ? `<p class="r33-code">Error code: <span class="r33-code__value">${safeCode}</span></p>` : "";
266
- return `<!doctype html>
267
- <html lang="en" data-theme="dark">
268
- <head>
269
- <meta charset="utf-8">
270
- <meta name="viewport" content="width=device-width, initial-scale=1">
271
- <title>${title} \xB7 route33.ai</title>
272
- <style>${PAGE_STYLE}</style>
273
- </head>
274
- <body>
275
- <main class="r33-page">
276
- <div class="r33-panel">
277
- ${BRAND_MARK}
278
- <span class="r33-status"><span class="${dotClass}"></span>${statusLabel}</span>
279
- <h1 class="r33-headline">${headline}</h1>
280
- <p class="r33-subline">${subline}</p>
281
- ${codeLine}
282
- </div>
283
- </main>
284
- </body>
285
- </html>`;
286
- };
287
-
288
- // src/auth/loopback-callback/loopback-callback.ts
289
- var createAuthLoopbackCallback = async () => {
290
- let redirectUri = "http://127.0.0.1/callback";
291
- let resolveCapture;
292
- const captured = new Promise((resolve) => {
293
- resolveCapture = resolve;
294
- });
295
- const server = createServer((request, response) => {
296
- const url = new URL(request.url ?? "/", redirectUri);
297
- if (request.method !== "GET" || url.pathname !== "/callback") {
298
- response.writeHead(404).end();
299
- return;
300
- }
301
- const resolve = resolveCapture;
302
- resolveCapture = void 0;
303
- resolve?.(url);
304
- const error = url.searchParams.get("error");
305
- const page = error === null || error.length === 0 ? buildCallbackPage("success") : buildCallbackPage("error", error);
306
- response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
307
- response.end(page);
308
- });
309
- await new Promise((resolve, reject) => {
310
- const onError = (cause) => {
311
- reject(new AuthError("AUTH_CALLBACK_LISTEN_FAILED", { cause }));
312
- };
313
- server.once("error", onError);
314
- server.listen(0, "127.0.0.1", () => {
315
- server.off("error", onError);
316
- resolve();
317
- });
318
- });
319
- const address = server.address();
320
- if (address === null || typeof address === "string") {
321
- server.close();
322
- throw new AuthError("AUTH_CALLBACK_LISTEN_FAILED");
323
- }
324
- redirectUri = `http://127.0.0.1:${String(address.port)}/callback`;
325
- return {
326
- redirectUri,
327
- close: () => {
328
- if (!server.listening) {
329
- return Promise.resolve();
330
- }
331
- return new Promise((resolve, reject) => {
332
- server.close((cause) => {
333
- if (cause === void 0) {
334
- resolve();
335
- return;
336
- }
337
- reject(new AuthError("AUTH_CALLBACK_CLEANUP_FAILED", { cause }));
338
- });
339
- });
340
- },
341
- wait: () => captured
342
- };
343
- };
344
-
345
- // src/auth/open-system-browser/open-system-browser.ts
346
- import { spawn } from "node:child_process";
347
- var openSystemBrowser = async (url, options = {}) => new Promise((resolve, reject) => {
348
- let command = "xdg-open";
349
- let args = [url.href];
350
- if (process.platform === "darwin") {
351
- command = "open";
352
- } else if (process.platform === "win32") {
353
- command = "cmd";
354
- args = ["/c", "start", "", url.href];
355
- }
356
- if (options.spawnUrl !== void 0) {
357
- options.spawnUrl(command, args, { detached: true, stdio: "ignore" });
358
- resolve();
359
- return;
360
- }
361
- const child = spawn(command, args, {
362
- detached: true,
363
- stdio: "ignore"
364
- });
365
- child.once("error", reject);
366
- child.once("spawn", () => {
367
- child.unref();
368
- resolve();
369
- });
370
- });
371
-
372
- // src/auth/open-browser-and-capture/open-browser-and-capture.ts
373
- var openBrowserAndCapture = async (options) => {
374
- const callback = await createAuthLoopbackCallback();
375
- const authorizationUrl = options.authorizationUrl(callback.redirectUri);
376
- const browserRunner = options.browserRunner ?? ((url) => openSystemBrowser(url));
377
- let timer;
378
- const timeout = new Promise((_resolve, reject) => {
379
- timer = setTimeout(() => {
380
- reject(new AuthError("AUTH_CALLBACK_TIMEOUT"));
381
- }, options.timeoutMs ?? 12e4);
382
- });
383
- const launch = browserRunner(authorizationUrl).catch((cause) => {
384
- throw new AuthError("AUTH_BROWSER_LAUNCH_FAILED", { cause });
385
- });
386
- try {
387
- const completed = await Promise.race([
388
- Promise.all([launch, callback.wait()]),
389
- timeout
390
- ]);
391
- const callbackUrl = completed[1];
392
- const actualState = callbackUrl.searchParams.get("state");
393
- if (actualState === null) {
394
- throw new AuthError("AUTH_CALLBACK_RESPONSE_INVALID");
395
- }
396
- const expectedState = Buffer.from(options.expectedState);
397
- const receivedState = Buffer.from(actualState);
398
- if (expectedState.length !== receivedState.length || !timingSafeEqual(expectedState, receivedState)) {
399
- throw new AuthError("AUTH_CALLBACK_STATE_MISMATCH");
400
- }
401
- const code = callbackUrl.searchParams.get("code");
402
- if (code === null || code.length === 0) {
403
- throw new AuthError("AUTH_CALLBACK_RESPONSE_INVALID");
404
- }
405
- return { code, redirectUri: callback.redirectUri };
406
- } finally {
407
- if (timer !== void 0) {
408
- clearTimeout(timer);
409
- }
410
- await callback.close();
411
- }
412
- };
413
-
414
- // src/auth/pkce-verifier-and-challenge/pkce-verifier-and-challenge.ts
415
- import { randomBytes } from "node:crypto";
416
-
417
- // src/auth/pkce-challenge/pkce-challenge.ts
418
- import { createHash } from "node:crypto";
419
- var pkceChallenge = (verifier) => createHash("sha256").update(verifier).digest("base64url");
420
-
421
- // src/auth/pkce-verifier-and-challenge/pkce-verifier-and-challenge.ts
422
- var createPkceVerifierAndChallenge = () => {
423
- const codeVerifier = randomBytes(32).toString("base64url");
424
- return {
425
- codeChallenge: pkceChallenge(codeVerifier),
426
- codeVerifier,
427
- state: randomBytes(32).toString("base64url")
428
- };
429
- };
430
-
431
- // src/auth/requested-scopes/requested-scopes.ts
432
- var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read projects:read keys:read keys:write";
433
-
434
- // src/auth/login-flow/login-flow.ts
435
- var loginFlow = async (options) => {
436
- const log = options.logger ?? logger;
437
- log.info("auth.login.started");
438
- const pkce = createPkceVerifierAndChallenge();
439
- const captured = await openBrowserAndCapture({
440
- authorizationUrl: (redirectUri) => options.session.authorizationUrl({
441
- clientId: options.clientId,
442
- codeChallenge: pkce.codeChallenge,
443
- redirectUri,
444
- scope: REQUESTED_OAUTH_SCOPES,
445
- state: pkce.state
446
- }),
447
- ...options.browserRunner === void 0 ? {} : { browserRunner: options.browserRunner },
448
- expectedState: pkce.state,
449
- ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
450
- });
451
- const tokenSet = await options.session.exchangeCode({
452
- code: captured.code,
453
- codeVerifier: pkce.codeVerifier,
454
- redirectUri: captured.redirectUri
455
- });
456
- let credential;
457
- try {
458
- credential = parseManagementJwt(tokenSet.access_token);
459
- } catch (cause) {
460
- throw new AuthError("AUTH_TOKEN_RESPONSE_INVALID", { cause });
461
- }
462
- log.info("auth.login.completed");
463
- return { credential, tokenSet };
464
- };
465
-
466
- // src/key-lease/default-gateway-key-renewal-ratio/default-gateway-key-renewal-ratio.ts
467
- var DEFAULT_GATEWAY_KEY_RENEWAL_RATIO = 0.8;
468
-
469
- // src/key-lease/default-gateway-key-ttl-ms/default-gateway-key-ttl-ms.ts
470
- var DEFAULT_GATEWAY_KEY_TTL_MS = 15 * 60 * 1e3;
471
-
472
93
  // src/key-lease/key-lease-error/key-lease-error.ts
473
94
  var REDACTED_CAUSE = "Route 33 gateway key lease dependency failed";
474
95
  var KeyLeaseError = class extends Error {
@@ -1098,6 +719,40 @@ var LeaseState = class _LeaseState {
1098
719
  }
1099
720
  };
1100
721
 
722
+ // src/management/drain-pages/drain-pages.ts
723
+ var drainPages = async (fetchPage) => {
724
+ const first = await fetchPage("");
725
+ const data = [...first.data];
726
+ let { page } = first;
727
+ while (page.has_more && page.next_cursor !== null) {
728
+ const next = await fetchPage(page.next_cursor);
729
+ data.push(...next.data);
730
+ ({ page } = next);
731
+ }
732
+ return { data, page: { ...page, has_more: false, next_cursor: null } };
733
+ };
734
+
735
+ // src/management/management-error/management-error.ts
736
+ var ManagementError = class extends Error {
737
+ constructor(code, options) {
738
+ super(
739
+ "Route 33 management request failed",
740
+ options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
741
+ );
742
+ this.code = code;
743
+ this.name = "ManagementError";
744
+ this.statusCode = options?.statusCode;
745
+ }
746
+ code;
747
+ statusCode;
748
+ };
749
+
750
+ // src/management/sdk-management-keys/sdk-management-keys.ts
751
+ import {
752
+ createRoute33Client,
753
+ Route33SdkError
754
+ } from "@r-33/sdk";
755
+
1101
756
  // src/contract/management-keys/parse-api-key/parse-api-key.ts
1102
757
  var parseApiKey = (value) => {
1103
758
  if (!isRecord(value) || !isOwnerType(value["ownership_type"]) || !isNullableString(value["project_id"])) {
@@ -1259,6 +914,39 @@ var parseOrganization = (value) => {
1259
914
  };
1260
915
  };
1261
916
 
917
+ // src/contract/management-keys/parse-project-budget-state/parse-project-budget-state.ts
918
+ var parseProjectBudgetState = (value) => {
919
+ if (!isRecord(value)) {
920
+ throw new ContractParseError("invalid project budget");
921
+ }
922
+ const stringField = (name) => {
923
+ const field = value[name];
924
+ if (typeof field !== "string") {
925
+ throw new ContractParseError("invalid project budget");
926
+ }
927
+ return field;
928
+ };
929
+ const cap = value["cap"];
930
+ if (typeof cap !== "number") {
931
+ throw new ContractParseError("invalid project budget");
932
+ }
933
+ const hasUsage = value["has_usage"];
934
+ if (typeof hasUsage !== "boolean") {
935
+ throw new ContractParseError("invalid project budget");
936
+ }
937
+ const source = value["source"];
938
+ if (source !== "own_cap" && source !== "project_default" && source !== "org_default" && source !== "tenant_default" && source !== "platform_default") {
939
+ throw new ContractParseError("invalid project budget");
940
+ }
941
+ return {
942
+ cap,
943
+ has_usage: hasUsage,
944
+ org_id: stringField("org_id"),
945
+ project_id: stringField("project_id"),
946
+ source
947
+ };
948
+ };
949
+
1262
950
  // src/contract/management-keys/parse-wire-money/parse-wire-money.ts
1263
951
  var parseWireMoney = (value) => {
1264
952
  if (!isRecord(value)) return null;
@@ -1281,248 +969,224 @@ var parseProject = (value) => {
1281
969
  };
1282
970
  };
1283
971
 
1284
- // src/management/management-error/management-error.ts
1285
- var ManagementError = class extends Error {
1286
- constructor(code, options) {
1287
- super(
1288
- "Route 33 management request failed",
1289
- options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
1290
- );
1291
- this.code = code;
1292
- this.name = "ManagementError";
1293
- this.statusCode = options?.statusCode;
972
+ // src/contract/management-keys/parse-user-memberships/parse-user-memberships.ts
973
+ var parseUserMemberships = (value) => {
974
+ if (!isRecord(value)) {
975
+ throw new ContractParseError("invalid user memberships");
1294
976
  }
1295
- code;
1296
- statusCode;
977
+ const rows = value["org_memberships"];
978
+ if (!Array.isArray(rows)) {
979
+ throw new ContractParseError("invalid user memberships");
980
+ }
981
+ return {
982
+ org_memberships: rows.map((row) => {
983
+ if (!isRecord(row)) {
984
+ throw new ContractParseError("invalid user memberships");
985
+ }
986
+ const orgId = row["org_id"];
987
+ const orgName = row["org_name"];
988
+ if (typeof orgId !== "string" || typeof orgName !== "string") {
989
+ throw new ContractParseError("invalid user memberships");
990
+ }
991
+ return { org_id: orgId, org_name: orgName };
992
+ })
993
+ };
1297
994
  };
1298
995
 
1299
- // src/management/management-http-transport/management-http-transport.ts
1300
- var ManagementHttpTransport = class {
1301
- #baseUrl;
1302
- #credential;
1303
- #fetchImpl;
1304
- #onUnauthorized;
1305
- #timeoutMs;
1306
- constructor(options) {
1307
- const baseUrl = options.baseUrl ?? "https://api.route33.ai/v1";
1308
- this.#baseUrl = new URL(baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`);
1309
- this.#credential = options.credential;
1310
- this.#fetchImpl = options.fetchImpl ?? fetch;
1311
- this.#onUnauthorized = options.onUnauthorized;
1312
- this.#timeoutMs = options.timeoutMs ?? 1e4;
1313
- }
1314
- /** Sends a request and reads one JSON value under the request timeout.
1315
- * @param request - Management path, method, and optional JSON body.
1316
- * @returns The untrusted response value.
1317
- */
1318
- json(request) {
1319
- return this.#perform(request, async (response) => {
1320
- try {
1321
- return await response.json();
1322
- } catch (cause) {
1323
- throw new ContractParseError("invalid management response", { cause });
1324
- }
1325
- });
1326
- }
1327
- /** Sends a request whose successful response has no body.
1328
- * @param request - Management path and method.
1329
- */
1330
- empty(request) {
1331
- return this.#perform(request, () => Promise.resolve());
1332
- }
1333
- async #perform(request, consume) {
1334
- const controller = new AbortController();
1335
- const timer = setTimeout(() => {
1336
- controller.abort();
1337
- }, this.#timeoutMs);
1338
- const headers = new Headers({
1339
- accept: "application/json",
1340
- authorization: `Bearer ${this.#credential.value}`
996
+ // src/management/sdk-management-keys/sdk-management-keys.ts
997
+ var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
998
+ var sdkManagementKeys = (options) => {
999
+ const baseUrl = options.apiBaseUrl.replace(API_PREFIX_PATTERN, "");
1000
+ const timeoutMs = options.timeoutMs ?? 1e4;
1001
+ const fetchImpl = options.fetchImpl;
1002
+ const observingFetch = (status) => fetchImpl === void 0 ? void 0 : async (input, init) => {
1003
+ const response = await fetchImpl(input, init);
1004
+ status.code = response.status;
1005
+ return response;
1006
+ };
1007
+ const callClient = (accessToken, status) => {
1008
+ const provider = {
1009
+ getToken: () => Promise.resolve(accessToken.value),
1010
+ onUnauthorized: () => Promise.resolve(accessToken.value)
1011
+ };
1012
+ const observedFetch = observingFetch(status);
1013
+ return createRoute33Client({
1014
+ baseUrl,
1015
+ provider,
1016
+ timeoutMs,
1017
+ ...observedFetch === void 0 ? {} : { fetch: observedFetch }
1341
1018
  });
1342
- if (request.body !== void 0) {
1343
- headers.set("content-type", "application/json");
1019
+ };
1020
+ const mapFailure = (cause) => {
1021
+ if (cause instanceof ManagementError || cause instanceof ContractParseError) {
1022
+ return cause;
1023
+ }
1024
+ if (cause instanceof Route33SdkError) {
1025
+ const code = cause.code === "SDK_TIMEOUT" ? "MANAGEMENT_TIMEOUT" : "MANAGEMENT_NETWORK_ERROR";
1026
+ return new ManagementError(code, { cause });
1344
1027
  }
1028
+ if (cause instanceof SyntaxError) {
1029
+ return new ContractParseError("invalid management response", { cause });
1030
+ }
1031
+ return new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
1032
+ };
1033
+ const call = async (accessToken, run) => {
1034
+ const status = { code: void 0 };
1345
1035
  try {
1346
- const send = () => this.#fetchImpl(new URL(request.path, this.#baseUrl), {
1347
- ...request.body === void 0 ? {} : { body: JSON.stringify(request.body) },
1348
- headers,
1349
- method: request.method,
1350
- signal: controller.signal
1351
- });
1352
- let response = await send();
1353
- if (response.status === 401 && this.#onUnauthorized !== void 0) {
1354
- await this.#onUnauthorized();
1355
- response = await send();
1356
- }
1357
- if (!response.ok) {
1036
+ const outcome = await run(callClient(accessToken, status));
1037
+ const code = status.code;
1038
+ if (code === void 0 || code < 200 || code >= 300) {
1358
1039
  throw new ManagementError(
1359
- response.status === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
1360
- { statusCode: response.status }
1040
+ code === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
1041
+ { statusCode: code }
1361
1042
  );
1362
1043
  }
1363
- return await consume(response);
1044
+ return outcome.data;
1364
1045
  } catch (cause) {
1365
- if (cause instanceof ManagementError) {
1366
- throw cause;
1367
- }
1368
- if (controller.signal.aborted) {
1369
- throw new ManagementError("MANAGEMENT_TIMEOUT", { cause });
1370
- }
1371
- if (cause instanceof ContractParseError) {
1372
- throw cause;
1373
- }
1374
- throw new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
1375
- } finally {
1376
- clearTimeout(timer);
1046
+ throw mapFailure(cause);
1377
1047
  }
1378
- }
1379
- };
1380
-
1381
- // src/management/http-management-keys/http-management-keys.ts
1382
- var HttpManagementKeys = class {
1383
- #credential;
1384
- #transport;
1385
- constructor(options) {
1386
- this.#credential = options.credential;
1387
- this.#transport = new ManagementHttpTransport(options);
1388
- }
1389
- /** Creates a future-expiring ownership-scoped key.
1390
- * @param accessToken - Credential required by the frozen contract.
1391
- * @param input - Key name, expiry, and ownership.
1392
- * @returns One-time key material.
1393
- */
1394
- async create(accessToken, input) {
1395
- this.#authorize(accessToken);
1396
- return parseKeyMaterial(
1397
- await this.#transport.json({
1398
- body: {
1399
- ...input.allowedModels === void 0 ? {} : { allowed_models: input.allowedModels },
1400
- ...input.description === void 0 ? {} : { description: input.description },
1401
- expires_at: input.expiresAt,
1402
- ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
1403
- name: input.name,
1404
- ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
1405
- owner_type: input.ownerType,
1406
- ...input.projectId === null ? {} : { project_id: input.projectId }
1407
- },
1408
- method: "POST",
1409
- path: "api-keys"
1410
- })
1411
- );
1412
- }
1413
- /** Treats a successful empty response as confirmation of permanent removal.
1414
- * @param accessToken - Credential required by the frozen contract.
1415
- * @param id - Key identifier.
1416
- */
1417
- async delete(accessToken, id) {
1418
- this.#authorize(accessToken);
1419
- await this.#transport.empty({
1420
- method: "DELETE",
1421
- path: `api-keys/${encodeURIComponent(id)}`
1422
- });
1423
- }
1424
- /** Gets a safe key DTO.
1425
- * @param accessToken - Credential required by the frozen contract.
1426
- * @param id - Key identifier.
1427
- * @returns The secret-free key DTO.
1428
- */
1429
- async get(accessToken, id) {
1430
- this.#authorize(accessToken);
1431
- return parseApiKey(
1432
- await this.#transport.json({
1433
- method: "GET",
1434
- path: `api-keys/${encodeURIComponent(id)}`
1435
- })
1436
- );
1437
- }
1438
- /** Lists safe key DTOs.
1439
- * @param accessToken - Credential required by the frozen contract.
1440
- * @returns The parsed key collection.
1441
- */
1442
- async list(accessToken) {
1443
- this.#authorize(accessToken);
1444
- return parseCollection(
1445
- await this.#transport.json({ method: "GET", path: "api-keys" }),
1048
+ };
1049
+ return {
1050
+ create: async (accessToken, input) => parseKeyMaterial(
1051
+ await call(
1052
+ accessToken,
1053
+ (client) => client.POST("/api/v1/api-keys", {
1054
+ body: {
1055
+ ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
1056
+ budget_currency: "EUR",
1057
+ ...input.description === void 0 ? {} : { description: input.description },
1058
+ expires_at: input.expiresAt,
1059
+ ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
1060
+ name: input.name,
1061
+ ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
1062
+ owner_type: input.ownerType,
1063
+ ...input.projectId === null ? {} : { project_id: input.projectId }
1064
+ }
1065
+ })
1066
+ )
1067
+ ),
1068
+ delete: async (accessToken, id) => {
1069
+ await call(
1070
+ accessToken,
1071
+ (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
1072
+ params: { path: { api_key_id: id } }
1073
+ })
1074
+ );
1075
+ },
1076
+ get: async (accessToken, id) => parseApiKey(
1077
+ await call(
1078
+ accessToken,
1079
+ (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
1080
+ params: { path: { api_key_id: id } }
1081
+ })
1082
+ )
1083
+ ),
1084
+ list: async (accessToken) => parseCollection(
1085
+ await call(accessToken, (client) => client.GET("/api/v1/api-keys", {})),
1446
1086
  parseApiKey
1447
- );
1448
- }
1449
- /** Lists organizations visible to the authenticated management subject.
1450
- * @param accessToken - Credential required by the frozen contract.
1451
- * @returns The parsed organization collection.
1452
- */
1453
- async listOrganizations(accessToken) {
1454
- this.#authorize(accessToken);
1455
- return parseCollection(
1456
- await this.#transport.json({ method: "GET", path: "orgs" }),
1087
+ ),
1088
+ listOrganizations: async (accessToken) => parseCollection(
1089
+ await call(accessToken, (client) => client.GET("/api/v1/orgs", {})),
1457
1090
  parseOrganization
1458
- );
1459
- }
1460
- /** Lists projects visible within an organisation filter.
1461
- * @param accessToken - Credential required by the frozen contract.
1462
- * @param organisationId - Required backend organisation filter.
1463
- * @returns The parsed project collection.
1464
- */
1465
- async listProjects(accessToken, organisationId) {
1466
- this.#authorize(accessToken);
1467
- if (organisationId.trim().length === 0) {
1468
- throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
1469
- statusCode: 400
1470
- });
1471
- }
1472
- const query = new URLSearchParams({
1473
- member_user_id: parseManagementSubject(accessToken),
1474
- org_id: organisationId
1475
- });
1476
- return parseCollection(
1477
- await this.#transport.json({
1478
- method: "GET",
1479
- path: `projects?${query.toString()}`
1480
- }),
1481
- parseProject
1482
- );
1483
- }
1484
- /** Regenerates one-time key material while preserving expiry when omitted.
1485
- * @param accessToken - Credential required by the frozen contract.
1486
- * @param id - Key identifier.
1487
- * @param expiresAt - Optional replacement expiry.
1488
- * @returns Regenerated one-time key material.
1489
- */
1490
- async regenerate(accessToken, id, expiresAt) {
1491
- this.#authorize(accessToken);
1492
- return parseKeyMaterial(
1493
- await this.#transport.json({
1494
- body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
1495
- method: "POST",
1496
- path: `api-keys/${encodeURIComponent(id)}/secrets`
1497
- })
1498
- );
1499
- }
1500
- /** Updates mutable key metadata.
1501
- * @param accessToken - Credential required by the frozen contract.
1502
- * @param id - Key identifier.
1503
- * @param input - Optional name and expiry replacements.
1504
- * @returns The updated safe key DTO.
1505
- */
1506
- async update(accessToken, id, input) {
1507
- this.#authorize(accessToken);
1508
- return parseApiKey(
1509
- await this.#transport.json({
1510
- body: {
1511
- ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
1512
- ...input.name === void 0 ? {} : { name: input.name }
1513
- },
1514
- method: "PATCH",
1515
- path: `api-keys/${encodeURIComponent(id)}`
1516
- })
1517
- );
1518
- }
1519
- #authorize(accessToken) {
1520
- if (accessToken.value !== this.#credential.value) {
1521
- throw new ManagementError("MANAGEMENT_UNAUTHORIZED", {
1522
- statusCode: 401
1523
- });
1524
- }
1091
+ ),
1092
+ listMemberships: async (accessToken, userId) => parseUserMemberships(
1093
+ await call(
1094
+ accessToken,
1095
+ (client) => client.GET("/api/v1/users/{user_id}/memberships", {
1096
+ params: { path: { user_id: userId } }
1097
+ })
1098
+ )
1099
+ ),
1100
+ listProjectBudgets: async (accessToken, userId) => parseCollection(
1101
+ await call(
1102
+ accessToken,
1103
+ (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
1104
+ params: { path: { user_id: userId } }
1105
+ })
1106
+ ),
1107
+ parseProjectBudgetState
1108
+ ),
1109
+ listProjects: async (accessToken, organisationId) => {
1110
+ if (organisationId.trim().length === 0) {
1111
+ throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
1112
+ statusCode: 400
1113
+ });
1114
+ }
1115
+ const query = {
1116
+ member_user_id: parseManagementSubject(accessToken),
1117
+ org_id: organisationId
1118
+ };
1119
+ const fetchPage = (cursor) => call(
1120
+ accessToken,
1121
+ (client) => client.GET("/api/v1/projects", {
1122
+ params: {
1123
+ query: cursor === "" ? query : { ...query, cursor }
1124
+ }
1125
+ })
1126
+ ).then((page) => parseCollection(page, parseProject));
1127
+ return drainPages(fetchPage);
1128
+ },
1129
+ regenerate: async (accessToken, id, expiresAt) => parseKeyMaterial(
1130
+ await call(
1131
+ accessToken,
1132
+ (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
1133
+ body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
1134
+ params: { path: { api_key_id: id } }
1135
+ })
1136
+ )
1137
+ ),
1138
+ update: async (accessToken, id, input) => parseApiKey(
1139
+ await call(
1140
+ accessToken,
1141
+ (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
1142
+ body: {
1143
+ budget_currency: "EUR",
1144
+ ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
1145
+ ...input.name === void 0 ? {} : { name: input.name }
1146
+ },
1147
+ params: { path: { api_key_id: id } }
1148
+ })
1149
+ )
1150
+ )
1151
+ };
1152
+ };
1153
+
1154
+ // src/route33-login/route33-login.ts
1155
+ import {
1156
+ AuthError,
1157
+ loginFlow
1158
+ } from "@r-33/auth-browser";
1159
+
1160
+ // src/requested-scopes/requested-scopes.ts
1161
+ var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read projects:read users:read keys:read keys:write";
1162
+
1163
+ // src/ux/callback-page-copy/callback-page-copy.ts
1164
+ var CALLBACK_PAGE_COPY = {
1165
+ errorHeadline: "Sign-in failed",
1166
+ errorSubline: "Return to OpenCode and retry.",
1167
+ successHeadline: "Signed in to route33",
1168
+ 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."
1169
+ };
1170
+
1171
+ // src/route33-login/route33-login.ts
1172
+ var route33Login = async (options) => {
1173
+ const log = options.logger ?? logger;
1174
+ const tokenSet = await loginFlow({
1175
+ ...options.browserRunner === void 0 ? {} : { browserRunner: options.browserRunner },
1176
+ clientId: options.clientId,
1177
+ logger: log,
1178
+ pageCopy: CALLBACK_PAGE_COPY,
1179
+ scope: REQUESTED_OAUTH_SCOPES,
1180
+ session: options.session,
1181
+ ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
1182
+ });
1183
+ let credential;
1184
+ try {
1185
+ credential = parseManagementJwt(tokenSet.access_token);
1186
+ } catch (cause) {
1187
+ throw new AuthError("AUTH_TOKEN_RESPONSE_INVALID", { cause });
1525
1188
  }
1189
+ return { credential, tokenSet };
1526
1190
  };
1527
1191
 
1528
1192
  // src/cli/production-smoke-error/production-smoke-error.ts
@@ -1550,6 +1214,7 @@ var parseManagementSubjectForSmoke = (credential) => {
1550
1214
  };
1551
1215
 
1552
1216
  // src/cli/precheck-route33-auth/precheck-route33-auth.ts
1217
+ import { createPkceVerifierAndChallenge } from "@r-33/auth-browser";
1553
1218
  var precheckRoute33Auth = async (options) => {
1554
1219
  const controller = new AbortController();
1555
1220
  const timer = setTimeout(() => {
@@ -1613,7 +1278,7 @@ var createLiveProductionSmokePlan = (options) => {
1613
1278
  issuerUrl: options.authIssuerUrl
1614
1279
  }),
1615
1280
  login: async () => {
1616
- const result = options.login === void 0 ? await loginFlow({
1281
+ const result = options.login === void 0 ? await route33Login({
1617
1282
  clientId: options.clientId,
1618
1283
  logger,
1619
1284
  session: createAuthSession({
@@ -1624,9 +1289,8 @@ var createLiveProductionSmokePlan = (options) => {
1624
1289
  timeoutMs: 12e4
1625
1290
  }) : await options.login();
1626
1291
  session = {
1627
- client: new HttpManagementKeys({
1628
- baseUrl: options.apiBaseUrl,
1629
- credential: result.credential,
1292
+ client: sdkManagementKeys({
1293
+ apiBaseUrl: options.apiBaseUrl,
1630
1294
  ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl }
1631
1295
  }),
1632
1296
  credential: result.credential,