@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.
@@ -525,9 +525,11 @@ var init_management_error = __esm({
525
525
  );
526
526
  this.code = code;
527
527
  this.name = "ManagementError";
528
+ this.rejection = options?.rejection;
528
529
  this.statusCode = options?.statusCode;
529
530
  }
530
531
  code;
532
+ rejection;
531
533
  statusCode;
532
534
  };
533
535
  }
@@ -4602,9 +4604,11 @@ var init_key_lease_error = __esm({
4602
4604
  );
4603
4605
  this.code = code;
4604
4606
  this.name = "KeyLeaseError";
4607
+ this.rejection = options?.rejection;
4605
4608
  this.statusCode = options?.statusCode;
4606
4609
  }
4607
4610
  code;
4611
+ rejection;
4608
4612
  statusCode;
4609
4613
  };
4610
4614
  }
@@ -4900,6 +4904,32 @@ var init_commit_staged_replacement2 = __esm({
4900
4904
  }
4901
4905
  });
4902
4906
 
4907
+ // src/key-lease/mint-failure/mint-failure.ts
4908
+ var mintFailure;
4909
+ var init_mint_failure = __esm({
4910
+ "src/key-lease/mint-failure/mint-failure.ts"() {
4911
+ "use strict";
4912
+ init_management_error2();
4913
+ init_key_lease_error2();
4914
+ mintFailure = (cause) => {
4915
+ const response = cause instanceof ManagementError ? cause : void 0;
4916
+ return new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
4917
+ cause,
4918
+ ...response?.rejection === void 0 ? {} : { rejection: response.rejection },
4919
+ ...response?.statusCode === void 0 ? {} : { statusCode: response.statusCode }
4920
+ });
4921
+ };
4922
+ }
4923
+ });
4924
+
4925
+ // src/key-lease/mint-failure/index.ts
4926
+ var init_mint_failure2 = __esm({
4927
+ "src/key-lease/mint-failure/index.ts"() {
4928
+ "use strict";
4929
+ init_mint_failure();
4930
+ }
4931
+ });
4932
+
4903
4933
  // src/key-lease/mint-fresh-lease/mint-fresh-lease.ts
4904
4934
  var mintFreshLease;
