@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.
@@ -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,12 @@ var LeaseState = class _LeaseState {
1098
719
  }
1099
720
  };
1100
721
 
722
+ // src/management/sdk-management-keys/sdk-management-keys.ts
723
+ import {
724
+ createRoute33Client,
725
+ Route33SdkError
726
+ } from "@r-33/sdk";
727
+
1101
728
  // src/contract/management-keys/parse-api-key/parse-api-key.ts
1102
729
  var parseApiKey = (value) => {
1103
730
  if (!isRecord(value) || !isOwnerType(value["ownership_type"]) || !isNullableString(value["project_id"])) {
@@ -1296,233 +923,184 @@ var ManagementError = class extends Error {
1296
923
  statusCode;
1297
924
  };
1298
925
 
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}`
926
+ // src/management/sdk-management-keys/sdk-management-keys.ts
927
+ var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
928
+ var sdkManagementKeys = (options) => {
929
+ const baseUrl = options.apiBaseUrl.replace(API_PREFIX_PATTERN, "");
930
+ const timeoutMs = options.timeoutMs ?? 1e4;
931
+ const fetchImpl = options.fetchImpl;
932
+ const observingFetch = (status) => fetchImpl === void 0 ? void 0 : async (input, init) => {
933
+ const response = await fetchImpl(input, init);
934
+ status.code = response.status;
935
+ return response;
936
+ };
937
+ const callClient = (accessToken, status) => {
938
+ const provider = {
939
+ getToken: () => Promise.resolve(accessToken.value),
940
+ onUnauthorized: () => Promise.resolve(accessToken.value)
941
+ };
942
+ const observedFetch = observingFetch(status);
943
+ return createRoute33Client({
944
+ baseUrl,
945
+ provider,
946
+ timeoutMs,
947
+ ...observedFetch === void 0 ? {} : { fetch: observedFetch }
1341
948
  });
1342
- if (request.body !== void 0) {
1343
- headers.set("content-type", "application/json");
949
+ };
950
+ const mapFailure = (cause) => {
951
+ if (cause instanceof ManagementError || cause instanceof ContractParseError) {
952
+ return cause;
953
+ }
954
+ if (cause instanceof Route33SdkError) {
955
+ const code = cause.code === "SDK_TIMEOUT" ? "MANAGEMENT_TIMEOUT" : "MANAGEMENT_NETWORK_ERROR";
956
+ return new ManagementError(code, { cause });
1344
957
  }
958
+ if (cause instanceof SyntaxError) {
959
+ return new ContractParseError("invalid management response", { cause });
960
+ }
961
+ return new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
962
+ };
963
+ const call = async (accessToken, run) => {
964
+ const status = { code: void 0 };
1345
965
  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) {
966
+ const outcome = await run(callClient(accessToken, status));
967
+ const code = status.code;
968
+ if (code === void 0 || code < 200 || code >= 300) {
1358
969
  throw new ManagementError(
1359
- response.status === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
1360
- { statusCode: response.status }
970
+ code === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
971
+ { statusCode: code }
1361
972
  );
1362
973
  }
1363
- return await consume(response);
974
+ return outcome.data;
1364
975
  } 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);
976
+ throw mapFailure(cause);
1377
977
  }
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" }),
978
+ };
979
+ return {
980
+ create: async (accessToken, input) => parseKeyMaterial(
981
+ await call(
982
+ accessToken,
983
+ (client) => client.POST("/api/v1/api-keys", {
984
+ body: {
985
+ ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
986
+ budget_currency: "EUR",
987
+ ...input.description === void 0 ? {} : { description: input.description },
988
+ expires_at: input.expiresAt,
989
+ ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
990
+ name: input.name,
991
+ ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
992
+ owner_type: input.ownerType,
993
+ ...input.projectId === null ? {} : { project_id: input.projectId }
994
+ }
995
+ })
996
+ )
997
+ ),
998
+ delete: async (accessToken, id) => {
999
+ await call(
1000
+ accessToken,
1001
+ (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
1002
+ params: { path: { api_key_id: id } }
1003
+ })
1004
+ );
1005
+ },
1006
+ get: async (accessToken, id) => parseApiKey(
1007
+ await call(
1008
+ accessToken,
1009
+ (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
1010
+ params: { path: { api_key_id: id } }
1011
+ })
1012
+ )
1013
+ ),
1014
+ list: async (accessToken) => parseCollection(
1015
+ await call(accessToken, (client) => client.GET("/api/v1/api-keys", {})),
1446
1016
  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" }),
1017
+ ),
1018
+ listOrganizations: async (accessToken) => parseCollection(
1019
+ await call(accessToken, (client) => client.GET("/api/v1/orgs", {})),
1457
1020
  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
- }
1021
+ ),
1022
+ listProjects: async (accessToken, organisationId) => {
1023
+ if (organisationId.trim().length === 0) {
1024
+ throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
1025
+ statusCode: 400
1026
+ });
1027
+ }
1028
+ return parseCollection(
1029
+ await call(
1030
+ accessToken,
1031
+ (client) => client.GET("/api/v1/projects", {
1032
+ params: {
1033
+ query: {
1034
+ member_user_id: parseManagementSubject(accessToken),
1035
+ org_id: organisationId
1036
+ }
1037
+ }
1038
+ })
1039
+ ),
1040
+ parseProject
1041
+ );
1042
+ },
1043
+ regenerate: async (accessToken, id, expiresAt) => parseKeyMaterial(
1044
+ await call(
1045
+ accessToken,
1046
+ (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
1047
+ body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
1048
+ params: { path: { api_key_id: id } }
1049
+ })
1050
+ )
1051
+ ),
1052
+ update: async (accessToken, id, input) => parseApiKey(
1053
+ await call(
1054
+ accessToken,
1055
+ (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
1056
+ body: {
1057
+ budget_currency: "EUR",
1058
+ ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
1059
+ ...input.name === void 0 ? {} : { name: input.name }
1060
+ },
1061
+ params: { path: { api_key_id: id } }
1062
+ })
1063
+ )
1064
+ )
1065
+ };
1066
+ };
1067
+
1068
+ // src/route33-login/route33-login.ts
1069
+ import {
1070
+ AuthError,
1071
+ loginFlow
1072
+ } from "@r-33/auth-browser";
1073
+
1074
+ // src/requested-scopes/requested-scopes.ts
1075
+ var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read projects:read keys:read keys:write";
1076
+
1077
+ // src/ux/callback-page-copy/callback-page-copy.ts
1078
+ var CALLBACK_PAGE_COPY = {
1079
+ errorHeadline: "Sign-in failed",
1080
+ errorSubline: "Return to OpenCode and retry.",
1081
+ successHeadline: "Signed in to route33",
1082
+ 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."
1083
+ };
1084
+
1085
+ // src/route33-login/route33-login.ts
1086
+ var route33Login = async (options) => {
1087
+ const log = options.logger ?? logger;
1088
+ const tokenSet = await loginFlow({
1089
+ ...options.browserRunner === void 0 ? {} : { browserRunner: options.browserRunner },
1090
+ clientId: options.clientId,
1091
+ logger: log,
1092
+ pageCopy: CALLBACK_PAGE_COPY,
1093
+ scope: REQUESTED_OAUTH_SCOPES,
1094
+ session: options.session,
1095
+ ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
1096
+ });
1097
+ let credential;
1098
+ try {
1099
+ credential = parseManagementJwt(tokenSet.access_token);
1100
+ } catch (cause) {
1101
+ throw new AuthError("AUTH_TOKEN_RESPONSE_INVALID", { cause });
1525
1102
  }
1103
+ return { credential, tokenSet };
1526
1104
  };
1527
1105
 
1528
1106
  // src/cli/production-smoke-error/production-smoke-error.ts
@@ -1550,6 +1128,7 @@ var parseManagementSubjectForSmoke = (credential) => {
1550
1128
  };
1551
1129
 
1552
1130
  // src/cli/precheck-route33-auth/precheck-route33-auth.ts
1131
+ import { createPkceVerifierAndChallenge } from "@r-33/auth-browser";
1553
1132
  var precheckRoute33Auth = async (options) => {
1554
1133
  const controller = new AbortController();
1555
1134
  const timer = setTimeout(() => {
@@ -1613,7 +1192,7 @@ var createLiveProductionSmokePlan = (options) => {
1613
1192
  issuerUrl: options.authIssuerUrl
1614
1193
  }),
1615
1194
  login: async () => {
1616
- const result = options.login === void 0 ? await loginFlow({
1195
+ const result = options.login === void 0 ? await route33Login({
1617
1196
  clientId: options.clientId,
1618
1197
  logger,
1619
1198
  session: createAuthSession({
@@ -1624,9 +1203,8 @@ var createLiveProductionSmokePlan = (options) => {
1624
1203
  timeoutMs: 12e4
1625
1204
  }) : await options.login();
1626
1205
  session = {
1627
- client: new HttpManagementKeys({
1628
- baseUrl: options.apiBaseUrl,
1629
- credential: result.credential,
1206
+ client: sdkManagementKeys({
1207
+ apiBaseUrl: options.apiBaseUrl,
1630
1208
  ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl }
1631
1209
  }),
1632
1210
  credential: result.credential,