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

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.
@@ -1813,16 +1813,25 @@ var HostStorageSecretStore = class {
1813
1813
  /** Reads and parses the scoped gateway credential.
1814
1814
  * @returns The persisted credential, when present.
1815
1815
  */
1816
+ /** Reads the scoped gateway credential out of the box envelope the
1817
+ * host's reactive storage uses, so the TUI part reads what the
1818
+ * server part wrote at the same plugin key.
1819
+ * @returns The persisted credential, when present.
1820
+ */
1816
1821
  async get() {
1817
1822
  const value = await this.#storage.get(this.#key);
1818
- return value === void 0 ? void 0 : parseGatewayKey(value);
1823
+ if (typeof value === "object" && value !== null && "value" in value && typeof value.value === "string") {
1824
+ return parseGatewayKey(value.value);
1825
+ }
1826
+ return typeof value === "string" ? parseGatewayKey(value) : void 0;
1819
1827
  }
1820
- /** Writes the scoped gateway credential only through host-owned storage.
1828
+ /** Writes the scoped gateway credential into the box envelope, through
1829
+ * host-owned storage only.
1821
1830
  * @param key - The credential to persist, or undefined to remove it.
1822
1831
  * @returns A promise that settles after the host write or removal.
1823
1832
  */
1824
1833
  set(key) {
1825
- return key === void 0 ? this.#storage.remove(this.#key) : this.#storage.set(this.#key, key.value);
1834
+ return key === void 0 ? this.#storage.remove(this.#key) : this.#storage.set(this.#key, { value: key.value });
1826
1835
  }
1827
1836
  };
1828
1837
 
@@ -1836,8 +1845,10 @@ var KeyLeaseError = class extends Error {
1836
1845
  );
1837
1846
  this.code = code;
1838
1847
  this.name = "KeyLeaseError";
1848
+ this.statusCode = options?.statusCode;
1839
1849
  }
1840
1850
  code;
1851
+ statusCode;
1841
1852
  };
1842
1853
 
1843
1854
  // src/key-lease/is-management-unauthorized/is-management-unauthorized.ts
@@ -1975,6 +1986,7 @@ var buildMintInput = (deps) => {
1975
1986
  managementSubject: deps.managementSubject
1976
1987
  });
1977
1988
  return {
1989
+ ...deps.attribution.orgId === void 0 ? {} : { activeOrgId: deps.attribution.orgId },
1978
1990
  allowedModels: deps.extras?.allowedModels,
1979
1991
  description: deps.extras?.description,
1980
1992
  expiresAt: new Date(
@@ -2077,6 +2089,21 @@ var rejectLease = async (options) => {
2077
2089
  }
2078
2090
  };
2079
2091
 
2092
+ // src/management/management-error/management-error.ts
2093
+ var ManagementError = class extends Error {
2094
+ constructor(code, options) {
2095
+ super(
2096
+ "Route 33 management request failed",
2097
+ options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
2098
+ );
2099
+ this.code = code;
2100
+ this.name = "ManagementError";
2101
+ this.statusCode = options?.statusCode;
2102
+ }
2103
+ code;
2104
+ statusCode;
2105
+ };
2106
+
2080
2107
  // src/key-lease/mint-key/mint-key.ts
2081
2108
  var mintKey = async (options) => {
2082
2109
  const now = options.clock();
@@ -2110,7 +2137,10 @@ var mintKey = async (options) => {
2110
2137
  if (isManagementUnauthorized(cause)) {
2111
2138
  throw new KeyLeaseError("KEY_LEASE_UNAUTHORIZED", { cause });
2112
2139
  }
2113
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", { cause });
2140
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
2141
+ cause,
2142
+ ...cause instanceof ManagementError && cause.statusCode !== void 0 ? { statusCode: cause.statusCode } : {}
2143
+ });
2114
2144
  }