4905
4935
  var init_mint_fresh_lease = __esm({
@@ -4908,6 +4938,7 @@ var init_mint_fresh_lease = __esm({
4908
4938
  init_build_mint_input2();
4909
4939
  init_commit_staged_replacement2();
4910
4940
  init_key_lease_error2();
4941
+ init_mint_failure2();
4911
4942
  mintFreshLease = async (deps) => {
4912
4943
  const now = deps.clock();
4913
4944
  const current = deps.state.snapshot();
@@ -4937,7 +4968,7 @@ var init_mint_fresh_lease = __esm({
4937
4968
  input
4938
4969
  );
4939
4970
  } catch (cause) {
4940
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", { cause });
4971
+ throw mintFailure(cause);
4941
4972
  }
4942
4973
  const minted = {
4943
4974
  key: material.key,
@@ -5064,10 +5095,10 @@ var mintKey;
5064
5095
  var init_mint_key = __esm({
5065
5096
  "src/key-lease/mint-key/mint-key.ts"() {
5066
5097
  "use strict";
5067
- init_management_error2();
5068
5098
  init_build_mint_input2();
5069
5099
  init_is_management_unauthorized2();
5070
5100
  init_key_lease_error2();
5101
+ init_mint_failure2();
5071
5102
  mintKey = async (options) => {
5072
5103
  const now = options.clock();
5073
5104
  if (!Number.isFinite(now)) {
@@ -5100,10 +5131,7 @@ var init_mint_key = __esm({
5100
5131
  if (isManagementUnauthorized(cause)) {
5101
5132
  throw new KeyLeaseError("KEY_LEASE_UNAUTHORIZED", { cause });
5102
5133
  }
5103
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
5104
- cause,
5105
- ...cause instanceof ManagementError && cause.statusCode !== void 0 ? { statusCode: cause.statusCode } : {}
5106
- });
5134
+ throw mintFailure(cause);
5107
5135
  }
5108
5136
  return {
5109
5137
  key: material.key,
@@ -5615,6 +5643,7 @@ var init_inspect_session = __esm({
5615
5643
  const lease = options.readLease();
5616
5644
  return {
5617
5645
  attribution,
5646
+ connected: options.connected,
5618
5647
  ...lease === void 0 ? {} : { lease: { expiresAt: lease.expiresAt, keyId: lease.keyId } }
5619
5648
  };
5620
5649
  };
@@ -5688,6 +5717,7 @@ var init_workspace_key_binding = __esm({
5688
5717
  "use strict";
5689
5718
  init_attribution();
5690
5719
  init_config();
5720
+ init_shared();
5691
5721
  init_scope_id2();
5692
5722
  ROTATION_WARNING = "This key will be rotated. Existing consumers will break. Continue?";
5693
5723
  pending = /* @__PURE__ */ new Map();
@@ -5701,10 +5731,10 @@ var init_workspace_key_binding = __esm({
5701
5731
  * @returns Secret-free options; local options do not need destructive consent.
5702
5732
  */
5703
5733
  async candidates(choice) {
5704
- const listing = this.#listings.get(choice.orgId) ?? this.deps.client.list(this.deps.token, choice.orgId);
5734
+ const listing = this.#listings.get(choice.orgId) ?? this.listKeys(choice.orgId);
5705
5735
  this.#listings.set(choice.orgId, listing);
5706
5736
  const rows = await listing;
5707
- const keys = rows.data.filter((row) => this.matches(row, choice));
5737
+ const keys = rows.filter((row) => this.matches(row, choice));
5708
5738
  if (keys.length === 0) return [];
5709
5739
  const local = await this.localKeys(new Set(keys.map((row) => row.id)));
5710
5740
  return keys.map((row) => ({
@@ -5713,8 +5743,18 @@ var init_workspace_key_binding = __esm({
5713
5743
  local: local.has(row.id)
5714
5744
  }));
5715
5745
  }
5746
+ async listKeys(orgId) {
5747
+ try {
5748
+ return (await this.deps.client.list(this.deps.token, orgId)).data;
5749
+ } catch {
5750
+ logger.warn(
5751
+ "Existing keys could not be listed; only new keys can be offered."
5752
+ );
5753
+ return [];
5754
+ }
5755
+ }
5716
5756
  matches(row, choice) {
5717
- 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");
5757
+ 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");
5718
5758
  }
5719
5759
  async localKeys(ids) {
5720
5760
  const found = /* @__PURE__ */ new Map();
@@ -5857,6 +5897,8 @@ var init_attribution_prompt = __esm({
5857
5897
  return `Personal \u2014 your own key${marker}${orgSuffix}`;
5858
5898
  };
5859
5899
  const budgetAllowance = (project) => {
5900
+ if (project.memberCap !== void 0)
5901
+ return `cap ${String(project.memberCap)} EUR`;
5860
5902
  const budget = project.effective_budget ?? project.max_budget;
5861
5903
  return budget === null ? "no cap set" : `cap ${budget.amount} ${budget.currency}`;
5862
5904
  };
@@ -5871,6 +5913,7 @@ var init_attribution_prompt = __esm({
5871
5913
  };
5872
5914
  return {
5873
5915
  label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${budgetAllowance(project)}`,
5916
+ maximum: project.memberCap,
5874
5917
  selection
5875
5918
  };
5876
5919
  });
@@ -5890,6 +5933,7 @@ var init_attribution_prompt = __esm({
5890
5933
  choicesBySelection[personal] = { kind: "personal", orgId: org.id };
5891
5934
  promptOptions.push({
5892
5935
  label: personalLabel(options.orgs.length > 1 ? org.name : void 0),
5936
+ maximum: org.personalBudget?.cap ?? void 0,
5893
5937
  selection: personal
5894
5938
  });
5895
5939
  }
@@ -5905,6 +5949,7 @@ var init_attribution_prompt = __esm({
5905
5949
  };
5906
5950
  promptOptions.push({
5907
5951
  label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${budgetAllowance(project)}`,
5952
+ maximum: project.memberCap,
5908
5953
  selection
5909
5954
  });
5910
5955
  }
@@ -5955,8 +6000,8 @@ var init_attribution_prompt_error = __esm({
5955
6000
  init_config();
5956
6001
  MESSAGES = {
5957
6002
  ATTRIBUTION_BACK: "Left budget selection without changing attribution.",
5958
- 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.",
5959
- ATTRIBUTION_SELECTION_INVALID: "That Route 33 option is no longer available. Connect again and pick another."
6003
+ ATTRIBUTION_PRESENTER_UNAVAILABLE: "Update to OpenCode v2 to assign a Route 33 budget in this folder.",
6004
+ ATTRIBUTION_SELECTION_INVALID: "That Route 33 option is no longer available; choose another budget."
5960
6005
  };
5961
6006
  AttributionPromptError = class extends GatewayCredentialError {
5962
6007
  code;
@@ -6151,7 +6196,7 @@ var REQUESTED_OAUTH_SCOPES;
6151
6196
  var init_requested_scopes = __esm({
6152
6197
  "src/requested-scopes/requested-scopes.ts"() {
6153
6198
  "use strict";
6154
- REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read profile projects:read users:read keys:read keys:write";
6199
+ REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read profile projects:read users:read keys:read keys:write models:read";
6155
6200
  }
6156
6201
  });
6157
6202
 
@@ -6221,20 +6266,34 @@ var init_login_session = __esm({
6221
6266
  #options;
6222
6267
  #result;
6223
6268
  #expiresAt;
6269
+ #clears = 0;
6224
6270
  constructor(options) {
6225
6271
  this.#options = options;
6226
6272
  }
6227
6273
  /**
6228
6274
  * Clears the session: the cached login result and the stored refresh
6229
- * token. The next login starts from scratch — /r33 logout and the
6230
- * auto-reconnect path both land here.
6275
+ * token. The next login starts from scratch — the removal of the host's
6276
+ * last Route 33 account and the auto-reconnect path both land here. A refresh still on its way to the
6277
+ * auth server is disowned: its rotated token is never stored.
6231
6278
  * @returns Resolved once the session and the stored refresh token are gone.
6232
6279
  */
6233
6280
  async clear() {
6281
+ this.#clears += 1;
6234
6282
  this.#result = void 0;
6235
6283
  this.#expiresAt = void 0;
6236
6284
  await this.#options.tokenStore?.set(void 0);
6237
6285
  }
6286
+ /**
6287
+ * Whether a session exists, judged without using it: a login resolved or
6288
+ * in flight in this process, or a stored refresh token. Read-only — the
6289
+ * token is never presented, so asking cannot rotate or revoke anything.
6290
+ * @returns True when there is a session to sign in with.
6291
+ */
6292
+ async hasSession() {
6293
+ if (this.#result !== void 0) return true;
6294
+ const stored = await this.#options.tokenStore?.get().catch(() => void 0);
6295
+ return stored !== void 0 && stored !== "";
6296
+ }
6238
6297
  /**
6239
6298
  * Resolves the login once per process, sharing in-flight attempts.
6240
6299
  * @param policy - Whether this attempt may start a browser login; an in-flight attempt is always shared.
@@ -6243,11 +6302,15 @@ var init_login_session = __esm({
6243
6302
  result(policy = {}) {
6244
6303
  if (this.#result !== void 0 && this.#expiresAt !== void 0 && Date.now() >= this.#expiresAt - EXPIRY_SKEW_MS) {
6245
6304
  this.#result = void 0;
6305
+ this.#expiresAt = void 0;
6306
+ }
6307
+ if (this.#result === void 0) {
6308
+ const attempt = this.#start(policy).catch((cause) => {
6309
+ if (this.#result === attempt) this.#result = void 0;
6310
+ throw cause;
6311
+ });
6312
+ this.#result = attempt;
6246
6313
  }
6247
- this.#result ??= this.#start(policy).catch((cause) => {
6248
- this.#result = void 0;
6249
- throw cause;
6250
- });
6251
6314
  return this.#result;
6252
6315
  }
6253
6316
  /**
@@ -6277,6 +6340,7 @@ var init_login_session = __esm({
6277
6340
  if (tokenStore === void 0) {
6278
6341
  return void 0;
6279
6342
  }
6343
+ const clears = this.#clears;
6280
6344
  const stored = await tokenStore.get();
6281
6345
  if (stored === void 0 || stored === "") {
6282
6346
  return void 0;
@@ -6285,6 +6349,9 @@ var init_login_session = __esm({
6285
6349
  if (tokenSet === void 0) {
6286
6350
  return void 0;
6287
6351
  }
6352
+ if (clears !== this.#clears) {
6353
+ throw new AuthError2("AUTH_REAUTHENTICATION_REQUIRED");
6354
+ }
6288
6355
  let credential;
6289
6356
  try {
6290
6357
  credential = parseManagementJwt(tokenSet.access_token);
@@ -6446,7 +6513,7 @@ var init_route33_runtime = __esm({
6446
6513
  const projectsById = new Map(
6447
6514
  listings.flatMap(({ data }) => data).map((project) => [project.id, project])
6448
6515
  );
6449
- return rows.flatMap(({ org_id, project_id }) => {
6516
+ return rows.flatMap(({ org_id, project_id, cap }) => {
6450
6517
  const project = projectsById.get(project_id);
6451
6518
  if (project === void 0) {
6452
6519
  return [];
@@ -6454,6 +6521,7 @@ var init_route33_runtime = __esm({
6454
6521
  return [
6455
6522
  {
6456
6523
  ...project,
6524
+ memberCap: cap,
6457
6525
  organisation: {
6458
6526
  id: org_id,
6459
6527
  name: organisationNames.get(org_id) ?? org_id
@@ -6569,7 +6637,10 @@ var init_route33_runtime = __esm({
6569
6637
  }),
6570
6638
  logout: () => this.#session.clear(),
6571
6639
  "rotate-now": () => rotateNow({
6572
- lease: (policy) => this.#lease({ ...this.#options.policy, ...policy })
6640
+ lease: async (policy) => {
6641
+ await this.#session.credential({ allowBrowser: false });
6642
+ return this.#lease({ ...this.#options.policy, ...policy });
6643
+ }
6573
6644
  })
6574
6645
  };
6575
6646
  }
@@ -6583,6 +6654,7 @@ var init_route33_runtime = __esm({
6583
6654
  await this.#hydrateState(installation);
6584
6655
  }
6585
6656
  const base = inspectSession({
6657
+ connected: await this.#session.hasSession(),
6586
6658
  readAttribution: () => attribution,
6587
6659
  readLease: () => installation?.state.snapshot()
6588
6660
  });
@@ -6590,10 +6662,9 @@ var init_route33_runtime = __esm({
6590
6662
  if (attribution === void 0 || keyId === void 0) {
6591
6663
  return base;
6592
6664
  }
6665
+ const credential = await this.#session.credential({ allowBrowser: false }).catch(() => void 0);
6666
+ if (credential === void 0) return { ...base, connected: false };
6593
6667
  try {
6594
- const credential = await this.#session.credential({
6595
- allowBrowser: false
6596
- });
6597
6668
  const details = await enrichInspection({
6598
6669
  attribution,
6599
6670
  client: this.#client(),
@@ -6606,16 +6677,24 @@ var init_route33_runtime = __esm({
6606
6677
  return base;
6607
6678
  }
6608
6679
  }
6680
+ /**
6681
+ * Lists the models a key on this budget may be limited to. Never opens a
6682
+ * browser; an organisation-level (personal) catalog needs the `models:read`
6683
+ * grant, so sessions signed in before that grant reject here.
6684
+ * @param scope - The budget being configured.
6685
+ * @returns Key-facing model ids with their readable names.
6686
+ */
6687
+ async catalogModelChoices(scope) {
6688
+ const credential = await this.#session.credential({ allowBrowser: false });
6689
+ return this.#client().listModelChoices(credential, scope);
6690
+ }
6609
6691
  /**
6610
6692
  * @param scope - The budget being configured. Omit to discover models for the current key.
6611
6693
  * @returns The management catalog for a budget, or the current key's gateway catalog.
6612
6694
  */
6613
6695
  async catalogModelIds(scope) {
6614
6696
  if (scope !== void 0) {
6615
- const credential = await this.#session.credential({
6616
- allowBrowser: false
6617
- });
6618
- return this.#client().listModelIds(credential, scope);
6697
+ return (await this.catalogModelChoices(scope)).map(({ id }) => id);
6619
6698
  }
6620
6699
  const workspace = await this.storedReusableKey();
6621
6700
  const personal = workspace === void 0 ? await this.#storedPersonalKey() : void 0;
@@ -6624,7 +6703,8 @@ var init_route33_runtime = __esm({
6624
6703
  const credential = await this.#session.credential({
6625
6704
  allowBrowser: false
6626
6705
  });
6627
- return this.#client().listModelIds(credential, {});
6706
+ const choices = await this.#client().listModelChoices(credential, {});
6707
+ return choices.map(({ id }) => id);
6628
6708
  }
6629
6709
  return gatewayModelIds({
6630
6710
  baseURL: readEnvBaseUrl() ?? DEFAULT_BASE_URL,
@@ -6705,6 +6785,29 @@ var init_route33_runtime = __esm({
6705
6785
  const key = keys.find((item) => item.id === keyId);
6706
6786
  return key === void 0 ? void 0 : { allowedModels: key.allowed_models };
6707
6787
  }
6788
+ /** V1 captures only the choice, not the plan; read only that owner's policy.
6789
+ * @param choice - The selected budget and its active organisation.
6790
+ * @returns The effective EUR cap, if the owner has a readable allowance.
6791
+ */
6792
+ async ownerBudgetCap(choice) {
6793
+ const token = await this.#session.credential({ allowBrowser: false });
6794
+ const subject = this.#subject(token);
6795
+ const client = this.#client();
6796
+ if (choice.kind === "personal") {
6797
+ const policy = await client.listBudgetPolicy(
6798
+ token,
6799
+ subject,
6800
+ choice.orgId
6801
+ );
6802
+ return policy.cap ?? void 0;
6803
+ }
6804
+ const budgets = await client.listProjectBudgets(
6805
+ token,
6806
+ subject,
6807
+ choice.orgId
6808
+ );
6809
+ return budgets.data.find((row) => row.project_id === choice.projectId)?.cap;
6810
+ }
6708
6811
  #client() {
6709
6812
  const client = this.#options.management.client;
6710
6813
  if (typeof client !== "function") {
@@ -6835,8 +6938,8 @@ var init_unattributed_prompt_gate = __esm({
6835
6938
  "src/v1-entry/unattributed-prompt-gate/unattributed-prompt-gate.ts"() {
6836
6939
  "use strict";
6837
6940
  init_attribution();
6838
- CONNECTION_COPY = "Not connected to Route 33. Run /connect, choose Route 33, and complete sign-in before assigning a budget with /r33.";
6839
- ATTRIBUTION_COPY = "This folder has no Route 33 budget assigned. Run /r33, choose Route 33, and assign a budget.";
6941
+ CONNECTION_COPY = "To sign in, run /connect and choose Route 33.";
6942
+ ATTRIBUTION_COPY = "This folder has no Route 33 budget; open /r33 and choose Change budget.";
6840
6943
  createUnattributedPromptGate = ({ directory, isConnected, outsideWorktree }) => async (input) => {
6841
6944
  if (input.model?.providerID !== "route_33") return Promise.resolve();
6842
6945
  if (!await isConnected()) throw new Error(CONNECTION_COPY);
@@ -7026,6 +7129,9 @@ var drainPages = async (fetchPage) => {
7026
7129
  // src/management/index.ts
7027
7130
  init_management_error2();
7028
7131
 
7132
+ // src/management/key-read-operations/key-read-operations.ts
7133
+ init_adapters();
7134
+
7029
7135
  // src/contract/management-keys/parse-api-key/parse-api-key.ts
7030
7136
  init_adapters();
7031
7137
  init_predicates();
@@ -7053,7 +7159,7 @@ var parseApiKey = (value) => {
7053
7159
  name: field("name"),
7054
7160
  org_id: field("org_id"),
7055
7161
  ownership_type: value["ownership_type"],
7056
- ...typeof value["owner_user_id"] === "string" ? { owner_user_id: value["owner_user_id"] } : {},
7162
+ ...isNullableString(value["user_id"]) ? { user_id: value["user_id"] } : {},
7057
7163
  project_id: value["project_id"],
7058
7164
  revoked: value["revoked"] === true,
7059
7165
  status
@@ -7313,6 +7419,18 @@ var keyReadOperations = (call) => {
7313
7419
  url.searchParams.set("cursor", cursor);
7314
7420
  return new Request(url, request);
7315
7421
  };
7422
+ const parsePage = (page) => {
7423
+ const collection = parseCollection(page, (row) => row);
7424
+ const data = collection.data.flatMap((row) => {
7425
+ try {
7426
+ return [parseApiKey(row)];
7427
+ } catch (error) {
7428
+ if (error instanceof ContractParseError) return [];
7429
+ throw error;
7430
+ }
7431
+ });
7432
+ return { ...collection, data };
7433
+ };
7316
7434
  return {
7317
7435
  get: async (accessToken, id, orgId) => parseApiKey(
7318
7436
  await call(
@@ -7327,7 +7445,7 @@ var keyReadOperations = (call) => {
7327
7445
  (cursor) => call(accessToken, orgId, (client) => {
7328
7446
  if (cursor !== "") client.use({ onRequest: withCursor(cursor) });
7329
7447
  return client.GET("/api/v1/api-keys", {});
7330
- }).then((page) => parseCollection(page, parseApiKey))
7448
+ }).then(parsePage)
7331
7449
  )
7332
7450
  };
7333
7451
  };
@@ -7391,31 +7509,63 @@ var keyWriteOperations = (call) => ({
7391
7509
  )
7392
7510
  });
7393
7511
 
7394
- // src/management/sdk-management-keys/exposed-catalog-ids/exposed-catalog-ids.ts
7512
+ // src/management/exposed-catalog-models/exposed-catalog-models.ts
7395
7513
  init_adapters();
7396
7514
  init_predicates();
7397
- var exposedCatalogIds = async (readPage) => {
7398
- const ids = /* @__PURE__ */ new Set();
7515
+
7516
+ // src/management/exposed-catalog-models/catalog-row-choices/catalog-row-choices.ts
7517
+ init_adapters();
7518
+ init_predicates();
7519
+
7520
+ // src/management/client-model-id/client-model-id.ts
7521
+ var clientModelId = (offeringId) => {
7522
+ const [provider, region, scope, vendor, ...modelParts] = offeringId.split(":");
7523
+ const slugParts = modelParts.at(-1) === "zdr" ? modelParts.slice(0, -1) : modelParts;
7524
+ const parts = [provider, region, scope, vendor, slugParts.join(":")];
7525
+ return parts.some((part) => part === void 0 || part === "") || /[\s,]/u.test(offeringId) ? void 0 : `${vendor ?? ""}/${slugParts.join(":")}`;
7526
+ };
7527
+
7528
+ // src/management/exposed-catalog-models/catalog-row-choices/catalog-row-choices.ts
7529
+ var catalogRowChoices = (row) => {
7530
+ if (!isRecord(row) || typeof row.id !== "string" || !row.id.trim() || typeof row.status !== "string")
7531
+ throw new ContractParseError("invalid model catalog item");
7532
+ if (row.status !== "exposed" || !Array.isArray(row.offerings)) return [];
7533
+ const label = typeof row.name === "string" && row.name.trim() !== "" ? row.name.trim() : void 0;
7534
+ return row.offerings.flatMap((offering) => {
7535
+ if (!isRecord(offering) || typeof offering.id !== "string" || offering.enabled !== true)
7536
+ return [];
7537
+ const id = clientModelId(offering.id);
7538
+ return id === void 0 ? [] : [{ id, name: label ?? id }];
7539
+ });
7540
+ };
7541
+
7542
+ // src/management/exposed-catalog-models/exposed-catalog-models.ts
7543
+ var exposedCatalogModels = async (readPage) => {
7544
+ const readRows = async (offset2) => {
7545
+ const page = await readPage(offset2);
7546
+ if (!isRecord(page) || !Array.isArray(page.models) || page.offset !== offset2 || typeof page.total !== "number" || !Number.isSafeInteger(page.total) || page.total < 0) {
7547
+ throw new ContractParseError("invalid model catalog page");
7548
+ }
7549
+ return { rows: page.models, total: page.total };
7550
+ };
7551
+ const names = /* @__PURE__ */ new Map();
7399
7552
  let offset = 0;
7400
7553
  for (; ; ) {
7401
- const page = await readPage(offset);
7402
- if (!isRecord(page) || !Array.isArray(page.models) || page.offset !== offset || typeof page.total !== "number" || !Number.isSafeInteger(page.total) || page.total < 0) {
7403
- throw new ContractParseError("invalid model catalog page");
7554
+ const { rows, total } = await readRows(offset);
7555
+ for (const { id, name } of rows.flatMap(catalogRowChoices)) {
7556
+ names.set(id, name);
7404
7557
  }
7405
- page.models.forEach((row) => {
7406
- if (!isRecord(row) || typeof row.id !== "string" || !row.id.trim() || typeof row.status !== "string")
7407
- throw new ContractParseError("invalid model catalog item");
7408
- if (row.status === "exposed") ids.add(row.id);
7409
- });
7410
- offset += page.models.length;
7411
- if (offset >= page.total || page.models.length === 0)
7412
- return [...ids].sort((left, right) => left.localeCompare(right));
7558
+ offset += rows.length;
7559
+ if (offset >= total || rows.length === 0) break;
7413
7560
  }
7561
+ return [...names].map(([id, name]) => ({ id, name })).sort(
7562
+ (left, right) => left.name.localeCompare(right.name) || left.id.localeCompare(right.id)
7563
+ );
7414
7564
  };
7415
7565
 
7416
7566
  // src/management/model-catalog-operations/model-catalog-operations.ts
7417
7567
  var modelCatalogOperations = (call) => ({
7418
- listModelIds: (token, { orgId, projectId }) => exposedCatalogIds(
7568
+ listModelChoices: (token, { orgId, projectId }) => exposedCatalogModels(
7419
7569
  (offset) => call(token, orgId, (client) => {
7420
7570
  const query = { offset };
7421
7571
  if (projectId !== void 0)
@@ -7476,6 +7626,30 @@ import {
7476
7626
  createRoute33Client,
7477
7627
  Route33SdkError
7478
7628
  } from "@r-33/sdk";
7629
+
7630
+ // src/management/sdk-management-call/rejection-of/rejection-of.ts
7631
+ init_predicates();
7632
+ var REFUSED = 422;
7633
+ var REJECTION_MAX_LENGTH = 200;
7634
+ var CONTROL = /\p{Cc}+/gu;
7635
+ var SECRET_PREFIXES = ["r33_", "eyj", "bearer "];
7636
+ var OPAQUE_MIN_LENGTH = 20;
7637
+ var rejectionOf = (outcome) => {
7638
+ const body = outcome.error;
7639
+ if (outcome.response?.status !== REFUSED || !isRecord(body)) return void 0;
7640
+ const raw = body["error"];
7641
+ if (typeof raw !== "string" || raw.length > REJECTION_MAX_LENGTH) {
7642
+ return void 0;
7643
+ }
7644
+ const sentence = raw.replaceAll(CONTROL, " ").replaceAll(/\s+/gu, " ").trim();
7645
+ const lower = sentence.toLowerCase();
7646
+ const secretShaped = SECRET_PREFIXES.some((prefix) => lower.includes(prefix)) || lower.split(" ").some(
7647
+ (word) => word.length >= OPAQUE_MIN_LENGTH && /\d/u.test(word) && /[a-z]/u.test(word)
7648
+ );
7649
+ return sentence === "" || secretShaped ? void 0 : sentence;
7650
+ };
7651
+
7652
+ // src/management/sdk-management-call/sdk-management-call.ts
7479
7653
  var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
7480
7654
  var ACTIVE_ORG_HEADER = "X-Active-Org-Id";
7481
7655
  var createSdkCall = (options) => {
@@ -7522,9 +7696,13 @@ var createSdkCall = (options) => {
7522
7696
  const outcome = await run(callClient(accessToken, activeOrgId));
7523
7697
  const code = outcome.response?.status;
7524
7698
  if (code === void 0 || code < 200 || code >= 300) {
7699
+ const rejection = rejectionOf(outcome);
7525
7700
  throw new ManagementError(
7526
7701
  code === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
7527
- { statusCode: code }
7702
+ {
7703
+ ...rejection === void 0 ? {} : { rejection },
7704
+ statusCode: code
7705
+ }
7528
7706
  );
7529
7707
  }
7530
7708
  return outcome.data;
@@ -7640,14 +7818,16 @@ var selectFromDialog = async (api, input) => new Promise((resolve2) => {
7640
7818
  // src/tui-entry/r33-command-reply/r33-command-reply.ts
7641
7819
  init_create_route33_plugin2();
7642
7820
 
7821
+ // src/v2-entry/r33-command/r33-command.ts
7822
+ import { AuthError as AuthError3 } from "@r-33/auth-browser";
7823
+
7643
7824
  // src/v2-entry/format-inspect-reply/format-inspect-reply.ts
7644
- var formatInspectReply = (inspection) => {
7645
- const lines = [];
7825
+ var formatInspectReply = (inspection, budgetAction) => {
7646
7826
  const { attribution, budget, key } = inspection;
7647
7827
  if (attribution === void 0) {
7648
- return "Route 33 is not connected in this folder \u2014 run /connect or /r33 to set a budget.";
7828
+ return inspection.connected ? `This folder has no Route 33 budget; open /r33 and choose ${budgetAction}.` : "To sign in, run /connect and choose Route 33.";
7649
7829
  }
7650
- const { organisationName, projectName } = key ?? {};
7830
+ const { organisationName, projectName } = { ...key };
7651
7831
  let label;
7652
7832
  let keyScope;
7653
7833
  switch (attribution.kind) {
@@ -7665,7 +7845,7 @@ var formatInspectReply = (inspection) => {
7665
7845
  }
7666
7846
  }
7667
7847
  const cap = budget === void 0 ? "" : [" \u2014 cap", budget.amount, budget.currency].filter((part) => part !== null).join(" ");
7668
- lines.push(`Budget: ${label}${cap}`);
7848
+ const lines = [`Budget: ${label}${cap}`];
7669
7849
  if (key !== void 0) {
7670
7850
  const scope = keyScope === "" ? "" : ` on ${keyScope}`;
7671
7851
  lines.push(`Key: ${key.name}${scope}`);
@@ -7678,7 +7858,7 @@ var formatInspectReply = (inspection) => {
7678
7858
  };
7679
7859
 
7680
7860
  // src/v2-entry/parse-r33-subcommand/parse-r33-subcommand.ts
7681
- var SUBCOMMANDS = ["inspect", "logout", "rotate", "reset"];
7861
+ var SUBCOMMANDS = ["inspect", "rotate", "reset"];
7682
7862
  var parseR33Subcommand = (promptText) => {
7683
7863
  const [first = "", ...rest] = promptText.trim().split(/\s+/u).filter(Boolean);
7684
7864
  const name = first.replace(/^\/+/u, "").split(":")[0] ?? "";
@@ -7690,29 +7870,38 @@ var parseR33Subcommand = (promptText) => {
7690
7870
  };
7691
7871
 
7692
7872
  // src/v2-entry/r33-command/r33-command.ts
7873
+ var SIGN_IN_COPY = "To sign in, run /connect and choose Route 33.";
7693
7874
  var executeR33Command = async (input) => {
7694
7875
  const subcommand = parseR33Subcommand(input.promptText);
7695
7876
  if (input.handlers === void 0) {
7696
- return "Route 33 is not connected in this folder. Run /connect, choose Route 33, and follow the steps.";
7877
+ return SIGN_IN_COPY;
7697
7878
  }
7879
+ const budgetAction = input.budgetAction ?? "Change budget";
7698
7880
  if (subcommand === "help") {
7699
- return "Route 33 usage: /r33 [inspect|rotate|reset|logout] \u2014 inspect shows attribution and key rotation, rotate rotates the key now, reset clears the assigned budget (assign again with /connect).";
7881
+ const { connected } = await input.handlers["inspect-session"]();
7882
+ return connected ? `To assign a budget, open /r33 and choose ${budgetAction}.` : SIGN_IN_COPY;
7700
7883
  }
7701
7884
  switch (subcommand) {
7702
7885
  case "rotate": {
7703
- const lease = await input.handlers["rotate-now"]();
7886
+ const lease = await input.handlers["rotate-now"]().catch(
7887
+ (error) => {
7888
+ if (error instanceof AuthError3) return void 0;
7889
+ throw error;
7890
+ }
7891
+ );
7892
+ if (lease === void 0) return SIGN_IN_COPY;
7704
7893
  return `Route 33 key rotated. Key ${lease.keyId} is valid until ${lease.expiresAt}.`;
7705
7894
  }
7706
- case "logout": {
7707
- await input.handlers["logout"]();
7708
- return "Logged out of Route 33 \u2014 the next OpenCode start signs in again.";
7709
- }
7710
7895
  case "reset": {
7711
7896
  await input.handlers["reset-attribution"]();
7712
- return "Route 33 attribution cleared. Run /connect, choose Route 33, and assign a budget again.";
7897
+ const { connected } = await input.handlers["inspect-session"]();
7898
+ return connected ? `Budget cleared; open /r33 and choose ${budgetAction}.` : `Budget cleared. ${SIGN_IN_COPY}`;
7713
7899
  }
7714
7900
  default: {
7715
- return formatInspectReply(await input.handlers["inspect-session"]());
7901
+ return formatInspectReply(
7902
+ await input.handlers["inspect-session"](),
7903
+ budgetAction
7904
+ );
7716
7905
  }
7717
7906
  }
7718
7907
  };
@@ -7862,18 +8051,24 @@ var alertFromDialog = (api, input) => new Promise((resolve2) => {
7862
8051
  var ATTRIBUTION_FIELD_KEY = "attribution";
7863
8052
 
7864
8053
  // src/v2-entry/parse-budget-answer/read-budget-cap/read-budget-cap.ts
7865
- var readBudgetCap = (answer) => {
7866
- const value = answer["budget_cap"];
7867
- if (value === void 0 || value === null) return null;
8054
+ var readBudgetCap = (answer, maximum) => {
8055
+ const value = answer["budget_cap"] ?? "";
7868
8056
  if (typeof value !== "string" && typeof value !== "number") {
7869
8057
  throw new TypeError("Budget cap must be a number or unlimited");
7870
8058
  }
7871
- if (typeof value === "string" && (value.trim() === "" || value.trim().toLowerCase() === "unlimited")) {
8059
+ if (typeof value === "string" && ["", "unlimited"].includes(value.trim().toLowerCase())) {
7872
8060
  return null;
7873
8061
  }
7874
8062
  const parsed = Number(value);
7875
- if (Number.isFinite(parsed) && parsed > 0) return parsed;
7876
- throw new RangeError("Budget cap must be a finite positive number");
8063
+ if (!Number.isFinite(parsed) || parsed <= 0) {
8064
+ throw new RangeError("Budget cap must be a finite positive number");
8065
+ }
8066
+ if (maximum !== void 0 && parsed > maximum) {
8067
+ throw new RangeError(
8068
+ `Entered ${String(value)} EUR; the selected budget allows at most ${String(maximum)} EUR.`
8069
+ );
8070
+ }
8071
+ return parsed;
7877
8072
  };
7878
8073
 
7879
8074
  // src/tui-entry/dialog-prompt/dialog-prompt.ts
@@ -7904,6 +8099,47 @@ var promptFromDialog = (api, input) => new Promise((resolve2) => {
7904
8099
  );
7905
8100
  });
7906
8101
 
8102
+ // src/tui-entry/v1-key-prompts/v1-select-models/v1-select-models.ts
8103
+ var ALL = /* @__PURE__ */ Symbol("All models");
8104
+ var DONE = /* @__PURE__ */ Symbol("Done");
8105
+ var TITLE = "Which models may this key use?";
8106
+ var v1SelectModels = async (api, models) => {
8107
+ const ticked = /* @__PURE__ */ new Set();
8108
+ const view = (cursor2) => {
8109
+ const count = String(ticked.size);
8110
+ const done = {
8111
+ title: `Done \u2014 use the ${count} selected model${ticked.size === 1 ? "" : "s"}`,
8112
+ value: DONE
8113
+ };
8114
+ const options = [
8115
+ ...ticked.size === 0 ? [] : [done],
8116
+ { title: "All models (inherit)", value: ALL },
8117
+ ...models.map(({ id, name }) => ({
8118
+ description: id,
8119
+ title: `${ticked.has(id) ? "[x]" : "[ ]"} ${name}`,
8120
+ value: id
8121
+ })),
8122
+ { title: "Back", value: BACK }
8123
+ ];
8124
+ return {
8125
+ ...cursor2 === void 0 ? {} : { current: cursor2 },
8126
+ options,
8127
+ title: ticked.size === 0 ? TITLE : `${TITLE} \u2014 ${count} selected`
8128
+ };
8129
+ };
8130
+ let cursor;
8131
+ for (; ; ) {
8132
+ const picked = await selectFromDialog(api, view(cursor));
8133
+ if (picked === void 0 || picked === BACK) return picked;
8134
+ if (picked === ALL) return [];
8135
+ if (picked === DONE) {
8136
+ return models.map(({ id }) => id).filter((id) => ticked.has(id));
8137
+ }
8138
+ if (!ticked.delete(picked)) ticked.add(picked);
8139
+ cursor = picked;
8140
+ }
8141
+ };
8142
+
7907
8143
  // src/tui-entry/v1-key-prompts/v1-key-prompts.ts
7908
8144
  var EXPIRY_OPTIONS = [
7909
8145
  { title: "30 days", value: "30" },
@@ -7924,12 +8160,21 @@ var v1KeyPrompts = async (deps) => {
7924
8160
  "e.g. opencode-desk, or "
7925
8161
  );
7926
8162
  if (typeof name !== "string") return name;
7927
- const capText = await prompt(
7928
- "Monthly budget cap in EUR",
7929
- "blank = unlimited, or "
7930
- );
7931
- if (typeof capText !== "string") return capText;
7932
- const cap = readBudgetCap({ budget_cap: capText });
8163
+ const askCap = async () => {
8164
+ const title = deps.maximum === void 0 ? "Monthly budget cap in EUR" : `Monthly budget cap in EUR (max ${String(deps.maximum)})`;
8165
+ for (; ; ) {
8166
+ const text = await prompt(title, "blank = unlimited, or ");
8167
+ if (typeof text !== "string") return text;
8168
+ try {
8169
+ return readBudgetCap({ budget_cap: text }, deps.maximum);
8170
+ } catch (error) {
8171
+ if (!(error instanceof RangeError)) throw error;
8172
+ await alertFromDialog(deps.api, { title, message: error.message });
8173
+ }
8174
+ }
8175
+ };
8176
+ const cap = await askCap();
8177
+ if (cap === BACK || cap === void 0) return cap;
7933
8178
  const description = await prompt("Description (optional)", "");
7934
8179
  if (typeof description !== "string") return description;
7935
8180
  const expiry = await selectFromDialog(deps.api, {
@@ -7937,17 +8182,10 @@ var v1KeyPrompts = async (deps) => {
7937
8182
  title: "When should the key expire?"
7938
8183
  });
7939
8184
  if (typeof expiry !== "string") return expiry;
7940
- const allowedModels = await selectFromDialog(deps.api, {
7941
- options: [
7942
- { title: "All models (inherit)", value: "all" },
7943
- ...deps.modelIds.map((id) => ({ title: id, value: id })),
7944
- { title: "Back", value: BACK }
7945
- ],
7946
- title: "Which models may this key use?"
7947
- });
7948
- if (typeof allowedModels !== "string") return allowedModels;
8185
+ const allowedModels = await v1SelectModels(deps.api, deps.models);
8186
+ if (typeof allowedModels !== "object") return allowedModels;
7949
8187
  return {
7950
- ...allowedModels === "all" ? {} : { allowedModels: [allowedModels] },
8188
+ ...allowedModels.length === 0 ? {} : { allowedModels },
7951
8189
  description,
7952
8190
  expiryDays: Number(expiry),
7953
8191
  maxBudgetAmount: cap,
@@ -7973,8 +8211,11 @@ var finishConnect = async (deps) => {
7973
8211
  }
7974
8212
  };
7975
8213
  const mint = async () => {
7976
- const modelIds = await runtime.catalogModelIds(picked.choice).catch(() => []);
7977
- const extras = await v1KeyPrompts({ api: deps.api, modelIds });
8214
+ const [models, maximum] = await Promise.all([
8215
+ runtime.catalogModelChoices(picked.choice).catch(() => []),
8216
+ runtime.ownerBudgetCap(picked.choice).catch(() => void 0)
8217
+ ]);
8218
+ const extras = await v1KeyPrompts({ api: deps.api, maximum, models });
7978
8219
  if (typeof extras !== "object") return extras;
7979
8220
  await runtime.mintWorkspaceKey(
7980
8221
  picked.choice,
@@ -8274,36 +8515,58 @@ init_attribution();
8274
8515
 
8275
8516
  // src/tui-entry/v2-connect-copy/v2-connect-copy.ts
8276
8517
  var V2_CONNECT_COPY = {
8277
- dismissed: "Route 33 is not set up for this folder yet. Press Enter to pick the budget, or run /connect and choose Route 33.",
8278
- expired: "The Route 33 sign-in link expired. Press Enter to retry, or run /connect and choose Route 33.",
8279
- manualFallback: "Route 33 is not connected in this folder. Run /connect, choose Route 33, and follow the steps.",
8280
- manualPath: "Press Enter to retry, or run /connect and choose Route 33, and follow the steps.",
8518
+ busyCreating: "Setting up your Route 33 key \u2014 please wait\u2026",
8519
+ busyPreparing: "Loading this budget's key options\u2026",
8520
+ busyTitle: "Route 33",
8521
+ dismissed: "Route 33 is not set up for this folder; open /r33 and choose Attribute.",
8522
+ expired: "Route 33 setup expired; open /r33 and choose Attribute.",
8523
+ manualFallback: "Guided Route 33 setup is unavailable; run /connect and choose Route 33.",
8524
+ manualPath: "Open /r33 and choose Attribute.",
8281
8525
  noBudgetsTitle: "Route 33 \u2014 no budgets available",
8282
- noBudgetsMulti: "No Route 33 budgets are available in this organisation yet. Ask an owner for a budget, then press Enter to pick another organisation.",
8283
- noBudgetsSingle: "No Route 33 budgets are available here yet. Ask an owner for a budget, then run /connect and choose Route 33.",
8526
+ noBudgetsMulti: "No budgets are available here; press Enter to pick another organisation.",
8527
+ noBudgetsSingle: "No Route 33 budgets are available here; ask an owner for a budget.",
8284
8528
  orgPickerTitle: "Which Route 33 organisation covers this folder?",
8285
8529
  pickerTitle: "Which budget covers Route 33 usage in this folder?",
8286
- setupIncomplete: "Route 33 setup did not complete. Press Enter to retry, or run /connect and choose Route 33.",
8287
- signInFailed: "Route 33 sign-in did not complete. Press Enter to retry, or run /connect and choose Route 33.",
8530
+ refusedRetry: "Change your answers and try again.",
8531
+ refusedTitle: "Route 33 \u2014 key not created",
8532
+ setupIncomplete: "Route 33 budget setup did not complete.",
8533
+ signInFailed: "Sign-in did not complete; run /connect and choose Route 33.",
8534
+ rotateFailed: "Route 33 could not rotate the key; restart OpenCode and try again.",
8288
8535
  legacyKeyConverted: "Route 33 key converted \u2713 \u2014 signing in to mint a fresh key for this folder.",
8289
8536
  legacyKeyMessage: "A Route 33 key from a previous version was found in this folder. Convert it to your personal budget?",
8290
8537
  legacyKeyTitle: "Route 33 \u2014 key from a previous version",
8291
8538
  signInActions: "Finish the sign-in in your browser \u2014 press o to open it, c to copy the link.",
8292
8539
  signInTitle: "Route 33 \u2014 sign in",
8293
- statusUnavailable: "Route 33 sign-in did not settle. Press Enter to retry, or run /connect and choose Route 33.",
8294
- stale: "That Route 33 option is no longer available. Press Enter to retry, or run /connect and choose Route 33.",
8540
+ statusUnavailable: "Could not confirm Route 33 setup; open /r33 and choose Attribute.",
8541
+ stale: "That Route 33 option is no longer available; open /r33 and choose Attribute.",
8295
8542
  success: "Route 33 connected \u2713 \u2014 pick a route_33 model and start.",
8296
- timedOut: "Route 33 sign-in timed out. Press Enter to retry, or run /connect and choose Route 33."
8543
+ timedOut: "Route 33 setup timed out; open /r33 and choose Attribute."
8297
8544
  };
8298
8545
 
8299
- // src/v2-entry/connect-copy/connect-copy.ts
8300
- var CONNECT_COPY = {
8301
- 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.",
8302
- failFastWorktree: "Route 33 attributes usage to a project inside a Git worktree. Open a Git repository (or run git init), then connect again.",
8303
- selectionInvalid: "That Route 33 option is no longer available. Connect again and pick another.",
8304
- signedInNextStep: "Signed in to Route 33 \u2713. One more step: connect again, choose Route 33, and assign a budget for this folder.",
8305
- budgetSelected: "Budget selected. Connect again to configure the key for this budget.",
8306
- mintNoBudget: "Route 33 could not create the key \u2014 its cap exceeds this budget. Ask an owner to raise the budget, or pick another."
8546
+ // src/tui-entry/v2-busy-dialog/v2-busy-dialog.ts
8547
+ init_abortable_sleep2();
8548
+ var withBusyDialog = async (dialog, copy, work, options = {}) => {
8549
+ const running = work();
8550
+ const settled = running.then(
8551
+ () => true,
8552
+ () => true
8553
+ );
8554
+ for (; ; ) {
8555
+ const dismissed = dialog.select({
8556
+ options: [{ disabled: true, title: copy.message, value: "busy" }],
8557
+ title: copy.title
8558
+ }).then(
8559
+ () => false,
8560
+ () => false
8561
+ );
8562
+ if (await Promise.race([settled, dismissed])) break;
8563
+ await abortableSleep(options.reopenDelayMs ?? 50);
8564
+ }
8565
+ try {
8566
+ dialog.clear();
8567
+ } catch {
8568
+ }
8569
+ return running;
8307
8570
  };
8308
8571
 
8309
8572
  // src/tui-entry/v2-outcome-copy/v2-outcome-copy.ts
@@ -8333,7 +8596,11 @@ var v2CompletionNotice = ({ dialog, expiryDays, keyName, label }) => () => dialo
8333
8596
  // src/tui-entry/v2-budget-picker/show-completion/show-completion.ts
8334
8597
  var showCompletion = (dialog, options, selection, extras) => {
8335
8598
  const label = options.find((option) => option.value === selection)?.label ?? selection;
8336
- const bound = extras[`existing_key:${selection}`];
8599
+ const text = (key) => {
8600
+ const value = extras[key];
8601
+ return typeof value === "string" ? value : void 0;
8602
+ };
8603
+ const bound = text(`existing_key:${selection}`);
8337
8604
  if (bound !== void 0 && bound !== "new") {
8338
8605
  void dialog.alert({
8339
8606
  title: "Route 33",
@@ -8343,21 +8610,54 @@ var showCompletion = (dialog, options, selection, extras) => {
8343
8610
  }
8344
8611
  void v2CompletionNotice({
8345
8612
  dialog,
8346
- expiryDays: extras["budget_expiry"],
8347
- keyName: extras["budget_name"] ?? "opencode",
8613
+ expiryDays: text("budget_expiry"),
8614
+ keyName: text("budget_name") ?? "opencode",
8348
8615
  label
8349
8616
  })();
8350
8617
  };
8351
8618
 
8619
+ // src/v2-entry/connect-copy/connect-copy.ts
8620
+ var CONNECT_COPY = {
8621
+ failFastClientId: "This Route 33 build has no OAuth client ID; reinstall it from the opencode-dist ref.",
8622
+ failFastWorktree: "To assign a Route 33 budget, open a Git repository.",
8623
+ selectionInvalid: "That Route 33 option is no longer available; open /r33 and choose Attribute.",
8624
+ signedInNextStep: "Signed in to Route 33; open /r33 and choose Attribute to assign a budget.",
8625
+ budgetSelected: "Budget selected but not assigned; open /r33 and choose Attribute to finish setup."
8626
+ };
8627
+ var KEY_FORM_COPY = {
8628
+ /** Prefix of a key the management API refused; its reason follows. */
8629
+ mintRefused: "Route 33 refused this key:",
8630
+ mintRefusedUnknown: "its settings are not allowed for this budget.",
8631
+ modelsNeedSignIn: "Choosing individual models needs a fresh Route 33 sign-in.",
8632
+ modelsUnavailable: "The model list is unavailable right now."
8633
+ };
8634
+
8635
+ // src/tui-entry/v2-budget-picker/answer-pass/read-pass-failure/read-pass-failure.ts
8636
+ var readPassFailure = (message) => {
8637
+ const start = message.indexOf(KEY_FORM_COPY.mintRefused);
8638
+ if (start !== -1) {
8639
+ return { kind: "refused", reason: message.slice(start).trim() };
8640
+ }
8641
+ return message.includes(CONNECT_COPY.budgetSelected) ? { kind: "budget-selected" } : { kind: "other" };
8642
+ };
8643
+
8352
8644
  // src/tui-entry/v2-budget-picker/answer-pass/answer-pass.ts
8353
8645
  var answerPass = async (deps) => {
8354
- let second;
8646
+ const failureOf = (settled2) => readPassFailure(settled2.kind === "failed" ? settled2.message ?? "" : "");
8647
+ let settled;
8355
8648
  try {
8356
- second = await deps.connect({
8357
- answer: { [deps.form.key]: deps.selection, ...deps.extras },
8358
- integrationID: "route33",
8359
- location: deps.locationInput,
8360
- methodID: "browser"
8649
+ settled = await withBusyDialog(deps.dialog, deps.busy, async () => {
8650
+ const started = await deps.connect({
8651
+ answer: { [deps.form.key]: deps.selection, ...deps.extras },
8652
+ integrationID: "route33",
8653
+ location: deps.locationInput,
8654
+ methodID: "browser"
8655
+ });
8656
+ const result = await deps.pollTerminal(started.data.attemptID);
8657
+ if (failureOf(result).kind === "budget-selected") {
8658
+ await deps.onBudgetSelected?.();
8659
+ }
8660
+ return result;
8361
8661
  });
8362
8662
  } catch (error) {
8363
8663
  deps.toast({
@@ -8366,49 +8666,91 @@ var answerPass = async (deps) => {
8366
8666
  });
8367
8667
  return "incomplete";
8368
8668
  }
8369
- const settled = await deps.pollTerminal(second.data.attemptID);
8370
- if (settled.kind !== "complete") {
8371
- if (settled.kind === "failed" && settled.message?.includes(CONNECT_COPY.budgetSelected) === true) {
8372
- return "budget-selected";
8373
- }
8374
- if (settled.kind === "failed" && (settled.message ?? "").includes(CONNECT_COPY.mintNoBudget)) {
8375
- return "no-budgets";
8376
- }
8669
+ if (settled.kind === "complete") {
8670
+ showCompletion(deps.dialog, deps.options, deps.selection, deps.extras);
8671
+ deps.toast({ message: V2_CONNECT_COPY.success, variant: "success" });
8672
+ return "complete";
8673
+ }
8674
+ const failure = failureOf(settled);
8675
+ if (failure.kind === "budget-selected") return "budget-selected";
8676
+ if (failure.kind !== "refused") {
8377
8677
  deps.toast(v2OutcomeCopy(settled, V2_CONNECT_COPY.setupIncomplete));
8378
8678
  return "incomplete";
8379
8679
  }
8380
- showCompletion(deps.dialog, deps.options, deps.selection, deps.extras);
8381
- deps.toast({ message: V2_CONNECT_COPY.success, variant: "success" });
8382
- return "complete";
8680
+ await deps.dialog.alert({
8681
+ message: `${failure.reason} ${V2_CONNECT_COPY.refusedRetry}`,
8682
+ title: V2_CONNECT_COPY.refusedTitle
8683
+ }).catch(() => void 0);
8684
+ return "refused";
8383
8685
  };
8384
8686
 
8385
8687
  // src/v2-entry/connect-form/connect-form.ts
8386
8688
  var ATTRIBUTION_FIELD_KEY2 = "attribution";
8387
8689
  var ORGANISATION_FIELD_KEY = "organisation";
8388
8690
  var BUDGET_CAP_FIELD_KEY = "budget_cap";
8389
-
8390
- // src/tui-entry/v2-integration-surface/v2-integration-surface.ts
8391
- var v2IntegrationSurface = (context) => context.client?.integration ?? context.client?.api?.integration;
8392
-
8393
- // src/v2-entry/v2-form-fields/v2-form-fields.ts
8394
- var v2FormFields = async (context) => {
8395
- const get = v2IntegrationSurface(context)?.get;
8396
- if (get === void 0) return [];
8397
- const integration = await get({
8398
- integrationID: "route33",
8399
- ...context.location === void 0 ? {} : { location: { directory: context.location.directory } }
8400
- }).catch(() => void 0);
8401
- const browserMethods = integration?.data.methods?.filter(
8402
- (entry) => entry.type === "oauth" && entry.id === "browser"
8691
+ var BUDGET_CAP_MAX_FIELD_KEY = "budget_cap_max";
8692
+ var PREPARED_BUDGET_FIELD_KEY = "prepared_budget";
8693
+ var ALL_MODELS_VALUE = "all";
8694
+ var ALL_MODELS_LABEL = "All models (inherit)";
8695
+
8696
+ // src/tui-entry/v2-budget-picker/select-many/select-many.ts
8697
+ var DONE2 = "\0done";
8698
+ var selectMany = async (dialog, input) => {
8699
+ const values = input.options.map(({ value }) => value);
8700
+ const ticked = new Set(
8701
+ (input.selected ?? []).filter((value) => values.includes(value))
8403
8702
  );
8404
- return browserMethods?.flatMap((entry) => entry.form ?? []) ?? [];
8703
+ const view = (cursor2) => {
8704
+ const count = String(ticked.size);
8705
+ const done = {
8706
+ title: `Done \u2014 use the ${count} selected model${ticked.size === 1 ? "" : "s"}`,
8707
+ value: DONE2
8708
+ };
8709
+ return {
8710
+ ...cursor2 === void 0 ? {} : { current: cursor2 },
8711
+ options: [
8712
+ ...ticked.size === 0 ? [] : [done],
8713
+ input.all,
8714
+ ...input.options.map((row) => ({
8715
+ ...row,
8716
+ title: `${ticked.has(row.value) ? "[x]" : "[ ]"} ${row.title}`
8717
+ }))
8718
+ ],
8719
+ title: ticked.size === 0 ? input.title : `${input.title} \u2014 ${count} selected`
8720
+ };
8721
+ };
8722
+ let cursor;
8723
+ for (; ; ) {
8724
+ const picked = await selectWithBack(dialog, view(cursor));
8725
+ if (typeof picked !== "string" || picked === input.all.value) return picked;
8726
+ if (picked === DONE2) return values.filter((value) => ticked.has(value));
8727
+ if (!values.includes(picked)) return void 0;
8728
+ if (!ticked.delete(picked)) ticked.add(picked);
8729
+ cursor = picked;
8730
+ }
8731
+ };
8732
+
8733
+ // src/v2-entry/v2-key-prompts/ask-models/ask-models.ts
8734
+ var askModels = async (dialog, input) => {
8735
+ const toRow = ({ description, label, value }) => ({
8736
+ ...description === void 0 ? {} : { description },
8737
+ title: label,
8738
+ value
8739
+ });
8740
+ const picked = await selectMany(dialog, {
8741
+ all: toRow(input.all),
8742
+ options: input.models.map(toRow),
8743
+ selected: input.previous?.split(",") ?? [],
8744
+ title: input.title
8745
+ });
8746
+ return typeof picked === "object" ? picked.join(",") : picked;
8405
8747
  };
8406
8748
 
8407
8749
  // src/v2-entry/v2-key-prompts/ask-field/ask-field.ts
8408
8750
  var askField = async (dialog, field, previous) => {
8409
8751
  const title = field.title ?? field.key;
8410
- const options = field.options ?? [];
8411
- if (options.length === 0) {
8752
+ const [first, ...rest] = field.options ?? [];
8753
+ if (first === void 0) {
8412
8754
  const text = await dialog.prompt({
8413
8755
  description: "Enter /back to return to the previous step, or Esc to cancel.",
8414
8756
  placeholder: field.placeholder,
@@ -8417,11 +8759,21 @@ var askField = async (dialog, field, previous) => {
8417
8759
  });
8418
8760
  return text === "/back" ? BACK : text;
8419
8761
  }
8762
+ const options = [first, ...rest];
8763
+ if (field.type === "multiselect") {
8764
+ return askModels(dialog, {
8765
+ all: { label: ALL_MODELS_LABEL, value: ALL_MODELS_VALUE },
8766
+ models: options,
8767
+ previous,
8768
+ title
8769
+ });
8770
+ }
8420
8771
  const selected = await selectWithBack(dialog, {
8421
8772
  current: options.some(({ value }) => value === previous) ? previous : void 0,
8422
- options: options.map((option) => ({
8423
- title: option.label,
8424
- value: option.value
8773
+ options: options.map(({ description, label, value }) => ({
8774
+ ...description === void 0 ? {} : { description },
8775
+ title: label,
8776
+ value
8425
8777
  })),
8426
8778
  title
8427
8779
  });
@@ -8433,6 +8785,11 @@ var askField = async (dialog, field, previous) => {
8433
8785
  // src/v2-entry/v2-key-prompts/v2-key-prompts.ts
8434
8786
  var v2KeyPrompts = async (deps) => {
8435
8787
  const answer = {};
8788
+ const limit = deps.fields.find(({ key }) => key === BUDGET_CAP_MAX_FIELD_KEY);
8789
+ const maximum = readBudgetCap({ budget_cap: limit?.placeholder }) ?? void 0;
8790
+ const questions = deps.fields.filter(
8791
+ ({ key }) => key !== BUDGET_CAP_MAX_FIELD_KEY && key !== PREPARED_BUDGET_FIELD_KEY
8792
+ );
8436
8793
  const collect = async (field) => {
8437
8794
  for (; ; ) {
8438
8795
  const value = await askField(
@@ -8443,7 +8800,7 @@ var v2KeyPrompts = async (deps) => {
8443
8800
  if (value === BACK || value === void 0) return value;
8444
8801
  if (field.key === BUDGET_CAP_FIELD_KEY) {
8445
8802
  try {
8446
- readBudgetCap({ [field.key]: value });
8803
+ readBudgetCap({ [field.key]: value }, maximum);
8447
8804
  } catch (error) {
8448
8805
  if (!(error instanceof RangeError)) throw error;
8449
8806
  await deps.dialog.alert({
@@ -8457,8 +8814,8 @@ var v2KeyPrompts = async (deps) => {
8457
8814
  }
8458
8815
  };
8459
8816
  let index = 0;
8460
- while (index < deps.fields.length) {
8461
- const field = deps.fields[index];
8817
+ while (index < questions.length) {
8818
+ const field = questions[index];
8462
8819
  if (!field) break;
8463
8820
  const value = await collect(field);
8464
8821
  if (value === BACK && index > 0) {
@@ -8470,101 +8827,133 @@ var v2KeyPrompts = async (deps) => {
8470
8827
  answer[field.key] = value;
8471
8828
  index++;
8472
8829
  }
8473
- return answer;
8830
+ return Object.fromEntries(
8831
+ questions.flatMap((field) => {
8832
+ const value = answer[field.key];
8833
+ if (value === void 0) return [];
8834
+ if (field.type !== "multiselect") return [[field.key, value]];
8835
+ return value === ALL_MODELS_VALUE ? [] : [[field.key, value.split(",")]];
8836
+ })
8837
+ );
8474
8838
  };
8475
8839
 
8476
- // src/tui-entry/v2-budget-picker/show-no-budgets/show-no-budgets.ts
8477
- var showNoBudgets = (dialog, multi) => dialog.alert({
8478
- message: multi ? V2_CONNECT_COPY.noBudgetsMulti : V2_CONNECT_COPY.noBudgetsSingle,
8479
- title: V2_CONNECT_COPY.noBudgetsTitle
8480
- });
8481
-
8482
- // src/tui-entry/v2-budget-picker/answer-step/answer-step.ts
8483
- var runAnswerStep = async (deps, budgetPrepared = false) => {
8484
- const loadFields = async () => {
8485
- const registered = await v2FormFields(deps.context);
8486
- const budgets = registered.find(
8487
- (field) => field.key === ATTRIBUTION_FIELD_KEY2
8488
- )?.options;
8489
- const matches = budgets === void 0 || budgets.some((row) => row.value === deps.selection);
8490
- return (matches ? registered : []).filter(
8491
- (field) => field.key !== ATTRIBUTION_FIELD_KEY2 && field.key !== ORGANISATION_FIELD_KEY
8492
- );
8493
- };
8494
- const fields = await loadFields();
8495
- if (budgetPrepared && fields.length === 0) {
8496
- deps.toast({ message: V2_CONNECT_COPY.setupIncomplete, variant: "error" });
8497
- return "done";
8498
- }
8840
+ // src/tui-entry/v2-budget-picker/answer-step/collect-key-answers/collect-key-answers.ts
8841
+ var collectKeyAnswers = async (deps) => {
8842
+ const { dialog, fields } = deps;
8843
+ const selector = fields.find(
8844
+ (field) => field.key === `existing_key:${deps.selection}`
8845
+ );
8846
+ const create = () => v2KeyPrompts({
8847
+ dialog,
8848
+ draft: deps.draft,
8849
+ fields: fields.filter(
8850
+ (field) => !field.key.startsWith("existing_key:") && field.key !== "rotation_confirmation"
8851
+ )
8852
+ });
8499
8853
  const confirmBinding = async (key) => {
8500
8854
  const field = fields.find((row) => row.key === "rotation_confirmation");
8501
- if (field?.options?.some((option) => option.value === key) !== true)
8855
+ if (field?.options?.some((option) => option.value === key) !== true) {
8502
8856
  return {};
8857
+ }
8503
8858
  if (field.title === void 0) return void 0;
8504
- const consent = await deps.dialog.confirm({
8859
+ const consent = await dialog.confirm({
8505
8860
  title: "Rotate key? (No: Back to key selection)",
8506
8861
  message: field.title
8507
8862
  });
8508
8863
  if (consent === false) return BACK;
8509
8864
  return consent ? { rotation_confirmation: key } : void 0;
8510
8865
  };
8511
- const collect = async () => {
8512
- const selector = fields.find(
8513
- (field) => field.key === `existing_key:${deps.selection}`
8514
- );
8515
- const create = () => v2KeyPrompts({
8516
- dialog: deps.dialog,
8517
- draft: deps.draft,
8518
- fields: fields.filter(
8519
- (field) => !field.key.startsWith("existing_key:") && field.key !== "rotation_confirmation"
8520
- )
8521
- });
8522
- if (!selector) return create();
8523
- const select = () => selectWithBack(deps.dialog, {
8866
+ if (!selector) return create();
8867
+ for (; ; ) {
8868
+ const selection = await selectWithBack(dialog, {
8524
8869
  title: selector.title ?? "Choose a key",
8525
8870
  options: (selector.options ?? []).map((option) => ({
8526
8871
  title: option.label,
8527
8872
  value: option.value
8528
8873
  }))
8529
8874
  });
8530
- for (; ; ) {
8531
- const selection = await select();
8532
- if (typeof selection !== "string") return selection;
8533
- if (selection === "new") {
8534
- const extras2 = await create();
8535
- if (extras2 === BACK) continue;
8536
- return extras2;
8537
- }
8538
- const confirmation = await confirmBinding(selection);
8539
- if (confirmation === BACK) continue;
8540
- return confirmation && { [selector.key]: selection, ...confirmation };
8541
- }
8542
- };
8543
- const extras = await collect();
8544
- if (extras === BACK) return "back";
8545
- if (extras === void 0) {
8546
- deps.toast({ message: V2_CONNECT_COPY.dismissed });
8547
- return "done";
8875
+ if (typeof selection !== "string") return selection;
8876
+ const answers = selection === "new" ? await create() : await confirmBinding(selection);
8877
+ if (answers === BACK) continue;
8878
+ if (answers === void 0 || selection === "new") return answers;
8879
+ return { [selector.key]: selection, ...answers };
8880
+ }
8881
+ };
8882
+
8883
+ // src/tui-entry/v2-integration-surface/v2-integration-surface.ts
8884
+ var v2IntegrationSurface = (context) => context.client?.integration ?? context.client?.api?.integration;
8885
+
8886
+ // src/v2-entry/v2-form-fields/v2-form-fields.ts
8887
+ var v2FormFields = async (context) => {
8888
+ const get = v2IntegrationSurface(context)?.get;
8889
+ if (get === void 0) return [];
8890
+ const integration = await get({
8891
+ integrationID: "route33",
8892
+ ...context.location === void 0 ? {} : { location: { directory: context.location.directory } }
8893
+ }).catch(() => void 0);
8894
+ const browserMethods = integration?.data.methods?.filter(
8895
+ (entry) => entry.type === "oauth" && entry.id === "browser"
8896
+ );
8897
+ return browserMethods?.flatMap((entry) => entry.form ?? []) ?? [];
8898
+ };
8899
+
8900
+ // src/tui-entry/v2-budget-picker/answer-step/prepare-key-fields/prepare-key-fields.ts
8901
+ var prepareKeyFields = async (deps) => {
8902
+ let registered = [];
8903
+ const outcome = await deps.prepare(async () => {
8904
+ registered = await v2FormFields(deps.context);
8905
+ });
8906
+ if (outcome !== "budget-selected") return void 0;
8907
+ const preparedFor = registered.find(
8908
+ (field) => field.key === PREPARED_BUDGET_FIELD_KEY
8909
+ )?.placeholder;
8910
+ const fields = registered.filter(
8911
+ (field) => field.key !== ATTRIBUTION_FIELD_KEY2 && field.key !== ORGANISATION_FIELD_KEY && field.key !== PREPARED_BUDGET_FIELD_KEY
8912
+ );
8913
+ if (fields.length === 0 || (preparedFor ?? deps.selection) !== deps.selection) {
8914
+ deps.toast({ message: V2_CONNECT_COPY.setupIncomplete, variant: "error" });
8915
+ return void 0;
8548
8916
  }
8549
- const outcome = await answerPass({
8917
+ return fields;
8918
+ };
8919
+
8920
+ // src/tui-entry/v2-budget-picker/answer-step/answer-step.ts
8921
+ var runAnswerStep = async (deps) => {
8922
+ const pass = (extras, message, onBudgetSelected) => answerPass({
8923
+ busy: { message, title: V2_CONNECT_COPY.busyTitle },
8550
8924
  connect: deps.connect,
8551
8925
  dialog: deps.dialog,
8552
8926
  extras,
8553
8927
  form: { key: deps.attributionFieldKey },
8554
8928
  locationInput: deps.locationInput,
8929
+ ...onBudgetSelected === void 0 ? {} : { onBudgetSelected },
8555
8930
  options: deps.budgetOptions,
8556
8931
  pollTerminal: deps.pollTerminal,
8557
8932
  selection: deps.selection,
8558
8933
  toast: deps.toast
8559
8934
  });
8560
- if (outcome === "budget-selected" && !budgetPrepared) {
8561
- return runAnswerStep(deps, true);
8562
- }
8563
- if (outcome === "no-budgets") {
8564
- await showNoBudgets(deps.dialog, deps.multi);
8565
- return deps.multi ? "retry" : "done";
8935
+ const fields = await prepareKeyFields({
8936
+ context: deps.context,
8937
+ prepare: (read) => pass({}, V2_CONNECT_COPY.busyPreparing, read),
8938
+ selection: deps.selection,
8939
+ toast: deps.toast
8940
+ });
8941
+ if (fields === void 0) return "done";
8942
+ for (; ; ) {
8943
+ const extras = await collectKeyAnswers({
8944
+ dialog: deps.dialog,
8945
+ draft: deps.draft,
8946
+ fields,
8947
+ selection: deps.selection
8948
+ });
8949
+ if (extras === BACK) return "back";
8950
+ if (extras === void 0) {
8951
+ deps.toast({ message: V2_CONNECT_COPY.dismissed });
8952
+ return "done";
8953
+ }
8954
+ const outcome = await pass(extras, V2_CONNECT_COPY.busyCreating);
8955
+ if (outcome !== "refused") return "done";
8566
8956
  }
8567
- return "done";
8568
8957
  };
8569
8958
 
8570
8959
  // src/tui-entry/v2-budget-picker/pick-budget/pick-budget.ts
@@ -8616,6 +9005,12 @@ var scopeBudgetOptions = (orgId, options) => orgId === void 0 ? options : option
8616
9005
  (option) => option.value.startsWith(orgSelectionPrefix(orgId))
8617
9006
  );
8618
9007
 
9008
+ // src/tui-entry/v2-budget-picker/show-no-budgets/show-no-budgets.ts
9009
+ var showNoBudgets = (dialog, multi) => dialog.alert({
9010
+ message: multi ? V2_CONNECT_COPY.noBudgetsMulti : V2_CONNECT_COPY.noBudgetsSingle,
9011
+ title: V2_CONNECT_COPY.noBudgetsTitle
9012
+ });
9013
+
8619
9014
  // src/tui-entry/v2-budget-picker/budget-round/budget-round.ts
8620
9015
  var runBudgetRound = async (deps) => {
8621
9016
  const multi = deps.orgs.length > 1;
@@ -8652,7 +9047,6 @@ var runBudgetRound = async (deps) => {
8652
9047
  context: deps.context,
8653
9048
  dialog: deps.dialog,
8654
9049
  locationInput: deps.locationInput,
8655
- multi,
8656
9050
  pollTerminal: deps.pollTerminal,
8657
9051
  selection,
8658
9052
  toast: deps.toast
@@ -8739,6 +9133,7 @@ var v2ConnectSurface = (context) => v2IntegrationSurface(context)?.oauth?.connec
8739
9133
 
8740
9134
  // src/tui-entry/v2-poll-terminal/v2-poll-terminal.ts
8741
9135
  init_abortable_sleep2();
9136
+ var FIRST_POLL_MS = 100;
8742
9137
  var createV2PollTerminal = ({
8743
9138
  locationInput,
8744
9139
  maxPolls = 600,
@@ -8748,7 +9143,7 @@ var createV2PollTerminal = ({
8748
9143
  }) => async (attemptID) => {
8749
9144
  let errors = 0;
8750
9145
  for (let poll = 0; poll < maxPolls; poll += 1) {
8751
- await abortableSleep(pollDelayMs);
9146
+ await abortableSleep(Math.min(pollDelayMs, FIRST_POLL_MS * 2 ** poll));
8752
9147
  try {
8753
9148
  const result = await status({
8754
9149
  attemptID,
@@ -8896,7 +9291,7 @@ var v2LegacyKeyGate = async ({
8896
9291
 
8897
9292
  // src/tui-entry/v2-autoconnect/v2-autoconnect.ts
8898
9293
  var v2Autoconnect = async (context, options = {}) => {
8899
- const directory = v2SetupDirectory(context);
9294
+ const directory = options.directory ?? v2SetupDirectory(context);
8900
9295
  if (directory === void 0) return;
8901
9296
  const unattributed = () => readAttribution({
8902
9297
  directory,
@@ -8929,10 +9324,19 @@ var v2Autoconnect = async (context, options = {}) => {
8929
9324
  // src/tui-entry/show-r33-menu/run-action/run-action.ts
8930
9325
  var runR33MenuAction = async (context, action, deps) => {
8931
9326
  try {
8932
- const reply = await executeR33Command({
8933
- handlers: deps.handlers(),
9327
+ const handlers = deps.handlers();
9328
+ const local = () => executeR33Command({
9329
+ budgetAction: "Attribute",
9330
+ handlers: handlers && {
9331
+ ...handlers,
9332
+ "inspect-session": async () => {
9333
+ const inspection = await handlers["inspect-session"]();
9334
+ return inspection.connected || deps.signedIn === void 0 ? inspection : { ...inspection, connected: await deps.signedIn() };
9335
+ }
9336
+ },
8934
9337
  promptText: `/r33 ${action}`
8935
9338
  });
9339
+ const reply = action === "rotate" && deps.rotate !== void 0 ? await deps.rotate() : await local();
8936
9340
  context.ui.toast.show({ message: reply, variant: "info" });
8937
9341
  } catch (error) {
8938
9342
  context.ui.toast.show({
@@ -8955,10 +9359,6 @@ var menuOptions2 = [
8955
9359
  {
8956
9360
  title: "Rotate key now",
8957
9361
  value: "rotate"
8958
- },
8959
- {
8960
- title: "Log out of Route 33",
8961
- value: "logout"
8962
9362
  }
8963
9363
  ];
8964
9364
  var showR33Menu = async (context, deps) => {
@@ -8974,7 +9374,7 @@ var showR33Menu = async (context, deps) => {
8974
9374
  directory: location.directory,
8975
9375
  outsideWorktree: "return-undefined"
8976
9376
  }) === void 0) {
8977
- await v2Autoconnect(context);
9377
+ await v2Autoconnect(context, { directory: location.directory });
8978
9378
  } else {
8979
9379
  await v2GuidedConnect({ context, unattributed: () => true });
8980
9380
  }
@@ -8983,6 +9383,40 @@ var showR33Menu = async (context, deps) => {
8983
9383
  await runR33MenuAction(context, selection, deps);
8984
9384
  };
8985
9385
 
9386
+ // src/v2-entry/is-account-removed/is-account-removed.ts
9387
+ init_predicates();
9388
+ var isAccountRemoved = (event) => {
9389
+ if (!isRecord(event) || event["type"] !== "credential.switched") return false;
9390
+ const data = event["data"];
9391
+ return isRecord(data) && data["integrationID"] === "route33" && data["credentialID"] === null;
9392
+ };
9393
+
9394
+ // src/tui-entry/v2-account-removal/v2-account-removal.ts
9395
+ var registerV2AccountRemoval = (deps) => {
9396
+ let awaitingWithdrawal = false;
9397
+ const integration = deps.data?.location.integration;
9398
+ const settle = (work) => {
9399
+ void Promise.resolve().then(work).catch(() => void 0);
9400
+ };
9401
+ const refresh = () => {
9402
+ settle(() => {
9403
+ integration?.invalidate?.(deps.location);
9404
+ return integration?.sync?.(deps.location);
9405
+ });
9406
+ };
9407
+ deps.data?.listen?.(({ details }) => {
9408
+ if (isAccountRemoved(details)) {
9409
+ awaitingWithdrawal = true;
9410
+ settle(() => deps.runtime?.commandHandlers().logout());
9411
+ refresh();
9412
+ return;
9413
+ }
9414
+ if (!awaitingWithdrawal || details.type !== "integration.updated") return;
9415
+ awaitingWithdrawal = false;
9416
+ refresh();
9417
+ });
9418
+ };
9419
+
8986
9420
  // src/tui-entry/v2-attribution-field/v2-attribution-field.ts
8987
9421
  var v2AttributionField = (methods) => {
8988
9422
  const browserMethods = methods?.filter(
@@ -9007,58 +9441,6 @@ var v2AttributionForm = async (context) => {
9007
9441
  return v2AttributionField(integration?.data.methods);
9008
9442
  };
9009
9443
 
9010
- // src/tui-entry/v2-route33-model-candidate/v2-route33-model-candidate.ts
9011
- var v2Route33ModelCandidate = (models) => {
9012
- for (const model of models) {
9013
- if (model.providerID === "route_33") {
9014
- return model;
9015
- }
9016
- }
9017
- return void 0;
9018
- };
9019
-
9020
- // src/tui-entry/v2-auto-select-target/v2-auto-select-target.ts
9021
- var v2AutoSelectTarget = async ({
9022
- activeSessions,
9023
- listModels,
9024
- locationInput
9025
- }) => {
9026
- const active = await activeSessions?.().catch(() => void 0);
9027
- const sessionID = Object.keys(active ?? {})[0];
9028
- if (sessionID === void 0) return void 0;
9029
- const listed = await listModels?.({
9030
- location: { directory: locationInput.directory }
9031
- }).catch(() => void 0);
9032
- const model = v2Route33ModelCandidate(listed?.data ?? []);
9033
- if (model === void 0) return void 0;
9034
- return { model, sessionID };
9035
- };
9036
-
9037
- // src/tui-entry/v2-auto-select-model/v2-auto-select-model.ts
9038
- var ROUTE_33_PROVIDER_ID = "route_33";
9039
- var v2AutoSelectModel = async ({
9040
- listModels,
9041
- currentModel,
9042
- activeSessions,
9043
- switchModel,
9044
- locationInput
9045
- }) => {
9046
- if (currentModel?.()?.providerID === ROUTE_33_PROVIDER_ID) return;
9047
- const target = await v2AutoSelectTarget({
9048
- activeSessions,
9049
- listModels,
9050
- locationInput
9051
- });
9052
- if (target === void 0) return;
9053
- await switchModel?.({
9054
- model: {
9055
- id: target.model.id,
9056
- providerID: target.model.providerID
9057
- },
9058
- sessionID: target.sessionID
9059
- });
9060
- };
9061
-
9062
9444
  // src/tui-entry/v2-boot-matrix/v2-boot-matrix.ts
9063
9445
  var v2BootMatrix = async ({
9064
9446
  probe,
@@ -9125,6 +9507,48 @@ var v2BootSessionProbe = async (deps) => {
9125
9507
  return token !== void 0 ? "alive" : "dead";
9126
9508
  };
9127
9509
 
9510
+ // src/tui-entry/v2-server-rotate/v2-server-rotate.ts
9511
+ init_config();
9512
+ init_predicates();
9513
+
9514
+ // src/v2-entry/session-rpc/session-rpc.ts
9515
+ var ROUTE33_SESSION_RPC = {
9516
+ events: {},
9517
+ id: "route33",
9518
+ methods: {
9519
+ /**
9520
+ * Rotates this folder's key and answers with the text to show. A handler
9521
+ * that throws reaches the caller without its message, so a refused
9522
+ * rotation is answered too: `failed` marks the reply as the reason.
9523
+ */
9524
+ rotate: {
9525
+ input: { additionalProperties: false, properties: {}, type: "object" },
9526
+ output: {
9527
+ additionalProperties: false,
9528
+ properties: { failed: { type: "boolean" }, reply: { type: "string" } },
9529
+ required: ["failed", "reply"],
9530
+ type: "object"
9531
+ }
9532
+ }
9533
+ }
9534
+ };
9535
+
9536
+ // src/tui-entry/v2-server-rotate/v2-server-rotate.ts
9537
+ var v2ServerRotate = async (context) => {
9538
+ const { client, location } = context;
9539
+ const answer = await (async () => {
9540
+ if (location === void 0) return void 0;
9541
+ return client?.rpc?.(ROUTE33_SESSION_RPC).rotate({}, { location: { directory: location.directory } });
9542
+ })().catch(() => void 0);
9543
+ const reply = isRecord(answer) ? answer["reply"] : void 0;
9544
+ const failed = isRecord(answer) ? answer["failed"] : void 0;
9545
+ if (typeof reply !== "string" || typeof failed !== "boolean") {
9546
+ throw new GatewayCredentialError(V2_CONNECT_COPY.rotateFailed);
9547
+ }
9548
+ if (failed) throw new GatewayCredentialError(reply);
9549
+ return reply;
9550
+ };
9551
+
9128
9552
  // src/tui-entry/v2-session-watch/v2-session-watch.ts
9129
9553
  init_abortable_sleep2();
9130
9554
  var watchV2SessionBecomeAlive = (deps) => {
@@ -9332,6 +9756,96 @@ var v2WizardControl = () => {
9332
9756
  };
9333
9757
  };
9334
9758
 
9759
+ // src/tui-entry/v2-route33-model-candidate/v2-route33-model-candidate.ts
9760
+ var v2Route33ModelCandidate = (model) => model.providerID === "route_33" && model.enabled !== false;
9761
+
9762
+ // src/tui-entry/v2-auto-select-target/v2-auto-select-target.ts
9763
+ var SKIP = "\0skip";
9764
+ var v2AutoSelectTarget = async (models, dialog) => {
9765
+ const candidates = models.filter(v2Route33ModelCandidate);
9766
+ if (candidates.length === 0) return void 0;
9767
+ const selected = await dialog.select({
9768
+ title: "Choose a Route 33 model",
9769
+ options: [
9770
+ { title: "Skip \u2014 keep the current model", value: SKIP },
9771
+ ...candidates.map(({ id, name }) => ({
9772
+ title: name ?? id,
9773
+ value: id
9774
+ }))
9775
+ ]
9776
+ });
9777
+ return candidates.find(({ id }) => id === selected);
9778
+ };
9779
+
9780
+ // src/tui-entry/v2-auto-select-model/v2-auto-select-model.ts
9781
+ var v2AutoSelectModel = async (context) => {
9782
+ const { ui, client, location } = context;
9783
+ const route = ui.router?.current();
9784
+ const session = client?.session;
9785
+ if (route?.type !== "session" || !session?.switchModel || !location) return;
9786
+ const pick = async () => {
9787
+ if (ui.model?.current()?.providerID === "route_33") return void 0;
9788
+ const listed = await client?.model?.list?.({ location });
9789
+ return v2AutoSelectTarget(listed?.data ?? [], ui.dialog);
9790
+ };
9791
+ const model = await pick();
9792
+ if (!model) return;
9793
+ await session.switchModel({
9794
+ model: { id: model.id, providerID: model.providerID },
9795
+ sessionID: route.sessionID
9796
+ });
9797
+ };
9798
+
9799
+ // src/tui-entry/v2-tui/with-attribution-picker/with-attribution-picker.ts
9800
+ var withAttributionPicker = async (context, run) => {
9801
+ const attempt = { complete: false };
9802
+ let notice;
9803
+ const location = context.location ?? context.data?.location.default();
9804
+ const client = {
9805
+ ...context.client,
9806
+ get integration() {
9807
+ const integration = v2IntegrationSurface(context);
9808
+ const status = integration?.oauth?.status;
9809
+ if (!status) return integration;
9810
+ return {
9811
+ ...integration,
9812
+ oauth: {
9813
+ ...integration.oauth,
9814
+ status: async (input) => {
9815
+ const result = await status(input);
9816
+ attempt.complete = result.data.status === "complete";
9817
+ return result;
9818
+ }
9819
+ }
9820
+ };
9821
+ }
9822
+ };
9823
+ await run({
9824
+ ...context,
9825
+ client,
9826
+ location,
9827
+ ui: {
9828
+ ...context.ui,
9829
+ dialog: {
9830
+ ...context.ui.dialog,
9831
+ alert: (input) => {
9832
+ const dismissed = context.ui.dialog.alert(input);
9833
+ if (attempt.complete) notice = dismissed;
9834
+ return dismissed;
9835
+ }
9836
+ }
9837
+ }
9838
+ });
9839
+ if (!attempt.complete) return;
9840
+ await notice;
9841
+ await v2AutoSelectModel({ ...context, location }).catch(() => {
9842
+ context.ui.toast.show({
9843
+ message: "Could not select a Route 33 model. Open /models to choose one.",
9844
+ variant: "error"
9845
+ });
9846
+ });
9847
+ };
9848
+
9335
9849
  // src/tui-entry/v2-tui/v2-tui.ts
9336
9850
  var createV2Tui = () => ({
9337
9851
  id: "route33",
@@ -9339,6 +9853,14 @@ var createV2Tui = () => ({
9339
9853
  const tuiRuntime = composeV2TuiRuntime(context);
9340
9854
  const menuHandlers = () => tuiRuntime?.commandHandlers();
9341
9855
  let stopSessionWatch = () => void 0;
9856
+ const signedIn = async () => await sessionProbe() === "alive" || await v2AttributionForm({ ...context, location }).catch(
9857
+ () => void 0
9858
+ ) !== void 0;
9859
+ const menu = (host) => showR33Menu(host, {
9860
+ handlers: menuHandlers,
9861
+ rotate: () => v2ServerRotate({ client: context.client, location }),
9862
+ signedIn
9863
+ });
9342
9864
  context.keymap?.layer(() => ({
9343
9865
  mode: "global",
9344
9866
  priority: 10,
@@ -9356,7 +9878,7 @@ var createV2Tui = () => ({
9356
9878
  wizard.menuRequested();
9357
9879
  stopSessionWatch();
9358
9880
  try {
9359
- await showR33Menu(context, { handlers: menuHandlers });
9881
+ await withAttributionPicker(context, menu);
9360
9882
  } finally {
9361
9883
  wizard.menuClosed();
9362
9884
  }
@@ -9408,19 +9930,9 @@ var createV2Tui = () => ({
9408
9930
  }
9409
9931
  return false;
9410
9932
  };
9411
- const autoSelect = () => {
9412
- const client = context.client;
9413
- if (client === void 0) return Promise.resolve();
9414
- return v2AutoSelectModel({
9415
- activeSessions: () => client.session?.active?.() ?? Promise.resolve({}),
9416
- currentModel: () => context.ui.model?.current?.(),
9417
- listModels: (input) => client.model?.list?.(input) ?? Promise.resolve({ data: [] }),
9418
- locationInput: { directory },
9419
- switchModel: (input) => client.session?.switchModel?.(input) ?? Promise.resolve()
9420
- });
9421
- };
9933
+ const automatic = (host) => v2Autoconnect(host, { superseded: wizard.superseded });
9422
9934
  const boot = async (options) => {
9423
- const outcome = await v2BootMatrix({
9935
+ await v2BootMatrix({
9424
9936
  assumedAlive: options?.assumedAlive === true,
9425
9937
  attributed,
9426
9938
  globalFallback: async () => {
@@ -9429,17 +9941,8 @@ var createV2Tui = () => ({
9429
9941
  return silent;
9430
9942
  },
9431
9943
  probe: sessionProbe,
9432
- wizard: () => v2Autoconnect(
9433
- // The wizard re-derives its directory from the context
9434
- // location, which is undefined until the first route lands —
9435
- // inject the boot location so the budget picker opens.
9436
- { ...context, location },
9437
- { superseded: wizard.superseded }
9438
- )
9944
+ wizard: () => withAttributionPicker({ ...context, location }, automatic)
9439
9945
  });
9440
- if (outcome.kind === "wizard-settled") {
9441
- void autoSelect().catch(() => void 0);
9442
- }
9443
9946
  };
9444
9947
  const lock = v2SetupLock({
9445
9948
  keymap: context.keymap === void 0 ? void 0 : {
@@ -9476,6 +9979,11 @@ var createV2Tui = () => ({
9476
9979
  return false;
9477
9980
  }
9478
9981
  });
9982
+ registerV2AccountRemoval({
9983
+ data: context.data,
9984
+ location,
9985
+ runtime: tuiRuntime
9986
+ });
9479
9987
  }
9480
9988
  });
9481
9989