@r-33/opencode 0.4.7-rc.30 → 0.4.7-rc.32

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.
@@ -2148,9 +2148,11 @@ var KeyLeaseError = class extends Error {
2148
2148
  );
2149
2149
  this.code = code;
2150
2150
  this.name = "KeyLeaseError";
2151
+ this.rejection = options?.rejection;
2151
2152
  this.statusCode = options?.statusCode;
2152
2153
  }
2153
2154
  code;
2155
+ rejection;
2154
2156
  statusCode;
2155
2157
  };
2156
2158
 
@@ -2315,6 +2317,33 @@ var commitStagedReplacement = async (stage, save, persist) => {
2315
2317
  }
2316
2318
  };
2317
2319
 
2320
+ // src/management/management-error/management-error.ts
2321
+ var ManagementError = class extends Error {
2322
+ constructor(code, options) {
2323
+ super(
2324
+ "Route 33 management request failed",
2325
+ options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
2326
+ );
2327
+ this.code = code;
2328
+ this.name = "ManagementError";
2329
+ this.rejection = options?.rejection;
2330
+ this.statusCode = options?.statusCode;
2331
+ }
2332
+ code;
2333
+ rejection;
2334
+ statusCode;
2335
+ };
2336
+
2337
+ // src/key-lease/mint-failure/mint-failure.ts
2338
+ var mintFailure = (cause) => {
2339
+ const response = cause instanceof ManagementError ? cause : void 0;
2340
+ return new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
2341
+ cause,
2342
+ ...response?.rejection === void 0 ? {} : { rejection: response.rejection },
2343
+ ...response?.statusCode === void 0 ? {} : { statusCode: response.statusCode }
2344
+ });
2345
+ };
2346
+
2318
2347
  // src/key-lease/mint-fresh-lease/mint-fresh-lease.ts
2319
2348
  var mintFreshLease = async (deps) => {
2320
2349
  const now = deps.clock();
@@ -2345,7 +2374,7 @@ var mintFreshLease = async (deps) => {
2345
2374
  input
2346
2375
  );
2347
2376
  } catch (cause) {
2348
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", { cause });
2377
+ throw mintFailure(cause);
2349
2378
  }
2350
2379
  const minted = {
2351
2380
  key: material.key,
@@ -2428,21 +2457,6 @@ var rejectLease = async (options) => {
2428
2457
  }
2429
2458
  };
2430
2459
 
2431
- // src/management/management-error/management-error.ts
2432
- var ManagementError = class extends Error {
2433
- constructor(code, options) {
2434
- super(
2435
- "Route 33 management request failed",
2436
- options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
2437
- );
2438
- this.code = code;
2439
- this.name = "ManagementError";
2440
- this.statusCode = options?.statusCode;
2441
- }
2442
- code;
2443
- statusCode;
2444
- };
2445
-
2446
2460
  // src/key-lease/mint-key/mint-key.ts
2447
2461
  var mintKey = async (options) => {
2448
2462
  const now = options.clock();
@@ -2476,10 +2490,7 @@ var mintKey = async (options) => {
2476
2490
  if (isManagementUnauthorized(cause)) {
2477
2491
  throw new KeyLeaseError("KEY_LEASE_UNAUTHORIZED", { cause });
2478
2492
  }
2479
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
2480
- cause,
2481
- ...cause instanceof ManagementError && cause.statusCode !== void 0 ? { statusCode: cause.statusCode } : {}
2482
- });
2493
+ throw mintFailure(cause);
2483
2494
  }
