@r-33/opencode 0.5.0 → 0.5.1

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.
@@ -1746,14 +1746,14 @@ var DEFAULT_GATEWAY_KEY_TTL_MS = 15 * 60 * 1e3;
1746
1746
  // src/key-lease/file-secret-store/file-secret-store.ts
1747
1747
  import { randomUUID as randomUUID2 } from "node:crypto";
1748
1748
  import * as fs11 from "node:fs/promises";
1749
- import * as path12 from "node:path";
1749
+ import * as path13 from "node:path";
1750
1750
 
1751
1751
  // src/attribution/clear-attribution/clear-attribution.ts
1752
1752
  import * as fs8 from "node:fs";
1753
1753
 
1754
1754
  // src/attribution/resolve-attribution-file/resolve-attribution-file.ts
1755
1755
  import * as fs7 from "node:fs";
1756
- import * as path8 from "node:path";
1756
+ import * as path9 from "node:path";
1757
1757
 
1758
1758
  // src/attribution/detect-worktree-root/detect-worktree-root.ts
1759
1759
  import * as fs6 from "node:fs";
@@ -1776,18 +1776,34 @@ var detectWorktreeRoot = (startDirectory) => {
1776
1776
  }
1777
1777
  };
1778
1778
 
1779
+ // src/attribution/global-attribution-file/global-attribution-file.ts
1780
+ import * as path8 from "node:path";
1781
+ var globalAttributionFile = () => path8.join(resolveV1SecretStoreDirectory(), "route33.attribution.json");
1782
+
1779
1783
  // src/attribution/resolve-attribution-file/resolve-attribution-file.ts
1784
+ var STATE_FILE = "route33.attribution.json";
1780
1785
  var resolveAttributionFile = (options) => {
1786
+ if (options.scope === "global") return globalAttributionFile();
1781
1787
  const worktreeRoot = detectWorktreeRoot(options.directory);
1782
1788
  if (worktreeRoot !== void 0) {
1783
- return path8.join(worktreeRoot, ".opencode", "route33.attribution.json");
1789
+ return path9.join(worktreeRoot, ".opencode", STATE_FILE);
1790
+ }
1791
+ switch (options.outsideWorktree) {
1792
+ case "use-directory":
1793
+ return path9.join(
1794
+ fs7.realpathSync(options.directory),
1795
+ ".opencode",
1796
+ STATE_FILE
1797
+ );
1798
+ case "use-global":
1799
+ return globalAttributionFile();
1800
+ case "return-undefined":
1801
+ return void 0;
1802
+ default: {
1803
+ const unexpected = options.outsideWorktree;
1804
+ throw new TypeError(`Unexpected policy: ${String(unexpected)}`);
1805
+ }
1784
1806
  }
1785
- const fallbackRoots = {
1786
- "return-undefined": void 0,
1787
- "use-directory": fs7.realpathSync(options.directory)
1788
- };
1789
- const fallbackRoot = fallbackRoots[options.outsideWorktree];
1790
- return fallbackRoot === void 0 ? void 0 : path8.join(fallbackRoot, ".opencode", "route33.attribution.json");
1791
1807
  };
1792
1808
 
1793
1809
  // src/attribution/clear-attribution/clear-attribution.ts
@@ -1800,9 +1816,15 @@ var clearAttribution = (options) => {
1800
1816
  return true;
1801
1817
  };
1802
1818
 
1819
+ // src/attribution/is-global-attribution/is-global-attribution.ts
1820
+ var isGlobalAttribution = (options) => options.scope === "global" || options.outsideWorktree === "use-global" && detectWorktreeRoot(options.directory) === void 0;
1821
+
1822
+ // src/attribution/is-global-choice/is-global-choice.ts
1823
+ var isGlobalChoice = (attribution) => attribution.kind === "personal" && attribution.boundKeyId === void 0;
1824
+
1803
1825
  // src/attribution/read-legacy-key/read-legacy-key.ts
1804
- import * as path9 from "node:path";
1805
- var LEGACY_KEY_RELATIVE_PATH = path9.join(".opencode", "route33.key");
1826
+ import * as path10 from "node:path";
1827
+ var LEGACY_KEY_RELATIVE_PATH = path10.join(".opencode", "route33.key");
1806
1828
 
1807
1829
  // src/attribution/parse-attribution/read-org-id/read-org-id.ts
1808
1830
  var readOrgId = (value) => {
@@ -1855,26 +1877,30 @@ var readAttribution = (options) => {
1855
1877
  }
1856
1878
  try {
1857
1879
  const parsed = JSON.parse(fs9.readFileSync(file, "utf8"));
1858
- return parseAttribution(parsed);
1880
+ const attribution = parseAttribution(parsed);
1881
+ return isGlobalAttribution(options) && !isGlobalChoice(attribution) ? void 0 : attribution;
1859
1882
  } catch {
1860
1883
  return void 0;
1861
1884
  }
1862
1885
  };
1863
1886
 
1864
1887
  // src/attribution/remove-legacy-key/remove-legacy-key.ts
1865
- import * as path10 from "node:path";
1866
- var LEGACY_KEY_RELATIVE_PATH2 = path10.join(".opencode", "route33.key");
1888
+ import * as path11 from "node:path";
1889
+ var LEGACY_KEY_RELATIVE_PATH2 = path11.join(".opencode", "route33.key");
1867
1890
 
