@r-33/opencode 0.4.7-rc.27 → 0.4.7-rc.28

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.
@@ -512,6 +512,35 @@ var init_cli = __esm({
512
512
  }
513
513
  });
514
514
 
515
+ // src/management/management-error/management-error.ts
516
+ var ManagementError;
517
+ var init_management_error = __esm({
518
+ "src/management/management-error/management-error.ts"() {
519
+ "use strict";
520
+ ManagementError = class extends Error {
521
+ constructor(code, options) {
522
+ super(
523
+ "Route 33 management request failed",
524
+ options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
525
+ );
526
+ this.code = code;
527
+ this.name = "ManagementError";
528
+ this.statusCode = options?.statusCode;
529
+ }
530
+ code;
531
+ statusCode;
532
+ };
533
+ }
534
+ });
535
+
536
+ // src/management/management-error/index.ts
537
+ var init_management_error2 = __esm({
538
+ "src/management/management-error/index.ts"() {
539
+ "use strict";
540
+ init_management_error();
541
+ }
542
+ });
543
+
515
544
  // src/contract/adapters/contract-parse-error/contract-parse-error.ts
516
545
  var ContractParseError;
517
546
  var init_contract_parse_error = __esm({
@@ -4025,16 +4054,25 @@ var init_host_storage_secret_store = __esm({
4025
4054
  /** Reads and parses the scoped gateway credential.
4026
4055
  * @returns The persisted credential, when present.
4027
4056
  */
4057
+ /** Reads the scoped gateway credential out of the box envelope the
4058
+ * host's reactive storage uses, so the TUI part reads what the
4059
+ * server part wrote at the same plugin key.
4060
+ * @returns The persisted credential, when present.
4061
+ */
4028
4062
  async get() {
4029
4063
  const value = await this.#storage.get(this.#key);
4030
- return value === void 0 ? void 0 : parseGatewayKey(value);
4064
+ if (typeof value === "object" && value !== null && "value" in value && typeof value.value === "string") {
4065
+ return parseGatewayKey(value.value);
4066
+ }
4067
+ return typeof value === "string" ? parseGatewayKey(value) : void 0;
4031
4068
  }
4032
- /** Writes the scoped gateway credential only through host-owned storage.
4069
+ /** Writes the scoped gateway credential into the box envelope, through
4070
+ * host-owned storage only.
4033
4071
  * @param key - The credential to persist, or undefined to remove it.
4034
4072
  * @returns A promise that settles after the host write or removal.
4035
4073
  */
4036
4074
  set(key) {
4037
- return key === void 0 ? this.#storage.remove(this.#key) : this.#storage.set(this.#key, key.value);
4075
+ return key === void 0 ? this.#storage.remove(this.#key) : this.#storage.set(this.#key, { value: key.value });
4038
4076
  }
4039
4077
  };
4040
4078
  }
@@ -4062,8 +4100,10 @@ var init_key_lease_error = __esm({
4062
4100
  );
4063
4101
  this.code = code;
4064
4102
  this.name = "KeyLeaseError";
4103
+ this.statusCode = options?.statusCode;
4065
4104
  }
4066
4105
  code;
4106
+ statusCode;
4067
4107
  };
4068
4108
  }
4069
4109
  });
@@ -4307,6 +4347,7 @@ var init_build_mint_input = __esm({
4307
4347
  managementSubject: deps.managementSubject
4308
4348
  });