2484
2495
  return {
2485
2496
  key: material.key,
@@ -2817,6 +2828,7 @@ var inspectSession = (options) => {
2817
2828
  const lease = options.readLease();
2818
2829
  return {
2819
2830
  attribution,
2831
+ connected: options.connected,
2820
2832
  ...lease === void 0 ? {} : { lease: { expiresAt: lease.expiresAt, keyId: lease.keyId } }
2821
2833
  };
2822
2834
  };
@@ -2847,10 +2859,10 @@ var WorkspaceKeyBinding = class {
2847
2859
  * @returns Secret-free options; local options do not need destructive consent.
2848
2860
  */
2849
2861
  async candidates(choice) {
2850
- const listing = this.#listings.get(choice.orgId) ?? this.deps.client.list(this.deps.token, choice.orgId);
2862
+ const listing = this.#listings.get(choice.orgId) ?? this.listKeys(choice.orgId);
2851
2863
  this.#listings.set(choice.orgId, listing);
2852
2864
  const rows = await listing;
2853
- const keys = rows.data.filter((row) => this.matches(row, choice));
2865
+ const keys = rows.filter((row) => this.matches(row, choice));
2854
2866
  if (keys.length === 0) return [];
2855
2867
  const local = await this.localKeys(new Set(keys.map((row) => row.id)));
2856
2868
  return keys.map((row) => ({
@@ -2859,8 +2871,18 @@ var WorkspaceKeyBinding = class {
2859
2871
  local: local.has(row.id)
2860
2872
  }));
2861
2873
  }
2874
+ async listKeys(orgId) {
2875
+ try {
2876
+ return (await this.deps.client.list(this.deps.token, orgId)).data;
2877
+ } catch {
2878
+ logger.warn(
2879
+ "Existing keys could not be listed; only new keys can be offered."
2880
+ );
2881
+ return [];
2882
+ }
2883
+ }
2862
2884
  matches(row, choice) {
2863
- return row.status === "active" && !row.revoked && Date.parse(row.expires_at) > this.deps.now && (choice.orgId === void 0 || row.org_id === choice.orgId) && row.owner_user_id === this.deps.subject && (choice.kind === "project" ? row.project_id === choice.projectId && row.ownership_type === "user_project" : row.project_id === null && row.ownership_type === "user_personal");
2885
+ return row.status === "active" && !row.revoked && Date.parse(row.expires_at) > this.deps.now && (choice.orgId === void 0 || row.org_id === choice.orgId) && row.user_id === this.deps.subject && (choice.kind === "project" ? row.project_id === choice.projectId && row.ownership_type === "user_project" : row.project_id === null && row.ownership_type === "user_personal");
2864
2886
  }
2865
2887
  async localKeys(ids) {
2866
2888
  const found = /* @__PURE__ */ new Map();
@@ -2959,6 +2981,8 @@ var createAttributionPrompt = (projects, options = {}) => {
2959
2981
  return `Personal \u2014 your own key${marker}${orgSuffix}`;
2960
2982
  };
2961
2983
  const budgetAllowance = (project) => {
2984
+ if (project.memberCap !== void 0)
2985
+ return `cap ${String(project.memberCap)} EUR`;
2962
2986
  const budget = project.effective_budget ?? project.max_budget;
2963
2987
  return budget === null ? "no cap set" : `cap ${budget.amount} ${budget.currency}`;
2964
2988
  };
@@ -2973,6 +2997,7 @@ var createAttributionPrompt = (projects, options = {}) => {
2973
2997
  };
2974
2998
  return {
2975
2999
  label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${budgetAllowance(project)}`,
3000
+ maximum: project.memberCap,
2976
3001
  selection
2977
3002
  };
2978
3003
  });
@@ -2992,6 +3017,7 @@ var createAttributionPrompt = (projects, options = {}) => {
2992
3017
  choicesBySelection[personal] = { kind: "personal", orgId: org.id };
2993
3018
  promptOptions.push({
2994
3019
  label: personalLabel(options.orgs.length > 1 ? org.name : void 0),
3020
+ maximum: org.personalBudget?.cap ?? void 0,
2995
3021
  selection: personal
2996
3022
  });
2997
3023
  }
@@ -3007,6 +3033,7 @@ var createAttributionPrompt = (projects, options = {}) => {
3007
3033
  };
3008
3034
  promptOptions.push({
3009
3035
  label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${budgetAllowance(project)}`,
3036
+ maximum: project.memberCap,
3010
3037
  selection
3011
3038
  });
3012
3039
  }
@@ -3022,8 +3049,8 @@ var createAttributionPrompt = (projects, options = {}) => {
3022
3049
  // src/ux/attribution-prompt-error/attribution-prompt-error.ts
3023
3050
  var MESSAGES = {
3024
3051
  ATTRIBUTION_BACK: "Left budget selection without changing attribution.",
3025
- ATTRIBUTION_PRESENTER_UNAVAILABLE: "Route 33 needs OpenCode v2 to assign a budget for this folder. Update to OpenCode v2, run /connect, choose Route 33, and follow the steps.",
3026
- ATTRIBUTION_SELECTION_INVALID: "That Route 33 option is no longer available. Connect again and pick another."
3052
+ ATTRIBUTION_PRESENTER_UNAVAILABLE: "Update to OpenCode v2 to assign a Route 33 budget in this folder.",
3053
+ ATTRIBUTION_SELECTION_INVALID: "That Route 33 option is no longer available; choose another budget."
3027
3054
  };
3028
3055
  var AttributionPromptError = class extends GatewayCredentialError {
3029
3056
  code;
@@ -3142,7 +3169,7 @@ import {
3142
3169
  } from "@r-33/auth-browser";
3143
3170
 
3144
3171
  // src/requested-scopes/requested-scopes.ts
3145
- var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read profile projects:read users:read keys:read keys:write";
3172
+ var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read profile projects:read users:read keys:read keys:write models:read";
3146
3173
 
3147
3174
  // src/route33-login/route33-login.ts
3148
3175
  var route33Login = async (options) => {
@@ -3171,20 +3198,34 @@ var LoginSession = class {
3171
3198
  #options;
3172
3199
  #result;
3173
3200
  #expiresAt;
3201
+ #clears = 0;
3174
3202
  constructor(options) {
3175
3203
  this.#options = options;
3176
3204
  }
3177
3205
  /**
3178
3206
  * Clears the session: the cached login result and the stored refresh
3179
- * token. The next login starts from scratch — /r33 logout and the
3180
- * auto-reconnect path both land here.
3207
+ * token. The next login starts from scratch — the removal of the host's
3208
+ * last Route 33 account and the auto-reconnect path both land here. A refresh still on its way to the
3209
+ * auth server is disowned: its rotated token is never stored.
3181
3210
  * @returns Resolved once the session and the stored refresh token are gone.
3182
3211
  */
3183
3212
  async clear() {
3213
+ this.#clears += 1;
3184
3214
  this.#result = void 0;
3185
3215
  this.#expiresAt = void 0;
3186
3216
  await this.#options.tokenStore?.set(void 0);
3187
3217
  }
3218
+ /**
3219
+ * Whether a session exists, judged without using it: a login resolved or
3220
+ * in flight in this process, or a stored refresh token. Read-only — the
3221
+ * token is never presented, so asking cannot rotate or revoke anything.
3222
+ * @returns True when there is a session to sign in with.
3223
+ */
3224
+ async hasSession() {
3225
+ if (this.#result !== void 0) return true;
3226
+ const stored = await this.#options.tokenStore?.get().catch(() => void 0);
3227
+ return stored !== void 0 && stored !== "";
3228
+ }
3188
3229
  /**
3189
3230
  * Resolves the login once per process, sharing in-flight attempts.
3190
3231
  * @param policy - Whether this attempt may start a browser login; an in-flight attempt is always shared.
@@ -3193,11 +3234,15 @@ var LoginSession = class {
3193
3234
  result(policy = {}) {
3194
3235
  if (this.#result !== void 0 && this.#expiresAt !== void 0 && Date.now() >= this.#expiresAt - EXPIRY_SKEW_MS) {
3195
3236
  this.#result = void 0;
3237
+ this.#expiresAt = void 0;
3238
+ }
3239
+ if (this.#result === void 0) {
3240
+ const attempt = this.#start(policy).catch((cause) => {
3241
+ if (this.#result === attempt) this.#result = void 0;
3242
+ throw cause;
3243
+ });
3244
+ this.#result = attempt;
3196
3245
  }
3197
- this.#result ??= this.#start(policy).catch((cause) => {
3198
- this.#result = void 0;
3199
- throw cause;
3200
- });
3201
3246
  return this.#result;
3202
3247
  }
3203
3248
  /**
@@ -3227,6 +3272,7 @@ var LoginSession = class {
3227
3272
  if (tokenStore === void 0) {
3228
3273
  return void 0;
3229
3274
  }
3275
+ const clears = this.#clears;
3230
3276
  const stored = await tokenStore.get();
3231
3277
  if (stored === void 0 || stored === "") {
3232
3278
  return void 0;
@@ -3235,6 +3281,9 @@ var LoginSession = class {
3235
3281
  if (tokenSet === void 0) {
3236
3282
  return void 0;
3237
3283
  }
3284
+ if (clears !== this.#clears) {
3285
+ throw new AuthError2("AUTH_REAUTHENTICATION_REQUIRED");
3286
+ }
3238
3287
  let credential;
3239
3288
  try {
3240
3289
  credential = parseManagementJwt(tokenSet.access_token);
@@ -3368,7 +3417,7 @@ var Route33Runtime = class {
3368
3417
  const projectsById = new Map(
3369
3418
  listings.flatMap(({ data }) => data).map((project) => [project.id, project])
3370
3419
  );
3371
- return rows.flatMap(({ org_id, project_id }) => {
3420
+ return rows.flatMap(({ org_id, project_id, cap }) => {
3372
3421
  const project = projectsById.get(project_id);
3373
3422
  if (project === void 0) {
3374
3423
  return [];
@@ -3376,6 +3425,7 @@ var Route33Runtime = class {
3376
3425
  return [
3377
3426
  {
3378
3427
  ...project,
3428
+ memberCap: cap,
3379
3429
  organisation: {
3380
3430
  id: org_id,
3381
3431
  name: organisationNames.get(org_id) ?? org_id
@@ -3491,7 +3541,10 @@ var Route33Runtime = class {
3491
3541
  }),
3492
3542
  logout: () => this.#session.clear(),
3493
3543
  "rotate-now": () => rotateNow({
3494
- lease: (policy) => this.#lease({ ...this.#options.policy, ...policy })
3544
+ lease: async (policy) => {
3545
+ await this.#session.credential({ allowBrowser: false });
3546
+ return this.#lease({ ...this.#options.policy, ...policy });
3547
+ }
3495
3548
  })
3496
3549
  };
3497
3550
  }
@@ -3505,6 +3558,7 @@ var Route33Runtime = class {
3505
3558
  await this.#hydrateState(installation);
3506
3559
  }
3507
3560
  const base = inspectSession({
3561
+ connected: await this.#session.hasSession(),
3508
3562
  readAttribution: () => attribution,
3509
3563
  readLease: () => installation?.state.snapshot()
3510
3564
  });
@@ -3512,10 +3566,9 @@ var Route33Runtime = class {
3512
3566
  if (attribution === void 0 || keyId === void 0) {
3513
3567
  return base;
3514
3568
  }
3569
+ const credential = await this.#session.credential({ allowBrowser: false }).catch(() => void 0);
3570
+ if (credential === void 0) return { ...base, connected: false };
3515
3571
  try {
3516
- const credential = await this.#session.credential({
3517
- allowBrowser: false
3518
- });
3519
3572
  const details = await enrichInspection({
3520
3573
  attribution,
3521
3574
  client: this.#client(),
@@ -3528,16 +3581,24 @@ var Route33Runtime = class {
3528
3581
  return base;
3529
3582
  }
3530
3583
  }
3584
+ /**
3585
+ * Lists the models a key on this budget may be limited to. Never opens a
3586
+ * browser; an organisation-level (personal) catalog needs the `models:read`
3587
+ * grant, so sessions signed in before that grant reject here.
3588
+ * @param scope - The budget being configured.
3589
+ * @returns Key-facing model ids with their readable names.
3590
+ */
3591
+ async catalogModelChoices(scope) {
3592
+ const credential = await this.#session.credential({ allowBrowser: false });
3593
+ return this.#client().listModelChoices(credential, scope);
3594
+ }
3531
3595
  /**
3532
3596
  * @param scope - The budget being configured. Omit to discover models for the current key.
3533
3597
  * @returns The management catalog for a budget, or the current key's gateway catalog.
3534
3598
  */
3535
3599
  async catalogModelIds(scope) {
3536
3600
  if (scope !== void 0) {
3537
- const credential = await this.#session.credential({
3538
- allowBrowser: false
3539
- });
3540
- return this.#client().listModelIds(credential, scope);
3601
+ return (await this.catalogModelChoices(scope)).map(({ id }) => id);
3541
3602
  }
3542
3603
  const workspace = await this.storedReusableKey();
3543
3604
  const personal = workspace === void 0 ? await this.#storedPersonalKey() : void 0;
@@ -3546,7 +3607,8 @@ var Route33Runtime = class {
3546
3607
  const credential = await this.#session.credential({
3547
3608
  allowBrowser: false
3548
3609
  });
3549
- return this.#client().listModelIds(credential, {});
3610
+ const choices = await this.#client().listModelChoices(credential, {});
3611
+ return choices.map(({ id }) => id);
3550
3612
  }
3551
3613
  return gatewayModelIds({
3552
3614
  baseURL: readEnvBaseUrl() ?? DEFAULT_BASE_URL,
@@ -3627,6 +3689,29 @@ var Route33Runtime = class {
3627
3689
  const key = keys.find((item) => item.id === keyId);
3628
3690
  return key === void 0 ? void 0 : { allowedModels: key.allowed_models };
3629
3691
  }
3692
+ /** V1 captures only the choice, not the plan; read only that owner's policy.
3693
+ * @param choice - The selected budget and its active organisation.
3694
+ * @returns The effective EUR cap, if the owner has a readable allowance.
3695
+ */
3696
+ async ownerBudgetCap(choice) {
3697
+ const token = await this.#session.credential({ allowBrowser: false });
3698
+ const subject = this.#subject(token);
3699
+ const client = this.#client();
3700
+ if (choice.kind === "personal") {
3701
+ const policy = await client.listBudgetPolicy(
3702
+ token,
3703
+ subject,
3704
+ choice.orgId
3705
+ );
3706
+ return policy.cap ?? void 0;
3707
+ }
3708
+ const budgets = await client.listProjectBudgets(
3709
+ token,
3710
+ subject,
3711
+ choice.orgId
3712
+ );
3713
+ return budgets.data.find((row) => row.project_id === choice.projectId)?.cap;
3714
+ }
3630
3715
  #client() {
3631
3716
  const client = this.#options.management.client;
3632
3717
  if (typeof client !== "function") {
@@ -3742,8 +3827,8 @@ var Route33Runtime = class {
3742
3827
  };
3743
3828
 
3744
3829
  // src/v1-entry/unattributed-prompt-gate/unattributed-prompt-gate.ts
3745
- var CONNECTION_COPY = "Not connected to Route 33. Run /connect, choose Route 33, and complete sign-in before assigning a budget with /r33.";
3746
- var ATTRIBUTION_COPY = "This folder has no Route 33 budget assigned. Run /r33, choose Route 33, and assign a budget.";
3830
+ var CONNECTION_COPY = "To sign in, run /connect and choose Route 33.";
3831
+ var ATTRIBUTION_COPY = "This folder has no Route 33 budget; open /r33 and choose Change budget.";
3747
3832
  var createUnattributedPromptGate = ({ directory, isConnected, outsideWorktree }) => async (input) => {
3748
3833
  if (input.model?.providerID !== "route_33") return Promise.resolve();
3749
3834
  if (!await isConnected()) throw new Error(CONNECTION_COPY);
@@ -3890,7 +3975,7 @@ var parseApiKey = (value) => {
3890
3975
  name: field("name"),
3891
3976
  org_id: field("org_id"),
3892
3977
  ownership_type: value["ownership_type"],
3893
- ...typeof value["owner_user_id"] === "string" ? { owner_user_id: value["owner_user_id"] } : {},
3978
+ ...isNullableString(value["user_id"]) ? { user_id: value["user_id"] } : {},
3894
3979
  project_id: value["project_id"],
3895
3980
  revoked: value["revoked"] === true,
3896
3981
  status
@@ -4133,6 +4218,18 @@ var keyReadOperations = (call) => {
4133
4218
  url.searchParams.set("cursor", cursor);
4134
4219
  return new Request(url, request);
4135
4220
  };
4221
+ const parsePage = (page) => {
4222
+ const collection = parseCollection(page, (row) => row);
4223
+ const data = collection.data.flatMap((row) => {
4224
+ try {
4225
+ return [parseApiKey(row)];
4226
+ } catch (error) {
4227
+ if (error instanceof ContractParseError) return [];
4228
+ throw error;
4229
+ }
4230
+ });
4231
+ return { ...collection, data };
4232
+ };
4136
4233
  return {
4137
4234
  get: async (accessToken, id, orgId) => parseApiKey(
4138
4235
  await call(
@@ -4147,7 +4244,7 @@ var keyReadOperations = (call) => {
4147
4244
  (cursor) => call(accessToken, orgId, (client) => {
4148
4245
  if (cursor !== "") client.use({ onRequest: withCursor(cursor) });
4149
4246
  return client.GET("/api/v1/api-keys", {});
4150
- }).then((page) => parseCollection(page, parseApiKey))
4247
+ }).then(parsePage)
4151
4248
  )
4152
4249
  };
4153
4250
  };
@@ -4211,29 +4308,55 @@ var keyWriteOperations = (call) => ({
4211
4308
  )
4212
4309
  });
4213
4310
 
4214
- // src/management/sdk-management-keys/exposed-catalog-ids/exposed-catalog-ids.ts
4215
- var exposedCatalogIds = async (readPage) => {
4216
- const ids = /* @__PURE__ */ new Set();
4311
+ // src/management/client-model-id/client-model-id.ts
4312
+ var clientModelId = (offeringId) => {
4313
+ const [provider, region, scope, vendor, ...modelParts] = offeringId.split(":");
4314
+ const slugParts = modelParts.at(-1) === "zdr" ? modelParts.slice(0, -1) : modelParts;
4315
+ const parts = [provider, region, scope, vendor, slugParts.join(":")];
4316
+ return parts.some((part) => part === void 0 || part === "") || /[\s,]/u.test(offeringId) ? void 0 : `${vendor ?? ""}/${slugParts.join(":")}`;
4317
+ };
4318
+
4319
+ // src/management/exposed-catalog-models/catalog-row-choices/catalog-row-choices.ts
4320
+ var catalogRowChoices = (row) => {
4321
+ if (!isRecord(row) || typeof row.id !== "string" || !row.id.trim() || typeof row.status !== "string")
4322
+ throw new ContractParseError("invalid model catalog item");
4323
+ if (row.status !== "exposed" || !Array.isArray(row.offerings)) return [];
4324
+ const label = typeof row.name === "string" && row.name.trim() !== "" ? row.name.trim() : void 0;
4325
+ return row.offerings.flatMap((offering) => {
4326
+ if (!isRecord(offering) || typeof offering.id !== "string" || offering.enabled !== true)
4327
+ return [];
4328
+ const id = clientModelId(offering.id);
4329
+ return id === void 0 ? [] : [{ id, name: label ?? id }];
4330
+ });
4331
+ };
4332
+
4333
+ // src/management/exposed-catalog-models/exposed-catalog-models.ts
4334
+ var exposedCatalogModels = async (readPage) => {
4335
+ const readRows = async (offset2) => {
4336
+ const page = await readPage(offset2);
4337
+ if (!isRecord(page) || !Array.isArray(page.models) || page.offset !== offset2 || typeof page.total !== "number" || !Number.isSafeInteger(page.total) || page.total < 0) {
4338
+ throw new ContractParseError("invalid model catalog page");
4339
+ }
4340
+ return { rows: page.models, total: page.total };
4341
+ };
4342
+ const names = /* @__PURE__ */ new Map();
4217
4343
  let offset = 0;
4218
4344
  for (; ; ) {
4219
- const page = await readPage(offset);
4220
- if (!isRecord(page) || !Array.isArray(page.models) || page.offset !== offset || typeof page.total !== "number" || !Number.isSafeInteger(page.total) || page.total < 0) {
4221
- throw new ContractParseError("invalid model catalog page");
4345
+ const { rows, total } = await readRows(offset);
4346
+ for (const { id, name } of rows.flatMap(catalogRowChoices)) {
4347
+ names.set(id, name);
4222
4348
  }
4223
- page.models.forEach((row) => {
4224
- if (!isRecord(row) || typeof row.id !== "string" || !row.id.trim() || typeof row.status !== "string")
4225
- throw new ContractParseError("invalid model catalog item");
4226
- if (row.status === "exposed") ids.add(row.id);
4227
- });
4228
- offset += page.models.length;
4229
- if (offset >= page.total || page.models.length === 0)
4230
- return [...ids].sort((left, right) => left.localeCompare(right));
4349
+ offset += rows.length;
4350
+ if (offset >= total || rows.length === 0) break;
4231
4351
  }
4352
+ return [...names].map(([id, name]) => ({ id, name })).sort(
4353
+ (left, right) => left.name.localeCompare(right.name) || left.id.localeCompare(right.id)
4354
+ );
4232
4355
  };
4233
4356
 
4234
4357
  // src/management/model-catalog-operations/model-catalog-operations.ts
4235
4358
  var modelCatalogOperations = (call) => ({
4236
- listModelIds: (token, { orgId, projectId }) => exposedCatalogIds(
4359
+ listModelChoices: (token, { orgId, projectId }) => exposedCatalogModels(
4237
4360
  (offset) => call(token, orgId, (client) => {
4238
4361
  const query = { offset };
4239
4362
  if (projectId !== void 0)
@@ -4290,6 +4413,29 @@ import {
4290
4413
  createRoute33Client,
4291
4414
  Route33SdkError
4292
4415
  } from "@r-33/sdk";
4416
+
4417
+ // src/management/sdk-management-call/rejection-of/rejection-of.ts
4418
+ var REFUSED = 422;
4419
+ var REJECTION_MAX_LENGTH = 200;
4420
+ var CONTROL = /\p{Cc}+/gu;
4421
+ var SECRET_PREFIXES = ["r33_", "eyj", "bearer "];
4422
+ var OPAQUE_MIN_LENGTH = 20;
4423
+ var rejectionOf = (outcome) => {
4424
+ const body = outcome.error;
4425
+ if (outcome.response?.status !== REFUSED || !isRecord(body)) return void 0;
4426
+ const raw = body["error"];
4427
+ if (typeof raw !== "string" || raw.length > REJECTION_MAX_LENGTH) {
4428
+ return void 0;
4429
+ }
4430
+ const sentence = raw.replaceAll(CONTROL, " ").replaceAll(/\s+/gu, " ").trim();
4431
+ const lower = sentence.toLowerCase();
4432
+ const secretShaped = SECRET_PREFIXES.some((prefix) => lower.includes(prefix)) || lower.split(" ").some(
4433
+ (word) => word.length >= OPAQUE_MIN_LENGTH && /\d/u.test(word) && /[a-z]/u.test(word)
4434
+ );
4435
+ return sentence === "" || secretShaped ? void 0 : sentence;
4436
+ };
4437
+
4438
+ // src/management/sdk-management-call/sdk-management-call.ts
4293
4439
  var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
4294
4440
  var ACTIVE_ORG_HEADER = "X-Active-Org-Id";
4295
4441
  var createSdkCall = (options) => {
@@ -4336,9 +4482,13 @@ var createSdkCall = (options) => {
4336
4482
  const outcome = await run(callClient(accessToken, activeOrgId));
4337
4483
  const code = outcome.response?.status;
4338
4484
  if (code === void 0 || code < 200 || code >= 300) {
4485
+ const rejection = rejectionOf(outcome);
4339
4486
  throw new ManagementError(
4340
4487
  code === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
4341
- { statusCode: code }
4488
+ {
4489
+ ...rejection === void 0 ? {} : { rejection },
4490
+ statusCode: code
4491
+ }
4342
4492
  );
4343
4493
  }
4344
4494
  return outcome.data;
@@ -4653,10 +4803,43 @@ import { createAuthorizationUrlStash as createAuthorizationUrlStash2 } from "@r-
4653
4803
  import { Integration, Provider } from "@opencode/plugin";
4654
4804
 
4655
4805
  // src/v2-entry/map-route33-model/map-route33-model.ts
4656
- import { Model as Model2 } from "@opencode/plugin";
4806
+ import { Model as Model3 } from "@opencode/plugin";
4657
4807
 
4658
- // src/v2-entry/map-route33-variant/map-route33-variant.ts
4808
+ // src/v2-entry/map-route33-cost/map-route33-cost.ts
4659
4809
  import { Model } from "@opencode/plugin";
4810
+ var LONG_CONTEXT_TOKENS = 2e5;
4811
+ var mapRoute33Cost = (cost) => {
4812
+ const rate = Model.Cost.fields.input;
4813
+ const read = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
4814
+ const tier = (rates) => {
4815
+ if (!isRecord(rates)) return [];
4816
+ const input = read(rates["input"]);
4817
+ const output = read(rates["output"]);
4818
+ if (input === void 0 || output === void 0) return [];
4819
+ return [
4820
+ {
4821
+ cache: {
4822
+ read: rate.make(read(rates["cache_read"]) ?? 0),
4823
+ write: rate.make(read(rates["cache_write"]) ?? 0)
4824
+ },
4825
+ input: rate.make(input),
4826
+ output: rate.make(output)
4827
+ }
4828
+ ];
4829
+ };
4830
+ const base = tier(cost);
4831
+ if (base.length === 0 || !isRecord(cost)) return [];
4832
+ return [
4833
+ ...base,
4834
+ ...tier(cost["context_over_200k"]).map((rates) => ({
4835
+ ...rates,
4836
+ tier: { size: LONG_CONTEXT_TOKENS, type: "context" }
4837
+ }))
4838
+ ];
4839
+ };
4840
+
4841
+ // src/v2-entry/map-route33-variant/map-route33-variant.ts
4842
+ import { Model as Model2 } from "@opencode/plugin";
4660
4843
  var mapRoute33Variant = (variants) => {
4661
4844
  if (variants === void 0) {
4662
4845
  return [];
@@ -4667,7 +4850,7 @@ var mapRoute33Variant = (variants) => {
4667
4850
  continue;
4668
4851
  }
4669
4852
  mapped.push({
4670
- id: Model.VariantID.make(variantID),
4853
+ id: Model2.VariantID.make(variantID),
4671
4854
  settings: structuredClone(overlay)
4672
4855
  });
4673
4856
  }
@@ -4676,8 +4859,9 @@ var mapRoute33Variant = (variants) => {
4676
4859
 
4677
4860
  // src/v2-entry/map-route33-model/map-route33-model.ts
4678
4861
  var mapRoute33Model = (providerID, modelID, model) => ({
4679
- ...Model2.Info.default(providerID, Model2.ID.make(modelID)),
4862
+ ...Model3.Info.default(providerID, Model3.ID.make(modelID)),
4680
4863
  name: typeof model.name === "string" ? model.name : modelID,
4864
+ cost: mapRoute33Cost(model.cost),
4681
4865
  ...model.variants === void 0 ? {} : {
4682
4866
  variants: mapRoute33Variant(
4683
4867
  model.variants
@@ -4721,11 +4905,12 @@ var bootstrapProvider = async (deps, sink) => {
4721
4905
  if (runtime2 === void 0) {
4722
4906
  return;
4723
4907
  }
4724
- try {
4725
- await runtime2.login({ allowBrowser: false });
4726
- } catch {
4727
- }
4908
+ const signedIn = await runtime2.login({ allowBrowser: false }).then(
4909
+ () => true,
4910
+ () => false
4911
+ );
4728
4912
  await deps.registerProjectForm().catch(() => void 0);
4913
+ if (!signedIn) return;
4729
4914
  try {
4730
4915
  const config = {};
4731
4916
  await deps.runConfig(config);
@@ -4761,18 +4946,24 @@ var readAllowedModels = (answer) => {
4761
4946
  };
4762
4947
 
4763
4948
  // src/v2-entry/parse-budget-answer/read-budget-cap/read-budget-cap.ts
4764
- var readBudgetCap = (answer) => {
4765
- const value = answer["budget_cap"];
4766
- if (value === void 0 || value === null) return null;
4949
+ var readBudgetCap = (answer, maximum) => {
4950
+ const value = answer["budget_cap"] ?? "";
4767
4951
  if (typeof value !== "string" && typeof value !== "number") {
4768
4952
  throw new TypeError("Budget cap must be a number or unlimited");
4769
4953
  }
4770
- if (typeof value === "string" && (value.trim() === "" || value.trim().toLowerCase() === "unlimited")) {
4954
+ if (typeof value === "string" && ["", "unlimited"].includes(value.trim().toLowerCase())) {
4771
4955
  return null;
4772
4956
  }
4773
4957
  const parsed = Number(value);
4774
- if (Number.isFinite(parsed) && parsed > 0) return parsed;
4775
- throw new RangeError("Budget cap must be a finite positive number");
4958
+ if (!Number.isFinite(parsed) || parsed <= 0) {
4959
+ throw new RangeError("Budget cap must be a finite positive number");
4960
+ }
4961
+ if (maximum !== void 0 && parsed > maximum) {
4962
+ throw new RangeError(
4963
+ `Entered ${String(value)} EUR; the selected budget allows at most ${String(maximum)} EUR.`
4964
+ );
4965
+ }
4966
+ return parsed;
4776
4967
  };
4777
4968
 
4778
4969
  // src/v2-entry/parse-budget-answer/read-budget-description/read-budget-description.ts
@@ -4798,7 +4989,7 @@ var readBudgetName = (answer) => {
4798
4989
  };
4799
4990
 
4800
4991
  // src/v2-entry/parse-budget-answer/parse-budget-answer.ts
4801
- var parseBudgetAnswer = (answer) => {
4992
+ var parseBudgetAnswer = (answer, maximum) => {
4802
4993
  const attribution = parseConnectAnswer(answer);
4803
4994
  if (attribution === void 0) {
4804
4995
  return void 0;
@@ -4809,7 +5000,7 @@ var parseBudgetAnswer = (answer) => {
4809
5000
  allowedModels: readAllowedModels(answer),
4810
5001
  description: readBudgetDescription(answer),
4811
5002
  expiryDays: readBudgetExpiry(answer),
4812
- maxBudgetAmount: readBudgetCap(answer),
5003
+ maxBudgetAmount: readBudgetCap(answer, maximum),
4813
5004
  name: readBudgetName(answer)
4814
5005
  }
4815
5006
  };
@@ -4817,23 +5008,32 @@ var parseBudgetAnswer = (answer) => {
4817
5008
 
4818
5009
  // src/v2-entry/connect-copy/connect-copy.ts
4819
5010
  var CONNECT_COPY = {
4820
- failFastClientId: "This Route 33 build has no OAuth client id. Reinstall it from the opencode-dist ref, or set ROUTE33_CLIENT_ID and restart OpenCode.",
4821
- failFastWorktree: "Route 33 attributes usage to a project inside a Git worktree. Open a Git repository (or run git init), then connect again.",
4822
- selectionInvalid: "That Route 33 option is no longer available. Connect again and pick another.",
4823
- signedInNextStep: "Signed in to Route 33 \u2713. One more step: connect again, choose Route 33, and assign a budget for this folder.",
4824
- budgetSelected: "Budget selected. Connect again to configure the key for this budget.",
4825
- mintNoBudget: "Route 33 could not create the key \u2014 its cap exceeds this budget. Ask an owner to raise the budget, or pick another."
5011
+ failFastClientId: "This Route 33 build has no OAuth client ID; reinstall it from the opencode-dist ref.",
5012
+ failFastWorktree: "To assign a Route 33 budget, open a Git repository.",
5013
+ selectionInvalid: "That Route 33 option is no longer available; open /r33 and choose Attribute.",
5014
+ signedInNextStep: "Signed in to Route 33; open /r33 and choose Attribute to assign a budget.",
5015
+ budgetSelected: "Budget selected but not assigned; open /r33 and choose Attribute to finish setup."
5016
+ };
5017
+ var KEY_FORM_COPY = {
5018
+ /** Prefix of a key the management API refused; its reason follows. */
5019
+ mintRefused: "Route 33 refused this key:",
5020
+ mintRefusedUnknown: "its settings are not allowed for this budget.",
5021
+ modelsNeedSignIn: "Choosing individual models needs a fresh Route 33 sign-in.",
5022
+ modelsUnavailable: "The model list is unavailable right now."
4826
5023
  };
4827
5024
 
4828
5025
  // src/v2-entry/apply-wizard-answer/map-mint-failure/map-mint-failure.ts
4829
- var MINT_BUDGET_FAILURE_STATUS = 422;
4830
- var mapMintFailure = (cause) => cause instanceof KeyLeaseError && cause.statusCode === MINT_BUDGET_FAILURE_STATUS ? new GatewayCredentialError(CONNECT_COPY.mintNoBudget) : cause;
5026
+ var MINT_REFUSED_STATUS = 422;
5027
+ var mapMintFailure = (cause) => cause instanceof KeyLeaseError && cause.statusCode === MINT_REFUSED_STATUS ? new GatewayCredentialError(
5028
+ `${KEY_FORM_COPY.mintRefused} ${cause.rejection ?? KEY_FORM_COPY.mintRefusedUnknown}`
5029
+ ) : cause;
4831
5030
 
4832
5031
  // src/v2-entry/apply-wizard-answer/apply-wizard-answer.ts
4833
5032
  var applyWizardAnswer = async (deps, answer) => {
4834
5033
  const selection = parseConnectAnswer(answer);
4835
5034
  if (selection === void 0) return;
4836
- const choice = deps.getPlan()?.choicesBySelection[selection];
5035
+ const plan = deps.getPlan();
5036
+ const choice = plan?.choicesBySelection[selection];
4837
5037
  if (choice === void 0) {
4838
5038
  throw new AttributionPromptError("ATTRIBUTION_SELECTION_INVALID");
4839
5039
  }
@@ -4844,9 +5044,12 @@ var applyWizardAnswer = async (deps, answer) => {
4844
5044
  );
4845
5045
  }
4846
5046
  };
5047
+ const maximum = plan?.options.find(
5048
+ (option) => option.selection === selection
5049
+ )?.maximum;
4847
5050
  const acquire = async (existing) => {
4848
5051
  if (existing === void 0 || existing === "new") {
4849
- const budget = parseBudgetAnswer(answer);
5052
+ const budget = parseBudgetAnswer(answer, maximum);
4850
5053
  if (budget && deps.mintWorkspaceKey) {
4851
5054
  try {
4852
5055
  await deps.mintWorkspaceKey(choice, budget.extras, () => {
@@ -4885,7 +5088,7 @@ var createConnectAuthorize = (deps) => async (answer = {}) => {
4885
5088
  }
4886
5089
  const callback = (async () => {
4887
5090
  const emptyAnswer = Object.keys(answer).length === 0;
4888
- if (emptyAnswer && readAttribution(deps.state) === void 0) {
5091
+ if (emptyAnswer) {
4889
5092
  const runtime2 = deps.getRuntime();
4890
5093
  if (runtime2 === void 0) {
4891
5094
  throw new GatewayCredentialError(
@@ -4893,11 +5096,13 @@ var createConnectAuthorize = (deps) => async (answer = {}) => {
4893
5096
  );
4894
5097
  }
4895
5098
  await runtime2.login();
4896
- try {
4897
- return await deps.resolveCredential();
4898
- } catch {
4899
- await deps.registerProjectForm();
4900
- throw new GatewayCredentialError(CONNECT_COPY.signedInNextStep);
5099
+ if (readAttribution(deps.state) === void 0) {
5100
+ try {
5101
+ return await deps.resolveCredential();
5102
+ } catch {
5103
+ await deps.registerProjectForm();
5104
+ throw new GatewayCredentialError(CONNECT_COPY.signedInNextStep);
5105
+ }
4901
5106
  }
4902
5107
  }
4903
5108
  const selection = parseConnectAnswer(answer);
@@ -4908,7 +5113,9 @@ var createConnectAuthorize = (deps) => async (answer = {}) => {
4908
5113
  if (readAttribution(deps.state) === void 0) {
4909
5114
  throw new GatewayCredentialError(CONNECT_COPY.selectionInvalid);
4910
5115
  }
4911
- return deps.resolveCredential();
5116
+ const credential = await deps.resolveCredential();
5117
+ if (emptyAnswer) await deps.registerProjectForm().catch(() => void 0);
5118
+ return credential;
4912
5119
  })();
4913
5120
  const decision = await deps.stash.urlForConnect(
4914
5121
  callback.then(() => void 0)
@@ -4926,9 +5133,14 @@ var ATTRIBUTION_FIELD_KEY2 = "attribution";
4926
5133
  var ORGANISATION_FIELD_KEY = "organisation";
4927
5134
  var BUDGET_NAME_FIELD_KEY = "budget_name";
4928
5135
  var BUDGET_CAP_FIELD_KEY = "budget_cap";
5136
+ var BUDGET_CAP_MAX_FIELD_KEY = "budget_cap_max";
5137
+ var PREPARED_BUDGET_FIELD_KEY = "prepared_budget";
4929
5138
  var BUDGET_DESCRIPTION_FIELD_KEY = "budget_description";
4930
5139
  var BUDGET_EXPIRY_FIELD_KEY = "budget_expiry";
4931
5140
  var ALLOWED_MODELS_FIELD_KEY = "allowed_models";
5141
+ var ALLOWED_MODELS_TITLE = "Which models may this key use?";
5142
+ var ALL_MODELS_VALUE = "all";
5143
+ var ALL_MODELS_LABEL = "All models (inherit)";
4932
5144
  var ORGANISATION_FIELD_TITLE = "Which Route 33 organisation covers this folder?";
4933
5145
  var EXPIRY_OPTIONS = [
4934
5146
  { label: "30 days", value: "30" },
@@ -4936,7 +5148,8 @@ var EXPIRY_OPTIONS = [
4936
5148
  { label: "180 days", value: "180" },
4937
5149
  { label: "1 year", value: "365" }
4938
5150
  ];
4939
- var buildConnectForm = (plan, modelIds) => {
5151
+ var buildConnectForm = (plan, key) => {
5152
+ const maximum = key?.maximum;
4940
5153
  const orgs = plan.orgs ?? [];
4941
5154
  const organisationField = {
4942
5155
  key: ORGANISATION_FIELD_KEY,
@@ -4958,7 +5171,7 @@ var buildConnectForm = (plan, modelIds) => {
4958
5171
  type: "string"
4959
5172
  };
4960
5173
  const budgetFields = orgs.length > 1 ? [organisationField, attributionField] : [attributionField];
4961
- if (modelIds === void 0) return budgetFields;
5174
+ if (key === void 0) return budgetFields;
4962
5175
  const promptFields = [
4963
5176
  {
4964
5177
  key: BUDGET_NAME_FIELD_KEY,
@@ -4969,7 +5182,7 @@ var buildConnectForm = (plan, modelIds) => {
4969
5182
  {
4970
5183
  key: BUDGET_CAP_FIELD_KEY,
4971
5184
  placeholder: "e.g. 50; blank or unlimited = no cap",
4972
- title: "Monthly budget cap in EUR",
5185
+ title: maximum === void 0 ? "Monthly budget cap in EUR" : `Monthly budget cap in EUR (max ${String(maximum)})`,
4973
5186
  type: "string"
4974
5187
  },
4975
5188
  {
@@ -4983,17 +5196,41 @@ var buildConnectForm = (plan, modelIds) => {
4983
5196
  title: "When should the key expire?",
4984
5197
  type: "string"
4985
5198
  },
4986
- {
5199
+ key.models.length === 0 ? {
4987
5200
  key: ALLOWED_MODELS_FIELD_KEY,
4988
5201
  options: [
4989
- { label: "All models (inherit)", value: "all" },
4990
- ...modelIds.map((id) => ({ label: id, value: id }))
5202
+ {
5203
+ ...key.modelsNote === void 0 ? {} : { description: key.modelsNote },
5204
+ label: ALL_MODELS_LABEL,
5205
+ value: ALL_MODELS_VALUE
5206
+ }
4991
5207
  ],
4992
- title: "Which models may this key use?",
5208
+ title: ALLOWED_MODELS_TITLE,
4993
5209
  type: "string"
5210
+ } : {
5211
+ description: "Select none to allow all models.",
5212
+ key: ALLOWED_MODELS_FIELD_KEY,
5213
+ options: key.models.map(({ id, name }) => ({
5214
+ description: id,
5215
+ label: name,
5216
+ value: id
5217
+ })),
5218
+ title: ALLOWED_MODELS_TITLE,
5219
+ type: "multiselect"
4994
5220
  }
4995
5221
  ];
4996
- return [...budgetFields, ...promptFields];
5222
+ const helper = (name, value) => ({
5223
+ hidden: true,
5224
+ key: name,
5225
+ placeholder: value,
5226
+ type: "string"
5227
+ });
5228
+ return [
5229
+ ...budgetFields,
5230
+ ...promptFields,
5231
+ ...maximum === void 0 ? [] : [helper(BUDGET_CAP_MAX_FIELD_KEY, String(maximum))],
5232
+ ...key.prepared === void 0 ? [] : [helper(PREPARED_BUDGET_FIELD_KEY, key.prepared)]
5233
+ ];
4997
5234
  };
4998
5235
 
4999
5236
  // src/v2-entry/direct-key-mode/direct-key-mode.ts
@@ -5132,8 +5369,8 @@ var gateFallback = async (deps, input, directory) => {
5132
5369
  };
5133
5370
 
5134
5371
  // src/v2-entry/v2-unattributed-model-gate/v2-unattributed-model-gate.ts
5135
- var CONNECTION_COPY2 = "Not connected to Route 33. Run /connect, choose Route 33, and complete sign-in before assigning a budget in this folder.";
5136
- var ATTRIBUTION_COPY2 = "This folder has no Route 33 budget assigned. Run /connect, choose Route 33, and complete the budget setup form.";
5372
+ var CONNECTION_COPY2 = "To sign in, run /connect and choose Route 33.";
5373
+ var ATTRIBUTION_COPY2 = "This folder has no Route 33 budget; open /r33 and choose Attribute.";
5137
5374
  var createV2UnattributedModelGate = (deps) => async (input) => {
5138
5375
  if (input.model.providerID !== "route_33") return;
5139
5376
  if (!await deps.isConnected()) throw new Error(CONNECTION_COPY2);
@@ -5173,6 +5410,132 @@ var registerRoute33ModelGate = async (deps) => deps.session.hook(
5173
5410
  { providerID: "route_33" }
5174
5411
  );
5175
5412
 
5413
+ // src/v2-entry/r33-command/r33-command.ts
5414
+ import { AuthError as AuthError3 } from "@r-33/auth-browser";
5415
+
5416
+ // src/v2-entry/format-inspect-reply/format-inspect-reply.ts
5417
+ var formatInspectReply = (inspection, budgetAction) => {
5418
+ const { attribution, budget, key } = inspection;
5419
+ if (attribution === void 0) {
5420
+ return inspection.connected ? `This folder has no Route 33 budget; open /r33 and choose ${budgetAction}.` : "To sign in, run /connect and choose Route 33.";
5421
+ }
5422
+ const { organisationName, projectName } = { ...key };
5423
+ let label;
5424
+ let keyScope;
5425
+ switch (attribution.kind) {
5426
+ case "personal":
5427
+ label = "Personal";
5428
+ keyScope = "your personal budget";
5429
+ break;
5430
+ case "project":
5431
+ label = `Project ${projectName ?? attribution.projectId}`;
5432
+ keyScope = [organisationName, projectName].filter(Boolean).join(" \xB7 ");
5433
+ break;
5434
+ default: {
5435
+ const unexpected = attribution;
5436
+ throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
5437
+ }
5438
+ }
5439
+ const cap = budget === void 0 ? "" : [" \u2014 cap", budget.amount, budget.currency].filter((part) => part !== null).join(" ");
5440
+ const lines = [`Budget: ${label}${cap}`];
5441
+ if (key !== void 0) {
5442
+ const scope = keyScope === "" ? "" : ` on ${keyScope}`;
5443
+ lines.push(`Key: ${key.name}${scope}`);
5444
+ }
5445
+ if (inspection.lease !== void 0) {
5446
+ lines.push(`Expires: ${inspection.lease.expiresAt}`);
5447
+ lines.push(`Key id: ${inspection.lease.keyId}`);
5448
+ }
5449
+ return lines.join("\n");
5450
+ };
5451
+
5452
+ // src/v2-entry/parse-r33-subcommand/parse-r33-subcommand.ts
5453
+ var SUBCOMMANDS = ["inspect", "rotate", "reset"];
5454
+ var parseR33Subcommand = (promptText) => {
5455
+ const [first = "", ...rest] = promptText.trim().split(/\s+/u).filter(Boolean);
5456
+ const name = first.replace(/^\/+/u, "").split(":")[0] ?? "";
5457
+ const argument = name === "r33" ? rest[0] : first;
5458
+ if (argument === void 0 || argument === "") {
5459
+ return "inspect";
5460
+ }
5461
+ return SUBCOMMANDS.includes(argument) ? argument : "help";
5462
+ };
5463
+
5464
+ // src/v2-entry/r33-command/r33-command.ts
5465
+ var SIGN_IN_COPY = "To sign in, run /connect and choose Route 33.";
5466
+ var executeR33Command = async (input) => {
5467
+ const subcommand = parseR33Subcommand(input.promptText);
5468
+ if (input.handlers === void 0) {
5469
+ return SIGN_IN_COPY;
5470
+ }
5471
+ const budgetAction = input.budgetAction ?? "Change budget";
5472
+ if (subcommand === "help") {
5473
+ const { connected } = await input.handlers["inspect-session"]();
5474
+ return connected ? `To assign a budget, open /r33 and choose ${budgetAction}.` : SIGN_IN_COPY;
5475
+ }
5476
+ switch (subcommand) {
5477
+ case "rotate": {
5478
+ const lease = await input.handlers["rotate-now"]().catch(
5479
+ (error) => {
5480
+ if (error instanceof AuthError3) return void 0;
5481
+ throw error;
5482
+ }
5483
+ );
5484
+ if (lease === void 0) return SIGN_IN_COPY;
5485
+ return `Route 33 key rotated. Key ${lease.keyId} is valid until ${lease.expiresAt}.`;
5486
+ }
5487
+ case "reset": {
5488
+ await input.handlers["reset-attribution"]();
5489
+ const { connected } = await input.handlers["inspect-session"]();
5490
+ return connected ? `Budget cleared; open /r33 and choose ${budgetAction}.` : `Budget cleared. ${SIGN_IN_COPY}`;
5491
+ }
5492
+ default: {
5493
+ return formatInspectReply(
5494
+ await input.handlers["inspect-session"](),
5495
+ budgetAction
5496
+ );
5497
+ }
5498
+ }
5499
+ };
5500
+
5501
+ // src/v2-entry/session-rpc/session-rpc.ts
5502
+ var ROUTE33_SESSION_RPC = {
5503
+ events: {},
5504
+ id: "route33",
5505
+ methods: {
5506
+ /**
5507
+ * Rotates this folder's key and answers with the text to show. A handler
5508
+ * that throws reaches the caller without its message, so a refused
5509
+ * rotation is answered too: `failed` marks the reply as the reason.
5510
+ */
5511
+ rotate: {
5512
+ input: { additionalProperties: false, properties: {}, type: "object" },
5513
+ output: {
5514
+ additionalProperties: false,
5515
+ properties: { failed: { type: "boolean" }, reply: { type: "string" } },
5516
+ required: ["failed", "reply"],
5517
+ type: "object"
5518
+ }
5519
+ }
5520
+ }
5521
+ };
5522
+
5523
+ // src/v2-entry/register-session-rpc/register-session-rpc.ts
5524
+ var registerSessionRpc = (rpc, deps) => rpc.register(ROUTE33_SESSION_RPC, {
5525
+ rotate: async () => {
5526
+ try {
5527
+ const reply = await executeR33Command({
5528
+ handlers: deps.getRuntime()?.commandHandlers(),
5529
+ promptText: "rotate"
5530
+ });
5531
+ return { failed: false, reply };
5532
+ } catch (error) {
5533
+ const reply = error instanceof Error ? error.message : String(error);
5534
+ return { failed: true, reply };
5535
+ }
5536
+ }
5537
+ });
5538
+
5176
5539
  // src/v2-entry/resolve-host-credential/resolve-host-credential.ts
5177
5540
  var NO_USABLE_LEASE_MESSAGE = "Signed in to Route 33 \u2713. One more step: this folder has no gateway key yet \u2014 pick its budget to finish setup.";
5178
5541
  var resolveHostCredential = async (deps) => {
@@ -5198,7 +5561,7 @@ var bindingFields = async (plan, binding) => {
5198
5561
  const confirmations = /* @__PURE__ */ new Map();
5199
5562
  const fields = [];
5200
5563
  for (const [selection, choice] of Object.entries(plan.choicesBySelection)) {
5201
- const keys = await binding.candidates(choice).catch(() => []);
5564
+ const keys = await binding.candidates(choice);
5202
5565
  if (!keys.length) continue;
5203
5566
  for (const key of keys) if (!key.local) confirmations.set(key.id, key.name);
5204
5567
  fields.push({
@@ -5230,6 +5593,19 @@ var bindingFields = async (plan, binding) => {
5230
5593
  return fields;
5231
5594
  };
5232
5595
 
5596
+ // src/v2-entry/selected-budget-form/read-model-choices/read-model-choices.ts
5597
+ var FORBIDDEN = 403;
5598
+ var readModelChoices = async (read) => {
5599
+ try {
5600
+ return { models: await read() };
5601
+ } catch (cause) {
5602
+ return {
5603
+ models: [],
5604
+ modelsNote: cause instanceof ManagementError && cause.statusCode === FORBIDDEN ? KEY_FORM_COPY.modelsNeedSignIn : KEY_FORM_COPY.modelsUnavailable
5605
+ };
5606
+ }
5607
+ };
5608
+
5233
5609
  // src/v2-entry/selected-budget-form/selected-budget-form.ts
5234
5610
  var selectedBudgetForm = async (plan, selection, runtime2) => {
5235
5611
  const option = plan.options.find((row) => row.selection === selection);
@@ -5241,9 +5617,54 @@ var selectedBudgetForm = async (plan, selection, runtime2) => {
5241
5617
  options: [option],
5242
5618
  choicesBySelection: { [selection]: choice }
5243
5619
  };
5244
- const ids = await runtime2.catalogModelIds(choice).catch(() => []);
5620
+ const choices = await readModelChoices(
5621
+ () => runtime2.catalogModelChoices(choice)
5622
+ );
5245
5623
  const keys = await bindingFields(scoped, await runtime2.workspaceKeyBinding());
5246
- return [...buildConnectForm(scoped, ids), ...keys];
5624
+ return [
5625
+ ...buildConnectForm(plan, {
5626
+ ...choices,
5627
+ ...option.maximum === void 0 ? {} : { maximum: option.maximum },
5628
+ prepared: selection
5629
+ }),
5630
+ ...keys
5631
+ ];
5632
+ };
5633
+
5634
+ // src/v2-entry/is-account-removed/is-account-removed.ts
5635
+ var isAccountRemoved = (event) => {
5636
+ if (!isRecord(event) || event["type"] !== "credential.switched") return false;
5637
+ const data = event["data"];
5638
+ return isRecord(data) && data["integrationID"] === "route33" && data["credentialID"] === null;
5639
+ };
5640
+
5641
+ // src/v2-entry/watch-account-removal/watch-account-removal.ts
5642
+ var watchAccountRemoval = (events, deps) => {
5643
+ const stop = new AbortController();
5644
+ const forget = async () => {
5645
+ await deps.getRuntime()?.commandHandlers().logout();
5646
+ await deps.registerProjectForm().catch(() => void 0);
5647
+ };
5648
+ const watch = async () => {
5649
+ const switches = events.subscribe({
5650
+ signal: stop.signal,
5651
+ types: ["credential.switched"]
5652
+ });
5653
+ for await (const event of switches) {
5654
+ if (!isAccountRemoved(event)) continue;
5655
+ await forget().catch(() => {
5656
+ logger.warn("account.removed.sign-in-not-forgotten");
5657
+ });
5658
+ }
5659
+ };
5660
+ void watch().catch(() => {
5661
+ if (!stop.signal.aborted) logger.warn("account.removed.watch-stopped");
5662
+ });
5663
+ return {
5664
+ dispose: () => {
5665
+ stop.abort();
5666
+ }
5667
+ };
5247
5668
  };
5248
5669
 
5249
5670
  // src/v2-entry/workspace-key-request-hook/workspace-key-request-hook.ts
@@ -5403,10 +5824,7 @@ var createRoute33V2Plugin = (options = {}) => {
5403
5824
  "http.request",
5404
5825
  createWorkspaceKeyHook({
5405
5826
  gatewayBase: readEnvBaseUrl() ?? DEFAULT_BASE_URL,
5406
- resolveKey: (directory) => {
5407
- const active = runtime2;
5408
- return active === void 0 ? Promise.resolve(void 0) : active.resolveWorkspaceCredential(directory);
5409
- },
5827
+ resolveKey: (directory) => runtime2?.resolveWorkspaceCredential(directory) ?? Promise.resolve(void 0),
5410
5828
  session: context.session
5411
5829
  })
5412
5830
  );
@@ -5416,6 +5834,9 @@ var createRoute33V2Plugin = (options = {}) => {
5416
5834
  listSessions: async () => (await context.session.list()).data,
5417
5835
  session: context.session
5418
5836
  });
5837
+ const session = { getRuntime: () => runtime2, registerProjectForm };
5838
+ const sessionRpc = await registerSessionRpc(context.rpc, session);
5839
+ const accountWatch = watchAccountRemoval(context.event, session);
5419
5840
  await bootstrapProvider(
5420
5841
  {
5421
5842
  getRuntime: () => runtime2,
@@ -5431,11 +5852,13 @@ var createRoute33V2Plugin = (options = {}) => {
5431
5852
  context.provider.reload()
5432
5853
  ]);
5433
5854
  return async () => {
5855
+ accountWatch.dispose();
5434
5856
  await Promise.all([
5435
5857
  integrationTransform.dispose(),
5436
5858
  providerTransform.dispose(),
5437
5859
  sessionHook.dispose(),
5438
- modelGate.dispose()
5860
+ modelGate.dispose(),
5861
+ sessionRpc.dispose()
5439
5862
  ]);
5440
5863
  };
5441
5864
  }