1868
1891
  // src/attribution/write-attribution/write-attribution.ts
1869
1892
  import { randomUUID } from "node:crypto";
1870
1893
  import * as fs10 from "node:fs";
1871
- import * as path11 from "node:path";
1894
+ import * as path12 from "node:path";
1872
1895
  var writeAttribution = (options, attribution) => {
1873
1896
  const file = resolveAttributionFile(options);
1874
1897
  if (file === void 0) {
1875
1898
  return false;
1876
1899
  }
1877
- fs10.mkdirSync(path11.dirname(file), { recursive: true });
1900
+ if (isGlobalAttribution(options) && !isGlobalChoice(attribution)) {
1901
+ return false;
1902
+ }
1903
+ fs10.mkdirSync(path12.dirname(file), { recursive: true });
1878
1904
  const temporaryFile = `${file}.${String(process.pid)}.${randomUUID()}.tmp`;
1879
1905
  try {
1880
1906
  fs10.writeFileSync(temporaryFile, `${JSON.stringify(attribution)}
@@ -2004,7 +2030,7 @@ var FileSecretStore = class {
2004
2030
  throw new TypeError("File secret store scope is not portable");
2005
2031
  }
2006
2032
  this.#directory = options.directory;
2007
- this.#file = path12.join(options.directory, `lease-${options.scopeId}.json`);
2033
+ this.#file = path13.join(options.directory, `lease-${options.scopeId}.json`);
2008
2034
  }
2009
2035
  /** Reads and parses the scoped gateway credential.
2010
2036
  * @returns The persisted credential, when present.
@@ -2057,7 +2083,7 @@ var FileSecretStore = class {
2057
2083
  async stage(key, lease) {
2058
2084
  await fs11.mkdir(this.#directory, { mode: 448, recursive: true });
2059
2085
  await fs11.chmod(this.#directory, 448);
2060
- const temporary = path12.join(this.#directory, `.lease-${randomUUID2()}.tmp`);
2086
+ const temporary = path13.join(this.#directory, `.lease-${randomUUID2()}.tmp`);
2061
2087
  try {
2062
2088
  const record = lease === void 0 ? key.value : { key: key.value, lease };
2063
2089
  await fs11.writeFile(temporary, `${JSON.stringify(record)}
@@ -2859,6 +2885,7 @@ var WorkspaceKeyBinding = class {
2859
2885
  * @returns Secret-free options; local options do not need destructive consent.
2860
2886
  */
2861
2887
  async candidates(choice) {
2888
+ if (detectWorktreeRoot(this.deps.state.directory) === void 0) return [];
2862
2889
  const listing = this.#listings.get(choice.orgId) ?? this.listKeys(choice.orgId);
2863
2890
  this.#listings.set(choice.orgId, listing);
2864
2891
  const rows = await listing;
@@ -2906,6 +2933,8 @@ var WorkspaceKeyBinding = class {
2906
2933
  * @returns The attribution to commit after saving the secret.
2907
2934
  */
2908
2935
  async bind(choice, id, confirmed) {
2936
+ if (detectWorktreeRoot(this.deps.state.directory) === void 0)
2937
+ throw new GatewayCredentialError("Key binding requires a worktree.");
2909
2938
  const row = await this.deps.client.get(this.deps.token, id, choice.orgId);
2910
2939
  if (row.id !== id || !this.matches(row, choice))
2911
2940
  throw new GatewayCredentialError(
@@ -3046,6 +3075,22 @@ var createAttributionPrompt = (projects, options = {}) => {
3046
3075
  };
3047
3076
  };
3048
3077
 
3078
+ // src/ux/attribution-plan/attribution-plan.ts
3079
+ var GLOBAL_ATTRIBUTION_NOTICE = "This folder is not a Git repository, so it cannot have its own budget. Choose the personal key for all such folders on this machine.";
3080
+ var attributionPlan = (input) => {
3081
+ const options = {
3082
+ orgs: input.orgs,
3083
+ personalKeyActive: input.personalKeyActive
3084
+ };
3085
+ return input.global ? {
3086
+ ...createAttributionPrompt([], options),
3087
+ notice: GLOBAL_ATTRIBUTION_NOTICE
3088
+ } : createAttributionPrompt(
3089
+ input.orgs.flatMap(({ projects }) => projects),
3090
+ options
3091
+ );
3092
+ };
3093
+
3049
3094
  // src/ux/attribution-prompt-error/attribution-prompt-error.ts
3050
3095
  var MESSAGES = {
3051
3096
  ATTRIBUTION_BACK: "Left budget selection without changing attribution.",
@@ -3458,10 +3503,11 @@ var Route33Runtime = class {
3458
3503
  }
3459
3504
  /**
3460
3505
  * Reads the stored key for a saved attribution without any login.
3506
+ * @param state - Whose attribution to read; this folder's by default.
3461
3507
  * @returns The reusable key and lease when the stored lease is still valid.
3462
3508
  */
3463
- async storedReusableKey() {
3464
- const attribution = readAttribution(this.#options.state);
3509
+ async storedReusableKey(state = this.#options.state) {
3510
+ const attribution = readAttribution(state);
3465
3511
  if (attribution === void 0) {
3466
3512
  return void 0;
3467
3513
  }
@@ -3510,7 +3556,7 @@ var Route33Runtime = class {
3510
3556
  async resolveWorkspaceCredential(directory) {
3511
3557
  const attribution = readAttribution({
3512
3558
  directory,
3513
- outsideWorktree: "return-undefined"
3559
+ outsideWorktree: this.#options.state.outsideWorktree
3514
3560
  });
3515
3561
  if (attribution === void 0) {
3516
3562
  const installation = this.#installation({ kind: "personal" });
@@ -3628,10 +3674,11 @@ var Route33Runtime = class {
3628
3674
  * @param extras - The wizard's key-creation answers.
3629
3675
  * @param directory - Optional worktree override for project leases.
3630
3676
  * @param saveAttribution - Wizard save that must succeed before replacing a live key.
3677
+ * @param state - Where that save lands; the directory's own state by default.
3631
3678
  * @returns The fresh key material with its lease metadata.
3632
3679
  */
3633
- async mintWorkspaceKey(attribution, extras, directory = this.#options.state.directory, saveAttribution) {
3634
- const file = resolveAttributionFile({ ...this.#options.state, directory });
3680
+ async mintWorkspaceKey(attribution, extras, directory = this.#options.state.directory, saveAttribution, state = { ...this.#options.state, directory }) {
3681
+ const file = resolveAttributionFile(state);
3635
3682
  if (file === void 0)
3636
3683
  throw new TypeError("Workspace attribution requires a worktree");
3637
3684
  const previous = statSync2(file, { bigint: true, throwIfNoEntry: false });
@@ -3674,7 +3721,7 @@ var Route33Runtime = class {
3674
3721
  async workspaceKeyAllowance(directory) {
3675
3722
  const attribution = readAttribution({
3676
3723
  directory,
3677
- outsideWorktree: "return-undefined"
3724
+ outsideWorktree: this.#options.state.outsideWorktree
3678
3725
  });
3679
3726
  if (attribution === void 0) {
3680
3727
  return void 0;
@@ -3860,6 +3907,7 @@ var createRoute33Plugin = (options = {}) => {
3860
3907
  ...options.config
3861
3908
  };
3862
3909
  const runtimeOptions = options.runtime;
3910
+ const outsideWorktree = options.outsideWorktree ?? "return-undefined";
3863
3911
  const installation = runtimeOptions === void 0 ? void 0 : runtimeOptions.installation ?? createLeaseInstallationFactory({
3864
3912
  listScopes: () => FileSecretStore.scopes(
3865
3913
  resolveV1SecretStoreDirectory({
@@ -3878,10 +3926,7 @@ var createRoute33Plugin = (options = {}) => {
3878
3926
  ...runtimeOptions,
3879
3927
  auth: { ...runtimeOptions.auth, clientId: clientId2 },
3880
3928
  installation,
3881
- state: {
3882
- directory: input.worktree,
3883
- outsideWorktree: "return-undefined"
3884
- }
3929
+ state: { directory: input.worktree, outsideWorktree }
3885
3930
  });
3886
3931
  if (runtime2 !== void 0) {
3887
3932
  options.bindRuntime?.(runtime2);
@@ -3919,7 +3964,7 @@ var createRoute33Plugin = (options = {}) => {
3919
3964
  return false;
3920
3965
  }
3921
3966
  },
3922
- outsideWorktree: "return-undefined"
3967
+ outsideWorktree
3923
3968
  });
3924
3969
  }
3925
3970
  return Promise.resolve({
@@ -5009,7 +5054,6 @@ var parseBudgetAnswer = (answer, maximum) => {
5009
5054
  // src/v2-entry/connect-copy/connect-copy.ts
5010
5055
  var CONNECT_COPY = {
5011
5056
  failFastClientId: "This Route 33 build has no OAuth client ID; reinstall it from the opencode-dist ref.",
5012
- failFastWorktree: "To assign a Route 33 budget, open a Git repository.",
5013
5057
  selectionInvalid: "That Route 33 option is no longer available; open /r33 and choose Attribute.",
5014
5058
  signedInNextStep: "Signed in to Route 33; open /r33 and choose Attribute to assign a budget.",
5015
5059
  budgetSelected: "Budget selected but not assigned; open /r33 and choose Attribute to finish setup."
@@ -5080,13 +5124,13 @@ var applyWizardAnswer = async (deps, answer) => {
5080
5124
 
5081
5125
  // src/v2-entry/connect-authorize/connect-authorize.ts
5082
5126
  var createConnectAuthorize = (deps) => async (answer = {}) => {
5083
- if (deps.clientId === "") {
5084
- throw new GatewayCredentialError(CONNECT_COPY.failFastClientId);
5085
- }
5086
- if (detectWorktreeRoot(deps.directory) === void 0) {
5087
- throw new GatewayCredentialError(CONNECT_COPY.failFastWorktree);
5088
- }
5127
+ const refuseUnusableBuild = () => {
5128
+ if (deps.clientId === "") {
5129
+ throw new GatewayCredentialError(CONNECT_COPY.failFastClientId);
5130
+ }
5131
+ };
5089
5132
  const callback = (async () => {
5133
+ refuseUnusableBuild();
5090
5134
  const emptyAnswer = Object.keys(answer).length === 0;
5091
5135
  if (emptyAnswer) {
5092
5136
  const runtime2 = deps.getRuntime();
@@ -5128,9 +5172,61 @@ var createConnectAuthorize = (deps) => async (answer = {}) => {
5128
5172
  };
5129
5173
  };
5130
5174
 
5131
- // src/v2-entry/connect-form/connect-form.ts
5132
- var ATTRIBUTION_FIELD_KEY2 = "attribution";
5175
+ // src/v2-entry/global-key-answer/global-key-answer.ts
5176
+ var ATTRIBUTION_SCOPE_FIELD_KEY = "attribution_scope";
5177
+ var GLOBAL_KEY_ANSWER = { [ATTRIBUTION_SCOPE_FIELD_KEY]: "global" };
5178
+ var isGlobalKeyAnswer = (answer) => answer[ATTRIBUTION_SCOPE_FIELD_KEY] === "global";
5179
+
5180
+ // src/v2-entry/connect-form/budget-question-copy/budget-question-copy.ts
5181
+ var budgetQuestionCopy = (plan) => plan.notice === void 0 ? {
5182
+ attribution: {
5183
+ title: "Which budget covers Route 33 usage in this folder?"
5184
+ },
5185
+ organisation: "Which Route 33 organisation covers this folder?"
5186
+ } : {
5187
+ attribution: {
5188
+ description: plan.notice,
5189
+ title: "Which personal key covers folders outside Git?"
5190
+ },
5191
+ organisation: "Which Route 33 organisation covers folders outside Git?"
5192
+ };
5193
+
5194
+ // src/v2-entry/connect-form/budget-fields/budget-fields.ts
5133
5195
  var ORGANISATION_FIELD_KEY = "organisation";
5196
+ var budgetFields = (plan) => {
5197
+ const orgs = plan.orgs ?? [];
5198
+ const copy = budgetQuestionCopy(plan);
5199
+ const organisationFields = orgs.length > 1 ? [
5200
+ {
5201
+ key: ORGANISATION_FIELD_KEY,
5202
+ options: orgs.map(({ id, name }) => ({ label: name, value: id })),
5203
+ title: copy.organisation,
5204
+ type: "string"
5205
+ }
5206
+ ] : [];
5207
+ const attributionField = {
5208
+ ...copy.attribution,
5209
+ key: ATTRIBUTION_FIELD_KEY,
5210
+ options: plan.options.map((option) => ({
5211
+ label: option.label,
5212
+ value: option.selection
5213
+ })),
5214
+ // Deliberately not required: the boot session probe connects without
5215
+ // an answer — a required field makes the host reject bare connects
5216
+ // (400 Missing required form field) and kills the probe. The wizard
5217
+ // still sends the attribution on its answer pass.
5218
+ type: "string"
5219
+ };
5220
+ const scopeFields = plan.notice === void 0 ? [{ hidden: true, key: ATTRIBUTION_SCOPE_FIELD_KEY, type: "string" }] : [];
5221
+ const [first = attributionField, ...rest] = [
5222
+ ...organisationFields,
5223
+ attributionField,
5224
+ ...scopeFields
5225
+ ];
5226
+ return [first, ...rest];
5227
+ };
5228
+
5229
+ // src/v2-entry/connect-form/connect-form.ts
5134
5230
  var BUDGET_NAME_FIELD_KEY = "budget_name";
5135
5231
  var BUDGET_CAP_FIELD_KEY = "budget_cap";
5136
5232
  var BUDGET_CAP_MAX_FIELD_KEY = "budget_cap_max";
@@ -5141,7 +5237,6 @@ var ALLOWED_MODELS_FIELD_KEY = "allowed_models";
5141
5237
  var ALLOWED_MODELS_TITLE = "Which models may this key use?";
5142
5238
  var ALL_MODELS_VALUE = "all";
5143
5239
  var ALL_MODELS_LABEL = "All models (inherit)";
5144
- var ORGANISATION_FIELD_TITLE = "Which Route 33 organisation covers this folder?";
5145
5240
  var EXPIRY_OPTIONS = [
5146
5241
  { label: "30 days", value: "30" },
5147
5242
  { label: "90 days", value: "90" },
@@ -5150,28 +5245,8 @@ var EXPIRY_OPTIONS = [
5150
5245
  ];
5151
5246
  var buildConnectForm = (plan, key) => {
5152
5247
  const maximum = key?.maximum;
5153
- const orgs = plan.orgs ?? [];
5154
- const organisationField = {
5155
- key: ORGANISATION_FIELD_KEY,
5156
- options: orgs.map(({ id, name }) => ({ label: name, value: id })),
5157
- title: ORGANISATION_FIELD_TITLE,
5158
- type: "string"
5159
- };
5160
- const attributionField = {
5161
- key: ATTRIBUTION_FIELD_KEY2,
5162
- options: plan.options.map((option) => ({
5163
- label: option.label,
5164
- value: option.selection
5165
- })),
5166
- // Deliberately not required: the boot session probe connects without
5167
- // an answer — a required field makes the host reject bare connects
5168
- // (400 Missing required form field) and kills the probe. The wizard
5169
- // still sends the attribution on its answer pass.
5170
- title: "Which budget covers Route 33 usage in this folder?",
5171
- type: "string"
5172
- };
5173
- const budgetFields = orgs.length > 1 ? [organisationField, attributionField] : [attributionField];
5174
- if (key === void 0) return budgetFields;
5248
+ const fields = budgetFields(plan);
5249
+ if (key === void 0) return fields;
5175
5250
  const promptFields = [
5176
5251
  {
5177
5252
  key: BUDGET_NAME_FIELD_KEY,
@@ -5226,7 +5301,7 @@ var buildConnectForm = (plan, key) => {
5226
5301
  type: "string"
5227
5302
  });
5228
5303
  return [
5229
- ...budgetFields,
5304
+ ...fields,
5230
5305
  ...promptFields,
5231
5306
  ...maximum === void 0 ? [] : [helper(BUDGET_CAP_MAX_FIELD_KEY, String(maximum))],
5232
5307
  ...key.prepared === void 0 ? [] : [helper(PREPARED_BUDGET_FIELD_KEY, key.prepared)]
@@ -5252,6 +5327,155 @@ var directKeyMode = async (context, options, compose) => {
5252
5327
  };
5253
5328
  };
5254
5329
 
5330
+ // src/v2-entry/resolve-host-credential/resolve-host-credential.ts
5331
+ 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.";
5332
+ var resolveHostCredential = async (deps) => {
5333
+ await deps.config();
5334
+ deps.onProvider(deps.parseProvider(void 0));
5335
+ const active = deps.runtime();
5336
+ const stored = await active?.storedReusableKey();
5337
+ if (stored === void 0) {
5338
+ throw new GatewayCredentialError(NO_USABLE_LEASE_MESSAGE);
5339
+ }
5340
+ await deps.reloadProviders();
5341
+ return {
5342
+ access: stored.key.value,
5343
+ expires: Date.parse(stored.lease.expiresAt),
5344
+ methodID: deps.methodID,
5345
+ refresh: stored.lease.keyId,
5346
+ type: "oauth"
5347
+ };
5348
+ };
5349
+
5350
+ // src/v2-entry/binding-fields/binding-fields.ts
5351
+ var bindingFields = async (plan, binding) => {
5352
+ const confirmations = /* @__PURE__ */ new Map();
5353
+ const fields = [];
5354
+ for (const [selection, choice] of Object.entries(plan.choicesBySelection)) {
5355
+ const keys = await binding.candidates(choice);
5356
+ if (!keys.length) continue;
5357
+ for (const key of keys) if (!key.local) confirmations.set(key.id, key.name);
5358
+ fields.push({
5359
+ key: `existing_key:${selection}`,
5360
+ type: "string",
5361
+ title: "Which key should this folder use?",
5362
+ options: [
5363
+ { label: "Mint a new key", value: "new" },
5364
+ ...keys.map((key) => ({
5365
+ label: `Bind ${key.name} (${key.id})`,
5366
+ value: key.id
5367
+ }))
5368
+ ]
5369
+ });
5370
+ }
5371
+ if (confirmations.size)
5372
+ fields.push({
5373
+ key: "rotation_confirmation",
5374
+ type: "string",
5375
+ title: ROTATION_WARNING,
5376
+ options: [
5377
+ { label: "No", value: "no" },
5378
+ ...Array.from(confirmations, ([id, name]) => ({
5379
+ label: `Yes, rotate ${name} (${id})`,
5380
+ value: id
5381
+ }))
5382
+ ]
5383
+ });
5384
+ return fields;
5385
+ };
5386
+
5387
+ // src/v2-entry/selected-budget-form/read-model-choices/read-model-choices.ts
5388
+ var FORBIDDEN = 403;
5389
+ var readModelChoices = async (read) => {
5390
+ try {
5391
+ return { models: await read() };
5392
+ } catch (cause) {
5393
+ return {
5394
+ models: [],
5395
+ modelsNote: cause instanceof ManagementError && cause.statusCode === FORBIDDEN ? KEY_FORM_COPY.modelsNeedSignIn : KEY_FORM_COPY.modelsUnavailable
5396
+ };
5397
+ }
5398
+ };
5399
+
5400
+ // src/v2-entry/selected-budget-form/selected-budget-form.ts
5401
+ var selectedBudgetForm = async (plan, selection, runtime2) => {
5402
+ const option = plan.options.find((row) => row.selection === selection);
5403
+ const choice = plan.choicesBySelection[selection];
5404
+ if (!option || !choice)
5405
+ throw new GatewayCredentialError(CONNECT_COPY.selectionInvalid);
5406
+ const scoped = {
5407
+ title: plan.title,
5408
+ options: [option],
5409
+ choicesBySelection: { [selection]: choice }
5410
+ };
5411
+ const choices = await readModelChoices(
5412
+ () => runtime2.catalogModelChoices(choice)
5413
+ );
5414
+ const keys = await bindingFields(scoped, await runtime2.workspaceKeyBinding());
5415
+ return [
5416
+ ...buildConnectForm(plan, {
5417
+ ...choices,
5418
+ ...option.maximum === void 0 ? {} : { maximum: option.maximum },
5419
+ prepared: selection
5420
+ }),
5421
+ ...keys
5422
+ ];
5423
+ };
5424
+
5425
+ // src/v2-entry/global-key-authorize/global-key-authorize.ts
5426
+ var createGlobalKeyAuthorize = (deps) => {
5427
+ const state = {
5428
+ directory: deps.directory,
5429
+ outsideWorktree: "use-global",
5430
+ scope: "global"
5431
+ };
5432
+ const runtime2 = () => {
5433
+ const active = deps.getRuntime();
5434
+ if (active === void 0) {
5435
+ throw new GatewayCredentialError(
5436
+ "Route 33 authorization is unavailable in this host"
5437
+ );
5438
+ }
5439
+ return active;
5440
+ };
5441
+ return createConnectAuthorize({
5442
+ clientId: deps.clientId,
5443
+ getPlan: deps.getPlan,
5444
+ getRuntime: deps.getRuntime,
5445
+ mintWorkspaceKey: async (attribution, extras, save) => runtime2().mintWorkspaceKey(attribution, extras, void 0, save, state),
5446
+ prepareBudget: async (selection, answer) => {
5447
+ const marker = `global:${selection}`;
5448
+ if (deps.form.answers(marker, answer)) return false;
5449
+ const plan = deps.getPlan();
5450
+ const choice = plan?.choicesBySelection[selection];
5451
+ if (!plan || !choice || !isGlobalChoice(choice)) {
5452
+ throw new GatewayCredentialError(CONNECT_COPY.selectionInvalid);
5453
+ }
5454
+ const active = runtime2();
5455
+ const fields = await selectedBudgetForm(plan, selection, {
5456
+ catalogModelChoices: (scope) => active.catalogModelChoices(scope),
5457
+ // A bound key is held per worktree: the global key is always new.
5458
+ workspaceKeyBinding: () => Promise.resolve({ candidates: () => Promise.resolve([]) })
5459
+ });
5460
+ await deps.form.register(fields, marker);
5461
+ return true;
5462
+ },
5463
+ registerProjectForm: deps.registerProjectForm,
5464
+ resolveCredential: () => resolveHostCredential({
5465
+ config: () => Promise.resolve(),
5466
+ methodID: deps.methodID,
5467
+ onProvider: () => void 0,
5468
+ parseProvider: () => void 0,
5469
+ reloadProviders: () => Promise.resolve(),
5470
+ runtime: () => ({
5471
+ storedReusableKey: () => runtime2().storedReusableKey(state)
5472
+ })
5473
+ }),
5474
+ stash: deps.stash,
5475
+ state
5476
+ });
5477
+ };
5478
+
5255
5479
  // src/v2-entry/host-lease-state-store/host-lease-state-store.ts
5256
5480
  var hostLeaseStateStore = (options) => ({
5257
5481
  // The box envelope keeps the server part's writes readable from the
@@ -5306,6 +5530,27 @@ var hostTokenStore = (options) => {
5306
5530
  };
5307
5531
  };
5308
5532
 
5533
+ // src/v2-entry/prepared-form/prepared-form.ts
5534
+ var SELECTION_KEYS = [
5535
+ ATTRIBUTION_FIELD_KEY,
5536
+ ATTRIBUTION_SCOPE_FIELD_KEY
5537
+ ];
5538
+ var createPreparedForm = (reload) => {
5539
+ let registered;
5540
+ let prepared;
5541
+ return {
5542
+ answers: (marker, answer) => prepared === marker && registered?.some(
5543
+ (field) => !SELECTION_KEYS.includes(field.key) && Object.hasOwn(answer, field.key)
5544
+ ) === true,
5545
+ fields: () => registered,
5546
+ register: async (fields, marker) => {
5547
+ registered = fields;
5548
+ prepared = marker;
5549
+ await reload();
5550
+ }
5551
+ };
5552
+ };
5553
+
5309
5554
  // src/v2-entry/model-gate-notify-from/model-gate-notify-from.ts
5310
5555
  var notifyFrom = async (session, sessionID, message) => {
5311
5556
  await session.synthetic?.({ delivery: "queue", sessionID, text: message });
@@ -5349,7 +5594,7 @@ var sessionModelUsage = (sessions) => {
5349
5594
  var gateDirectory = async (deps, sessionID) => {
5350
5595
  const session = await deps.session.get({ sessionID });
5351
5596
  const directory = session?.location.directory ?? deps.fallbackDirectory;
5352
- return { directory, outsideWorktree: "return-undefined" };
5597
+ return { directory, outsideWorktree: "use-global" };
5353
5598
  };
5354
5599
 
5355
5600
  // src/v2-entry/gate-fallback/gate-fallback.ts
@@ -5536,101 +5781,6 @@ var registerSessionRpc = (rpc, deps) => rpc.register(ROUTE33_SESSION_RPC, {
5536
5781
  }
5537
5782
  });
5538
5783
 
5539
- // src/v2-entry/resolve-host-credential/resolve-host-credential.ts
5540
- var NO_USABLE_LEASE_MESSAGE = "Signed in to Route 33 \u2713. One more step: this folder has no gateway key yet \u2014 pick its budget to finish setup.";
5541
- var resolveHostCredential = async (deps) => {
5542
- await deps.config();
5543
- deps.onProvider(deps.parseProvider(void 0));
5544
- const active = deps.runtime();
5545
- const stored = await active?.storedReusableKey();
5546
- if (stored === void 0) {
5547
- throw new GatewayCredentialError(NO_USABLE_LEASE_MESSAGE);
5548
- }
5549
- await deps.reloadProviders();
5550
- return {
5551
- access: stored.key.value,
5552
- expires: Date.parse(stored.lease.expiresAt),
5553
- methodID: deps.methodID,
5554
- refresh: stored.lease.keyId,
5555
- type: "oauth"
5556
- };
5557
- };
5558
-
5559
- // src/v2-entry/binding-fields/binding-fields.ts
5560
- var bindingFields = async (plan, binding) => {
5561
- const confirmations = /* @__PURE__ */ new Map();
5562
- const fields = [];
5563
- for (const [selection, choice] of Object.entries(plan.choicesBySelection)) {
5564
- const keys = await binding.candidates(choice);
5565
- if (!keys.length) continue;
5566
- for (const key of keys) if (!key.local) confirmations.set(key.id, key.name);
5567
- fields.push({
5568
- key: `existing_key:${selection}`,
5569
- type: "string",
5570
- title: "Which key should this folder use?",
5571
- options: [
5572
- { label: "Mint a new key", value: "new" },
5573
- ...keys.map((key) => ({
5574
- label: `Bind ${key.name} (${key.id})`,
5575
- value: key.id
5576
- }))
5577
- ]
5578
- });
5579
- }
5580
- if (confirmations.size)
5581
- fields.push({
5582
- key: "rotation_confirmation",
5583
- type: "string",
5584
- title: ROTATION_WARNING,
5585
- options: [
5586
- { label: "No", value: "no" },
5587
- ...Array.from(confirmations, ([id, name]) => ({
5588
- label: `Yes, rotate ${name} (${id})`,
5589
- value: id
5590
- }))
5591
- ]
5592
- });
5593
- return fields;
5594
- };
5595
-
5596
- // src/v2-entry/selected-budget-form/read-model-choices/read-model-choices.ts
5597
- var FORBIDDEN = 403;
5598
- var readModelChoices = async (read) => {
5599
- try {
5600
- return { models: await read() };
5601
- } catch (cause) {
5602
- return {
5603
- models: [],
5604
- modelsNote: cause instanceof ManagementError && cause.statusCode === FORBIDDEN ? KEY_FORM_COPY.modelsNeedSignIn : KEY_FORM_COPY.modelsUnavailable
5605
- };
5606
- }
5607
- };
5608
-
5609
- // src/v2-entry/selected-budget-form/selected-budget-form.ts
5610
- var selectedBudgetForm = async (plan, selection, runtime2) => {
5611
- const option = plan.options.find((row) => row.selection === selection);
5612
- const choice = plan.choicesBySelection[selection];
5613
- if (!option || !choice)
5614
- throw new GatewayCredentialError(CONNECT_COPY.selectionInvalid);
5615
- const scoped = {
5616
- title: plan.title,
5617
- options: [option],
5618
- choicesBySelection: { [selection]: choice }
5619
- };
5620
- const choices = await readModelChoices(
5621
- () => runtime2.catalogModelChoices(choice)
5622
- );
5623
- const keys = await bindingFields(scoped, await runtime2.workspaceKeyBinding());
5624
- return [
5625
- ...buildConnectForm(plan, {
5626
- ...choices,
5627
- ...option.maximum === void 0 ? {} : { maximum: option.maximum },
5628
- prepared: selection
5629
- }),
5630
- ...keys
5631
- ];
5632
- };
5633
-
5634
5784
  // src/v2-entry/is-account-removed/is-account-removed.ts
5635
5785
  var isAccountRemoved = (event) => {
5636
5786
  if (!isRecord(event) || event["type"] !== "credential.switched") return false;
@@ -5683,6 +5833,7 @@ var createWorkspaceKeyHook = (deps) => async (input) => {
5683
5833
  };
5684
5834
 
5685
5835
  // src/v2-entry/create-route33-v2-plugin/create-route33-v2-plugin.ts
5836
+ var ACCOUNT_LABEL = "Route 33";
5686
5837
  var createRoute33V2Plugin = (options = {}) => {
5687
5838
  const clientId2 = options.clientId ?? readEnvClientId() ?? DEFAULT_ROUTE33_CLIENT_ID;
5688
5839
  const issuerUrl2 = options.issuerUrl ?? readEnvAuthIssuer() ?? DEFAULT_AUTH_ISSUER_URL;
@@ -5698,8 +5849,9 @@ var createRoute33V2Plugin = (options = {}) => {
5698
5849
  const stash = createAuthorizationUrlStash2();
5699
5850
  const state = {
5700
5851
  directory: context.location.directory,
5701
- outsideWorktree: "return-undefined"
5852
+ outsideWorktree: "use-global"
5702
5853
  };
5854
+ const global = isGlobalAttribution(state);
5703
5855
  const installation = createLeaseInstallationFactory({
5704
5856
  listScopes: () => HostStorageSecretStore.scopes(context.storage),
5705
5857
  createSecretStore: (scopeId) => new HostStorageSecretStore({
@@ -5713,9 +5865,8 @@ var createRoute33V2Plugin = (options = {}) => {
5713
5865
  });
5714
5866
  let runtime2;
5715
5867
  let provider = mapRoute33V2Provider(void 0);
5716
- let connectFields;
5717
5868
  let plan;
5718
- let preparedBudget;
5869
+ const form = createPreparedForm(() => context.integration.reload());
5719
5870
  const runtimeInput = {
5720
5871
  ...options.runtime ?? buildProductionRuntimeOptions({
5721
5872
  apiBaseUrl,
@@ -5732,6 +5883,7 @@ var createRoute33V2Plugin = (options = {}) => {
5732
5883
  runtime2 = instance;
5733
5884
  },
5734
5885
  clientId: clientId2,
5886
+ outsideWorktree: state.outsideWorktree,
5735
5887
  runtime: runtimeInput
5736
5888
  })({ worktree: context.location.directory });
5737
5889
  const resolveCredential = () => resolveHostCredential({
@@ -5755,23 +5907,17 @@ var createRoute33V2Plugin = (options = {}) => {
5755
5907
  activeRuntime.listMintableOrgs({ allowBrowser: false }).catch(() => void 0),
5756
5908
  activeRuntime.hasPersonalLease().catch(() => false)
5757
5909
  ]);
5758
- preparedBudget = void 0;
5759
5910
  if (mintableOrgs === void 0) {
5760
5911
  plan = void 0;
5761
- connectFields = void 0;
5762
- await context.integration.reload();
5912
+ await form.register(void 0);
5763
5913
  return;
5764
5914
  }
5765
- plan = createAttributionPrompt(
5766
- mintableOrgs.flatMap(({ projects }) => projects),
5767
- { personalKeyActive, orgs: mintableOrgs }
5768
- );
5769
- connectFields = buildConnectForm(plan);
5770
- await context.integration.reload();
5915
+ const orgs = mintableOrgs;
5916
+ plan = attributionPlan({ global, orgs, personalKeyActive });
5917
+ await form.register(buildConnectForm(plan));
5771
5918
  };
5772
5919
  const authorize = createConnectAuthorize({
5773
5920
  clientId: clientId2,
5774
- directory: context.location.directory,
5775
5921
  getPlan: () => plan,
5776
5922
  getRuntime: () => runtime2,
5777
5923
  mintWorkspaceKey: (attribution, extras, save) => {
@@ -5786,15 +5932,11 @@ var createRoute33V2Plugin = (options = {}) => {
5786
5932
  return active.mintWorkspaceKey(attribution, extras, void 0, save);
5787
5933
  },
5788
5934
  prepareBudget: async (selection, answer) => {
5789
- if (preparedBudget === selection && connectFields?.some(
5790
- (field) => field.key !== "attribution" && Object.hasOwn(answer, field.key)
5791
- ) === true)
5792
- return false;
5935
+ if (form.answers(selection, answer)) return false;
5793
5936
  if (!runtime2 || !plan)
5794
5937
  throw new GatewayCredentialError(CONNECT_COPY.selectionInvalid);
5795
- connectFields = await selectedBudgetForm(plan, selection, runtime2);
5796
- preparedBudget = selection;
5797
- await context.integration.reload();
5938
+ const fields = await selectedBudgetForm(plan, selection, runtime2);
5939
+ await form.register(fields, selection);
5798
5940
  return true;
5799
5941
  },
5800
5942
  registerProjectForm,
@@ -5802,19 +5944,34 @@ var createRoute33V2Plugin = (options = {}) => {
5802
5944
  stash,
5803
5945
  state
5804
5946
  });
5947
+ const authorizeGlobalKey = createGlobalKeyAuthorize({
5948
+ clientId: clientId2,
5949
+ directory: context.location.directory,
5950
+ form,
5951
+ getPlan: () => plan,
5952
+ getRuntime: () => runtime2,
5953
+ methodID,
5954
+ registerProjectForm,
5955
+ stash
5956
+ });
5805
5957
  const providerTransform = await context.provider.transform((editor) => {
5806
5958
  editor.add(provider);
5807
5959
  });
5808
5960
  const integrationTransform = await context.integration.transform(
5809
5961
  (editor) => {
5810
5962
  editor.method.update({
5811
- authorize: (answer) => authorize(answer),
5963
+ authorize: (answer) => (isGlobalKeyAnswer(answer) ? authorizeGlobalKey : authorize)(
5964
+ answer
5965
+ ),
5812
5966
  integrationID: "route33",
5967
+ // One name for the one account: unnamed, the host numbers each
5968
+ // new account after the ones it already holds.
5969
+ label: () => ACCOUNT_LABEL,
5813
5970
  method: {
5814
5971
  id: methodID,
5815
5972
  label: TRUSTED_PARTY_COPY.title,
5816
5973
  type: "oauth",
5817
- ...connectFields === void 0 ? {} : { form: connectFields }
5974
+ ...form.fields() === void 0 ? {} : { form: form.fields() }
5818
5975
  },
5819
5976
  refresh: () => resolveCredential()
5820
5977
  });