4309
4349
  return {
4350
+ ...deps.attribution.orgId === void 0 ? {} : { activeOrgId: deps.attribution.orgId },
4310
4351
  allowedModels: deps.extras?.allowedModels,
4311
4352
  description: deps.extras?.description,
4312
4353
  expiresAt: new Date(
@@ -4469,6 +4510,7 @@ var mintKey;
4469
4510
  var init_mint_key = __esm({
4470
4511
  "src/key-lease/mint-key/mint-key.ts"() {
4471
4512
  "use strict";
4513
+ init_management_error2();
4472
4514
  init_build_mint_input2();
4473
4515
  init_is_management_unauthorized2();
4474
4516
  init_key_lease_error2();
@@ -4504,7 +4546,10 @@ var init_mint_key = __esm({
4504
4546
  if (isManagementUnauthorized(cause)) {
4505
4547
  throw new KeyLeaseError("KEY_LEASE_UNAUTHORIZED", { cause });
4506
4548
  }
4507
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", { cause });
4549
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
4550
+ cause,
4551
+ ...cause instanceof ManagementError && cause.statusCode !== void 0 ? { statusCode: cause.statusCode } : {}
4552
+ });
4508
4553
  }
4509
4554
  return {
4510
4555
  key: material.key,
@@ -4973,6 +5018,33 @@ var init_read_legacy_key2 = __esm({
4973
5018
  }
4974
5019
  });
4975
5020
 
5021
+ // src/attribution/parse-attribution/read-org-id/read-org-id.ts
5022
+ var readOrgId;
5023
+ var init_read_org_id = __esm({
5024
+ "src/attribution/parse-attribution/read-org-id/read-org-id.ts"() {
5025
+ "use strict";
5026
+ init_adapters();
5027
+ readOrgId = (value) => {
5028
+ const orgId = value["orgId"];
5029
+ if (orgId === void 0) {
5030
+ return void 0;
5031
+ }
5032
+ if (typeof orgId !== "string") {
5033
+ throw new ContractParseError("invalid attribution");
5034
+ }
5035
+ return orgId;
5036
+ };
5037
+ }
5038
+ });
5039
+
5040
+ // src/attribution/parse-attribution/read-org-id/index.ts
5041
+ var init_read_org_id2 = __esm({
5042
+ "src/attribution/parse-attribution/read-org-id/index.ts"() {
5043
+ "use strict";
5044
+ init_read_org_id();
5045
+ }
5046
+ });
5047
+
4976
5048
  // src/attribution/parse-attribution/parse-attribution.ts
4977
5049
  var parseAttribution;
4978
5050
  var init_parse_attribution = __esm({
@@ -4980,15 +5052,21 @@ var init_parse_attribution = __esm({
4980
5052
  "use strict";
4981
5053
  init_adapters();
4982
5054
  init_predicates();
5055
+ init_read_org_id2();
4983
5056
  parseAttribution = (value) => {
4984
5057
  if (!isRecord(value)) {
4985
5058
  throw new ContractParseError("invalid attribution");
4986
5059
  }
5060
+ const orgId = readOrgId(value);
4987
5061
  if (value["kind"] === "personal") {
4988
- return { kind: "personal" };
5062
+ return { kind: "personal", ...orgId === void 0 ? {} : { orgId } };
4989
5063
  }
4990
5064
  if (value["kind"] === "project" && typeof value["projectId"] === "string") {
4991
- return { kind: "project", projectId: value["projectId"] };
5065
+ return {
5066
+ kind: "project",
5067
+ ...orgId === void 0 ? {} : { orgId },
5068
+ projectId: value["projectId"]
5069
+ };
4992
5070
  }
4993
5071
  throw new ContractParseError("invalid attribution");
4994
5072
  };
@@ -5434,49 +5512,146 @@ var init_commands = __esm({
5434
5512
  }
5435
5513
  });
5436
5514
 
5515
+ // src/ux/attribution-prompt/org-selection-prefix/org-selection-prefix.ts
5516
+ var orgSelectionPrefix;
5517
+ var init_org_selection_prefix = __esm({
5518
+ "src/ux/attribution-prompt/org-selection-prefix/org-selection-prefix.ts"() {
5519
+ "use strict";
5520
+ orgSelectionPrefix = (orgId) => `org:${orgId}:`;
5521
+ }
5522
+ });
5523
+
5524
+ // src/ux/attribution-prompt/org-selection-prefix/index.ts
5525
+ var init_org_selection_prefix2 = __esm({
5526
+ "src/ux/attribution-prompt/org-selection-prefix/index.ts"() {
5527
+ "use strict";
5528
+ init_org_selection_prefix();
5529
+ }
5530
+ });
5531
+
5532
+ // src/ux/attribution-prompt/personal-budgeted/personal-budgeted.ts
5533
+ var personalBudgeted;
5534
+ var init_personal_budgeted = __esm({
5535
+ "src/ux/attribution-prompt/personal-budgeted/personal-budgeted.ts"() {
5536
+ "use strict";
5537
+ personalBudgeted = (org) => {
5538
+ const cap = org.personalBudget?.cap;
5539
+ return cap === void 0 || cap !== null && cap > 0;
5540
+ };
5541
+ }
5542
+ });
5543
+
5544
+ // src/ux/attribution-prompt/personal-budgeted/index.ts
5545
+ var init_personal_budgeted2 = __esm({
5546
+ "src/ux/attribution-prompt/personal-budgeted/index.ts"() {
5547
+ "use strict";
5548
+ init_personal_budgeted();
5549
+ }
5550
+ });
5551
+
5437
5552
  // src/ux/attribution-prompt/attribution-prompt.ts
5438
- var PERSONAL_KEY_ACTIVE_MARKER, createAttributionPrompt;
5553
+ var PERSONAL_KEY_ACTIVE_MARKER, PROMPT_TITLE, createAttributionPrompt;
5439
5554
  var init_attribution_prompt = __esm({
5440
5555
  "src/ux/attribution-prompt/attribution-prompt.ts"() {
5441
5556
  "use strict";
5557
+ init_org_selection_prefix2();
5558
+ init_personal_budgeted2();
5442
5559
  PERSONAL_KEY_ACTIVE_MARKER = "machine key active";
5560
+ PROMPT_TITLE = "Choose where Route 33 should manage this key";
5443
5561
  createAttributionPrompt = (projects, options = {}) => {
5444
- const choicesBySelection = {
5445
- personal: { kind: "personal" }
5562
+ const personalLabel = (orgName) => {
5563
+ const marker = options.personalKeyActive === true ? ` (${PERSONAL_KEY_ACTIVE_MARKER})` : "";
5564
+ const orgSuffix = orgName === void 0 ? "" : ` \u2014 ${orgName}`;
5565
+ return `Personal \u2014 your own key${marker}${orgSuffix}`;
5446
5566
  };
5447
- const projectOptions = projects.map((project) => {
5448
- const selection = `project:${project.id}`;
5449
- choicesBySelection[selection] = {
5450
- kind: "project",
5451
- projectId: project.id
5452
- };
5567
+ const budgetAllowance = (project) => {
5453
5568
  const budget = project.effective_budget ?? project.max_budget;
5454
- const allowance = budget === null ? "no cap set" : `cap ${budget.amount} ${budget.currency}`;
5569
+ return budget === null ? "no cap set" : `cap ${budget.amount} ${budget.currency}`;
5570
+ };
5571
+ const choicesBySelection = {};
5572
+ if (options.orgs === void 0) {
5573
+ choicesBySelection.personal = { kind: "personal" };
5574
+ const projectOptions = projects.map((project) => {
5575
+ const selection = `project:${project.id}`;
5576
+ choicesBySelection[selection] = {
5577
+ kind: "project",
5578
+ projectId: project.id
5579
+ };
5580
+ return {
5581
+ label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${budgetAllowance(project)}`,
5582
+ selection
5583
+ };
5584
+ });
5455
5585
  return {
5456
- label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${allowance}`,
5457
- selection
5586
+ choicesBySelection,
5587
+ options: [
5588
+ { label: personalLabel(), selection: "personal" },
5589
+ ...projectOptions
5590
+ ],
5591
+ title: PROMPT_TITLE
5458
5592
  };
5459
- });
5593
+ }
5594
+ const promptOptions = [];
5595
+ for (const org of options.orgs) {
5596
+ const personal = `${orgSelectionPrefix(org.id)}personal`;
5597
+ if (personalBudgeted(org)) {
5598
+ choicesBySelection[personal] = { kind: "personal", orgId: org.id };
5599
+ promptOptions.push({
5600
+ label: personalLabel(options.orgs.length > 1 ? org.name : void 0),
5601
+ selection: personal
5602
+ });
5603
+ }
5604
+ for (const project of projects) {
5605
+ if (project.organisation.id !== org.id) {
5606
+ continue;
5607
+ }
5608
+ const selection = `${orgSelectionPrefix(org.id)}project:${project.id}`;
5609
+ choicesBySelection[selection] = {
5610
+ kind: "project",
5611
+ orgId: org.id,
5612
+ projectId: project.id
5613
+ };
5614
+ promptOptions.push({
5615
+ label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${budgetAllowance(project)}`,
5616
+ selection
5617
+ });
5618
+ }
5619
+ }
5460
5620
  return {
5461
5621
  choicesBySelection,
5462
- options: [
5463
- {
5464
- label: options.personalKeyActive === true ? `Personal \u2014 your own key (${PERSONAL_KEY_ACTIVE_MARKER})` : "Personal \u2014 your own key",
5465
- selection: "personal"
5466
- },
5467
- ...projectOptions
5468
- ],
5469
- title: "Choose where Route 33 should manage this key"
5622
+ options: promptOptions,
5623
+ orgs: options.orgs,
5624
+ title: PROMPT_TITLE
5470
5625
  };
5471
5626
  };
5472
5627
  }
5473
5628
  });
5474
5629
 
5630
+ // src/ux/attribution-prompt/is-personal-selection/is-personal-selection.ts
5631
+ var PERSONAL_SELECTION_SUFFIX, isPersonalSelection;
5632
+ var init_is_personal_selection = __esm({
5633
+ "src/ux/attribution-prompt/is-personal-selection/is-personal-selection.ts"() {
5634
+ "use strict";
5635
+ PERSONAL_SELECTION_SUFFIX = ":personal";
5636
+ isPersonalSelection = (selection) => selection === "personal" || selection.endsWith(PERSONAL_SELECTION_SUFFIX);
5637
+ }
5638
+ });
5639
+
5640
+ // src/ux/attribution-prompt/is-personal-selection/index.ts
5641
+ var init_is_personal_selection2 = __esm({
5642
+ "src/ux/attribution-prompt/is-personal-selection/index.ts"() {
5643
+ "use strict";
5644
+ init_is_personal_selection();
5645
+ }
5646
+ });
5647
+
5475
5648
  // src/ux/attribution-prompt/index.ts
5476
5649
  var init_attribution_prompt2 = __esm({
5477
5650
  "src/ux/attribution-prompt/index.ts"() {
5478
5651
  "use strict";
5479
5652
  init_attribution_prompt();
5653
+ init_is_personal_selection2();
5654
+ init_org_selection_prefix2();
5480
5655
  }
5481
5656
  });
5482
5657
 
@@ -5604,7 +5779,7 @@ var REQUESTED_OAUTH_SCOPES;
5604
5779
  var init_requested_scopes = __esm({
5605
5780
  "src/requested-scopes/requested-scopes.ts"() {
5606
5781
  "use strict";
5607
- REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read projects:read users:read keys:read keys:write";
5782
+ REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read profile projects:read users:read keys:read keys:write";
5608
5783
  }
5609
5784
  });
5610
5785
 
@@ -5817,9 +5992,8 @@ var init_route33_runtime = __esm({
5817
5992
  * Lists exactly the projects the current management login can mint keys
5818
5993
  * on: the login's per-user budget rows intersected with the
5819
5994
  * member-visible project listing, organisation names stitched from the
5820
- * login's own memberships. Orgs the login merely administers carry no
5821
- * budget row and drop out — the picker never offers a project whose
5822
- * keys the login cannot create. A `allowBrowser: false` policy makes
5995
+ * login's own memberships. Zero-cap rows drop out — a project whose
5996
+ * budget cannot spend never mints. A `allowBrowser: false` policy makes
5823
5997
  * the call non-blocking: a dead session rejects instead of opening a
5824
5998
  * browser, so the picker's form registration never stalls a boot.
5825
5999
  * @param policy - Whether a dead session may open a browser login.
@@ -5833,21 +6007,69 @@ var init_route33_runtime = __esm({
5833
6007
  client.listProjectBudgets(credential, subject),
5834
6008
  client.listMemberships(credential, subject)
5835
6009
  ]);
5836
- const organisationNames = new Map(
5837
- memberships.org_memberships.map(({ org_id, org_name }) => [
5838
- org_id,
5839
- org_name
5840
- ])
6010
+ return this.#budgetedProjects(
6011
+ credential,
6012
+ client,
6013
+ budgets,
6014
+ new Map(
6015
+ memberships.org_memberships.map(({ org_id, org_name }) => [
6016
+ org_id,
6017
+ org_name
6018
+ ])
6019
+ )
6020
+ );
6021
+ }
6022
+ /**
6023
+ * Lists one organisation per membership with that organisation's
6024
+ * mintable projects and effective personal budget — the wizard's org
6025
+ * picker data. Budgets resolve per organisation (the active-org
6026
+ * header), so rows never mix orgs; zero-cap rows drop out, and an
6027
+ * unreadable organisation degrades to its empty picker — or an unknown
6028
+ * personal budget — instead of failing the whole list.
6029
+ * @param policy - Whether a dead session may open a browser login.
6030
+ * @returns One mintable-projects entry per organisation membership.
6031
+ */
6032
+ async listMintableOrgs(policy = {}) {
6033
+ const credential = await this.#session.credential(policy);
6034
+ const subject = this.#subject(credential);
6035
+ const client = this.#client();
6036
+ const memberships = await client.listMemberships(credential, subject);
6037
+ return Promise.all(
6038
+ memberships.org_memberships.map(async ({ org_id, org_name }) => ({
6039
+ id: org_id,
6040
+ name: org_name,
6041
+ personalBudget: await client.listBudgetPolicy(credential, subject, org_id).then((budget) => ({ cap: budget.cap })).catch(() => void 0),
6042
+ projects: await client.listProjectBudgets(credential, subject, org_id).then(
6043
+ (budgets) => this.#budgetedProjects(
6044
+ credential,
6045
+ client,
6046
+ budgets,
6047
+ /* @__PURE__ */ new Map([[org_id, org_name]])
6048
+ )
6049
+ ).catch(() => [])
6050
+ }))
5841
6051
  );
6052
+ }
6053
+ /**
6054
+ * Joins cap-bearing budget rows with their listed projects; zero caps
6055
+ * never mint.
6056
+ * @param credential - The management bearer token for project listings.
6057
+ * @param client - The management contract implementation.
6058
+ * @param budgets - The login's per-user budget rows.
6059
+ * @param organisationNames - The login's org names by org id.
6060
+ * @returns The mintable projects carrying organisation context.
6061
+ */
6062
+ async #budgetedProjects(credential, client, budgets, organisationNames) {
6063
+ const rows = budgets.data.filter((row) => row.cap > 0);
5842
6064
  const listings = await Promise.all(
5843
- [...new Set(budgets.data.map(({ org_id }) => org_id))].map(
6065
+ [...new Set(rows.map(({ org_id }) => org_id))].map(
5844
6066
  (orgId) => client.listProjects(credential, orgId)
5845
6067
  )
5846
6068
  );
5847
6069
  const projectsById = new Map(
5848
6070
  listings.flatMap(({ data }) => data).map((project) => [project.id, project])
5849
6071
  );
5850
- return budgets.data.flatMap(({ org_id, project_id }) => {
6072
+ return rows.flatMap(({ org_id, project_id }) => {
5851
6073
  const project = projectsById.get(project_id);
5852
6074
  if (project === void 0) {
5853
6075
  return [];
@@ -6362,20 +6584,8 @@ var drainPages = async (fetchPage) => {
6362
6584
  return { data, page: { ...page, has_more: false, next_cursor: null } };
6363
6585
  };
6364
6586
 
6365
- // src/management/management-error/management-error.ts
6366
- var ManagementError = class extends Error {
6367
- constructor(code, options) {
6368
- super(
6369
- "Route 33 management request failed",
6370
- options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
6371
- );
6372
- this.code = code;
6373
- this.name = "ManagementError";
6374
- this.statusCode = options?.statusCode;
6375
- }
6376
- code;
6377
- statusCode;
6378
- };
6587
+ // src/management/index.ts
6588
+ init_management_error2();
6379
6589
 
6380
6590
  // src/management/sdk-management-keys/sdk-management-keys.ts
6381
6591
  init_adapters();
@@ -6417,6 +6627,28 @@ var parseApiKey = (value) => {
6417
6627
  };
6418
6628
  };
6419
6629
 
6630
+ // src/contract/management-keys/parse-budget-policy/parse-budget-policy.ts
6631
+ init_adapters();
6632
+ init_predicates();
6633
+ var parseBudgetPolicy = (value) => {
6634
+ if (!isRecord(value)) {
6635
+ throw new ContractParseError("invalid budget policy");
6636
+ }
6637
+ const cap = value["cap"];
6638
+ if (typeof cap !== "number" && cap !== null) {
6639
+ throw new ContractParseError("invalid budget policy");
6640
+ }
6641
+ const orgId = value["org_id"];
6642
+ if (typeof orgId !== "string") {
6643
+ throw new ContractParseError("invalid budget policy");
6644
+ }
6645
+ const source = value["source"];
6646
+ if (source !== "own_cap" && source !== "project_default" && source !== "org_default" && source !== "tenant_default" && source !== "platform_default") {
6647
+ throw new ContractParseError("invalid budget policy");
6648
+ }
6649
+ return { cap, org_id: orgId, source };
6650
+ };
6651
+
6420
6652
  // src/contract/management-keys/parse-collection/parse-collection.ts
6421
6653
  init_adapters();
6422
6654
  init_predicates();
@@ -6641,28 +6873,49 @@ var parseUserMemberships = (value) => {
6641
6873
  };
6642
6874
  };
6643
6875
 
6876
+ // src/management/sdk-management-keys/sdk-management-keys.ts
6877
+ init_management_error2();
6878
+
6879
+ // src/management/sdk-management-keys/mint-request-body/mint-request-body.ts
6880
+ var buildMintRequestBody = (input) => ({
6881
+ ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
6882
+ budget_currency: "EUR",
6883
+ ...input.description === void 0 ? {} : { description: input.description },
6884
+ expires_at: input.expiresAt,
6885
+ ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
6886
+ name: input.name,
6887
+ ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
6888
+ owner_type: input.ownerType,
6889
+ ...input.projectId === null ? {} : { project_id: input.projectId }
6890
+ });
6891
+
6644
6892
  // src/management/sdk-management-keys/sdk-management-keys.ts
6645
6893
  var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
6894
+ var ACTIVE_ORG_HEADER = "X-Active-Org-Id";
6646
6895
  var sdkManagementKeys = (options) => {
6647
6896
  const baseUrl = options.apiBaseUrl.replace(API_PREFIX_PATTERN, "");
6648
6897
  const timeoutMs = options.timeoutMs ?? 1e4;
6649
6898
  const fetchImpl = options.fetchImpl;
6650
- const observingFetch = (status) => fetchImpl === void 0 ? void 0 : async (input, init) => {
6651
- const response = await fetchImpl(input, init);
6652
- status.code = response.status;
6653
- return response;
6899
+ const activeOrgFetch = (activeOrgId) => activeOrgId === void 0 ? void 0 : (input, init) => {
6900
+ if (input instanceof Request) {
6901
+ input.headers.set(ACTIVE_ORG_HEADER, activeOrgId);
6902
+ }
6903
+ if (init?.headers instanceof Headers) {
6904
+ init.headers.set(ACTIVE_ORG_HEADER, activeOrgId);
6905
+ }
6906
+ return (fetchImpl ?? globalThis.fetch)(input, init);
6654
6907
  };
6655
- const callClient = (accessToken, status) => {
6908
+ const callClient = (accessToken, activeOrgId) => {
6656
6909
  const provider = {
6657
6910
  getToken: () => Promise.resolve(accessToken.value),
6658
6911
  onUnauthorized: () => Promise.resolve(accessToken.value)
6659
6912
  };
6660
- const observedFetch = observingFetch(status);
6913
+ const fetch2 = activeOrgFetch(activeOrgId) ?? fetchImpl;
6661
6914
  return createRoute33Client({
6662
6915
  baseUrl,
6663
6916
  provider,
6664
6917
  timeoutMs,
6665
- ...observedFetch === void 0 ? {} : { fetch: observedFetch }
6918
+ ...fetch2 === void 0 ? {} : { fetch: fetch2 }
6666
6919
  });
6667
6920
  };
6668
6921
  const mapFailure = (cause) => {
@@ -6678,11 +6931,10 @@ var sdkManagementKeys = (options) => {
6678
6931
  }
6679
6932
  return new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
6680
6933
  };
6681
- const call = async (accessToken, run) => {
6682
- const status = { code: void 0 };
6934
+ const call = async (accessToken, activeOrgId, run) => {
6683
6935
  try {
6684
- const outcome = await run(callClient(accessToken, status));
6685
- const code = status.code;
6936
+ const outcome = await run(callClient(accessToken, activeOrgId));
6937
+ const code = outcome.response?.status;
6686
6938
  if (code === void 0 || code < 200 || code >= 300) {
6687
6939
  throw new ManagementError(
6688
6940
  code === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
@@ -6698,24 +6950,16 @@ var sdkManagementKeys = (options) => {
6698
6950
  create: async (accessToken, input) => parseKeyMaterial(
6699
6951
  await call(
6700
6952
  accessToken,
6953
+ input.activeOrgId,
6701
6954
  (client) => client.POST("/api/v1/api-keys", {
6702
- body: {
6703
- ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
6704
- budget_currency: "EUR",
6705
- ...input.description === void 0 ? {} : { description: input.description },
6706
- expires_at: input.expiresAt,
6707
- ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
6708
- name: input.name,
6709
- ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
6710
- owner_type: input.ownerType,
6711
- ...input.projectId === null ? {} : { project_id: input.projectId }
6712
- }
6955
+ body: buildMintRequestBody(input)
6713
6956
  })
6714
6957
  )
6715
6958
  ),
6716
6959
  delete: async (accessToken, id) => {
6717
6960
  await call(
6718
6961
  accessToken,
6962
+ void 0,
6719
6963
  (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
6720
6964
  params: { path: { api_key_id: id } }
6721
6965
  })
@@ -6724,30 +6968,50 @@ var sdkManagementKeys = (options) => {
6724
6968
  get: async (accessToken, id) => parseApiKey(
6725
6969
  await call(
6726
6970
  accessToken,
6971
+ void 0,
6727
6972
  (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
6728
6973
  params: { path: { api_key_id: id } }
6729
6974
  })
6730
6975
  )
6731
6976
  ),
6732
6977
  list: async (accessToken) => parseCollection(
6733
- await call(accessToken, (client) => client.GET("/api/v1/api-keys", {})),
6978
+ await call(
6979
+ accessToken,
6980
+ void 0,
6981
+ (client) => client.GET("/api/v1/api-keys", {})
6982
+ ),
6734
6983
  parseApiKey
6735
6984
  ),
6736
6985
  listOrganizations: async (accessToken) => parseCollection(
6737
- await call(accessToken, (client) => client.GET("/api/v1/orgs", {})),
6986
+ await call(
6987
+ accessToken,
6988
+ void 0,
6989
+ (client) => client.GET("/api/v1/orgs", {})
6990
+ ),
6738
6991
  parseOrganization
6739
6992
  ),
6740
6993
  listMemberships: async (accessToken, userId) => parseUserMemberships(
6741
6994
  await call(
6742
6995
  accessToken,
6996
+ void 0,
6743
6997
  (client) => client.GET("/api/v1/users/{user_id}/memberships", {
6744
6998
  params: { path: { user_id: userId } }
6745
6999
  })
6746
7000
  )
6747
7001
  ),
6748
- listProjectBudgets: async (accessToken, userId) => parseCollection(
7002
+ listBudgetPolicy: async (accessToken, userId, activeOrgId) => parseBudgetPolicy(
7003
+ await call(
7004
+ accessToken,
7005
+ activeOrgId,
7006
+ (client) => client.GET("/api/v1/users/{user_id}/budget-policy", {
7007
+ params: { path: { user_id: userId } }
7008
+ })
7009
+ )
7010
+ ),
7011
+ listProjectBudgets: async (accessToken, userId, activeOrgId) => parseCollection(
6749
7012
  await call(
6750
7013
  accessToken,
7014
+ activeOrgId,
6751
7015
  (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
6752
7016
  params: { path: { user_id: userId } }
6753
7017
  })
@@ -6766,6 +7030,7 @@ var sdkManagementKeys = (options) => {
6766
7030
  };
6767
7031
  const fetchPage = (cursor) => call(
6768
7032
  accessToken,
7033
+ void 0,
6769
7034
  (client) => client.GET("/api/v1/projects", {
6770
7035
  params: {
6771
7036
  query: cursor === "" ? query : { ...query, cursor }
@@ -6777,6 +7042,7 @@ var sdkManagementKeys = (options) => {
6777
7042
  regenerate: async (accessToken, id, expiresAt) => parseKeyMaterial(
6778
7043
  await call(
6779
7044
  accessToken,
7045
+ void 0,
6780
7046
  (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
6781
7047
  body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
6782
7048
  params: { path: { api_key_id: id } }
@@ -6786,6 +7052,7 @@ var sdkManagementKeys = (options) => {
6786
7052
  update: async (accessToken, id, input) => parseApiKey(
6787
7053
  await call(
6788
7054
  accessToken,
7055
+ void 0,
6789
7056
  (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
6790
7057
  body: {
6791
7058
  budget_currency: "EUR",
@@ -7341,7 +7608,11 @@ var V2_CONNECT_COPY = {
7341
7608
  dismissed: "Route 33 is not set up for this folder yet. Press Enter to pick the budget, or run /connect and choose Route 33.",
7342
7609
  expired: "The Route 33 sign-in link expired. Press Enter to retry, or run /connect and choose Route 33.",
7343
7610
  manualFallback: "Route 33 is not connected in this folder. Run /connect, choose Route 33, and follow the steps.",
7344
- manualPath: "Press Enter to retry, or run /connect, choose Route 33, and follow the steps.",
7611
+ manualPath: "Press Enter to retry, or run /connect and choose Route 33, and follow the steps.",
7612
+ noBudgetsTitle: "Route 33 \u2014 no budgets available",
7613
+ noBudgetsMulti: "No Route 33 budgets are available in this organisation yet. Ask an owner for a budget, then press Enter to pick another organisation.",
7614
+ noBudgetsSingle: "No Route 33 budgets are available here yet. Ask an owner for a budget, then run /connect and choose Route 33.",
7615
+ orgPickerTitle: "Which Route 33 organisation covers this folder?",
7345
7616
  pickerTitle: "Which budget covers Route 33 usage in this folder?",
7346
7617
  setupIncomplete: "Route 33 setup did not complete. Press Enter to retry, or run /connect and choose Route 33.",
7347
7618
  signInFailed: "Route 33 sign-in did not complete. Press Enter to retry, or run /connect and choose Route 33.",
@@ -7356,6 +7627,15 @@ var V2_CONNECT_COPY = {
7356
7627
  timedOut: "Route 33 sign-in timed out. Press Enter to retry, or run /connect and choose Route 33."
7357
7628
  };
7358
7629
 
7630
+ // src/v2-entry/connect-copy/connect-copy.ts
7631
+ var CONNECT_COPY = {
7632
+ 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.",
7633
+ failFastWorktree: "Route 33 attributes usage to a project inside a Git worktree. Open a Git repository (or run git init), then connect again.",
7634
+ selectionInvalid: "That Route 33 option is no longer available. Connect again and pick another.",
7635
+ signedInNextStep: "Signed in to Route 33 \u2713. One more step: connect again, choose Route 33, and assign a budget for this folder.",
7636
+ mintNoBudget: "Route 33 could not create the key \u2014 its cap exceeds this budget. Ask an owner to raise the budget, or pick another."
7637
+ };
7638
+
7359
7639
  // src/tui-entry/v2-outcome-copy/v2-outcome-copy.ts
7360
7640
  var v2OutcomeCopy = (outcome, failedFallback) => {
7361
7641
  if (outcome.kind === "failed") {
@@ -7406,17 +7686,28 @@ var answerPass = async (deps) => {
7406
7686
  message: `${error instanceof Error ? error.message : String(error)} ${V2_CONNECT_COPY.manualPath}`,
7407
7687
  variant: "error"
7408
7688
  });
7409
- return;
7689
+ return "incomplete";
7410
7690
  }
7411
7691
  const settled = await deps.pollTerminal(second.data.attemptID);
7412
7692
  if (settled.kind !== "complete") {
7693
+ if (settled.kind === "failed" && (settled.message ?? "").includes(CONNECT_COPY.mintNoBudget)) {
7694
+ return "no-budgets";
7695
+ }
7413
7696
  deps.toast(v2OutcomeCopy(settled, V2_CONNECT_COPY.setupIncomplete));
7414
- return;
7697
+ return "incomplete";
7415
7698
  }
7416
7699
  showCompletion(deps.dialog, deps.options, deps.selection, deps.extras);
7417
7700
  deps.toast({ message: V2_CONNECT_COPY.success, variant: "success" });
7701
+ return "complete";
7418
7702
  };
7419
7703
 
7704
+ // src/v2-entry/connect-form/connect-form.ts
7705
+ var ATTRIBUTION_FIELD_KEY = "attribution";
7706
+ var ORGANISATION_FIELD_KEY = "organisation";
7707
+
7708
+ // src/v2-entry/parse-connect-answer/parse-connect-answer.ts
7709
+ var ATTRIBUTION_FIELD_KEY2 = "attribution";
7710
+
7420
7711
  // src/tui-entry/v2-integration-surface/v2-integration-surface.ts
7421
7712
  var v2IntegrationSurface = (context) => context.client?.integration ?? context.client?.api?.integration;
7422
7713
 
@@ -7463,87 +7754,175 @@ var v2KeyPrompts = async (deps) => {
7463
7754
  return answer;
7464
7755
  };
7465
7756
 
7466
- // src/tui-entry/v2-budget-picker/v2-budget-picker.ts
7467
- var v2BudgetPicker = async (deps) => {
7468
- if (!deps.unattributed()) {
7469
- deps.toast({ message: V2_CONNECT_COPY.success, variant: "success" });
7470
- return;
7757
+ // src/tui-entry/v2-budget-picker/show-no-budgets/show-no-budgets.ts
7758
+ var showNoBudgets = (dialog, multi) => dialog.alert({
7759
+ message: multi ? V2_CONNECT_COPY.noBudgetsMulti : V2_CONNECT_COPY.noBudgetsSingle,
7760
+ title: V2_CONNECT_COPY.noBudgetsTitle
7761
+ });
7762
+
7763
+ // src/tui-entry/v2-budget-picker/answer-step/answer-step.ts
7764
+ var runAnswerStep = async (deps) => {
7765
+ const fields = (await v2FormFields(deps.context)).filter(
7766
+ (field) => field.key !== ATTRIBUTION_FIELD_KEY && field.key !== ORGANISATION_FIELD_KEY
7767
+ );
7768
+ const extras = await v2KeyPrompts({ dialog: deps.dialog, fields });
7769
+ if (extras === void 0) {
7770
+ deps.toast({ message: V2_CONNECT_COPY.dismissed });
7771
+ return "done";
7772
+ }
7773
+ const outcome = await answerPass({
7774
+ connect: deps.connect,
7775
+ dialog: deps.dialog,
7776
+ extras,
7777
+ form: { key: deps.attributionFieldKey },
7778
+ locationInput: deps.locationInput,
7779
+ options: deps.budgetOptions,
7780
+ pollTerminal: deps.pollTerminal,
7781
+ selection: deps.selection,
7782
+ toast: deps.toast
7783
+ });
7784
+ if (outcome === "no-budgets") {
7785
+ await showNoBudgets(deps.dialog, deps.multi);
7786
+ return deps.multi ? "retry" : "done";
7471
7787
  }
7472
- const options = deps.form.options ?? [];
7788
+ return "done";
7789
+ };
7790
+
7791
+ // src/tui-entry/v2-budget-picker/pick-budget/pick-budget.ts
7792
+ var pickBudget = async (deps) => {
7473
7793
  const selection = await deps.dialog.select({
7474
- options: options.map((option) => ({
7794
+ options: deps.options.map((option) => ({
7475
7795
  description: option.description,
7476
7796
  title: option.label,
7477
7797
  value: option.value
7478
7798
  })),
7479
- title: deps.form.title ?? V2_CONNECT_COPY.pickerTitle
7799
+ title: deps.title
7480
7800
  });
7481
7801
  if (selection === void 0) {
7482
7802
  deps.toast({ message: V2_CONNECT_COPY.dismissed });
7483
- return;
7803
+ return void 0;
7484
7804
  }
7485
- const pickerOptions = options;
7486
- if (!pickerOptions.some((option) => option.value === selection)) {
7805
+ if (!deps.budgetOptions.some((option) => option.value === selection)) {
7487
7806
  deps.toast({ message: V2_CONNECT_COPY.stale, variant: "error" });
7488
- return;
7807
+ return void 0;
7489
7808
  }
7490
- if (!deps.unattributed()) {
7491
- deps.toast({ message: V2_CONNECT_COPY.success, variant: "success" });
7492
- return;
7809
+ return selection;
7810
+ };
7811
+
7812
+ // src/tui-entry/v2-budget-picker/pick-org/pick-org.ts
7813
+ var pickOrg = async (deps) => {
7814
+ if (deps.orgs.length <= 1) {
7815
+ return { kind: "picked", orgId: deps.orgs[0]?.value };
7493
7816
  }
7494
- const fields = (await v2FormFields(deps.context)).filter(
7495
- (field) => field.key !== deps.form.key
7496
- );
7497
- const extras = await v2KeyPrompts({ dialog: deps.dialog, fields });
7498
- if (extras === void 0) {
7817
+ const orgId = await deps.dialog.select({
7818
+ options: deps.orgs.map((option) => ({
7819
+ title: option.label,
7820
+ value: option.value
7821
+ })),
7822
+ title: deps.title
7823
+ });
7824
+ if (orgId === void 0) {
7499
7825
  deps.toast({ message: V2_CONNECT_COPY.dismissed });
7500
- return;
7826
+ return { kind: "dismissed" };
7827
+ }
7828
+ return { kind: "picked", orgId };
7829
+ };
7830
+
7831
+ // src/tui-entry/v2-budget-picker/scope-budget-options/scope-budget-options.ts
7832
+ init_ux();
7833
+ var scopeBudgetOptions = (orgId, options) => orgId === void 0 ? options : options.filter(
7834
+ (option) => option.value.startsWith(orgSelectionPrefix(orgId))
7835
+ );
7836
+
7837
+ // src/tui-entry/v2-budget-picker/budget-round/budget-round.ts
7838
+ var runBudgetRound = async (deps) => {
7839
+ const multi = deps.orgs.length > 1;
7840
+ const org = await pickOrg({
7841
+ dialog: deps.dialog,
7842
+ orgs: deps.orgs,
7843
+ title: deps.orgTitle ?? V2_CONNECT_COPY.orgPickerTitle,
7844
+ toast: deps.toast
7845
+ });
7846
+ if (org.kind === "dismissed") {
7847
+ return "done";
7848
+ }
7849
+ const scoped = scopeBudgetOptions(org.orgId, deps.budgetOptions);
7850
+ if (scoped.length === 0) {
7851
+ await showNoBudgets(deps.dialog, multi);
7852
+ return multi ? "retry" : "done";
7853
+ }
7854
+ const selection = await pickBudget({
7855
+ budgetOptions: deps.budgetOptions,
7856
+ dialog: deps.dialog,
7857
+ options: scoped,
7858
+ title: deps.budgetTitle ?? V2_CONNECT_COPY.pickerTitle,
7859
+ toast: deps.toast
7860
+ });
7861
+ if (selection === void 0) {
7862
+ return "done";
7863
+ }
7864
+ if (!deps.unattributed()) {
7865
+ deps.toast({ message: V2_CONNECT_COPY.success, variant: "success" });
7866
+ return "done";
7501
7867
  }
7502
- await answerPass({
7868
+ return runAnswerStep({
7869
+ attributionFieldKey: "attribution",
7870
+ budgetOptions: deps.budgetOptions,
7503
7871
  connect: deps.connect,
7872
+ context: deps.context,
7504
7873
  dialog: deps.dialog,
7505
- extras,
7506
- form: deps.form,
7507
7874
  locationInput: deps.locationInput,
7508
- options: pickerOptions,
7875
+ multi,
7509
7876
  pollTerminal: deps.pollTerminal,
7510
7877
  selection,
7511
7878
  toast: deps.toast
7512
7879
  });
7513
7880
  };
7514
7881
 
7515
- // src/tui-entry/v2-form-reader/v2-form-reader.ts
7516
- init_abortable_sleep2();
7517
-
7518
- // src/tui-entry/v2-attribution-field/v2-attribution-field.ts
7519
- var v2AttributionField = (methods) => {
7520
- const browserMethods = methods?.filter(
7521
- (entry) => entry.type === "oauth" && entry.id === "browser"
7882
+ // src/tui-entry/v2-budget-picker/v2-budget-picker.ts
7883
+ var v2BudgetPicker = async (deps) => {
7884
+ if (!deps.unattributed()) {
7885
+ deps.toast({ message: V2_CONNECT_COPY.success, variant: "success" });
7886
+ return;
7887
+ }
7888
+ const attributionField = deps.formFields.find(
7889
+ (field) => field.key === ATTRIBUTION_FIELD_KEY2
7522
7890
  );
7523
- const fields = browserMethods?.flatMap((entry) => entry.form ?? []);
7524
- const field = fields?.find((entry) => entry.key === "attribution");
7525
- if (field?.options === void 0 || field.options.length === 0) {
7526
- return void 0;
7891
+ if (attributionField === void 0) {
7892
+ deps.toast({ message: V2_CONNECT_COPY.manualFallback, variant: "error" });
7893
+ return;
7894
+ }
7895
+ const orgField = deps.formFields.find(
7896
+ (field) => field.key === ORGANISATION_FIELD_KEY
7897
+ );
7898
+ for (; ; ) {
7899
+ const round = await runBudgetRound({
7900
+ budgetOptions: attributionField.options ?? [],
7901
+ budgetTitle: attributionField.title,
7902
+ connect: deps.connect,
7903
+ context: deps.context,
7904
+ dialog: deps.dialog,
7905
+ locationInput: deps.locationInput,
7906
+ orgTitle: orgField?.title,
7907
+ orgs: orgField?.options ?? [],
7908
+ pollTerminal: deps.pollTerminal,
7909
+ toast: deps.toast,
7910
+ unattributed: deps.unattributed
7911
+ });
7912
+ if (round !== "retry") {
7913
+ return;
7914
+ }
7527
7915
  }
7528
- return field;
7529
- };
7530
-
7531
- // src/tui-entry/v2-attribution-form/v2-attribution-form.ts
7532
- var v2AttributionForm = async (context) => {
7533
- const get = v2IntegrationSurface(context)?.get;
7534
- if (get === void 0) return void 0;
7535
- const integration = await get({
7536
- integrationID: "route33",
7537
- ...context.location === void 0 ? {} : { location: { directory: context.location.directory } }
7538
- }).catch(() => void 0);
7539
- return v2AttributionField(integration?.data.methods);
7540
7916
  };
7541
7917
 
7542
7918
  // src/tui-entry/v2-form-reader/v2-form-reader.ts
7919
+ init_abortable_sleep2();
7543
7920
  var createV2FormReader = ({ attempts = 5, context, retryDelayMs = 500 }) => async () => {
7544
7921
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
7545
- const form = await v2AttributionForm(context);
7546
- if (form !== void 0) return form;
7922
+ const fields = await v2FormFields(context);
7923
+ if (fields.length > 0) {
7924
+ return fields;
7925
+ }
7547
7926
  if (attempt < attempts) {
7548
7927
  await abortableSleep(retryDelayMs);
7549
7928
  }
@@ -7663,12 +8042,12 @@ var v2GuidedConnect = async (deps) => {
7663
8042
  if (surfaces === void 0) return;
7664
8043
  const { connect, dialog, locationInput, pollTerminal, toast } = surfaces;
7665
8044
  if (deps.superseded?.() === true) return;
7666
- const form = await createV2FormReader({
8045
+ const formFields = await createV2FormReader({
7667
8046
  attempts: deps.formReadAttempts,
7668
8047
  context,
7669
8048
  retryDelayMs: deps.retryDelayMs
7670
8049
  })();
7671
- if (form === void 0) {
8050
+ if (formFields === void 0) {
7672
8051
  toast({ message: V2_CONNECT_COPY.manualFallback, variant: "error" });
7673
8052
  return;
7674
8053
  }
@@ -7676,7 +8055,7 @@ var v2GuidedConnect = async (deps) => {
7676
8055
  connect,
7677
8056
  context,
7678
8057
  dialog,
7679
- form,
8058
+ formFields,
7680
8059
  locationInput,
7681
8060
  pollTerminal,
7682
8061
  toast,
@@ -7800,6 +8179,30 @@ var showR33Menu = async (context, deps) => {
7800
8179
  await runR33MenuAction(context, selection, deps);
7801
8180
  };
7802
8181
 
8182
+ // src/tui-entry/v2-attribution-field/v2-attribution-field.ts
8183
+ var v2AttributionField = (methods) => {
8184
+ const browserMethods = methods?.filter(
8185
+ (entry) => entry.type === "oauth" && entry.id === "browser"
8186
+ );
8187
+ const fields = browserMethods?.flatMap((entry) => entry.form ?? []);
8188
+ const field = fields?.find((entry) => entry.key === "attribution");
8189
+ if (field?.options === void 0 || field.options.length === 0) {
8190
+ return void 0;
8191
+ }
8192
+ return field;
8193
+ };
8194
+
8195
+ // src/tui-entry/v2-attribution-form/v2-attribution-form.ts
8196
+ var v2AttributionForm = async (context) => {
8197
+ const get = v2IntegrationSurface(context)?.get;
8198
+ if (get === void 0) return void 0;
8199
+ const integration = await get({
8200
+ integrationID: "route33",
8201
+ ...context.location === void 0 ? {} : { location: { directory: context.location.directory } }
8202
+ }).catch(() => void 0);
8203
+ return v2AttributionField(integration?.data.methods);
8204
+ };
8205
+
7803
8206
  // src/tui-entry/v2-route33-model-candidate/v2-route33-model-candidate.ts
7804
8207
  var v2Route33ModelCandidate = (models) => {
7805
8208
  for (const model of models) {
@@ -7875,82 +8278,65 @@ var v2BootMatrix = async ({
7875
8278
 
7876
8279
  // src/tui-entry/v2-boot-reentry/v2-boot-reentry.ts
7877
8280
  var registerV2BootReentry = (deps) => {
8281
+ const debounceMs = deps.debounceMs ?? 1e3;
8282
+ const maxAttempts = deps.maxAttempts ?? 3;
8283
+ let attempts = 0;
8284
+ let timer;
8285
+ const fire = () => {
8286
+ attempts += 1;
8287
+ void deps.start().catch(() => void 0).then(() => {
8288
+ if (!deps.pending()) attempts = 0;
8289
+ });
8290
+ };
7878
8291
  deps.listen?.((event) => {
7879
8292
  if (!event.details.type.includes("integration")) return;
7880
8293
  if (deps.superseded()) return;
7881
8294
  if (!deps.pending()) return;
7882
- void deps.start().catch(() => void 0);
8295
+ if (attempts >= maxAttempts) return;
8296
+ if (timer !== void 0) clearTimeout(timer);
8297
+ timer = setTimeout(() => {
8298
+ timer = void 0;
8299
+ if (deps.superseded() || !deps.pending()) return;
8300
+ fire();
8301
+ }, debounceMs);
7883
8302
  });
7884
8303
  };
7885
8304
 
7886
- // src/v2-entry/connect-copy/connect-copy.ts
7887
- var CONNECT_COPY = {
7888
- 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.",
7889
- failFastWorktree: "Route 33 attributes usage to a project inside a Git worktree. Open a Git repository (or run git init), then connect again.",
7890
- selectionInvalid: "That Route 33 option is no longer available. Connect again and pick another.",
7891
- signedInNextStep: "Signed in to Route 33 \u2713. One more step: connect again, choose Route 33, and assign a budget for this folder."
7892
- };
7893
-
7894
- // src/v2-entry/resolve-host-credential/resolve-host-credential.ts
7895
- init_config();
7896
- var NO_USABLE_LEASE_MESSAGE = "Signed in to Route 33 \u2713. One more step: this folder has no gateway key yet \u2014 pick its budget to finish setup.";
7897
-
7898
- // src/tui-entry/v2-session-probe/v2-session-probe.ts
7899
- var v2SessionProbe = async ({
7900
- connect,
7901
- locationInput,
7902
- cancel,
7903
- status,
7904
- probePolls = 3,
7905
- pollDelayMs = 1e3,
7906
- sleep = (ms) => new Promise((resolve2) => {
7907
- setTimeout(resolve2, ms);
7908
- })
7909
- }) => {
7910
- let attempt;
7911
- try {
7912
- attempt = await connect({
7913
- integrationID: "route33",
7914
- location: locationInput,
7915
- methodID: "browser"
7916
- });
7917
- } catch {
7918
- return "dead";
7919
- }
7920
- const attemptID = attempt.data.attemptID;
7921
- const pollVerdict = (data) => {
7922
- if (data.status === "complete") return "alive";
7923
- if (data.status === "failed") {
7924
- const alive = [
7925
- CONNECT_COPY.signedInNextStep,
7926
- NO_USABLE_LEASE_MESSAGE
7927
- ].some((marker) => data.message?.includes(marker) === true);
7928
- return alive ? "alive" : "dead";
8305
+ // src/tui-entry/v2-session-watch/v2-session-watch.ts
8306
+ init_abortable_sleep2();
8307
+ var watchV2SessionBecomeAlive = (deps) => {
8308
+ const sleep = deps.sleep ?? abortableSleep;
8309
+ const now = deps.now ?? Date.now;
8310
+ const deadline = now() + (deps.watchMs ?? 12e4);
8311
+ let stopped = false;
8312
+ const isStopped = () => stopped;
8313
+ const pending = () => {
8314
+ try {
8315
+ return deps.pending();
8316
+ } catch {
8317
+ return false;
7929
8318
  }
7930
- if (data.status === "expired") return "dead";
7931
- return void 0;
7932
8319
  };
7933
- for (let poll = 0; poll < probePolls; poll += 1) {
7934
- if (poll > 0) {
7935
- await sleep(pollDelayMs);
8320
+ const poll = async () => {
8321
+ while (!isStopped()) {
8322
+ if (!pending()) return;
8323
+ if (now() >= deadline) return;
8324
+ const alive = await deps.probe().catch(() => false);
8325
+ if (isStopped()) return;
8326
+ if (alive) {
8327
+ if (!pending()) return;
8328
+ await deps.onAlive().catch(() => void 0);
8329
+ return;
8330
+ }
8331
+ await sleep(deps.pollDelayMs ?? 2e3);
7936
8332
  }
7937
- const result = await status({
7938
- attemptID,
7939
- integrationID: "route33",
7940
- location: locationInput
7941
- });
7942
- const verdict = pollVerdict(result.data);
7943
- if (verdict !== void 0) {
7944
- return verdict;
8333
+ };
8334
+ void poll();
8335
+ return {
8336
+ stop: () => {
8337
+ stopped = true;
7945
8338
  }
7946
- }
7947
- const cancelAttempt = cancel?.({
7948
- attemptID,
7949
- integrationID: "route33",
7950
- location: locationInput
7951
- });
7952
- await cancelAttempt?.catch(() => void 0);
7953
- return "dead";
8339
+ };
7954
8340
  };
7955
8341
 
7956
8342
  // src/tui-entry/v2-setup-lock/v2-setup-lock.ts
@@ -8002,25 +8388,28 @@ init_route33_runtime2();
8002
8388
  init_shared();
8003
8389
 
8004
8390
  // src/v2-entry/host-lease-state-store/host-lease-state-store.ts
8005
- init_adapters();
8006
8391
  init_lease_state2();
8007
8392
  var hostLeaseStateStore = (options) => ({
8393
+ // The box envelope keeps the server part's writes readable from the
8394
+ // TUI part's reactive storage at the same plugin key.
8008
8395
  get: async () => {
8009
8396
  const value = await options.storage.get(options.key);
8010
- if (value === void 0) {
8011
- return void 0;
8397
+ if (typeof value === "object" && value !== null && "value" in value && typeof value.value === "string") {
8398
+ return LeaseState.restore(JSON.parse(value.value)).snapshot();
8012
8399
  }
8013
- if (typeof value !== "string") {
8014
- throw new ContractParseError("lease metadata must be a JSON string");
8400
+ if (typeof value === "string") {
8401
+ return LeaseState.restore(JSON.parse(value)).snapshot();
8015
8402
  }
8016
- return LeaseState.restore(JSON.parse(value)).snapshot();
8403
+ return void 0;
8017
8404
  },
8018
8405
  set: async (state) => {
8019
8406
  if (state === void 0) {
8020
8407
  await options.storage.remove(options.key);
8021
8408
  return;
8022
8409
  }
8023
- await options.storage.set(options.key, JSON.stringify(state));
8410
+ await options.storage.set(options.key, {
8411
+ value: JSON.stringify(state)
8412
+ });
8024
8413
  }
8025
8414
  });
8026
8415
 
@@ -8029,20 +8418,24 @@ var DEFAULT_TOKEN_KEY = "route33_auth";
8029
8418
  var LEGACY_TOKEN_KEY = "route33:auth";
8030
8419
  var hostTokenStore = (options) => {
8031
8420
  const key = options.key ?? DEFAULT_TOKEN_KEY;
8421
+ const readBoxed = async () => {
8422
+ const value = await options.storage.get(key);
8423
+ if (typeof value === "object" && value !== null && "value" in value && typeof value.value === "string") {
8424
+ return value.value;
8425
+ }
8426
+ return typeof value === "string" ? value : void 0;
8427
+ };
8428
+ const readLegacy = async () => {
8429
+ const legacy = await options.storage.get(LEGACY_TOKEN_KEY);
8430
+ return typeof legacy === "string" ? legacy : void 0;
8431
+ };
8032
8432
  return {
8033
- get: async () => {
8034
- const value = await options.storage.get(key);
8035
- if (typeof value === "string") {
8036
- return value;
8037
- }
8038
- const legacy = await options.storage.get(LEGACY_TOKEN_KEY);
8039
- return typeof legacy === "string" ? legacy : void 0;
8040
- },
8433
+ get: async () => await readBoxed() ?? await readLegacy(),
8041
8434
  set: async (value) => {
8042
8435
  if (value === void 0) {
8043
8436
  await options.storage.remove(key);
8044
8437
  } else {
8045
- await options.storage.set(key, value);
8438
+ await options.storage.set(key, { value });
8046
8439
  }
8047
8440
  await options.storage.remove(LEGACY_TOKEN_KEY);
8048
8441
  }
@@ -8122,6 +8515,7 @@ var createV2Tui = () => ({
8122
8515
  setup: (context) => {
8123
8516
  const tuiRuntime = composeV2TuiRuntime(context);
8124
8517
  const menuHandlers = () => tuiRuntime?.commandHandlers();
8518
+ let stopSessionWatch = () => void 0;
8125
8519
  context.keymap?.layer(() => ({
8126
8520
  mode: "global",
8127
8521
  priority: 10,
@@ -8137,6 +8531,7 @@ var createV2Tui = () => ({
8137
8531
  enabled: () => true,
8138
8532
  run: async () => {
8139
8533
  wizard.menuRequested();
8534
+ stopSessionWatch();
8140
8535
  try {
8141
8536
  await showR33Menu(context, { handlers: menuHandlers });
8142
8537
  } finally {
@@ -8155,13 +8550,22 @@ var createV2Tui = () => ({
8155
8550
  directory,
8156
8551
  outsideWorktree: "return-undefined"
8157
8552
  }) !== void 0;
8158
- const connect = v2ConnectSurface(context);
8159
- const status = v2StatusSurface(context);
8553
+ const sessionProbe = async () => {
8554
+ const get = context.client?.integration?.get;
8555
+ if (get === void 0) {
8556
+ return "alive";
8557
+ }
8558
+ const info = await get({
8559
+ integrationID: "route33",
8560
+ ...location === void 0 ? {} : { location }
8561
+ }).catch(() => void 0);
8562
+ return (info?.data.connections?.length ?? 0) > 0 ? "alive" : "dead";
8563
+ };
8160
8564
  const globalFallback = async () => {
8161
8565
  if (detectWorktreeRoot(directory) !== void 0) return false;
8162
8566
  const form = await v2AttributionForm(context).catch(() => void 0);
8163
8567
  for (const option of form?.options ?? []) {
8164
- if (option.value === "personal" && option.label.includes(PERSONAL_KEY_ACTIVE_MARKER)) {
8568
+ if (isPersonalSelection(option.value) && option.label.includes(PERSONAL_KEY_ACTIVE_MARKER)) {
8165
8569
  return true;
8166
8570
  }
8167
8571
  }
@@ -8187,12 +8591,7 @@ var createV2Tui = () => ({
8187
8591
  globalPersonalKey = silent;
8188
8592
  return silent;
8189
8593
  },
8190
- probe: () => connect === void 0 || status === void 0 ? Promise.resolve("alive") : v2SessionProbe({
8191
- cancel: context.client?.integration?.oauth?.cancel,
8192
- connect,
8193
- locationInput: { directory },
8194
- status
8195
- }),
8594
+ probe: sessionProbe,
8196
8595
  wizard: () => v2Autoconnect(
8197
8596
  // The wizard re-derives its directory from the context
8198
8597
  // location, which is undefined until the first route lands —
@@ -8219,11 +8618,26 @@ var createV2Tui = () => ({
8219
8618
  run: boot
8220
8619
  });
8221
8620
  void lock.start().catch(() => void 0);
8621
+ const sessionWatch = watchV2SessionBecomeAlive({
8622
+ onAlive: () => lock.start({ assumedAlive: true }),
8623
+ pending: () => v2SetupDirectory({ location: { directory } }) !== void 0,
8624
+ probe: () => sessionProbe().then(
8625
+ (verdict) => verdict === "alive",
8626
+ () => false
8627
+ )
8628
+ });
8629
+ stopSessionWatch = sessionWatch.stop;
8222
8630
  registerV2BootReentry({
8223
8631
  listen: context.data?.listen,
8224
8632
  pending: () => v2SetupDirectory({ location: { directory } }) !== void 0,
8225
8633
  start: () => lock.start({ assumedAlive: true }),
8226
- superseded: wizard.superseded
8634
+ superseded: () => {
8635
+ if (wizard.superseded()) {
8636
+ stopSessionWatch();
8637
+ return true;
8638
+ }
8639
+ return false;
8640
+ }
8227
8641
  });
8228
8642
  }
8229
8643
  });