2115
2145
  return {
2116
2146
  key: material.key,
@@ -2403,16 +2433,33 @@ var clearAttribution = (options) => {
2403
2433
  import * as path10 from "node:path";
2404
2434
  var LEGACY_KEY_RELATIVE_PATH = path10.join(".opencode", "route33.key");
2405
2435
 
2436
+ // src/attribution/parse-attribution/read-org-id/read-org-id.ts
2437
+ var readOrgId = (value) => {
2438
+ const orgId = value["orgId"];
2439
+ if (orgId === void 0) {
2440
+ return void 0;
2441
+ }
2442
+ if (typeof orgId !== "string") {
2443
+ throw new ContractParseError("invalid attribution");
2444
+ }
2445
+ return orgId;
2446
+ };
2447
+
2406
2448
  // src/attribution/parse-attribution/parse-attribution.ts
2407
2449
  var parseAttribution = (value) => {
2408
2450
  if (!isRecord(value)) {
2409
2451
  throw new ContractParseError("invalid attribution");
2410
2452
  }
2453
+ const orgId = readOrgId(value);
2411
2454
  if (value["kind"] === "personal") {
2412
- return { kind: "personal" };
2455
+ return { kind: "personal", ...orgId === void 0 ? {} : { orgId } };
2413
2456
  }
2414
2457
  if (value["kind"] === "project" && typeof value["projectId"] === "string") {
2415
- return { kind: "project", projectId: value["projectId"] };
2458
+ return {
2459
+ kind: "project",
2460
+ ...orgId === void 0 ? {} : { orgId },
2461
+ projectId: value["projectId"]
2462
+ };
2416
2463
  }
2417
2464
  throw new ContractParseError("invalid attribution");
2418
2465
  };
@@ -2631,35 +2678,82 @@ var rotateNow = async (options) => {
2631
2678
  return rotated.lease;
2632
2679
  };
2633
2680
 
2681
+ // src/ux/attribution-prompt/org-selection-prefix/org-selection-prefix.ts
2682
+ var orgSelectionPrefix = (orgId) => `org:${orgId}:`;
2683
+
2684
+ // src/ux/attribution-prompt/personal-budgeted/personal-budgeted.ts
2685
+ var personalBudgeted = (org) => {
2686
+ const cap = org.personalBudget?.cap;
2687
+ return cap === void 0 || cap !== null && cap > 0;
2688
+ };
2689
+
2634
2690
  // src/ux/attribution-prompt/attribution-prompt.ts
2635
2691
  var PERSONAL_KEY_ACTIVE_MARKER = "machine key active";
2692
+ var PROMPT_TITLE = "Choose where Route 33 should manage this key";
2636
2693
  var createAttributionPrompt = (projects, options = {}) => {
2637
- const choicesBySelection = {
2638
- personal: { kind: "personal" }
2694
+ const personalLabel = (orgName) => {
2695
+ const marker = options.personalKeyActive === true ? ` (${PERSONAL_KEY_ACTIVE_MARKER})` : "";
2696
+ const orgSuffix = orgName === void 0 ? "" : ` \u2014 ${orgName}`;
2697
+ return `Personal \u2014 your own key${marker}${orgSuffix}`;
2639
2698
  };
2640
- const projectOptions = projects.map((project) => {
2641
- const selection = `project:${project.id}`;
2642
- choicesBySelection[selection] = {
2643
- kind: "project",
2644
- projectId: project.id
2645
- };
2699
+ const budgetAllowance = (project) => {
2646
2700
  const budget = project.effective_budget ?? project.max_budget;
2647
- const allowance = budget === null ? "no cap set" : `cap ${budget.amount} ${budget.currency}`;
2701
+ return budget === null ? "no cap set" : `cap ${budget.amount} ${budget.currency}`;
2702
+ };
2703
+ const choicesBySelection = {};
2704
+ if (options.orgs === void 0) {
2705
+ choicesBySelection.personal = { kind: "personal" };
2706
+ const projectOptions = projects.map((project) => {
2707
+ const selection = `project:${project.id}`;
2708
+ choicesBySelection[selection] = {
2709
+ kind: "project",
2710
+ projectId: project.id
2711
+ };
2712
+ return {
2713
+ label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${budgetAllowance(project)}`,
2714
+ selection
2715
+ };
2716
+ });
2648
2717
  return {
2649
- label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${allowance}`,
2650
- selection
2718
+ choicesBySelection,
2719
+ options: [
2720
+ { label: personalLabel(), selection: "personal" },
2721
+ ...projectOptions
2722
+ ],
2723
+ title: PROMPT_TITLE
2651
2724
  };
2652
- });
2725
+ }
2726
+ const promptOptions = [];
2727
+ for (const org of options.orgs) {
2728
+ const personal = `${orgSelectionPrefix(org.id)}personal`;
2729
+ if (personalBudgeted(org)) {
2730
+ choicesBySelection[personal] = { kind: "personal", orgId: org.id };
2731
+ promptOptions.push({
2732
+ label: personalLabel(options.orgs.length > 1 ? org.name : void 0),
2733
+ selection: personal
2734
+ });
2735
+ }
2736
+ for (const project of projects) {
2737
+ if (project.organisation.id !== org.id) {
2738
+ continue;
2739
+ }
2740
+ const selection = `${orgSelectionPrefix(org.id)}project:${project.id}`;
2741
+ choicesBySelection[selection] = {
2742
+ kind: "project",
2743
+ orgId: org.id,
2744
+ projectId: project.id
2745
+ };
2746
+ promptOptions.push({
2747
+ label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${budgetAllowance(project)}`,
2748
+ selection
2749
+ });
2750
+ }
2751
+ }
2653
2752
  return {
2654
2753
  choicesBySelection,
2655
- options: [
2656
- {
2657
- label: options.personalKeyActive === true ? `Personal \u2014 your own key (${PERSONAL_KEY_ACTIVE_MARKER})` : "Personal \u2014 your own key",
2658
- selection: "personal"
2659
- },
2660
- ...projectOptions
2661
- ],
2662
- title: "Choose where Route 33 should manage this key"
2754
+ options: promptOptions,
2755
+ orgs: options.orgs,
2756
+ title: PROMPT_TITLE
2663
2757
  };
2664
2758
  };
2665
2759
 
@@ -2720,7 +2814,7 @@ import {
2720
2814
  } from "@r-33/auth-browser";
2721
2815
 
2722
2816
  // src/requested-scopes/requested-scopes.ts
2723
- var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read projects:read users:read keys:read keys:write";
2817
+ var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read profile projects:read users:read keys:read keys:write";
2724
2818
 
2725
2819
  // src/route33-login/route33-login.ts
2726
2820
  var route33Login = async (options) => {
@@ -2869,9 +2963,8 @@ var Route33Runtime = class {
2869
2963
  * Lists exactly the projects the current management login can mint keys
2870
2964
  * on: the login's per-user budget rows intersected with the
2871
2965
  * member-visible project listing, organisation names stitched from the
2872
- * login's own memberships. Orgs the login merely administers carry no
2873
- * budget row and drop out — the picker never offers a project whose
2874
- * keys the login cannot create. A `allowBrowser: false` policy makes
2966
+ * login's own memberships. Zero-cap rows drop out — a project whose
2967
+ * budget cannot spend never mints. A `allowBrowser: false` policy makes
2875
2968
  * the call non-blocking: a dead session rejects instead of opening a
2876
2969
  * browser, so the picker's form registration never stalls a boot.
2877
2970
  * @param policy - Whether a dead session may open a browser login.
@@ -2885,21 +2978,69 @@ var Route33Runtime = class {
2885
2978
  client.listProjectBudgets(credential, subject),
2886
2979
  client.listMemberships(credential, subject)
2887
2980
  ]);
2888
- const organisationNames = new Map(
2889
- memberships.org_memberships.map(({ org_id, org_name }) => [
2890
- org_id,
2891
- org_name
2892
- ])
2981
+ return this.#budgetedProjects(
2982
+ credential,
2983
+ client,
2984
+ budgets,
2985
+ new Map(
2986
+ memberships.org_memberships.map(({ org_id, org_name }) => [
2987
+ org_id,
2988
+ org_name
2989
+ ])
2990
+ )
2893
2991
  );
2992
+ }
2993
+ /**
2994
+ * Lists one organisation per membership with that organisation's
2995
+ * mintable projects and effective personal budget — the wizard's org
2996
+ * picker data. Budgets resolve per organisation (the active-org
2997
+ * header), so rows never mix orgs; zero-cap rows drop out, and an
2998
+ * unreadable organisation degrades to its empty picker — or an unknown
2999
+ * personal budget — instead of failing the whole list.
3000
+ * @param policy - Whether a dead session may open a browser login.
3001
+ * @returns One mintable-projects entry per organisation membership.
3002
+ */
3003
+ async listMintableOrgs(policy = {}) {
3004
+ const credential = await this.#session.credential(policy);
3005
+ const subject = this.#subject(credential);
3006
+ const client = this.#client();
3007
+ const memberships = await client.listMemberships(credential, subject);
3008
+ return Promise.all(
3009
+ memberships.org_memberships.map(async ({ org_id, org_name }) => ({
3010
+ id: org_id,
3011
+ name: org_name,
3012
+ personalBudget: await client.listBudgetPolicy(credential, subject, org_id).then((budget) => ({ cap: budget.cap })).catch(() => void 0),
3013
+ projects: await client.listProjectBudgets(credential, subject, org_id).then(
3014
+ (budgets) => this.#budgetedProjects(
3015
+ credential,
3016
+ client,
3017
+ budgets,
3018
+ /* @__PURE__ */ new Map([[org_id, org_name]])
3019
+ )
3020
+ ).catch(() => [])
3021
+ }))
3022
+ );
3023
+ }
3024
+ /**
3025
+ * Joins cap-bearing budget rows with their listed projects; zero caps
3026
+ * never mint.
3027
+ * @param credential - The management bearer token for project listings.
3028
+ * @param client - The management contract implementation.
3029
+ * @param budgets - The login's per-user budget rows.
3030
+ * @param organisationNames - The login's org names by org id.
3031
+ * @returns The mintable projects carrying organisation context.
3032
+ */
3033
+ async #budgetedProjects(credential, client, budgets, organisationNames) {
3034
+ const rows = budgets.data.filter((row) => row.cap > 0);
2894
3035
  const listings = await Promise.all(
2895
- [...new Set(budgets.data.map(({ org_id }) => org_id))].map(
3036
+ [...new Set(rows.map(({ org_id }) => org_id))].map(
2896
3037
  (orgId) => client.listProjects(credential, orgId)
2897
3038
  )
2898
3039
  );
2899
3040
  const projectsById = new Map(
2900
3041
  listings.flatMap(({ data }) => data).map((project) => [project.id, project])
2901
3042
  );
2902
- return budgets.data.flatMap(({ org_id, project_id }) => {
3043
+ return rows.flatMap(({ org_id, project_id }) => {
2903
3044
  const project = projectsById.get(project_id);
2904
3045
  if (project === void 0) {
2905
3046
  return [];
@@ -3334,21 +3475,6 @@ var drainPages = async (fetchPage) => {
3334
3475
  return { data, page: { ...page, has_more: false, next_cursor: null } };
3335
3476
  };
3336
3477
 
3337
- // src/management/management-error/management-error.ts
3338
- var ManagementError = class extends Error {
3339
- constructor(code, options) {
3340
- super(
3341
- "Route 33 management request failed",
3342
- options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
3343
- );
3344
- this.code = code;
3345
- this.name = "ManagementError";
3346
- this.statusCode = options?.statusCode;
3347
- }
3348
- code;
3349
- statusCode;
3350
- };
3351
-
3352
3478
  // src/management/sdk-management-keys/sdk-management-keys.ts
3353
3479
  import {
3354
3480
  createRoute33Client,
@@ -3386,6 +3512,26 @@ var parseApiKey = (value) => {
3386
3512
  };
3387
3513
  };
3388
3514
 
3515
+ // src/contract/management-keys/parse-budget-policy/parse-budget-policy.ts
3516
+ var parseBudgetPolicy = (value) => {
3517
+ if (!isRecord(value)) {
3518
+ throw new ContractParseError("invalid budget policy");
3519
+ }
3520
+ const cap = value["cap"];
3521
+ if (typeof cap !== "number" && cap !== null) {
3522
+ throw new ContractParseError("invalid budget policy");
3523
+ }
3524
+ const orgId = value["org_id"];
3525
+ if (typeof orgId !== "string") {
3526
+ throw new ContractParseError("invalid budget policy");
3527
+ }
3528
+ const source = value["source"];
3529
+ if (source !== "own_cap" && source !== "project_default" && source !== "org_default" && source !== "tenant_default" && source !== "platform_default") {
3530
+ throw new ContractParseError("invalid budget policy");
3531
+ }
3532
+ return { cap, org_id: orgId, source };
3533
+ };
3534
+
3389
3535
  // src/contract/management-keys/parse-collection/parse-collection.ts
3390
3536
  var parseCollection = (value, parseItem) => {
3391
3537
  if (!isRecord(value)) {
@@ -3595,28 +3741,46 @@ var parseUserMemberships = (value) => {
3595
3741
  };
3596
3742
  };
3597
3743
 
3744
+ // src/management/sdk-management-keys/mint-request-body/mint-request-body.ts
3745
+ var buildMintRequestBody = (input) => ({
3746
+ ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
3747
+ budget_currency: "EUR",
3748
+ ...input.description === void 0 ? {} : { description: input.description },
3749
+ expires_at: input.expiresAt,
3750
+ ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
3751
+ name: input.name,
3752
+ ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
3753
+ owner_type: input.ownerType,
3754
+ ...input.projectId === null ? {} : { project_id: input.projectId }
3755
+ });
3756
+
3598
3757
  // src/management/sdk-management-keys/sdk-management-keys.ts
3599
3758
  var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
3759
+ var ACTIVE_ORG_HEADER = "X-Active-Org-Id";
3600
3760
  var sdkManagementKeys = (options) => {
3601
3761
  const baseUrl = options.apiBaseUrl.replace(API_PREFIX_PATTERN, "");
3602
3762
  const timeoutMs = options.timeoutMs ?? 1e4;
3603
3763
  const fetchImpl = options.fetchImpl;
3604
- const observingFetch = (status) => fetchImpl === void 0 ? void 0 : async (input, init) => {
3605
- const response = await fetchImpl(input, init);
3606
- status.code = response.status;
3607
- return response;
3764
+ const activeOrgFetch = (activeOrgId) => activeOrgId === void 0 ? void 0 : (input, init) => {
3765
+ if (input instanceof Request) {
3766
+ input.headers.set(ACTIVE_ORG_HEADER, activeOrgId);
3767
+ }
3768
+ if (init?.headers instanceof Headers) {
3769
+ init.headers.set(ACTIVE_ORG_HEADER, activeOrgId);
3770
+ }
3771
+ return (fetchImpl ?? globalThis.fetch)(input, init);
3608
3772
  };
3609
- const callClient = (accessToken, status) => {
3773
+ const callClient = (accessToken, activeOrgId) => {
3610
3774
  const provider = {
3611
3775
  getToken: () => Promise.resolve(accessToken.value),
3612
3776
  onUnauthorized: () => Promise.resolve(accessToken.value)
3613
3777
  };
3614
- const observedFetch = observingFetch(status);
3778
+ const fetch2 = activeOrgFetch(activeOrgId) ?? fetchImpl;
3615
3779
  return createRoute33Client({
3616
3780
  baseUrl,
3617
3781
  provider,
3618
3782
  timeoutMs,
3619
- ...observedFetch === void 0 ? {} : { fetch: observedFetch }
3783
+ ...fetch2 === void 0 ? {} : { fetch: fetch2 }
3620
3784
  });
3621
3785
  };
3622
3786
  const mapFailure = (cause) => {
@@ -3632,11 +3796,10 @@ var sdkManagementKeys = (options) => {
3632
3796
  }
3633
3797
  return new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
3634
3798
  };
3635
- const call = async (accessToken, run) => {
3636
- const status = { code: void 0 };
3799
+ const call = async (accessToken, activeOrgId, run) => {
3637
3800
  try {
3638
- const outcome = await run(callClient(accessToken, status));
3639
- const code = status.code;
3801
+ const outcome = await run(callClient(accessToken, activeOrgId));
3802
+ const code = outcome.response?.status;
3640
3803
  if (code === void 0 || code < 200 || code >= 300) {
3641
3804
  throw new ManagementError(
3642
3805
  code === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
@@ -3652,24 +3815,16 @@ var sdkManagementKeys = (options) => {
3652
3815
  create: async (accessToken, input) => parseKeyMaterial(
3653
3816
  await call(
3654
3817
  accessToken,
3818
+ input.activeOrgId,
3655
3819
  (client) => client.POST("/api/v1/api-keys", {
3656
- body: {
3657
- ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
3658
- budget_currency: "EUR",
3659
- ...input.description === void 0 ? {} : { description: input.description },
3660
- expires_at: input.expiresAt,
3661
- ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
3662
- name: input.name,
3663
- ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
3664
- owner_type: input.ownerType,
3665
- ...input.projectId === null ? {} : { project_id: input.projectId }
3666
- }
3820
+ body: buildMintRequestBody(input)
3667
3821
  })
3668
3822
  )
3669
3823
  ),
3670
3824
  delete: async (accessToken, id) => {
3671
3825
  await call(
3672
3826
  accessToken,
3827
+ void 0,
3673
3828
  (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
3674
3829
  params: { path: { api_key_id: id } }
3675
3830
  })
@@ -3678,30 +3833,50 @@ var sdkManagementKeys = (options) => {
3678
3833
  get: async (accessToken, id) => parseApiKey(
3679
3834
  await call(
3680
3835
  accessToken,
3836
+ void 0,
3681
3837
  (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
3682
3838
  params: { path: { api_key_id: id } }
3683
3839
  })
3684
3840
  )
3685
3841
  ),
3686
3842
  list: async (accessToken) => parseCollection(
3687
- await call(accessToken, (client) => client.GET("/api/v1/api-keys", {})),
3843
+ await call(
3844
+ accessToken,
3845
+ void 0,
3846
+ (client) => client.GET("/api/v1/api-keys", {})
3847
+ ),
3688
3848
  parseApiKey
3689
3849
  ),
3690
3850
  listOrganizations: async (accessToken) => parseCollection(
3691
- await call(accessToken, (client) => client.GET("/api/v1/orgs", {})),
3851
+ await call(
3852
+ accessToken,
3853
+ void 0,
3854
+ (client) => client.GET("/api/v1/orgs", {})
3855
+ ),
3692
3856
  parseOrganization
3693
3857
  ),
3694
3858
  listMemberships: async (accessToken, userId) => parseUserMemberships(
3695
3859
  await call(
3696
3860
  accessToken,
3861
+ void 0,
3697
3862
  (client) => client.GET("/api/v1/users/{user_id}/memberships", {
3698
3863
  params: { path: { user_id: userId } }
3699
3864
  })
3700
3865
  )
3701
3866
  ),
3702
- listProjectBudgets: async (accessToken, userId) => parseCollection(
3867
+ listBudgetPolicy: async (accessToken, userId, activeOrgId) => parseBudgetPolicy(
3703
3868
  await call(
3704
3869
  accessToken,
3870
+ activeOrgId,
3871
+ (client) => client.GET("/api/v1/users/{user_id}/budget-policy", {
3872
+ params: { path: { user_id: userId } }
3873
+ })
3874
+ )
3875
+ ),
3876
+ listProjectBudgets: async (accessToken, userId, activeOrgId) => parseCollection(
3877
+ await call(
3878
+ accessToken,
3879
+ activeOrgId,
3705
3880
  (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
3706
3881
  params: { path: { user_id: userId } }
3707
3882
  })
@@ -3720,6 +3895,7 @@ var sdkManagementKeys = (options) => {
3720
3895
  };
3721
3896
  const fetchPage = (cursor) => call(
3722
3897
  accessToken,
3898
+ void 0,
3723
3899
  (client) => client.GET("/api/v1/projects", {
3724
3900
  params: {
3725
3901
  query: cursor === "" ? query : { ...query, cursor }
@@ -3731,6 +3907,7 @@ var sdkManagementKeys = (options) => {
3731
3907
  regenerate: async (accessToken, id, expiresAt) => parseKeyMaterial(
3732
3908
  await call(
3733
3909
  accessToken,
3910
+ void 0,
3734
3911
  (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
3735
3912
  body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
3736
3913
  params: { path: { api_key_id: id } }
@@ -3740,6 +3917,7 @@ var sdkManagementKeys = (options) => {
3740
3917
  update: async (accessToken, id, input) => parseApiKey(
3741
3918
  await call(
3742
3919
  accessToken,
3920
+ void 0,
3743
3921
  (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
3744
3922
  body: {
3745
3923
  budget_currency: "EUR",
@@ -4174,6 +4352,19 @@ var parseBudgetAnswer = (answer) => {
4174
4352
  };
4175
4353
  };
4176
4354
 
4355
+ // src/v2-entry/connect-copy/connect-copy.ts
4356
+ var CONNECT_COPY = {
4357
+ 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.",
4358
+ failFastWorktree: "Route 33 attributes usage to a project inside a Git worktree. Open a Git repository (or run git init), then connect again.",
4359
+ selectionInvalid: "That Route 33 option is no longer available. Connect again and pick another.",
4360
+ signedInNextStep: "Signed in to Route 33 \u2713. One more step: connect again, choose Route 33, and assign a budget for this folder.",
4361
+ mintNoBudget: "Route 33 could not create the key \u2014 its cap exceeds this budget. Ask an owner to raise the budget, or pick another."
4362
+ };
4363
+
4364
+ // src/v2-entry/apply-wizard-answer/map-mint-failure/map-mint-failure.ts
4365
+ var MINT_BUDGET_FAILURE_STATUS = 422;
4366
+ var mapMintFailure = (cause) => cause instanceof KeyLeaseError && cause.statusCode === MINT_BUDGET_FAILURE_STATUS ? new GatewayCredentialError(CONNECT_COPY.mintNoBudget) : cause;
4367
+
4177
4368
  // src/v2-entry/apply-wizard-answer/apply-wizard-answer.ts
4178
4369
  var applyWizardAnswer = async (deps, answer) => {
4179
4370
  const budget = parseBudgetAnswer(answer);
@@ -4183,18 +4374,18 @@ var applyWizardAnswer = async (deps, answer) => {
4183
4374
  if (choice === void 0) {
4184
4375
  throw new AttributionPromptError("ATTRIBUTION_SELECTION_INVALID");
4185
4376
  }
4186
- writeAttribution(deps.state, choice);
4187
- if (budget !== void 0 && deps.mintWorkspaceKey !== void 0) {
4188
- await deps.mintWorkspaceKey(choice, budget.extras);
4377
+ if (choice.orgId !== void 0) {
4378
+ deps.onOrgAnswered(choice.orgId);
4189
4379
  }
4190
- };
4191
-
4192
- // src/v2-entry/connect-copy/connect-copy.ts
4193
- var CONNECT_COPY = {
4194
- 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.",
4195
- failFastWorktree: "Route 33 attributes usage to a project inside a Git worktree. Open a Git repository (or run git init), then connect again.",
4196
- selectionInvalid: "That Route 33 option is no longer available. Connect again and pick another.",
4197
- signedInNextStep: "Signed in to Route 33 \u2713. One more step: connect again, choose Route 33, and assign a budget for this folder."
4380
+ const mint = deps.mintWorkspaceKey;
4381
+ if (budget !== void 0 && mint !== void 0) {
4382
+ try {
4383
+ await mint(choice, budget.extras);
4384
+ } catch (cause) {
4385
+ throw mapMintFailure(cause);
4386
+ }
4387
+ }
4388
+ writeAttribution(deps.state, choice);
4198
4389
  };
4199
4390
 
4200
4391
  // src/v2-entry/connect-authorize/connect-authorize.ts
@@ -4241,19 +4432,28 @@ var createConnectAuthorize = (deps) => async (answer = {}) => {
4241
4432
 
4242
4433
  // src/v2-entry/connect-form/connect-form.ts
4243
4434
  var ATTRIBUTION_FIELD_KEY2 = "attribution";
4435
+ var ORGANISATION_FIELD_KEY = "organisation";
4244
4436
  var BUDGET_NAME_FIELD_KEY = "budget_name";
4245
4437
  var BUDGET_CAP_FIELD_KEY = "budget_cap";
4246
4438
  var BUDGET_DESCRIPTION_FIELD_KEY = "budget_description";
4247
4439
  var BUDGET_EXPIRY_FIELD_KEY = "budget_expiry";
4248
4440
  var ALLOWED_MODELS_FIELD_KEY = "allowed_models";
4441
+ var ORGANISATION_FIELD_TITLE = "Which Route 33 organisation covers this folder?";
4249
4442
  var EXPIRY_OPTIONS = [
4250
4443
  { label: "30 days", value: "30" },
4251
4444
  { label: "90 days", value: "90" },
4252
4445
  { label: "180 days", value: "180" },
4253
4446
  { label: "1 year", value: "365" }
4254
4447
  ];
4255
- var buildConnectForm = (plan, modelIds = []) => [
4256
- {
4448
+ var buildConnectForm = (plan, modelIds = []) => {
4449
+ const orgs = plan.orgs ?? [];
4450
+ const organisationField = {
4451
+ key: ORGANISATION_FIELD_KEY,
4452
+ options: orgs.map(({ id, name }) => ({ label: name, value: id })),
4453
+ title: ORGANISATION_FIELD_TITLE,
4454
+ type: "string"
4455
+ };
4456
+ const attributionField = {
4257
4457
  key: ATTRIBUTION_FIELD_KEY2,
4258
4458
  options: plan.options.map((option) => ({
4259
4459
  label: option.label,
@@ -4265,40 +4465,43 @@ var buildConnectForm = (plan, modelIds = []) => [
4265
4465
  // still sends the attribution on its answer pass.
4266
4466
  title: "Which budget covers Route 33 usage in this folder?",
4267
4467
  type: "string"
4268
- },
4269
- {
4270
- key: BUDGET_NAME_FIELD_KEY,
4271
- placeholder: "e.g. opencode-desk",
4272
- title: "Name for the new Route 33 key",
4273
- type: "string"
4274
- },
4275
- {
4276
- key: BUDGET_CAP_FIELD_KEY,
4277
- placeholder: "blank = unlimited",
4278
- title: "Monthly budget cap in EUR",
4279
- type: "string"
4280
- },
4281
- {
4282
- key: BUDGET_DESCRIPTION_FIELD_KEY,
4283
- title: "Description (optional)",
4284
- type: "string"
4285
- },
4286
- {
4287
- key: BUDGET_EXPIRY_FIELD_KEY,
4288
- options: EXPIRY_OPTIONS,
4289
- title: "When should the key expire?",
4290
- type: "string"
4291
- },
4292
- {
4293
- key: ALLOWED_MODELS_FIELD_KEY,
4294
- options: [
4295
- { label: "All models (inherit)", value: "all" },
4296
- ...modelIds.map((id) => ({ label: id, value: id }))
4297
- ],
4298
- title: "Which models may this key use?",
4299
- type: "string"
4300
- }
4301
- ];
4468
+ };
4469
+ const promptFields = [
4470
+ {
4471
+ key: BUDGET_NAME_FIELD_KEY,
4472
+ placeholder: "e.g. opencode-desk",
4473
+ title: "Name for the new Route 33 key",
4474
+ type: "string"
4475
+ },
4476
+ {
4477
+ key: BUDGET_CAP_FIELD_KEY,
4478
+ placeholder: "blank = unlimited",
4479
+ title: "Monthly budget cap in EUR",
4480
+ type: "string"
4481
+ },
4482
+ {
4483
+ key: BUDGET_DESCRIPTION_FIELD_KEY,
4484
+ title: "Description (optional)",
4485
+ type: "string"
4486
+ },
4487
+ {
4488
+ key: BUDGET_EXPIRY_FIELD_KEY,
4489
+ options: EXPIRY_OPTIONS,
4490
+ title: "When should the key expire?",
4491
+ type: "string"
4492
+ },
4493
+ {
4494
+ key: ALLOWED_MODELS_FIELD_KEY,
4495
+ options: [
4496
+ { label: "All models (inherit)", value: "all" },
4497
+ ...modelIds.map((id) => ({ label: id, value: id }))
4498
+ ],
4499
+ title: "Which models may this key use?",
4500
+ type: "string"
4501
+ }
4502
+ ];
4503
+ return orgs.length > 1 ? [organisationField, attributionField, ...promptFields] : [attributionField, ...promptFields];
4504
+ };
4302
4505
 
4303
4506
  // src/v2-entry/direct-key-mode/direct-key-mode.ts
4304
4507
  var directKeyMode = async (context, options, compose) => {
@@ -4321,22 +4524,26 @@ var directKeyMode = async (context, options, compose) => {
4321
4524
 
4322
4525
  // src/v2-entry/host-lease-state-store/host-lease-state-store.ts
4323
4526
  var hostLeaseStateStore = (options) => ({
4527
+ // The box envelope keeps the server part's writes readable from the
4528
+ // TUI part's reactive storage at the same plugin key.
4324
4529
  get: async () => {
4325
4530
  const value = await options.storage.get(options.key);
4326
- if (value === void 0) {
4327
- return void 0;
4531
+ if (typeof value === "object" && value !== null && "value" in value && typeof value.value === "string") {
4532
+ return LeaseState.restore(JSON.parse(value.value)).snapshot();
4328
4533
  }
4329
- if (typeof value !== "string") {
4330
- throw new ContractParseError("lease metadata must be a JSON string");
4534
+ if (typeof value === "string") {
4535
+ return LeaseState.restore(JSON.parse(value)).snapshot();
4331
4536
  }
4332
- return LeaseState.restore(JSON.parse(value)).snapshot();
4537
+ return void 0;
4333
4538
  },
4334
4539
  set: async (state) => {
4335
4540
  if (state === void 0) {
4336
4541
  await options.storage.remove(options.key);
4337
4542
  return;
4338
4543
  }
4339
- await options.storage.set(options.key, JSON.stringify(state));
4544
+ await options.storage.set(options.key, {
4545
+ value: JSON.stringify(state)
4546
+ });
4340
4547
  }
4341
4548
  });
4342
4549
 
@@ -4345,20 +4552,24 @@ var DEFAULT_TOKEN_KEY = "route33_auth";
4345
4552
  var LEGACY_TOKEN_KEY = "route33:auth";
4346
4553
  var hostTokenStore = (options) => {
4347
4554
  const key = options.key ?? DEFAULT_TOKEN_KEY;
4555
+ const readBoxed = async () => {
4556
+ const value = await options.storage.get(key);
4557
+ if (typeof value === "object" && value !== null && "value" in value && typeof value.value === "string") {
4558
+ return value.value;
4559
+ }
4560
+ return typeof value === "string" ? value : void 0;
4561
+ };
4562
+ const readLegacy = async () => {
4563
+ const legacy = await options.storage.get(LEGACY_TOKEN_KEY);
4564
+ return typeof legacy === "string" ? legacy : void 0;
4565
+ };
4348
4566
  return {
4349
- get: async () => {
4350
- const value = await options.storage.get(key);
4351
- if (typeof value === "string") {
4352
- return value;
4353
- }
4354
- const legacy = await options.storage.get(LEGACY_TOKEN_KEY);
4355
- return typeof legacy === "string" ? legacy : void 0;
4356
- },
4567
+ get: async () => await readBoxed() ?? await readLegacy(),
4357
4568
  set: async (value) => {
4358
4569
  if (value === void 0) {
4359
4570
  await options.storage.remove(key);
4360
4571
  } else {
4361
- await options.storage.set(key, value);
4572
+ await options.storage.set(key, { value });
4362
4573
  }
4363
4574
  await options.storage.remove(LEGACY_TOKEN_KEY);
4364
4575
  }
@@ -4531,6 +4742,7 @@ var createRoute33V2Plugin = (options = {}) => {
4531
4742
  let provider = mapRoute33V2Provider(void 0);
4532
4743
  let connectFields;
4533
4744
  let plan;
4745
+ let selectedOrgId;
4534
4746
  const runtimeInput = {
4535
4747
  ...options.runtime ?? buildProductionRuntimeOptions({
4536
4748
  apiBaseUrl,
@@ -4568,18 +4780,28 @@ var createRoute33V2Plugin = (options = {}) => {
4568
4780
  if (activeRuntime === void 0) {
4569
4781
  return;
4570
4782
  }
4571
- const [projects, modelIds, personalKeyActive] = await Promise.all([
4572
- activeRuntime.listMintableProjects({ allowBrowser: false }).catch(() => void 0),
4783
+ const [mintableOrgs, modelIds, personalKeyActive] = await Promise.all([
4784
+ activeRuntime.listMintableOrgs({ allowBrowser: false }).catch(() => void 0),
4573
4785
  activeRuntime.catalogModelIds().catch(() => []),
4574
4786
  activeRuntime.hasPersonalLease().catch(() => false)
4575
4787
  ]);
4576
- if (projects === void 0) {
4788
+ if (mintableOrgs === void 0) {
4577
4789
  plan = void 0;
4578
4790
  connectFields = void 0;
4579
4791
  await context.integration.reload();
4580
4792
  return;
4581
4793
  }
4582
- plan = createAttributionPrompt(projects, { personalKeyActive });
4794
+ const orgs = mintableOrgs.filter(
4795
+ (org) => selectedOrgId === void 0 || org.id === selectedOrgId
4796
+ ).map(({ id, name, personalBudget }) => ({
4797
+ id,
4798
+ name,
4799
+ ...personalBudget === void 0 ? {} : { personalBudget }
4800
+ }));
4801
+ plan = createAttributionPrompt(
4802
+ mintableOrgs.flatMap(({ projects }) => projects),
4803
+ { personalKeyActive, orgs }
4804
+ );
4583
4805
  connectFields = buildConnectForm(plan, modelIds);
4584
4806
  await context.integration.reload();
4585
4807
  };
@@ -4606,6 +4828,9 @@ var createRoute33V2Plugin = (options = {}) => {
4606
4828
  extras
4607
4829
  );
4608
4830
  },
4831
+ onOrgAnswered: (orgId) => {
4832
+ selectedOrgId = orgId;
4833
+ },
4609
4834
  registerProjectForm,
4610
4835
  resolveCredential,
4611
4836
  stash,