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

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
6275
  * token. The next login starts from scratch — /r33 logout and the
6230
- * auto-reconnect path both land here.
6276
+ * 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
@@ -6583,6 +6651,7 @@ var init_route33_runtime = __esm({
6583
6651
  await this.#hydrateState(installation);
6584
6652
  }
6585
6653
  const base = inspectSession({
6654
+ connected: await this.#session.hasSession(),
6586
6655
  readAttribution: () => attribution,
6587
6656
  readLease: () => installation?.state.snapshot()
6588
6657
  });
@@ -6590,10 +6659,9 @@ var init_route33_runtime = __esm({
6590
6659
  if (attribution === void 0 || keyId === void 0) {
6591
6660
  return base;
6592
6661
  }
6662
+ const credential = await this.#session.credential({ allowBrowser: false }).catch(() => void 0);
6663
+ if (credential === void 0) return { ...base, connected: false };
6593
6664
  try {
6594
- const credential = await this.#session.credential({
6595
- allowBrowser: false
6596
- });
6597
6665
  const details = await enrichInspection({
6598
6666
  attribution,
6599
6667
  client: this.#client(),
@@ -6606,16 +6674,24 @@ var init_route33_runtime = __esm({
6606
6674
  return base;
6607
6675
  }
6608
6676
  }
6677
+ /**
6678
+ * Lists the models a key on this budget may be limited to. Never opens a
6679
+ * browser; an organisation-level (personal) catalog needs the `models:read`
6680
+ * grant, so sessions signed in before that grant reject here.
6681
+ * @param scope - The budget being configured.
6682
+ * @returns Key-facing model ids with their readable names.
6683
+ */
6684
+ async catalogModelChoices(scope) {
6685
+ const credential = await this.#session.credential({ allowBrowser: false });
6686
+ return this.#client().listModelChoices(credential, scope);
6687
+ }
6609
6688
  /**
6610
6689
  * @param scope - The budget being configured. Omit to discover models for the current key.
6611
6690
  * @returns The management catalog for a budget, or the current key's gateway catalog.
6612
6691
  */
6613
6692
  async catalogModelIds(scope) {
6614
6693
  if (scope !== void 0) {
6615
- const credential = await this.#session.credential({
6616
- allowBrowser: false
6617
- });
6618
- return this.#client().listModelIds(credential, scope);
6694
+ return (await this.catalogModelChoices(scope)).map(({ id }) => id);
6619
6695
  }
6620
6696
  const workspace = await this.storedReusableKey();
6621
6697
  const personal = workspace === void 0 ? await this.#storedPersonalKey() : void 0;
@@ -6624,7 +6700,8 @@ var init_route33_runtime = __esm({
6624
6700
  const credential = await this.#session.credential({
6625
6701
  allowBrowser: false
6626
6702
  });
6627
- return this.#client().listModelIds(credential, {});
6703
+ const choices = await this.#client().listModelChoices(credential, {});
6704
+ return choices.map(({ id }) => id);
6628
6705
  }
6629
6706
  return gatewayModelIds({
6630
6707
  baseURL: readEnvBaseUrl() ?? DEFAULT_BASE_URL,
@@ -6705,6 +6782,29 @@ var init_route33_runtime = __esm({
6705
6782
  const key = keys.find((item) => item.id === keyId);
6706
6783
  return key === void 0 ? void 0 : { allowedModels: key.allowed_models };
6707
6784
  }
6785
+ /** V1 captures only the choice, not the plan; read only that owner's policy.
6786
+ * @param choice - The selected budget and its active organisation.
6787
+ * @returns The effective EUR cap, if the owner has a readable allowance.
6788
+ */
6789
+ async ownerBudgetCap(choice) {
6790
+ const token = await this.#session.credential({ allowBrowser: false });
6791
+ const subject = this.#subject(token);
6792
+ const client = this.#client();
6793
+ if (choice.kind === "personal") {
6794
+ const policy = await client.listBudgetPolicy(
6795
+ token,
6796
+ subject,
6797
+ choice.orgId
6798
+ );
6799
+ return policy.cap ?? void 0;
6800
+ }
6801
+ const budgets = await client.listProjectBudgets(
6802
+ token,
6803
+ subject,
6804
+ choice.orgId
6805
+ );
6806
+ return budgets.data.find((row) => row.project_id === choice.projectId)?.cap;
6807
+ }
6708
6808
  #client() {
6709
6809
  const client = this.#options.management.client;
6710
6810
  if (typeof client !== "function") {
@@ -6835,8 +6935,8 @@ var init_unattributed_prompt_gate = __esm({
6835
6935
  "src/v1-entry/unattributed-prompt-gate/unattributed-prompt-gate.ts"() {
6836
6936
  "use strict";
6837
6937
  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.";
6938
+ CONNECTION_COPY = "To sign in, run /connect and choose Route 33.";
6939
+ ATTRIBUTION_COPY = "This folder has no Route 33 budget; open /r33 and choose Change budget.";
6840
6940
  createUnattributedPromptGate = ({ directory, isConnected, outsideWorktree }) => async (input) => {
6841
6941
  if (input.model?.providerID !== "route_33") return Promise.resolve();
6842
6942
  if (!await isConnected()) throw new Error(CONNECTION_COPY);
@@ -7026,6 +7126,9 @@ var drainPages = async (fetchPage) => {
7026
7126
  // src/management/index.ts
7027
7127
  init_management_error2();
7028
7128
 
7129
+ // src/management/key-read-operations/key-read-operations.ts
7130
+ init_adapters();
7131
+
7029
7132
  // src/contract/management-keys/parse-api-key/parse-api-key.ts
7030
7133
  init_adapters();
7031
7134
  init_predicates();
@@ -7053,7 +7156,7 @@ var parseApiKey = (value) => {
7053
7156
  name: field("name"),
7054
7157
  org_id: field("org_id"),
7055
7158
  ownership_type: value["ownership_type"],
7056
- ...typeof value["owner_user_id"] === "string" ? { owner_user_id: value["owner_user_id"] } : {},
7159
+ ...isNullableString(value["user_id"]) ? { user_id: value["user_id"] } : {},
7057
7160
  project_id: value["project_id"],
7058
7161
  revoked: value["revoked"] === true,
7059
7162
  status
@@ -7313,6 +7416,18 @@ var keyReadOperations = (call) => {
7313
7416
  url.searchParams.set("cursor", cursor);
7314
7417
  return new Request(url, request);
7315
7418
  };
7419
+ const parsePage = (page) => {
7420
+ const collection = parseCollection(page, (row) => row);
7421
+ const data = collection.data.flatMap((row) => {
7422
+ try {
7423
+ return [parseApiKey(row)];
7424
+ } catch (error) {
7425
+ if (error instanceof ContractParseError) return [];
7426
+ throw error;
7427
+ }
7428
+ });
7429
+ return { ...collection, data };
7430
+ };
7316
7431
  return {
7317
7432
  get: async (accessToken, id, orgId) => parseApiKey(
7318
7433
  await call(
@@ -7327,7 +7442,7 @@ var keyReadOperations = (call) => {
7327
7442
  (cursor) => call(accessToken, orgId, (client) => {
7328
7443
  if (cursor !== "") client.use({ onRequest: withCursor(cursor) });
7329
7444
  return client.GET("/api/v1/api-keys", {});
7330
- }).then((page) => parseCollection(page, parseApiKey))
7445
+ }).then(parsePage)
7331
7446
  )
7332
7447
  };
7333
7448
  };
@@ -7391,31 +7506,63 @@ var keyWriteOperations = (call) => ({
7391
7506
  )
7392
7507
  });
7393
7508
 
7394
- // src/management/sdk-management-keys/exposed-catalog-ids/exposed-catalog-ids.ts
7509
+ // src/management/exposed-catalog-models/exposed-catalog-models.ts
7395
7510
  init_adapters();
7396
7511
  init_predicates();
7397
- var exposedCatalogIds = async (readPage) => {
7398
- const ids = /* @__PURE__ */ new Set();
7512
+
7513
+ // src/management/exposed-catalog-models/catalog-row-choices/catalog-row-choices.ts
7514
+ init_adapters();
7515
+ init_predicates();
7516
+
7517
+ // src/management/client-model-id/client-model-id.ts
7518
+ var clientModelId = (offeringId) => {
7519
+ const [provider, region, scope, vendor, ...modelParts] = offeringId.split(":");
7520
+ const slugParts = modelParts.at(-1) === "zdr" ? modelParts.slice(0, -1) : modelParts;
7521
+ const parts = [provider, region, scope, vendor, slugParts.join(":")];
7522
+ return parts.some((part) => part === void 0 || part === "") || /[\s,]/u.test(offeringId) ? void 0 : `${vendor ?? ""}/${slugParts.join(":")}`;
7523
+ };
7524
+
7525
+ // src/management/exposed-catalog-models/catalog-row-choices/catalog-row-choices.ts
7526
+ var catalogRowChoices = (row) => {
7527
+ if (!isRecord(row) || typeof row.id !== "string" || !row.id.trim() || typeof row.status !== "string")
7528
+ throw new ContractParseError("invalid model catalog item");
7529
+ if (row.status !== "exposed" || !Array.isArray(row.offerings)) return [];
7530
+ const label = typeof row.name === "string" && row.name.trim() !== "" ? row.name.trim() : void 0;
7531
+ return row.offerings.flatMap((offering) => {
7532
+ if (!isRecord(offering) || typeof offering.id !== "string" || offering.enabled !== true)
7533
+ return [];
7534
+ const id = clientModelId(offering.id);
7535
+ return id === void 0 ? [] : [{ id, name: label ?? id }];
7536
+ });
7537
+ };
7538
+
7539
+ // src/management/exposed-catalog-models/exposed-catalog-models.ts
7540
+ var exposedCatalogModels = async (readPage) => {
7541
+ const readRows = async (offset2) => {
7542
+ const page = await readPage(offset2);
7543
+ if (!isRecord(page) || !Array.isArray(page.models) || page.offset !== offset2 || typeof page.total !== "number" || !Number.isSafeInteger(page.total) || page.total < 0) {
7544
+ throw new ContractParseError("invalid model catalog page");
7545
+ }
7546
+ return { rows: page.models, total: page.total };
7547
+ };
7548
+ const names = /* @__PURE__ */ new Map();
7399
7549
  let offset = 0;
7400
7550
  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");
7551
+ const { rows, total } = await readRows(offset);
7552
+ for (const { id, name } of rows.flatMap(catalogRowChoices)) {
7553
+ names.set(id, name);
7404
7554
  }
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));
7555
+ offset += rows.length;
7556
+ if (offset >= total || rows.length === 0) break;
7413
7557
  }
7558
+ return [...names].map(([id, name]) => ({ id, name })).sort(
7559
+ (left, right) => left.name.localeCompare(right.name) || left.id.localeCompare(right.id)
7560
+ );
7414
7561
  };
7415
7562
 
7416
7563
  // src/management/model-catalog-operations/model-catalog-operations.ts
7417
7564
  var modelCatalogOperations = (call) => ({
7418
- listModelIds: (token, { orgId, projectId }) => exposedCatalogIds(
7565
+ listModelChoices: (token, { orgId, projectId }) => exposedCatalogModels(
7419
7566
  (offset) => call(token, orgId, (client) => {
7420
7567
  const query = { offset };
7421
7568
  if (projectId !== void 0)
@@ -7476,6 +7623,30 @@ import {
7476
7623
  createRoute33Client,
7477
7624
  Route33SdkError
7478
7625
  } from "@r-33/sdk";
7626
+
7627
+ // src/management/sdk-management-call/rejection-of/rejection-of.ts
7628
+ init_predicates();
7629
+ var REFUSED = 422;
7630
+ var REJECTION_MAX_LENGTH = 200;
7631
+ var CONTROL = /\p{Cc}+/gu;
7632
+ var SECRET_PREFIXES = ["r33_", "eyj", "bearer "];
7633
+ var OPAQUE_MIN_LENGTH = 20;
7634
+ var rejectionOf = (outcome) => {
7635
+ const body = outcome.error;
7636
+ if (outcome.response?.status !== REFUSED || !isRecord(body)) return void 0;
7637
+ const raw = body["error"];
7638
+ if (typeof raw !== "string" || raw.length > REJECTION_MAX_LENGTH) {
7639
+ return void 0;
7640
+ }
7641
+ const sentence = raw.replaceAll(CONTROL, " ").replaceAll(/\s+/gu, " ").trim();
7642
+ const lower = sentence.toLowerCase();
7643
+ const secretShaped = SECRET_PREFIXES.some((prefix) => lower.includes(prefix)) || lower.split(" ").some(
7644
+ (word) => word.length >= OPAQUE_MIN_LENGTH && /\d/u.test(word) && /[a-z]/u.test(word)
7645
+ );
7646
+ return sentence === "" || secretShaped ? void 0 : sentence;
7647
+ };
7648
+
7649
+ // src/management/sdk-management-call/sdk-management-call.ts
7479
7650
  var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
7480
7651
  var ACTIVE_ORG_HEADER = "X-Active-Org-Id";
7481
7652
  var createSdkCall = (options) => {
@@ -7522,9 +7693,13 @@ var createSdkCall = (options) => {
7522
7693
  const outcome = await run(callClient(accessToken, activeOrgId));
7523
7694
  const code = outcome.response?.status;
7524
7695
  if (code === void 0 || code < 200 || code >= 300) {
7696
+ const rejection = rejectionOf(outcome);
7525
7697
  throw new ManagementError(
7526
7698
  code === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
7527
- { statusCode: code }
7699
+ {
7700
+ ...rejection === void 0 ? {} : { rejection },
7701
+ statusCode: code
7702
+ }
7528
7703
  );
7529
7704
  }
7530
7705
  return outcome.data;
@@ -7641,13 +7816,12 @@ var selectFromDialog = async (api, input) => new Promise((resolve2) => {
7641
7816
  init_create_route33_plugin2();
7642
7817
 
7643
7818
  // src/v2-entry/format-inspect-reply/format-inspect-reply.ts
7644
- var formatInspectReply = (inspection) => {
7645
- const lines = [];
7819
+ var formatInspectReply = (inspection, budgetAction) => {
7646
7820
  const { attribution, budget, key } = inspection;
7647
7821
  if (attribution === void 0) {
7648
- return "Route 33 is not connected in this folder \u2014 run /connect or /r33 to set a budget.";
7822
+ 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
7823
  }
7650
- const { organisationName, projectName } = key ?? {};
7824
+ const { organisationName, projectName } = { ...key };
7651
7825
  let label;
7652
7826
  let keyScope;
7653
7827
  switch (attribution.kind) {
@@ -7665,7 +7839,7 @@ var formatInspectReply = (inspection) => {
7665
7839
  }
7666
7840
  }
7667
7841
  const cap = budget === void 0 ? "" : [" \u2014 cap", budget.amount, budget.currency].filter((part) => part !== null).join(" ");
7668
- lines.push(`Budget: ${label}${cap}`);
7842
+ const lines = [`Budget: ${label}${cap}`];
7669
7843
  if (key !== void 0) {
7670
7844
  const scope = keyScope === "" ? "" : ` on ${keyScope}`;
7671
7845
  lines.push(`Key: ${key.name}${scope}`);
@@ -7690,13 +7864,16 @@ var parseR33Subcommand = (promptText) => {
7690
7864
  };
7691
7865
 
7692
7866
  // src/v2-entry/r33-command/r33-command.ts
7867
+ var SIGN_IN_COPY = "To sign in, run /connect and choose Route 33.";
7693
7868
  var executeR33Command = async (input) => {
7694
7869
  const subcommand = parseR33Subcommand(input.promptText);
7695
7870
  if (input.handlers === void 0) {
7696
- return "Route 33 is not connected in this folder. Run /connect, choose Route 33, and follow the steps.";
7871
+ return SIGN_IN_COPY;
7697
7872
  }
7873
+ const budgetAction = input.budgetAction ?? "Change budget";
7698
7874
  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).";
7875
+ const { connected } = await input.handlers["inspect-session"]();
7876
+ return connected ? `To assign a budget, open /r33 and choose ${budgetAction}.` : SIGN_IN_COPY;
7700
7877
  }
7701
7878
  switch (subcommand) {
7702
7879
  case "rotate": {
@@ -7705,14 +7882,18 @@ var executeR33Command = async (input) => {
7705
7882
  }
7706
7883
  case "logout": {
7707
7884
  await input.handlers["logout"]();
7708
- return "Logged out of Route 33 \u2014 the next OpenCode start signs in again.";
7885
+ return `Logged out of Route 33. ${SIGN_IN_COPY}`;
7709
7886
  }
7710
7887
  case "reset": {
7711
7888
  await input.handlers["reset-attribution"]();
7712
- return "Route 33 attribution cleared. Run /connect, choose Route 33, and assign a budget again.";
7889
+ const { connected } = await input.handlers["inspect-session"]();
7890
+ return connected ? `Budget cleared; open /r33 and choose ${budgetAction}.` : `Budget cleared. ${SIGN_IN_COPY}`;
7713
7891
  }
7714
7892
  default: {
7715
- return formatInspectReply(await input.handlers["inspect-session"]());
7893
+ return formatInspectReply(
7894
+ await input.handlers["inspect-session"](),
7895
+ budgetAction
7896
+ );
7716
7897
  }
7717
7898
  }
7718
7899
  };
@@ -7862,18 +8043,24 @@ var alertFromDialog = (api, input) => new Promise((resolve2) => {
7862
8043
  var ATTRIBUTION_FIELD_KEY = "attribution";
7863
8044
 
7864
8045
  // 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;
8046
+ var readBudgetCap = (answer, maximum) => {
8047
+ const value = answer["budget_cap"] ?? "";
7868
8048
  if (typeof value !== "string" && typeof value !== "number") {
7869
8049
  throw new TypeError("Budget cap must be a number or unlimited");
7870
8050
  }
7871
- if (typeof value === "string" && (value.trim() === "" || value.trim().toLowerCase() === "unlimited")) {
8051
+ if (typeof value === "string" && ["", "unlimited"].includes(value.trim().toLowerCase())) {
7872
8052
  return null;
7873
8053
  }
7874
8054
  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");
8055
+ if (!Number.isFinite(parsed) || parsed <= 0) {
8056
+ throw new RangeError("Budget cap must be a finite positive number");
8057
+ }
8058
+ if (maximum !== void 0 && parsed > maximum) {
8059
+ throw new RangeError(
8060
+ `Entered ${String(value)} EUR; the selected budget allows at most ${String(maximum)} EUR.`
8061
+ );
8062
+ }
8063
+ return parsed;
7877
8064
  };
7878
8065
 
7879
8066
  // src/tui-entry/dialog-prompt/dialog-prompt.ts
@@ -7904,6 +8091,47 @@ var promptFromDialog = (api, input) => new Promise((resolve2) => {
7904
8091
  );
7905
8092
  });
7906
8093
 
8094
+ // src/tui-entry/v1-key-prompts/v1-select-models/v1-select-models.ts
8095
+ var ALL = /* @__PURE__ */ Symbol("All models");
8096
+ var DONE = /* @__PURE__ */ Symbol("Done");
8097
+ var TITLE = "Which models may this key use?";
8098
+ var v1SelectModels = async (api, models) => {
8099
+ const ticked = /* @__PURE__ */ new Set();
8100
+ const view = (cursor2) => {
8101
+ const count = String(ticked.size);
8102
+ const done = {
8103
+ title: `Done \u2014 use the ${count} selected model${ticked.size === 1 ? "" : "s"}`,
8104
+ value: DONE
8105
+ };
8106
+ const options = [
8107
+ ...ticked.size === 0 ? [] : [done],
8108
+ { title: "All models (inherit)", value: ALL },
8109
+ ...models.map(({ id, name }) => ({
8110
+ description: id,
8111
+ title: `${ticked.has(id) ? "[x]" : "[ ]"} ${name}`,
8112
+ value: id
8113
+ })),
8114
+ { title: "Back", value: BACK }
8115
+ ];
8116
+ return {
8117
+ ...cursor2 === void 0 ? {} : { current: cursor2 },
8118
+ options,
8119
+ title: ticked.size === 0 ? TITLE : `${TITLE} \u2014 ${count} selected`
8120
+ };
8121
+ };
8122
+ let cursor;
8123
+ for (; ; ) {
8124
+ const picked = await selectFromDialog(api, view(cursor));
8125
+ if (picked === void 0 || picked === BACK) return picked;
8126
+ if (picked === ALL) return [];
8127
+ if (picked === DONE) {
8128
+ return models.map(({ id }) => id).filter((id) => ticked.has(id));
8129
+ }
8130
+ if (!ticked.delete(picked)) ticked.add(picked);
8131
+ cursor = picked;
8132
+ }
8133
+ };
8134
+
7907
8135
  // src/tui-entry/v1-key-prompts/v1-key-prompts.ts
7908
8136
  var EXPIRY_OPTIONS = [
7909
8137
  { title: "30 days", value: "30" },
@@ -7924,12 +8152,21 @@ var v1KeyPrompts = async (deps) => {
7924
8152
  "e.g. opencode-desk, or "
7925
8153
  );
7926
8154
  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 });
8155
+ const askCap = async () => {
8156
+ const title = deps.maximum === void 0 ? "Monthly budget cap in EUR" : `Monthly budget cap in EUR (max ${String(deps.maximum)})`;
8157
+ for (; ; ) {
8158
+ const text = await prompt(title, "blank = unlimited, or ");
8159
+ if (typeof text !== "string") return text;
8160
+ try {
8161
+ return readBudgetCap({ budget_cap: text }, deps.maximum);
8162
+ } catch (error) {
8163
+ if (!(error instanceof RangeError)) throw error;
8164
+ await alertFromDialog(deps.api, { title, message: error.message });
8165
+ }
8166
+ }
8167
+ };
8168
+ const cap = await askCap();
8169
+ if (cap === BACK || cap === void 0) return cap;
7933
8170
  const description = await prompt("Description (optional)", "");
7934
8171
  if (typeof description !== "string") return description;
7935
8172
  const expiry = await selectFromDialog(deps.api, {
@@ -7937,17 +8174,10 @@ var v1KeyPrompts = async (deps) => {
7937
8174
  title: "When should the key expire?"
7938
8175
  });
7939
8176
  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;
8177
+ const allowedModels = await v1SelectModels(deps.api, deps.models);
8178
+ if (typeof allowedModels !== "object") return allowedModels;
7949
8179
  return {
7950
- ...allowedModels === "all" ? {} : { allowedModels: [allowedModels] },
8180
+ ...allowedModels.length === 0 ? {} : { allowedModels },
7951
8181
  description,
7952
8182
  expiryDays: Number(expiry),
7953
8183
  maxBudgetAmount: cap,
@@ -7973,8 +8203,11 @@ var finishConnect = async (deps) => {
7973
8203
  }
7974
8204
  };
7975
8205
  const mint = async () => {
7976
- const modelIds = await runtime.catalogModelIds(picked.choice).catch(() => []);
7977
- const extras = await v1KeyPrompts({ api: deps.api, modelIds });
8206
+ const [models, maximum] = await Promise.all([
8207
+ runtime.catalogModelChoices(picked.choice).catch(() => []),
8208
+ runtime.ownerBudgetCap(picked.choice).catch(() => void 0)
8209
+ ]);
8210
+ const extras = await v1KeyPrompts({ api: deps.api, maximum, models });
7978
8211
  if (typeof extras !== "object") return extras;
7979
8212
  await runtime.mintWorkspaceKey(
7980
8213
  picked.choice,
@@ -8274,36 +8507,58 @@ init_attribution();
8274
8507
 
8275
8508
  // src/tui-entry/v2-connect-copy/v2-connect-copy.ts
8276
8509
  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.",
8510
+ busyCreating: "Setting up your Route 33 key \u2014 please wait\u2026",
8511
+ busyPreparing: "Loading this budget's key options\u2026",
8512
+ busyTitle: "Route 33",
8513
+ dismissed: "Route 33 is not set up for this folder; open /r33 and choose Attribute.",
8514
+ expired: "Route 33 setup expired; open /r33 and choose Attribute.",
8515
+ manualFallback: "Guided Route 33 setup is unavailable; run /connect and choose Route 33.",
8516
+ manualPath: "Open /r33 and choose Attribute.",
8281
8517
  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.",
8518
+ noBudgetsMulti: "No budgets are available here; press Enter to pick another organisation.",
8519
+ noBudgetsSingle: "No Route 33 budgets are available here; ask an owner for a budget.",
8284
8520
  orgPickerTitle: "Which Route 33 organisation covers this folder?",
8285
8521
  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.",
8522
+ refusedRetry: "Change your answers and try again.",
8523
+ refusedTitle: "Route 33 \u2014 key not created",
8524
+ setupIncomplete: "Route 33 budget setup did not complete.",
8525
+ signInFailed: "Sign-in did not complete; run /connect and choose Route 33.",
8526
+ logoutFailed: "Route 33 could not log out; restart OpenCode and try again.",
8288
8527
  legacyKeyConverted: "Route 33 key converted \u2713 \u2014 signing in to mint a fresh key for this folder.",
8289
8528
  legacyKeyMessage: "A Route 33 key from a previous version was found in this folder. Convert it to your personal budget?",
8290
8529
  legacyKeyTitle: "Route 33 \u2014 key from a previous version",
8291
8530
  signInActions: "Finish the sign-in in your browser \u2014 press o to open it, c to copy the link.",
8292
8531
  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.",
8532
+ statusUnavailable: "Could not confirm Route 33 setup; open /r33 and choose Attribute.",
8533
+ stale: "That Route 33 option is no longer available; open /r33 and choose Attribute.",
8295
8534
  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."
8535
+ timedOut: "Route 33 setup timed out; open /r33 and choose Attribute."
8297
8536
  };
8298
8537
 
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."
8538
+ // src/tui-entry/v2-busy-dialog/v2-busy-dialog.ts
8539
+ init_abortable_sleep2();
8540
+ var withBusyDialog = async (dialog, copy, work, options = {}) => {
8541
+ const running = work();
8542
+ const settled = running.then(
8543
+ () => true,
8544
+ () => true
8545
+ );
8546
+ for (; ; ) {
8547
+ const dismissed = dialog.select({
8548
+ options: [{ disabled: true, title: copy.message, value: "busy" }],
8549
+ title: copy.title
8550
+ }).then(
8551
+ () => false,
8552
+ () => false
8553
+ );
8554
+ if (await Promise.race([settled, dismissed])) break;
8555
+ await abortableSleep(options.reopenDelayMs ?? 50);
8556
+ }
8557
+ try {
8558
+ dialog.clear();
8559
+ } catch {
8560
+ }
8561
+ return running;
8307
8562
  };
8308
8563
 
8309
8564
  // src/tui-entry/v2-outcome-copy/v2-outcome-copy.ts
@@ -8333,7 +8588,11 @@ var v2CompletionNotice = ({ dialog, expiryDays, keyName, label }) => () => dialo
8333
8588
  // src/tui-entry/v2-budget-picker/show-completion/show-completion.ts
8334
8589
  var showCompletion = (dialog, options, selection, extras) => {
8335
8590
  const label = options.find((option) => option.value === selection)?.label ?? selection;
8336
- const bound = extras[`existing_key:${selection}`];
8591
+ const text = (key) => {
8592
+ const value = extras[key];
8593
+ return typeof value === "string" ? value : void 0;
8594
+ };
8595
+ const bound = text(`existing_key:${selection}`);
8337
8596
  if (bound !== void 0 && bound !== "new") {
8338
8597
  void dialog.alert({
8339
8598
  title: "Route 33",
@@ -8343,21 +8602,54 @@ var showCompletion = (dialog, options, selection, extras) => {
8343
8602
  }
8344
8603
  void v2CompletionNotice({
8345
8604
  dialog,
8346
- expiryDays: extras["budget_expiry"],
8347
- keyName: extras["budget_name"] ?? "opencode",
8605
+ expiryDays: text("budget_expiry"),
8606
+ keyName: text("budget_name") ?? "opencode",
8348
8607
  label
8349
8608
  })();
8350
8609
  };
8351
8610
 
8611
+ // src/v2-entry/connect-copy/connect-copy.ts
8612
+ var CONNECT_COPY = {
8613
+ failFastClientId: "This Route 33 build has no OAuth client ID; reinstall it from the opencode-dist ref.",
8614
+ failFastWorktree: "To assign a Route 33 budget, open a Git repository.",
8615
+ selectionInvalid: "That Route 33 option is no longer available; open /r33 and choose Attribute.",
8616
+ signedInNextStep: "Signed in to Route 33; open /r33 and choose Attribute to assign a budget.",
8617
+ budgetSelected: "Budget selected but not assigned; open /r33 and choose Attribute to finish setup."
8618
+ };
8619
+ var KEY_FORM_COPY = {
8620
+ /** Prefix of a key the management API refused; its reason follows. */
8621
+ mintRefused: "Route 33 refused this key:",
8622
+ mintRefusedUnknown: "its settings are not allowed for this budget.",
8623
+ modelsNeedSignIn: "Choosing individual models needs a fresh Route 33 sign-in.",
8624
+ modelsUnavailable: "The model list is unavailable right now."
8625
+ };
8626
+
8627
+ // src/tui-entry/v2-budget-picker/answer-pass/read-pass-failure/read-pass-failure.ts
8628
+ var readPassFailure = (message) => {
8629
+ const start = message.indexOf(KEY_FORM_COPY.mintRefused);
8630
+ if (start !== -1) {
8631
+ return { kind: "refused", reason: message.slice(start).trim() };
8632
+ }
8633
+ return message.includes(CONNECT_COPY.budgetSelected) ? { kind: "budget-selected" } : { kind: "other" };
8634
+ };
8635
+
8352
8636
  // src/tui-entry/v2-budget-picker/answer-pass/answer-pass.ts
8353
8637
  var answerPass = async (deps) => {
8354
- let second;
8638
+ const failureOf = (settled2) => readPassFailure(settled2.kind === "failed" ? settled2.message ?? "" : "");
8639
+ let settled;
8355
8640
  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"
8641
+ settled = await withBusyDialog(deps.dialog, deps.busy, async () => {
8642
+ const started = await deps.connect({
8643
+ answer: { [deps.form.key]: deps.selection, ...deps.extras },
8644
+ integrationID: "route33",
8645
+ location: deps.locationInput,
8646
+ methodID: "browser"
8647
+ });
8648
+ const result = await deps.pollTerminal(started.data.attemptID);
8649
+ if (failureOf(result).kind === "budget-selected") {
8650
+ await deps.onBudgetSelected?.();
8651
+ }
8652
+ return result;
8361
8653
  });
8362
8654
  } catch (error) {
8363
8655
  deps.toast({
@@ -8366,49 +8658,91 @@ var answerPass = async (deps) => {
8366
8658
  });
8367
8659
  return "incomplete";
8368
8660
  }
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
- }
8661
+ if (settled.kind === "complete") {
8662
+ showCompletion(deps.dialog, deps.options, deps.selection, deps.extras);
8663
+ deps.toast({ message: V2_CONNECT_COPY.success, variant: "success" });
8664
+ return "complete";
8665
+ }
8666
+ const failure = failureOf(settled);
8667
+ if (failure.kind === "budget-selected") return "budget-selected";
8668
+ if (failure.kind !== "refused") {
8377
8669
  deps.toast(v2OutcomeCopy(settled, V2_CONNECT_COPY.setupIncomplete));
8378
8670
  return "incomplete";
8379
8671
  }
8380
- showCompletion(deps.dialog, deps.options, deps.selection, deps.extras);
8381
- deps.toast({ message: V2_CONNECT_COPY.success, variant: "success" });
8382
- return "complete";
8672
+ await deps.dialog.alert({
8673
+ message: `${failure.reason} ${V2_CONNECT_COPY.refusedRetry}`,
8674
+ title: V2_CONNECT_COPY.refusedTitle
8675
+ }).catch(() => void 0);
8676
+ return "refused";
8383
8677
  };
8384
8678
 
8385
8679
  // src/v2-entry/connect-form/connect-form.ts
8386
8680
  var ATTRIBUTION_FIELD_KEY2 = "attribution";
8387
8681
  var ORGANISATION_FIELD_KEY = "organisation";
8388
8682
  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"
8683
+ var BUDGET_CAP_MAX_FIELD_KEY = "budget_cap_max";
8684
+ var PREPARED_BUDGET_FIELD_KEY = "prepared_budget";
8685
+ var ALL_MODELS_VALUE = "all";
8686
+ var ALL_MODELS_LABEL = "All models (inherit)";
8687
+
8688
+ // src/tui-entry/v2-budget-picker/select-many/select-many.ts
8689
+ var DONE2 = "\0done";
8690
+ var selectMany = async (dialog, input) => {
8691
+ const values = input.options.map(({ value }) => value);
8692
+ const ticked = new Set(
8693
+ (input.selected ?? []).filter((value) => values.includes(value))
8403
8694
  );
8404
- return browserMethods?.flatMap((entry) => entry.form ?? []) ?? [];
8695
+ const view = (cursor2) => {
8696
+ const count = String(ticked.size);
8697
+ const done = {
8698
+ title: `Done \u2014 use the ${count} selected model${ticked.size === 1 ? "" : "s"}`,
8699
+ value: DONE2
8700
+ };
8701
+ return {
8702
+ ...cursor2 === void 0 ? {} : { current: cursor2 },
8703
+ options: [
8704
+ ...ticked.size === 0 ? [] : [done],
8705
+ input.all,
8706
+ ...input.options.map((row) => ({
8707
+ ...row,
8708
+ title: `${ticked.has(row.value) ? "[x]" : "[ ]"} ${row.title}`
8709
+ }))
8710
+ ],
8711
+ title: ticked.size === 0 ? input.title : `${input.title} \u2014 ${count} selected`
8712
+ };
8713
+ };
8714
+ let cursor;
8715
+ for (; ; ) {
8716
+ const picked = await selectWithBack(dialog, view(cursor));
8717
+ if (typeof picked !== "string" || picked === input.all.value) return picked;
8718
+ if (picked === DONE2) return values.filter((value) => ticked.has(value));
8719
+ if (!values.includes(picked)) return void 0;
8720
+ if (!ticked.delete(picked)) ticked.add(picked);
8721
+ cursor = picked;
8722
+ }
8723
+ };
8724
+
8725
+ // src/v2-entry/v2-key-prompts/ask-models/ask-models.ts
8726
+ var askModels = async (dialog, input) => {
8727
+ const toRow = ({ description, label, value }) => ({
8728
+ ...description === void 0 ? {} : { description },
8729
+ title: label,
8730
+ value
8731
+ });
8732
+ const picked = await selectMany(dialog, {
8733
+ all: toRow(input.all),
8734
+ options: input.models.map(toRow),
8735
+ selected: input.previous?.split(",") ?? [],
8736
+ title: input.title
8737
+ });
8738
+ return typeof picked === "object" ? picked.join(",") : picked;
8405
8739
  };
8406
8740
 
8407
8741
  // src/v2-entry/v2-key-prompts/ask-field/ask-field.ts
8408
8742
  var askField = async (dialog, field, previous) => {
8409
8743
  const title = field.title ?? field.key;
8410
- const options = field.options ?? [];
8411
- if (options.length === 0) {
8744
+ const [first, ...rest] = field.options ?? [];
8745
+ if (first === void 0) {
8412
8746
  const text = await dialog.prompt({
8413
8747
  description: "Enter /back to return to the previous step, or Esc to cancel.",
8414
8748
  placeholder: field.placeholder,
@@ -8417,11 +8751,21 @@ var askField = async (dialog, field, previous) => {
8417
8751
  });
8418
8752
  return text === "/back" ? BACK : text;
8419
8753
  }
8754
+ const options = [first, ...rest];
8755
+ if (field.type === "multiselect") {
8756
+ return askModels(dialog, {
8757
+ all: { label: ALL_MODELS_LABEL, value: ALL_MODELS_VALUE },
8758
+ models: options,
8759
+ previous,
8760
+ title
8761
+ });
8762
+ }
8420
8763
  const selected = await selectWithBack(dialog, {
8421
8764
  current: options.some(({ value }) => value === previous) ? previous : void 0,
8422
- options: options.map((option) => ({
8423
- title: option.label,
8424
- value: option.value
8765
+ options: options.map(({ description, label, value }) => ({
8766
+ ...description === void 0 ? {} : { description },
8767
+ title: label,
8768
+ value
8425
8769
  })),
8426
8770
  title
8427
8771
  });
@@ -8433,6 +8777,11 @@ var askField = async (dialog, field, previous) => {
8433
8777
  // src/v2-entry/v2-key-prompts/v2-key-prompts.ts
8434
8778
  var v2KeyPrompts = async (deps) => {
8435
8779
  const answer = {};
8780
+ const limit = deps.fields.find(({ key }) => key === BUDGET_CAP_MAX_FIELD_KEY);
8781
+ const maximum = readBudgetCap({ budget_cap: limit?.placeholder }) ?? void 0;
8782
+ const questions = deps.fields.filter(
8783
+ ({ key }) => key !== BUDGET_CAP_MAX_FIELD_KEY && key !== PREPARED_BUDGET_FIELD_KEY
8784
+ );
8436
8785
  const collect = async (field) => {
8437
8786
  for (; ; ) {
8438
8787
  const value = await askField(
@@ -8443,7 +8792,7 @@ var v2KeyPrompts = async (deps) => {
8443
8792
  if (value === BACK || value === void 0) return value;
8444
8793
  if (field.key === BUDGET_CAP_FIELD_KEY) {
8445
8794
  try {
8446
- readBudgetCap({ [field.key]: value });
8795
+ readBudgetCap({ [field.key]: value }, maximum);
8447
8796
  } catch (error) {
8448
8797
  if (!(error instanceof RangeError)) throw error;
8449
8798
  await deps.dialog.alert({
@@ -8457,8 +8806,8 @@ var v2KeyPrompts = async (deps) => {
8457
8806
  }
8458
8807
  };
8459
8808
  let index = 0;
8460
- while (index < deps.fields.length) {
8461
- const field = deps.fields[index];
8809
+ while (index < questions.length) {
8810
+ const field = questions[index];
8462
8811
  if (!field) break;
8463
8812
  const value = await collect(field);
8464
8813
  if (value === BACK && index > 0) {
@@ -8470,101 +8819,133 @@ var v2KeyPrompts = async (deps) => {
8470
8819
  answer[field.key] = value;
8471
8820
  index++;
8472
8821
  }
8473
- return answer;
8822
+ return Object.fromEntries(
8823
+ questions.flatMap((field) => {
8824
+ const value = answer[field.key];
8825
+ if (value === void 0) return [];
8826
+ if (field.type !== "multiselect") return [[field.key, value]];
8827
+ return value === ALL_MODELS_VALUE ? [] : [[field.key, value.split(",")]];
8828
+ })
8829
+ );
8474
8830
  };
8475
8831
 
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
- }
8832
+ // src/tui-entry/v2-budget-picker/answer-step/collect-key-answers/collect-key-answers.ts
8833
+ var collectKeyAnswers = async (deps) => {
8834
+ const { dialog, fields } = deps;
8835
+ const selector = fields.find(
8836
+ (field) => field.key === `existing_key:${deps.selection}`
8837
+ );
8838
+ const create = () => v2KeyPrompts({
8839
+ dialog,
8840
+ draft: deps.draft,
8841
+ fields: fields.filter(
8842
+ (field) => !field.key.startsWith("existing_key:") && field.key !== "rotation_confirmation"
8843
+ )
8844
+ });
8499
8845
  const confirmBinding = async (key) => {
8500
8846
  const field = fields.find((row) => row.key === "rotation_confirmation");
8501
- if (field?.options?.some((option) => option.value === key) !== true)
8847
+ if (field?.options?.some((option) => option.value === key) !== true) {
8502
8848
  return {};
8849
+ }
8503
8850
  if (field.title === void 0) return void 0;
8504
- const consent = await deps.dialog.confirm({
8851
+ const consent = await dialog.confirm({
8505
8852
  title: "Rotate key? (No: Back to key selection)",
8506
8853
  message: field.title
8507
8854
  });
8508
8855
  if (consent === false) return BACK;
8509
8856
  return consent ? { rotation_confirmation: key } : void 0;
8510
8857
  };
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, {
8858
+ if (!selector) return create();
8859
+ for (; ; ) {
8860
+ const selection = await selectWithBack(dialog, {
8524
8861
  title: selector.title ?? "Choose a key",
8525
8862
  options: (selector.options ?? []).map((option) => ({
8526
8863
  title: option.label,
8527
8864
  value: option.value
8528
8865
  }))
8529
8866
  });
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";
8867
+ if (typeof selection !== "string") return selection;
8868
+ const answers = selection === "new" ? await create() : await confirmBinding(selection);
8869
+ if (answers === BACK) continue;
8870
+ if (answers === void 0 || selection === "new") return answers;
8871
+ return { [selector.key]: selection, ...answers };
8548
8872
  }
8549
- const outcome = await answerPass({
8873
+ };
8874
+
8875
+ // src/tui-entry/v2-integration-surface/v2-integration-surface.ts
8876
+ var v2IntegrationSurface = (context) => context.client?.integration ?? context.client?.api?.integration;
8877
+
8878
+ // src/v2-entry/v2-form-fields/v2-form-fields.ts
8879
+ var v2FormFields = async (context) => {
8880
+ const get = v2IntegrationSurface(context)?.get;
8881
+ if (get === void 0) return [];
8882
+ const integration = await get({
8883
+ integrationID: "route33",
8884
+ ...context.location === void 0 ? {} : { location: { directory: context.location.directory } }
8885
+ }).catch(() => void 0);
8886
+ const browserMethods = integration?.data.methods?.filter(
8887
+ (entry) => entry.type === "oauth" && entry.id === "browser"
8888
+ );
8889
+ return browserMethods?.flatMap((entry) => entry.form ?? []) ?? [];
8890
+ };
8891
+
8892
+ // src/tui-entry/v2-budget-picker/answer-step/prepare-key-fields/prepare-key-fields.ts
8893
+ var prepareKeyFields = async (deps) => {
8894
+ let registered = [];
8895
+ const outcome = await deps.prepare(async () => {
8896
+ registered = await v2FormFields(deps.context);
8897
+ });
8898
+ if (outcome !== "budget-selected") return void 0;
8899
+ const preparedFor = registered.find(
8900
+ (field) => field.key === PREPARED_BUDGET_FIELD_KEY
8901
+ )?.placeholder;
8902
+ const fields = registered.filter(
8903
+ (field) => field.key !== ATTRIBUTION_FIELD_KEY2 && field.key !== ORGANISATION_FIELD_KEY && field.key !== PREPARED_BUDGET_FIELD_KEY
8904
+ );
8905
+ if (fields.length === 0 || (preparedFor ?? deps.selection) !== deps.selection) {
8906
+ deps.toast({ message: V2_CONNECT_COPY.setupIncomplete, variant: "error" });
8907
+ return void 0;
8908
+ }
8909
+ return fields;
8910
+ };
8911
+
8912
+ // src/tui-entry/v2-budget-picker/answer-step/answer-step.ts
8913
+ var runAnswerStep = async (deps) => {
8914
+ const pass = (extras, message, onBudgetSelected) => answerPass({
8915
+ busy: { message, title: V2_CONNECT_COPY.busyTitle },
8550
8916
  connect: deps.connect,
8551
8917
  dialog: deps.dialog,
8552
8918
  extras,
8553
8919
  form: { key: deps.attributionFieldKey },
8554
8920
  locationInput: deps.locationInput,
8921
+ ...onBudgetSelected === void 0 ? {} : { onBudgetSelected },
8555
8922
  options: deps.budgetOptions,
8556
8923
  pollTerminal: deps.pollTerminal,
8557
8924
  selection: deps.selection,
8558
8925
  toast: deps.toast
8559
8926
  });
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";
8927
+ const fields = await prepareKeyFields({
8928
+ context: deps.context,
8929
+ prepare: (read) => pass({}, V2_CONNECT_COPY.busyPreparing, read),
8930
+ selection: deps.selection,
8931
+ toast: deps.toast
8932
+ });
8933
+ if (fields === void 0) return "done";
8934
+ for (; ; ) {
8935
+ const extras = await collectKeyAnswers({
8936
+ dialog: deps.dialog,
8937
+ draft: deps.draft,
8938
+ fields,
8939
+ selection: deps.selection
8940
+ });
8941
+ if (extras === BACK) return "back";
8942
+ if (extras === void 0) {
8943
+ deps.toast({ message: V2_CONNECT_COPY.dismissed });
8944
+ return "done";
8945
+ }
8946
+ const outcome = await pass(extras, V2_CONNECT_COPY.busyCreating);
8947
+ if (outcome !== "refused") return "done";
8566
8948
  }
8567
- return "done";
8568
8949
  };
8569
8950
 
8570
8951
  // src/tui-entry/v2-budget-picker/pick-budget/pick-budget.ts
@@ -8616,6 +8997,12 @@ var scopeBudgetOptions = (orgId, options) => orgId === void 0 ? options : option
8616
8997
  (option) => option.value.startsWith(orgSelectionPrefix(orgId))
8617
8998
  );
8618
8999
 
9000
+ // src/tui-entry/v2-budget-picker/show-no-budgets/show-no-budgets.ts
9001
+ var showNoBudgets = (dialog, multi) => dialog.alert({
9002
+ message: multi ? V2_CONNECT_COPY.noBudgetsMulti : V2_CONNECT_COPY.noBudgetsSingle,
9003
+ title: V2_CONNECT_COPY.noBudgetsTitle
9004
+ });
9005
+
8619
9006
  // src/tui-entry/v2-budget-picker/budget-round/budget-round.ts
8620
9007
  var runBudgetRound = async (deps) => {
8621
9008
  const multi = deps.orgs.length > 1;
@@ -8652,7 +9039,6 @@ var runBudgetRound = async (deps) => {
8652
9039
  context: deps.context,
8653
9040
  dialog: deps.dialog,
8654
9041
  locationInput: deps.locationInput,
8655
- multi,
8656
9042
  pollTerminal: deps.pollTerminal,
8657
9043
  selection,
8658
9044
  toast: deps.toast
@@ -8739,6 +9125,7 @@ var v2ConnectSurface = (context) => v2IntegrationSurface(context)?.oauth?.connec
8739
9125
 
8740
9126
  // src/tui-entry/v2-poll-terminal/v2-poll-terminal.ts
8741
9127
  init_abortable_sleep2();
9128
+ var FIRST_POLL_MS = 100;
8742
9129
  var createV2PollTerminal = ({
8743
9130
  locationInput,
8744
9131
  maxPolls = 600,
@@ -8748,7 +9135,7 @@ var createV2PollTerminal = ({
8748
9135
  }) => async (attemptID) => {
8749
9136
  let errors = 0;
8750
9137
  for (let poll = 0; poll < maxPolls; poll += 1) {
8751
- await abortableSleep(pollDelayMs);
9138
+ await abortableSleep(Math.min(pollDelayMs, FIRST_POLL_MS * 2 ** poll));
8752
9139
  try {
8753
9140
  const result = await status({
8754
9141
  attemptID,
@@ -8896,7 +9283,7 @@ var v2LegacyKeyGate = async ({
8896
9283
 
8897
9284
  // src/tui-entry/v2-autoconnect/v2-autoconnect.ts
8898
9285
  var v2Autoconnect = async (context, options = {}) => {
8899
- const directory = v2SetupDirectory(context);
9286
+ const directory = options.directory ?? v2SetupDirectory(context);
8900
9287
  if (directory === void 0) return;
8901
9288
  const unattributed = () => readAttribution({
8902
9289
  directory,
@@ -8929,8 +9316,21 @@ var v2Autoconnect = async (context, options = {}) => {
8929
9316
  // src/tui-entry/show-r33-menu/run-action/run-action.ts
8930
9317
  var runR33MenuAction = async (context, action, deps) => {
8931
9318
  try {
9319
+ const handlers = deps.handlers();
8932
9320
  const reply = await executeR33Command({
8933
- handlers: deps.handlers(),
9321
+ budgetAction: "Attribute",
9322
+ handlers: handlers && {
9323
+ ...handlers,
9324
+ "inspect-session": async () => {
9325
+ const inspection = await handlers["inspect-session"]();
9326
+ return inspection.connected || deps.signedIn === void 0 ? inspection : { ...inspection, connected: await deps.signedIn() };
9327
+ },
9328
+ logout: async () => {
9329
+ if (deps.logout === void 0) return handlers.logout();
9330
+ await deps.logout();
9331
+ await handlers.logout().catch(() => void 0);
9332
+ }
9333
+ },
8934
9334
  promptText: `/r33 ${action}`
8935
9335
  });
8936
9336
  context.ui.toast.show({ message: reply, variant: "info" });
@@ -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
  }
@@ -9007,58 +9407,6 @@ var v2AttributionForm = async (context) => {
9007
9407
  return v2AttributionField(integration?.data.methods);
9008
9408
  };
9009
9409
 
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
9410
  // src/tui-entry/v2-boot-matrix/v2-boot-matrix.ts
9063
9411
  var v2BootMatrix = async ({
9064
9412
  probe,
@@ -9125,6 +9473,46 @@ var v2BootSessionProbe = async (deps) => {
9125
9473
  return token !== void 0 ? "alive" : "dead";
9126
9474
  };
9127
9475
 
9476
+ // src/tui-entry/v2-server-logout/v2-server-logout.ts
9477
+ init_config();
9478
+ init_predicates();
9479
+
9480
+ // src/v2-entry/session-rpc/session-rpc.ts
9481
+ var ROUTE33_SESSION_RPC = {
9482
+ events: {},
9483
+ id: "route33",
9484
+ methods: {
9485
+ /** Ends the Route 33 session; answers `signedOut: true` once it is gone. */
9486
+ logout: {
9487
+ input: { additionalProperties: false, properties: {}, type: "object" },
9488
+ output: {
9489
+ additionalProperties: false,
9490
+ properties: { signedOut: { type: "boolean" } },
9491
+ required: ["signedOut"],
9492
+ type: "object"
9493
+ }
9494
+ }
9495
+ }
9496
+ };
9497
+
9498
+ // src/tui-entry/v2-server-logout/v2-server-logout.ts
9499
+ var v2ServerLogout = async (context) => {
9500
+ const { client, location } = context;
9501
+ const confirmed = await (async () => {
9502
+ if (location === void 0) return false;
9503
+ const answer = await client?.rpc?.(ROUTE33_SESSION_RPC).logout({}, { location: { directory: location.directory } });
9504
+ return isRecord(answer) && answer["signedOut"] === true;
9505
+ })().catch(() => false);
9506
+ if (!confirmed) {
9507
+ throw new GatewayCredentialError(V2_CONNECT_COPY.logoutFailed);
9508
+ }
9509
+ const integration = context.data?.location.integration;
9510
+ await Promise.resolve().then(() => {
9511
+ integration?.invalidate?.(location);
9512
+ return integration?.sync?.(location);
9513
+ }).catch(() => void 0);
9514
+ };
9515
+
9128
9516
  // src/tui-entry/v2-session-watch/v2-session-watch.ts
9129
9517
  init_abortable_sleep2();
9130
9518
  var watchV2SessionBecomeAlive = (deps) => {
@@ -9332,6 +9720,98 @@ var v2WizardControl = () => {
9332
9720
  };
9333
9721
  };
9334
9722
 
9723
+ // src/tui-entry/v2-route33-model-candidate/v2-route33-model-candidate.ts
9724
+ var v2Route33ModelCandidate = (model) => model.providerID === "route_33" && model.enabled !== false;
9725
+
9726
+ // src/tui-entry/v2-auto-select-target/v2-auto-select-target.ts
9727
+ var v2AutoSelectTarget = async (models, dialog) => {
9728
+ const candidates = models.filter(v2Route33ModelCandidate);
9729
+ if (candidates.length === 0) return void 0;
9730
+ const selected = await dialog.select({
9731
+ title: "Choose a Route 33 model",
9732
+ options: candidates.map(({ id, name }) => ({
9733
+ title: name ?? id,
9734
+ value: id
9735
+ }))
9736
+ });
9737
+ return candidates.find(({ id }) => id === selected);
9738
+ };
9739
+
9740
+ // src/tui-entry/v2-auto-select-model/v2-auto-select-model.ts
9741
+ var v2AutoSelectModel = async (context) => {
9742
+ const { ui, client, location } = context;
9743
+ const route = ui.router?.current();
9744
+ const pick = async () => {
9745
+ if (!location || ui.model?.current()?.providerID === "route_33")
9746
+ return void 0;
9747
+ const listed = await client?.model?.list?.({ location });
9748
+ return v2AutoSelectTarget(listed?.data ?? [], ui.dialog);
9749
+ };
9750
+ const model = await pick();
9751
+ if (!model) return;
9752
+ if (route?.type === "session" && client?.session?.switchModel) {
9753
+ await client.session.switchModel({
9754
+ model: { id: model.id, providerID: model.providerID },
9755
+ sessionID: route.sessionID
9756
+ });
9757
+ return;
9758
+ }
9759
+ ui.toast.show({
9760
+ message: `Open /models and choose ${model.name ?? model.id} under Route 33 to use it.`,
9761
+ variant: "info"
9762
+ });
9763
+ };
9764
+
9765
+ // src/tui-entry/v2-tui/with-attribution-picker/with-attribution-picker.ts
9766
+ var withAttributionPicker = async (context, run) => {
9767
+ const attempt = { complete: false };
9768
+ let notice;
9769
+ const location = context.location ?? context.data?.location.default();
9770
+ const client = {
9771
+ ...context.client,
9772
+ get integration() {
9773
+ const integration = v2IntegrationSurface(context);
9774
+ const status = integration?.oauth?.status;
9775
+ if (!status) return integration;
9776
+ return {
9777
+ ...integration,
9778
+ oauth: {
9779
+ ...integration.oauth,
9780
+ status: async (input) => {
9781
+ const result = await status(input);
9782
+ attempt.complete = result.data.status === "complete";
9783
+ return result;
9784
+ }
9785
+ }
9786
+ };
9787
+ }
9788
+ };
9789
+ await run({
9790
+ ...context,
9791
+ client,
9792
+ location,
9793
+ ui: {
9794
+ ...context.ui,
9795
+ dialog: {
9796
+ ...context.ui.dialog,
9797
+ alert: (input) => {
9798
+ const dismissed = context.ui.dialog.alert(input);
9799
+ if (attempt.complete) notice = dismissed;
9800
+ return dismissed;
9801
+ }
9802
+ }
9803
+ }
9804
+ });
9805
+ if (!attempt.complete) return;
9806
+ await notice;
9807
+ await v2AutoSelectModel({ ...context, location }).catch(() => {
9808
+ context.ui.toast.show({
9809
+ message: "Could not select a Route 33 model. Open /models to choose one.",
9810
+ variant: "error"
9811
+ });
9812
+ });
9813
+ };
9814
+
9335
9815
  // src/tui-entry/v2-tui/v2-tui.ts
9336
9816
  var createV2Tui = () => ({
9337
9817
  id: "route33",
@@ -9339,6 +9819,18 @@ var createV2Tui = () => ({
9339
9819
  const tuiRuntime = composeV2TuiRuntime(context);
9340
9820
  const menuHandlers = () => tuiRuntime?.commandHandlers();
9341
9821
  let stopSessionWatch = () => void 0;
9822
+ const signedIn = async () => await sessionProbe() === "alive" || await v2AttributionForm({ ...context, location }).catch(
9823
+ () => void 0
9824
+ ) !== void 0;
9825
+ const menu = (host) => showR33Menu(host, {
9826
+ handlers: menuHandlers,
9827
+ logout: () => v2ServerLogout({
9828
+ client: context.client,
9829
+ data: context.data,
9830
+ location
9831
+ }),
9832
+ signedIn
9833
+ });
9342
9834
  context.keymap?.layer(() => ({
9343
9835
  mode: "global",
9344
9836
  priority: 10,
@@ -9356,7 +9848,7 @@ var createV2Tui = () => ({
9356
9848
  wizard.menuRequested();
9357
9849
  stopSessionWatch();
9358
9850
  try {
9359
- await showR33Menu(context, { handlers: menuHandlers });
9851
+ await withAttributionPicker(context, menu);
9360
9852
  } finally {
9361
9853
  wizard.menuClosed();
9362
9854
  }
@@ -9408,19 +9900,9 @@ var createV2Tui = () => ({
9408
9900
  }
9409
9901
  return false;
9410
9902
  };
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
- };
9903
+ const automatic = (host) => v2Autoconnect(host, { superseded: wizard.superseded });
9422
9904
  const boot = async (options) => {
9423
- const outcome = await v2BootMatrix({
9905
+ await v2BootMatrix({
9424
9906
  assumedAlive: options?.assumedAlive === true,
9425
9907
  attributed,
9426
9908
  globalFallback: async () => {
@@ -9429,17 +9911,8 @@ var createV2Tui = () => ({
9429
9911
  return silent;
9430
9912
  },
9431
9913
  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
- )
9914
+ wizard: () => withAttributionPicker({ ...context, location }, automatic)
9439
9915
  });
9440
- if (outcome.kind === "wizard-settled") {
9441
- void autoSelect().catch(() => void 0);
9442
- }
9443
9916
  };
9444
9917
  const lock = v2SetupLock({
9445
9918
  keymap: context.keymap === void 0 ? void 0 : {