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

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.
@@ -1744,12 +1744,258 @@ var DEFAULT_GATEWAY_KEY_RENEWAL_RATIO = 0.8;
1744
1744
  var DEFAULT_GATEWAY_KEY_TTL_MS = 15 * 60 * 1e3;
1745
1745
 
1746
1746
  // src/key-lease/file-secret-store/file-secret-store.ts
1747
- import { randomUUID } from "node:crypto";
1748
- import * as fs6 from "node:fs/promises";
1747
+ import { randomUUID as randomUUID2 } from "node:crypto";
1748
+ import * as fs11 from "node:fs/promises";
1749
+ import * as path12 from "node:path";
1750
+
1751
+ // src/attribution/clear-attribution/clear-attribution.ts
1752
+ import * as fs8 from "node:fs";
1753
+
1754
+ // src/attribution/resolve-attribution-file/resolve-attribution-file.ts
1755
+ import * as fs7 from "node:fs";
1756
+ import * as path8 from "node:path";
1757
+
1758
+ // src/attribution/detect-worktree-root/detect-worktree-root.ts
1759
+ import * as fs6 from "node:fs";
1749
1760
  import * as path7 from "node:path";
1761
+ var detectWorktreeRoot = (startDirectory) => {
1762
+ let directory = fs6.realpathSync(startDirectory);
1763
+ for (; ; ) {
1764
+ const gitEntry = path7.join(directory, ".git");
1765
+ if (fs6.existsSync(gitEntry)) {
1766
+ const entry = fs6.statSync(gitEntry);
1767
+ if (entry.isDirectory() || entry.isFile()) {
1768
+ return directory;
1769
+ }
1770
+ }
1771
+ const parent = path7.dirname(directory);
1772
+ if (parent === directory) {
1773
+ return void 0;
1774
+ }
1775
+ directory = parent;
1776
+ }
1777
+ };
1778
+
1779
+ // src/attribution/resolve-attribution-file/resolve-attribution-file.ts
1780
+ var resolveAttributionFile = (options) => {
1781
+ const worktreeRoot = detectWorktreeRoot(options.directory);
1782
+ if (worktreeRoot !== void 0) {
1783
+ return path8.join(worktreeRoot, ".opencode", "route33.attribution.json");
1784
+ }
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
+ };
1792
+
1793
+ // src/attribution/clear-attribution/clear-attribution.ts
1794
+ var clearAttribution = (options) => {
1795
+ const file = resolveAttributionFile(options);
1796
+ if (file === void 0) {
1797
+ return false;
1798
+ }
1799
+ fs8.rmSync(file, { force: true });
1800
+ return true;
1801
+ };
1802
+
1803
+ // 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");
1806
+
1807
+ // src/attribution/parse-attribution/read-org-id/read-org-id.ts
1808
+ var readOrgId = (value) => {
1809
+ const orgId = value["orgId"];
1810
+ if (orgId === void 0) {
1811
+ return void 0;
1812
+ }
1813
+ if (typeof orgId !== "string") {
1814
+ throw new ContractParseError("invalid attribution");
1815
+ }
1816
+ return orgId;
1817
+ };
1818
+
1819
+ // src/attribution/parse-attribution/parse-attribution.ts
1820
+ var parseAttribution = (value) => {
1821
+ if (!isRecord(value)) {
1822
+ throw new ContractParseError("invalid attribution");
1823
+ }
1824
+ const orgId = readOrgId(value);
1825
+ const binding = (() => {
1826
+ const { boundKeyId, boundScopeId } = value;
1827
+ if (boundKeyId === void 0 && boundScopeId === void 0) return {};
1828
+ if (typeof boundKeyId !== "string" || !boundKeyId)
1829
+ throw new ContractParseError("invalid bound key id");
1830
+ if (boundScopeId === void 0) return { boundKeyId };
1831
+ if (typeof boundScopeId !== "string" || !/^[a-f0-9]{64}$/u.test(boundScopeId))
1832
+ throw new ContractParseError("invalid bound scope id");
1833
+ return { boundKeyId, boundScopeId };
1834
+ })();
1835
+ if (value["kind"] === "personal") {
1836
+ return { ...binding, kind: "personal", orgId };
1837
+ }
1838
+ if (value["kind"] === "project" && typeof value["projectId"] === "string") {
1839
+ return {
1840
+ ...binding,
1841
+ kind: "project",
1842
+ ...orgId === void 0 ? {} : { orgId },
1843
+ projectId: value["projectId"]
1844
+ };
1845
+ }
1846
+ throw new ContractParseError("invalid attribution");
1847
+ };
1848
+
1849
+ // src/attribution/read-attribution/read-attribution.ts
1850
+ import * as fs9 from "node:fs";
1851
+ var readAttribution = (options) => {
1852
+ const file = resolveAttributionFile(options);
1853
+ if (file === void 0) {
1854
+ return void 0;
1855
+ }
1856
+ try {
1857
+ const parsed = JSON.parse(fs9.readFileSync(file, "utf8"));
1858
+ return parseAttribution(parsed);
1859
+ } catch {
1860
+ return void 0;
1861
+ }
1862
+ };
1863
+
1864
+ // 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");
1867
+
1868
+ // src/attribution/write-attribution/write-attribution.ts
1869
+ import { randomUUID } from "node:crypto";
1870
+ import * as fs10 from "node:fs";
1871
+ import * as path11 from "node:path";
1872
+ var writeAttribution = (options, attribution) => {
1873
+ const file = resolveAttributionFile(options);
1874
+ if (file === void 0) {
1875
+ return false;
1876
+ }
1877
+ fs10.mkdirSync(path11.dirname(file), { recursive: true });
1878
+ const temporaryFile = `${file}.${String(process.pid)}.${randomUUID()}.tmp`;
1879
+ try {
1880
+ fs10.writeFileSync(temporaryFile, `${JSON.stringify(attribution)}
1881
+ `, "utf8");
1882
+ fs10.renameSync(temporaryFile, file);
1883
+ } catch (error) {
1884
+ fs10.rmSync(temporaryFile, { force: true });
1885
+ throw error;
1886
+ }
1887
+ return true;
1888
+ };
1889
+
1890
+ // src/key-lease/lease-state/lease-state.ts
1891
+ var LeaseState = class _LeaseState {
1892
+ /** Current committed snapshot; mutation is limited to compare-and-swap transitions. */
1893
+ #current;
1894
+ constructor(current) {
1895
+ this.#current = current;
1896
+ }
1897
+ /** Restores untrusted persisted metadata or an empty lease.
1898
+ * @param value - Persisted metadata, or undefined for a new installation.
1899
+ * @returns A lease-state coordinator.
1900
+ */
1901
+ static restore(value) {
1902
+ if (value === void 0) {
1903
+ return new _LeaseState(void 0);
1904
+ }
1905
+ if (!isRecord(value)) {
1906
+ throw new ContractParseError("invalid gateway key lease state");
1907
+ }
1908
+ const fields = Object.keys(value);
1909
+ if (fields.some(
1910
+ (field) => !["attribution", "expiresAt", "keyId", "wizardRequest"].includes(
1911
+ field
1912
+ )
1913
+ )) {
1914
+ throw new ContractParseError("invalid gateway key lease state");
1915
+ }
1916
+ const expiresAt = value["expiresAt"];
1917
+ const keyId = value["keyId"];
1918
+ const wizardRequest = value["wizardRequest"];
1919
+ if (typeof expiresAt !== "string" || !Number.isFinite(Date.parse(expiresAt)) || typeof keyId !== "string" || keyId.length === 0 || wizardRequest !== void 0 && typeof wizardRequest !== "string") {
1920
+ throw new ContractParseError("invalid gateway key lease state");
1921
+ }
1922
+ return new _LeaseState({
1923
+ attribution: parseAttribution(value["attribution"]),
1924
+ expiresAt,
1925
+ keyId,
1926
+ wizardRequest
1927
+ });
1928
+ }
1929
+ /** Reads the current non-secret metadata.
1930
+ * @returns The current lease metadata, if one is committed.
1931
+ */
1932
+ snapshot() {
1933
+ return this.#current;
1934
+ }
1935
+ /** Checks whether current metadata belongs to an attribution.
1936
+ * @param attribution - The requested ownership choice.
1937
+ * @returns Whether the current lease has the same attribution.
1938
+ */
1939
+ matchesAttribution(attribution) {
1940
+ if (this.#current === void 0) {
1941
+ return false;
1942
+ }
1943
+ switch (this.#current.attribution.kind) {
1944
+ case "personal":
1945
+ return attribution.kind === "personal";
1946
+ case "project":
1947
+ return attribution.kind === "project" && attribution.projectId === this.#current.attribution.projectId;
1948
+ default:
1949
+ return _LeaseState.#unexpectedAttribution(this.#current.attribution);
1950
+ }
1951
+ }
1952
+ /** Atomically swaps metadata when the expected snapshot is still current.
1953
+ * @param expected - Snapshot observed before asynchronous renewal.
1954
+ * @param next - Fresh metadata to commit.
1955
+ * @returns Whether the swap committed.
1956
+ */
1957
+ compareAndSwap(expected, next) {
1958
+ if (this.#current !== expected) {
1959
+ return false;
1960
+ }
1961
+ this.#current = next;
1962
+ return true;
1963
+ }
1964
+ /** Clears metadata only while the expected snapshot remains current.
1965
+ * @param expected - Snapshot whose lease is being invalidated.
1966
+ * @returns Whether the state was cleared.
1967
+ */
1968
+ clear(expected) {
1969
+ if (this.#current !== expected) {
1970
+ return false;
1971
+ }
1972
+ this.#current = void 0;
1973
+ return true;
1974
+ }
1975
+ static #unexpectedAttribution(value) {
1976
+ throw new TypeError(`Unexpected attribution: ${String(value)}`);
1977
+ }
1978
+ };
1979
+
1980
+ // src/key-lease/file-secret-store/file-secret-store.ts
1750
1981
  var FileSecretStore = class {
1751
1982
  #directory;
1752
1983
  #file;
1984
+ /** Lists only lease files, never opening a secret to discover its scope.
1985
+ * @param directory - Machine-local private lease directory.
1986
+ * @returns Known scope ids, or none before the first lease.
1987
+ */
1988
+ static async scopes(directory) {
1989
+ try {
1990
+ return (await fs11.readdir(directory)).flatMap(
1991
+ (name) => /^lease-([a-f0-9]{64})\.json$/u.exec(name)?.slice(1) ?? []
1992
+ );
1993
+ } catch (cause) {
1994
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
1995
+ return [];
1996
+ throw cause;
1997
+ }
1998
+ }
1753
1999
  constructor(options) {
1754
2000
  if (options.directory.length === 0) {
1755
2001
  throw new TypeError("File secret store requires a directory");
@@ -1758,15 +2004,25 @@ var FileSecretStore = class {
1758
2004
  throw new TypeError("File secret store scope is not portable");
1759
2005
  }
1760
2006
  this.#directory = options.directory;
1761
- this.#file = path7.join(options.directory, `lease-${options.scopeId}.json`);
2007
+ this.#file = path12.join(options.directory, `lease-${options.scopeId}.json`);
1762
2008
  }
1763
2009
  /** Reads and parses the scoped gateway credential.
1764
2010
  * @returns The persisted credential, when present.
1765
2011
  */
1766
2012
  async get() {
2013
+ const value = await this.#read();
2014
+ if (value === void 0) return void 0;
2015
+ return parseGatewayKey(isRecord(value) ? value["key"] : value);
2016
+ }
2017
+ /** @returns Metadata saved with the key, absent for legacy key-only files. */
2018
+ async getLease() {
2019
+ const value = await this.#read();
2020
+ return isRecord(value) ? LeaseState.restore(value["lease"]).snapshot() : void 0;
2021
+ }
2022
+ async #read() {
1767
2023
  let contents;
1768
2024
  try {
1769
- contents = await fs6.readFile(this.#file, "utf8");
2025
+ contents = await fs11.readFile(this.#file, "utf8");
1770
2026
  } catch (cause) {
1771
2027
  if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
1772
2028
  return void 0;
@@ -1774,31 +2030,50 @@ var FileSecretStore = class {
1774
2030
  throw cause;
1775
2031
  }
1776
2032
  const value = JSON.parse(contents);
1777
- return parseGatewayKey(value);
2033
+ return value;
1778
2034
  }
1779
2035
  /** Writes the scoped gateway credential through an atomic private file.
1780
2036
  * @param key - The credential to persist, or undefined to remove it.
2037
+ * @param lease - Metadata to commit in the same atomic write as the wizard key.
1781
2038
  * @returns A promise that settles after the file write or removal.
1782
2039
  */
1783
- async set(key) {
2040
+ async set(key, lease) {
1784
2041
  if (key === void 0) {
1785
- await fs6.rm(this.#file, { force: true });
2042
+ await fs11.rm(this.#file, { force: true });
1786
2043
  return;
1787
2044
  }
1788
- await fs6.mkdir(this.#directory, { mode: 448, recursive: true });
1789
- await fs6.chmod(this.#directory, 448);
1790
- const temporary = path7.join(this.#directory, `.lease-${randomUUID()}.tmp`);
2045
+ const staged = await this.stage(key, lease);
1791
2046
  try {
1792
- await fs6.writeFile(temporary, `${JSON.stringify(key.value)}
2047
+ await staged.commit();
2048
+ } finally {
2049
+ await staged.discard();
2050
+ }
2051
+ }
2052
+ /** Prepares a private file without changing the credential visible to readers.
2053
+ * @param key - Replacement credential.
2054
+ * @param lease - Metadata promoted with the credential.
2055
+ * @returns Operations to publish the file or remove the temporary copy.
2056
+ */
2057
+ async stage(key, lease) {
2058
+ await fs11.mkdir(this.#directory, { mode: 448, recursive: true });
2059
+ await fs11.chmod(this.#directory, 448);
2060
+ const temporary = path12.join(this.#directory, `.lease-${randomUUID2()}.tmp`);
2061
+ try {
2062
+ const record = lease === void 0 ? key.value : { key: key.value, lease };
2063
+ await fs11.writeFile(temporary, `${JSON.stringify(record)}
1793
2064
  `, {
1794
2065
  encoding: "utf8",
1795
2066
  flag: "wx",
1796
2067
  mode: 384
1797
2068
  });
1798
- await fs6.rename(temporary, this.#file);
1799
- } finally {
1800
- await fs6.rm(temporary, { force: true });
2069
+ } catch (cause) {
2070
+ await fs11.rm(temporary, { force: true });
2071
+ throw cause;
1801
2072
  }
2073
+ return {
2074
+ commit: () => fs11.rename(temporary, this.#file),
2075
+ discard: () => fs11.rm(temporary, { force: true })
2076
+ };
1802
2077
  }
1803
2078
  };
1804
2079
 
@@ -1806,6 +2081,30 @@ var FileSecretStore = class {
1806
2081
  var HostStorageSecretStore = class {
1807
2082
  #key;
1808
2083
  #storage;
2084
+ /** @param storage - Plugin-owned host storage.
2085
+ * @returns The persisted lease scopes across all result pages.
2086
+ */
2087
+ static async scopes(storage) {
2088
+ const scopes = [];
2089
+ let after;
2090
+ do {
2091
+ const page = await storage.scan({
2092
+ prefix: "route33_lease_",
2093
+ ...after === void 0 ? {} : { after }
2094
+ });
2095
+ for (const { key } of page.entries)
2096
+ scopes.push(
2097
+ .../^route33_lease_([a-f0-9]{64})$/u.exec(key)?.slice(1) ?? []
2098
+ );
2099
+ after = page.next;
2100
+ } while (after !== void 0);
2101
+ return scopes;
2102
+ }
2103
+ /** @returns Metadata written atomically with this secret, if available. */
2104
+ async getLease() {
2105
+ const entry = await this.#storage.get(this.#key);
2106
+ return typeof entry === "object" && entry !== null && "lease" in entry && typeof entry.lease === "string" ? LeaseState.restore(JSON.parse(entry.lease)).snapshot() : void 0;
2107
+ }
1809
2108
  constructor(options) {
1810
2109
  this.#key = options.key;
1811
2110
  this.#storage = options.storage;
@@ -1828,10 +2127,14 @@ var HostStorageSecretStore = class {
1828
2127
  /** Writes the scoped gateway credential into the box envelope, through
1829
2128
  * host-owned storage only.
1830
2129
  * @param key - The credential to persist, or undefined to remove it.
2130
+ * @param lease
1831
2131
  * @returns A promise that settles after the host write or removal.
1832
2132
  */
1833
- set(key) {
1834
- return key === void 0 ? this.#storage.remove(this.#key) : this.#storage.set(this.#key, { value: key.value });
2133
+ set(key, lease) {
2134
+ return key === void 0 ? this.#storage.remove(this.#key) : this.#storage.set(this.#key, {
2135
+ value: key.value,
2136
+ ...lease ? { lease: JSON.stringify(lease) } : {}
2137
+ });
1835
2138
  }
1836
2139
  };
1837
2140
 
@@ -1998,9 +2301,35 @@ var buildMintInput = (deps) => {
1998
2301
  };
1999
2302
  };
2000
2303
 
2304
+ // src/key-lease/commit-staged-replacement/commit-staged-replacement.ts
2305
+ var commitStagedReplacement = async (stage, save, persist) => {
2306
+ const storeFailure = (cause) => {
2307
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
2308
+ };
2309
+ const staged = await stage().catch(storeFailure);
2310
+ try {
2311
+ save();
2312
+ await (staged ? staged.commit() : persist()).catch(storeFailure);
2313
+ } finally {
2314
+ await staged?.discard();
2315
+ }
2316
+ };
2317
+
2001
2318
  // src/key-lease/mint-fresh-lease/mint-fresh-lease.ts
2002
2319
  var mintFreshLease = async (deps) => {
2003
2320
  const now = deps.clock();
2321
+ const current = deps.state.snapshot();
2322
+ const reusable = () => {
2323
+ if (deps.wizardRequest !== void 0 && current?.wizardRequest === deps.wizardRequest && deps.storedKey !== void 0 && Date.parse(current.expiresAt) > now) {
2324
+ return { key: deps.storedKey, lease: current };
2325
+ }
2326
+ return void 0;
2327
+ };
2328
+ const reused = reusable();
2329
+ if (reused !== void 0) {
2330
+ deps.saveAttribution?.();
2331
+ return reused;
2332
+ }
2004
2333
  const input = buildMintInput({
2005
2334
  attribution: deps.attribution,
2006
2335
  extras: deps.extras,
@@ -2023,13 +2352,23 @@ var mintFreshLease = async (deps) => {
2023
2352
  lease: {
2024
2353
  attribution: deps.attribution,
2025
2354
  expiresAt: material.expires_at,
2026
- keyId: material.id
2355
+ keyId: material.id,
2356
+ ...deps.wizardRequest === void 0 ? {} : { wizardRequest: deps.wizardRequest }
2027
2357
  }
2028
2358
  };
2029
- try {
2030
- await deps.secretStore.set(minted.key);
2031
- } catch (cause) {
2359
+ const storeFailure = (cause) => {
2032
2360
  throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
2361
+ };
2362
+ const persist = () => deps.secretStore.set(minted.key, minted.lease);
2363
+ if (deps.saveAttribution && deps.storedKey !== void 0) {
2364
+ await commitStagedReplacement(
2365
+ () => deps.secretStore.stage?.(minted.key, minted.lease) ?? Promise.resolve(void 0),
2366
+ deps.saveAttribution,
2367
+ persist
2368
+ );
2369
+ } else {
2370
+ await persist().catch(storeFailure);
2371
+ deps.saveAttribution?.();
2033
2372
  }
2034
2373
  deps.state.compareAndSwap(deps.state.snapshot(), minted.lease);
2035
2374
  return minted;
@@ -2206,7 +2545,7 @@ var renewKey = async (options) => {
2206
2545
  }
2207
2546
  }
2208
2547
  try {
2209
- await options.secretStore.set(renewed.key);
2548
+ await options.secretStore.set(renewed.key, renewed.lease);
2210
2549
  } catch (cause) {
2211
2550
  const cleared = await discard(renewed.lease.keyId);
2212
2551
  if (!cleared) {
@@ -2326,7 +2665,10 @@ var leaseForAttribution = async (options) => {
2326
2665
  secretStore: options.installation.secretStore,
2327
2666
  state: options.installation.state,
2328
2667
  stateStore: options.installation.stateStore,
2329
- ttlMs: policy.ttlMs
2668
+ ttlMs: policy.ttlMs,
2669
+ wizardRequest: options.request.wizardRequest,
2670
+ saveAttribution: options.request.saveAttribution,
2671
+ storedKey
2330
2672
  });
2331
2673
  }
2332
2674
  const reusable = reusableLease({
@@ -2372,229 +2714,15 @@ var leaseForAttribution = async (options) => {
2372
2714
  });
2373
2715
  }
2374
2716
  return renewed;
2375
- } catch (cause) {
2376
- return mapRenewalFailure({ cause, current, now });
2377
- }
2378
- };
2379
-
2380
- // src/attribution/clear-attribution/clear-attribution.ts
2381
- import * as fs9 from "node:fs";
2382
-
2383
- // src/attribution/resolve-attribution-file/resolve-attribution-file.ts
2384
- import * as fs8 from "node:fs";
2385
- import * as path9 from "node:path";
2386
-
2387
- // src/attribution/detect-worktree-root/detect-worktree-root.ts
2388
- import * as fs7 from "node:fs";
2389
- import * as path8 from "node:path";
2390
- var detectWorktreeRoot = (startDirectory) => {
2391
- let directory = fs7.realpathSync(startDirectory);
2392
- for (; ; ) {
2393
- const gitEntry = path8.join(directory, ".git");
2394
- if (fs7.existsSync(gitEntry)) {
2395
- const entry = fs7.statSync(gitEntry);
2396
- if (entry.isDirectory() || entry.isFile()) {
2397
- return directory;
2398
- }
2399
- }
2400
- const parent = path8.dirname(directory);
2401
- if (parent === directory) {
2402
- return void 0;
2403
- }
2404
- directory = parent;
2405
- }
2406
- };
2407
-
2408
- // src/attribution/resolve-attribution-file/resolve-attribution-file.ts
2409
- var resolveAttributionFile = (options) => {
2410
- const worktreeRoot = detectWorktreeRoot(options.directory);
2411
- if (worktreeRoot !== void 0) {
2412
- return path9.join(worktreeRoot, ".opencode", "route33.attribution.json");
2413
- }
2414
- const fallbackRoots = {
2415
- "return-undefined": void 0,
2416
- "use-directory": fs8.realpathSync(options.directory)
2417
- };
2418
- const fallbackRoot = fallbackRoots[options.outsideWorktree];
2419
- return fallbackRoot === void 0 ? void 0 : path9.join(fallbackRoot, ".opencode", "route33.attribution.json");
2420
- };
2421
-
2422
- // src/attribution/clear-attribution/clear-attribution.ts
2423
- var clearAttribution = (options) => {
2424
- const file = resolveAttributionFile(options);
2425
- if (file === void 0) {
2426
- return false;
2427
- }
2428
- fs9.rmSync(file, { force: true });
2429
- return true;
2430
- };
2431
-
2432
- // src/attribution/read-legacy-key/read-legacy-key.ts
2433
- import * as path10 from "node:path";
2434
- var LEGACY_KEY_RELATIVE_PATH = path10.join(".opencode", "route33.key");
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
-
2448
- // src/attribution/parse-attribution/parse-attribution.ts
2449
- var parseAttribution = (value) => {
2450
- if (!isRecord(value)) {
2451
- throw new ContractParseError("invalid attribution");
2452
- }
2453
- const orgId = readOrgId(value);
2454
- if (value["kind"] === "personal") {
2455
- return { kind: "personal", ...orgId === void 0 ? {} : { orgId } };
2456
- }
2457
- if (value["kind"] === "project" && typeof value["projectId"] === "string") {
2458
- return {
2459
- kind: "project",
2460
- ...orgId === void 0 ? {} : { orgId },
2461
- projectId: value["projectId"]
2462
- };
2463
- }
2464
- throw new ContractParseError("invalid attribution");
2465
- };
2466
-
2467
- // src/attribution/read-attribution/read-attribution.ts
2468
- import * as fs10 from "node:fs";
2469
- var readAttribution = (options) => {
2470
- const file = resolveAttributionFile(options);
2471
- if (file === void 0) {
2472
- return void 0;
2473
- }
2474
- try {
2475
- const parsed = JSON.parse(fs10.readFileSync(file, "utf8"));
2476
- return parseAttribution(parsed);
2477
- } catch {
2478
- return void 0;
2479
- }
2480
- };
2481
-
2482
- // src/attribution/remove-legacy-key/remove-legacy-key.ts
2483
- import * as path11 from "node:path";
2484
- var LEGACY_KEY_RELATIVE_PATH2 = path11.join(".opencode", "route33.key");
2485
-
2486
- // src/attribution/write-attribution/write-attribution.ts
2487
- import { randomUUID as randomUUID2 } from "node:crypto";
2488
- import * as fs11 from "node:fs";
2489
- import * as path12 from "node:path";
2490
- var writeAttribution = (options, attribution) => {
2491
- const file = resolveAttributionFile(options);
2492
- if (file === void 0) {
2493
- return false;
2494
- }
2495
- fs11.mkdirSync(path12.dirname(file), { recursive: true });
2496
- const temporaryFile = `${file}.${String(process.pid)}.${randomUUID2()}.tmp`;
2497
- try {
2498
- fs11.writeFileSync(temporaryFile, `${JSON.stringify(attribution)}
2499
- `, "utf8");
2500
- fs11.renameSync(temporaryFile, file);
2501
- } catch (error) {
2502
- fs11.rmSync(temporaryFile, { force: true });
2503
- throw error;
2504
- }
2505
- return true;
2506
- };
2507
-
2508
- // src/key-lease/lease-state/lease-state.ts
2509
- var LeaseState = class _LeaseState {
2510
- /** Current committed snapshot; mutation is limited to compare-and-swap transitions. */
2511
- #current;
2512
- constructor(current) {
2513
- this.#current = current;
2514
- }
2515
- /** Restores untrusted persisted metadata or an empty lease.
2516
- * @param value - Persisted metadata, or undefined for a new installation.
2517
- * @returns A lease-state coordinator.
2518
- */
2519
- static restore(value) {
2520
- if (value === void 0) {
2521
- return new _LeaseState(void 0);
2522
- }
2523
- if (!isRecord(value)) {
2524
- throw new ContractParseError("invalid gateway key lease state");
2525
- }
2526
- const fields = Object.keys(value);
2527
- if (fields.length !== 3 || fields.some(
2528
- (field) => field !== "attribution" && field !== "expiresAt" && field !== "keyId"
2529
- )) {
2530
- throw new ContractParseError("invalid gateway key lease state");
2531
- }
2532
- const expiresAt = value["expiresAt"];
2533
- const keyId = value["keyId"];
2534
- if (typeof expiresAt !== "string" || !Number.isFinite(Date.parse(expiresAt)) || typeof keyId !== "string" || keyId.length === 0) {
2535
- throw new ContractParseError("invalid gateway key lease state");
2536
- }
2537
- return new _LeaseState({
2538
- attribution: parseAttribution(value["attribution"]),
2539
- expiresAt,
2540
- keyId
2541
- });
2542
- }
2543
- /** Reads the current non-secret metadata.
2544
- * @returns The current lease metadata, if one is committed.
2545
- */
2546
- snapshot() {
2547
- return this.#current;
2548
- }
2549
- /** Checks whether current metadata belongs to an attribution.
2550
- * @param attribution - The requested ownership choice.
2551
- * @returns Whether the current lease has the same attribution.
2552
- */
2553
- matchesAttribution(attribution) {
2554
- if (this.#current === void 0) {
2555
- return false;
2556
- }
2557
- switch (this.#current.attribution.kind) {
2558
- case "personal":
2559
- return attribution.kind === "personal";
2560
- case "project":
2561
- return attribution.kind === "project" && attribution.projectId === this.#current.attribution.projectId;
2562
- default:
2563
- return _LeaseState.#unexpectedAttribution(this.#current.attribution);
2564
- }
2565
- }
2566
- /** Atomically swaps metadata when the expected snapshot is still current.
2567
- * @param expected - Snapshot observed before asynchronous renewal.
2568
- * @param next - Fresh metadata to commit.
2569
- * @returns Whether the swap committed.
2570
- */
2571
- compareAndSwap(expected, next) {
2572
- if (this.#current !== expected) {
2573
- return false;
2574
- }
2575
- this.#current = next;
2576
- return true;
2577
- }
2578
- /** Clears metadata only while the expected snapshot remains current.
2579
- * @param expected - Snapshot whose lease is being invalidated.
2580
- * @returns Whether the state was cleared.
2581
- */
2582
- clear(expected) {
2583
- if (this.#current !== expected) {
2584
- return false;
2585
- }
2586
- this.#current = void 0;
2587
- return true;
2588
- }
2589
- static #unexpectedAttribution(value) {
2590
- throw new TypeError(`Unexpected attribution: ${String(value)}`);
2717
+ } catch (cause) {
2718
+ return mapRenewalFailure({ cause, current, now });
2591
2719
  }
2592
2720
  };
2593
2721
 
2594
2722
  // src/key-lease/lease-installation-factory/lease-installation-factory.ts
2595
2723
  var createLeaseInstallationFactory = (options) => {
2596
2724
  const installations = /* @__PURE__ */ new Map();
2597
- return (scopeId) => {
2725
+ const open = (scopeId) => {
2598
2726
  const existing = installations.get(scopeId);
2599
2727
  if (existing !== void 0) {
2600
2728
  return existing;
@@ -2608,6 +2736,14 @@ var createLeaseInstallationFactory = (options) => {
2608
2736
  installations.set(scopeId, installation);
2609
2737
  return installation;
2610
2738
  };
2739
+ return Object.assign(open, {
2740
+ scopes: async () => [
2741
+ .../* @__PURE__ */ new Set([
2742
+ ...installations.keys(),
2743
+ ...await options.listScopes?.() ?? []
2744
+ ])
2745
+ ]
2746
+ });
2611
2747
  };
2612
2748
 
2613
2749
  // src/key-lease/scope-id/scope-id.ts
@@ -2634,12 +2770,29 @@ var deriveScopeId = (input) => {
2634
2770
  throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
2635
2771
  }
2636
2772
  }
2773
+ if (input.attribution.boundKeyId !== void 0) {
2774
+ if (input.folderRealpath === void 0)
2775
+ throw new TypeError("Bound keys require a worktree");
2776
+ if (input.attribution.boundScopeId !== void 0)
2777
+ return input.attribution.boundScopeId;
2778
+ identity = [
2779
+ ...identity,
2780
+ "binding",
2781
+ input.folderRealpath,
2782
+ input.attribution.orgId ?? "",
2783
+ input.attribution.boundKeyId
2784
+ ];
2785
+ }
2637
2786
  return createHash2("sha256").update(JSON.stringify(identity)).digest("hex");
2638
2787
  };
2639
2788
 
2640
2789
  // src/requested-client-id/requested-client-id.ts
2641
2790
  var DEFAULT_ROUTE33_CLIENT_ID = false ? "" : "oa_platform_203623de";
2642
2791
 
2792
+ // src/route33-runtime/route33-runtime.ts
2793
+ import { createHash as createHash3 } from "node:crypto";
2794
+ import { statSync as statSync2 } from "node:fs";
2795
+
2643
2796
  // src/catalog/gateway-model-ids/gateway-model-ids.ts
2644
2797
  var gatewayModelIds = async (deps) => {
2645
2798
  const { baseURL, gatewayKey, ...rest } = deps;
@@ -2653,8 +2806,9 @@ var gatewayModelIds = async (deps) => {
2653
2806
 
2654
2807
  // src/commands/change-attribution/change-attribution.ts
2655
2808
  var changeAttribution = async (options) => {
2656
- await options.clear();
2657
- return options.prompt();
2809
+ const choice = await options.prompt();
2810
+ await options.commit(choice);
2811
+ return choice;
2658
2812
  };
2659
2813
 
2660
2814
  // src/commands/inspect-session/inspect-session.ts
@@ -2678,6 +2832,114 @@ var rotateNow = async (options) => {
2678
2832
  return rotated.lease;
2679
2833
  };
2680
2834
 
2835
+ // src/key-lease/workspace-key-binding/workspace-key-binding.ts
2836
+ import { mkdir as mkdir2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
2837
+ import { dirname as dirname4 } from "node:path";
2838
+ var ROTATION_WARNING = "This key will be rotated. Existing consumers will break. Continue?";
2839
+ var pending = /* @__PURE__ */ new Map();
2840
+ var WorkspaceKeyBinding = class {
2841
+ constructor(deps) {
2842
+ this.deps = deps;
2843
+ }
2844
+ deps;
2845
+ #listings = /* @__PURE__ */ new Map();
2846
+ /** @param choice - The budget selected by the user.
2847
+ * @returns Secret-free options; local options do not need destructive consent.
2848
+ */
2849
+ async candidates(choice) {
2850
+ const listing = this.#listings.get(choice.orgId) ?? this.deps.client.list(this.deps.token, choice.orgId);
2851
+ this.#listings.set(choice.orgId, listing);
2852
+ const rows = await listing;
2853
+ const keys = rows.data.filter((row) => this.matches(row, choice));
2854
+ if (keys.length === 0) return [];
2855
+ const local = await this.localKeys(new Set(keys.map((row) => row.id)));
2856
+ return keys.map((row) => ({
2857
+ id: row.id,
2858
+ name: row.name,
2859
+ local: local.has(row.id)
2860
+ }));
2861
+ }
2862
+ matches(row, choice) {
2863
+ return row.status === "active" && !row.revoked && Date.parse(row.expires_at) > this.deps.now && (choice.orgId === void 0 || row.org_id === choice.orgId) && row.owner_user_id === this.deps.subject && (choice.kind === "project" ? row.project_id === choice.projectId && row.ownership_type === "user_project" : row.project_id === null && row.ownership_type === "user_personal");
2864
+ }
2865
+ async localKeys(ids) {
2866
+ const found = /* @__PURE__ */ new Map();
2867
+ for (const scope of await this.deps.installations.scopes?.() ?? []) {
2868
+ const store = this.deps.installations(scope);
2869
+ const lease = await this.metadata(store);
2870
+ if (!lease || !ids.has(lease.keyId) || Date.parse(lease.expiresAt) <= this.deps.now)
2871
+ continue;
2872
+ const key = await store.secretStore.get();
2873
+ if (key && (await this.metadata(store))?.keyId === lease.keyId)
2874
+ found.set(lease.keyId, scope);
2875
+ }
2876
+ return found;
2877
+ }
2878
+ async metadata(store) {
2879
+ return await store.secretStore.getLease?.() ?? await store.stateStore?.get() ?? store.state.snapshot();
2880
+ }
2881
+ /** @param choice - Selected attribution; the live key must still belong to it.
2882
+ * @param id - Selected management key id, never its secret.
2883
+ * @param confirmed - Explicit consent to rotate this id if plaintext is unavailable.
2884
+ * @returns The attribution to commit after saving the secret.
2885
+ */
2886
+ async bind(choice, id, confirmed) {
2887
+ const row = await this.deps.client.get(this.deps.token, id, choice.orgId);
2888
+ if (row.id !== id || !this.matches(row, choice))
2889
+ throw new GatewayCredentialError(
2890
+ "This key is not available for the selected budget."
2891
+ );
2892
+ const file = resolveAttributionFile(this.deps.state);
2893
+ if (file === void 0)
2894
+ throw new GatewayCredentialError("Key binding requires a worktree.");
2895
+ const bound = { ...choice, boundKeyId: id };
2896
+ const scope = deriveScopeId({
2897
+ attribution: bound,
2898
+ folderRealpath: detectWorktreeRoot(this.deps.state.directory)
2899
+ });
2900
+ const marker = `${file}.${scope}.rotation`;
2901
+ const retry = pending.get(marker);
2902
+ const localScope = retry === void 0 ? (await this.localKeys(/* @__PURE__ */ new Set([id]))).get(id) : void 0;
2903
+ if (localScope !== void 0) return { ...bound, boundScopeId: localScope };
2904
+ const target = this.deps.installations(scope);
2905
+ const { key, lease } = retry ?? await this.rotate(bound, marker, confirmed);
2906
+ await target.secretStore.set(key, lease);
2907
+ await target.stateStore?.set(lease);
2908
+ target.state.compareAndSwap(target.state.snapshot(), lease);
2909
+ await rm2(marker, { force: true });
2910
+ pending.delete(marker);
2911
+ return bound;
2912
+ }
2913
+ async rotate(bound, marker, confirmed) {
2914
+ if (!confirmed) throw new GatewayCredentialError(ROTATION_WARNING);
2915
+ const id = bound.boundKeyId;
2916
+ await mkdir2(dirname4(marker), { recursive: true });
2917
+ try {
2918
+ await writeFile2(marker, "pending\n", { flag: "wx", mode: 384 });
2919
+ } catch (cause) {
2920
+ if (cause instanceof Error && "code" in cause && cause.code === "EEXIST")
2921
+ throw new GatewayCredentialError(
2922
+ "Rotation is already pending. Retry saving in the original session or choose a new key."
2923
+ );
2924
+ throw cause;
2925
+ }
2926
+ const rotated = await this.deps.client.regenerate(
2927
+ this.deps.token,
2928
+ id,
2929
+ void 0,
2930
+ bound.orgId
2931
+ );
2932
+ if (rotated.id !== id)
2933
+ throw new GatewayCredentialError("Rotation returned a different key.");
2934
+ const material = {
2935
+ key: rotated.key,
2936
+ lease: { attribution: bound, expiresAt: rotated.expires_at, keyId: id }
2937
+ };
2938
+ pending.set(marker, material);
2939
+ return material;
2940
+ }
2941
+ };
2942
+
2681
2943
  // src/ux/attribution-prompt/org-selection-prefix/org-selection-prefix.ts
2682
2944
  var orgSelectionPrefix = (orgId) => `org:${orgId}:`;
2683
2945
 
@@ -2759,6 +3021,7 @@ var createAttributionPrompt = (projects, options = {}) => {
2759
3021
 
2760
3022
  // src/ux/attribution-prompt-error/attribution-prompt-error.ts
2761
3023
  var MESSAGES = {
3024
+ ATTRIBUTION_BACK: "Left budget selection without changing attribution.",
2762
3025
  ATTRIBUTION_PRESENTER_UNAVAILABLE: "Route 33 needs OpenCode v2 to assign a budget for this folder. Update to OpenCode v2, run /connect, choose Route 33, and follow the steps.",
2763
3026
  ATTRIBUTION_SELECTION_INVALID: "That Route 33 option is no longer available. Connect again and pick another."
2764
3027
  };
@@ -2772,8 +3035,9 @@ var AttributionPromptError = class extends GatewayCredentialError {
2772
3035
  };
2773
3036
 
2774
3037
  // src/ux/prompt-flow/prompt-flow.ts
3038
+ var BACK_SELECTION = "/back";
2775
3039
  var resolveAttribution = async (options) => {
2776
- const remembered = readAttribution(options.state);
3040
+ const remembered = options.state && readAttribution(options.state);
2777
3041
  if (remembered !== void 0) {
2778
3042
  return remembered;
2779
3043
  }
@@ -2781,12 +3045,16 @@ var resolveAttribution = async (options) => {
2781
3045
  throw new AttributionPromptError("ATTRIBUTION_PRESENTER_UNAVAILABLE");
2782
3046
  }
2783
3047
  const plan = createAttributionPrompt(await options.loadProjects());
2784
- const selection = await options.presenter.pick(plan);
3048
+ const selection = await options.presenter.pick({
3049
+ ...plan,
3050
+ options: [...plan.options, { label: "Back", selection: BACK_SELECTION }]
3051
+ });
3052
+ if (selection === BACK_SELECTION)
3053
+ throw new AttributionPromptError("ATTRIBUTION_BACK");
2785
3054
  const attribution = plan.choicesBySelection[selection];
2786
3055
  if (attribution === void 0) {
2787
3056
  throw new AttributionPromptError("ATTRIBUTION_SELECTION_INVALID");
2788
3057
  }
2789
- writeAttribution(options.state, attribution);
2790
3058
  return attribution;
2791
3059
  };
2792
3060
 
@@ -2804,6 +3072,66 @@ var CALLBACK_PAGE_COPY = {
2804
3072
  successSubline: "Return to OpenCode \u2014 one more step may wait there: if it asks which budget covers usage, pick a project. This window can be closed."
2805
3073
  };
2806
3074
 
3075
+ // src/route33-runtime/enrich-inspection/enrich-inspection.ts
3076
+ var enrichInspection = async ({
3077
+ attribution,
3078
+ client,
3079
+ credential,
3080
+ keyId,
3081
+ subject
3082
+ }) => {
3083
+ const key = await client.get(credential, keyId);
3084
+ const orgId = key.org_id;
3085
+ if (attribution.orgId !== void 0 && attribution.orgId !== orgId) {
3086
+ return {};
3087
+ }
3088
+ const keyDetails = {
3089
+ name: key.name,
3090
+ organisationName: null,
3091
+ projectName: null
3092
+ };
3093
+ switch (attribution.kind) {
3094
+ case "personal": {
3095
+ if (key.project_id !== null) {
3096
+ return {};
3097
+ }
3098
+ return client.listBudgetPolicy(credential, subject(), orgId).then(
3099
+ ({ cap }) => cap === null ? { key: keyDetails } : {
3100
+ key: keyDetails,
3101
+ budget: { amount: String(cap), currency: null }
3102
+ }
3103
+ ).catch(() => ({ key: keyDetails }));
3104
+ }
3105
+ case "project": {
3106
+ const { projectId } = attribution;
3107
+ if (key.project_id !== projectId) {
3108
+ return {};
3109
+ }
3110
+ return Promise.all([
3111
+ client.listProjects(credential, orgId).then(
3112
+ ({ data }) => data.find(({ id, org_id }) => id === projectId && org_id === orgId)
3113
+ ).catch(() => void 0),
3114
+ client.listOrganizations(credential).then(({ data }) => data.find(({ id }) => id === orgId)?.name ?? null).catch(() => null)
3115
+ ]).then(([project, organisationName]) => {
3116
+ const title = project?.name.trim() ?? "";
3117
+ const budget = project?.effective_budget ?? project?.max_budget;
3118
+ return {
3119
+ key: {
3120
+ ...keyDetails,
3121
+ organisationName,
3122
+ projectName: title === "" ? null : title
3123
+ },
3124
+ ...budget == null ? {} : { budget }
3125
+ };
3126
+ });
3127
+ }
3128
+ default: {
3129
+ const unexpected = attribution;
3130
+ throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
3131
+ }
3132
+ }
3133
+ };
3134
+
2807
3135
  // src/route33-runtime/login-session/login-session.ts
2808
3136
  import { AuthError as AuthError2 } from "@r-33/auth-browser";
2809
3137
 
@@ -3089,6 +3417,8 @@ var Route33Runtime = class {
3089
3417
  }
3090
3418
  const installation = this.#installation(attribution);
3091
3419
  await this.#hydrateState(installation);
3420
+ if (attribution.boundKeyId !== void 0)
3421
+ return this.#boundKey(installation, attribution.boundKeyId);
3092
3422
  const storedKey = await installation.secretStore.get();
3093
3423
  return reusableLease({
3094
3424
  attribution,
@@ -3146,24 +3476,14 @@ var Route33Runtime = class {
3146
3476
  commandHandlers() {
3147
3477
  return {
3148
3478
  "change-attribution": () => changeAttribution({
3149
- clear: () => {
3150
- clearAttribution(this.#options.state);
3479
+ commit: async (choice) => {
3480
+ await this.#leaseAttribution(choice, this.#options.policy);
3481
+ if (!writeAttribution(this.#options.state, choice))
3482
+ throw new TypeError("Workspace attribution requires a worktree");
3151
3483
  },
3152
- prompt: () => this.#resolveAttribution()
3484
+ prompt: () => this.pickAttribution()
3153
3485
  }),
3154
- "inspect-session": async () => {
3155
- try {
3156
- return await this.#inspectSession();
3157
- } catch {
3158
- return inspectSession({
3159
- readAttribution: () => readAttribution(this.#options.state),
3160
- readLease: () => {
3161
- const attribution = readAttribution(this.#options.state);
3162
- return attribution === void 0 ? void 0 : this.#installation(attribution).state.snapshot();
3163
- }
3164
- });
3165
- }
3166
- },
3486
+ "inspect-session": () => this.#inspectSession(),
3167
3487
  "reset-attribution": () => resetAttribution({
3168
3488
  clear: () => {
3169
3489
  clearAttribution(this.#options.state);
@@ -3175,53 +3495,58 @@ var Route33Runtime = class {
3175
3495
  })
3176
3496
  };
3177
3497
  }
3178
- /** Enriched session inspection: the plain report plus the key's name and organisation/project.
3498
+ /** Adds fresh display metadata without prompting for sign-in or changing attribution.
3179
3499
  * @returns A safe session report that cannot carry gateway plaintext.
3180
3500
  */
3181
3501
  async #inspectSession() {
3502
+ const attribution = readAttribution(this.#options.state);
3503
+ const installation = attribution === void 0 ? void 0 : this.#installation(attribution);
3504
+ if (installation !== void 0) {
3505
+ await this.#hydrateState(installation);
3506
+ }
3182
3507
  const base = inspectSession({
3183
- readAttribution: () => readAttribution(this.#options.state),
3184
- readLease: () => {
3185
- const attribution = readAttribution(this.#options.state);
3186
- return attribution === void 0 ? void 0 : this.#installation(attribution).state.snapshot();
3187
- }
3508
+ readAttribution: () => attribution,
3509
+ readLease: () => installation?.state.snapshot()
3188
3510
  });
3189
3511
  const keyId = base.lease?.keyId;
3190
- if (keyId === void 0) {
3512
+ if (attribution === void 0 || keyId === void 0) {
3191
3513
  return base;
3192
3514
  }
3193
- const credential = await this.#session.credential();
3194
- const client = this.#client();
3195
- const [keys, projects] = await Promise.all([
3196
- client.list(credential).then((collection) => collection.data).catch(() => []),
3197
- this.listProjects().catch(() => [])
3198
- ]);
3199
- const key = keys.find((item) => item.id === keyId);
3200
- if (key === void 0) {
3515
+ try {
3516
+ const credential = await this.#session.credential({
3517
+ allowBrowser: false
3518
+ });
3519
+ const details = await enrichInspection({
3520
+ attribution,
3521
+ client: this.#client(),
3522
+ credential,
3523
+ keyId,
3524
+ subject: () => this.#subject(credential)
3525
+ });
3526
+ return { ...base, ...details };
3527
+ } catch {
3201
3528
  return base;
3202
3529
  }
3203
- const projectId = key.project_id ?? null;
3204
- const project = projectId === null ? void 0 : projects.find((item) => item.id === projectId);
3205
- return {
3206
- ...base,
3207
- key: {
3208
- name: key.name,
3209
- organisationName: project?.organisation.name ?? null,
3210
- projectName: project?.name ?? null
3211
- }
3212
- };
3213
3530
  }
3214
3531
  /**
3215
- * Lists the gateway catalog's model ids under the current stored key —
3216
- * the connect form's allowed-models picker offers exactly these.
3217
- * @returns Catalog model ids, empty while no key or catalog exists.
3532
+ * @param scope - The budget being configured. Omit to discover models for the current key.
3533
+ * @returns The management catalog for a budget, or the current key's gateway catalog.
3218
3534
  */
3219
- async catalogModelIds() {
3535
+ async catalogModelIds(scope) {
3536
+ if (scope !== void 0) {
3537
+ const credential = await this.#session.credential({
3538
+ allowBrowser: false
3539
+ });
3540
+ return this.#client().listModelIds(credential, scope);
3541
+ }
3220
3542
  const workspace = await this.storedReusableKey();
3221
3543
  const personal = workspace === void 0 ? await this.#storedPersonalKey() : void 0;
3222
3544
  const value = workspace?.key.value ?? personal?.value;
3223
3545
  if (value === void 0) {
3224
- return [];
3546
+ const credential = await this.#session.credential({
3547
+ allowBrowser: false
3548
+ });
3549
+ return this.#client().listModelIds(credential, {});
3225
3550
  }
3226
3551
  return gatewayModelIds({
3227
3552
  baseURL: readEnvBaseUrl() ?? DEFAULT_BASE_URL,
@@ -3240,12 +3565,41 @@ var Route33Runtime = class {
3240
3565
  * @param attribution - The budget the wizard selected.
3241
3566
  * @param extras - The wizard's key-creation answers.
3242
3567
  * @param directory - Optional worktree override for project leases.
3568
+ * @param saveAttribution - Wizard save that must succeed before replacing a live key.
3243
3569
  * @returns The fresh key material with its lease metadata.
3244
3570
  */
3245
- async mintWorkspaceKey(attribution, extras, directory = this.#options.state.directory) {
3571
+ async mintWorkspaceKey(attribution, extras, directory = this.#options.state.directory, saveAttribution) {
3572
+ const file = resolveAttributionFile({ ...this.#options.state, directory });
3573
+ if (file === void 0)
3574
+ throw new TypeError("Workspace attribution requires a worktree");
3575
+ const previous = statSync2(file, { bigint: true, throwIfNoEntry: false });
3576
+ const wizardRequest = createHash3("sha256").update(
3577
+ JSON.stringify([
3578
+ file,
3579
+ previous?.ino.toString(),
3580
+ previous?.mtimeNs.toString(),
3581
+ attribution,
3582
+ extras,
3583
+ this.#subject(await this.#session.credential())
3584
+ ])
3585
+ ).digest("hex");
3246
3586
  return this.#leaseAttribution(attribution, void 0, directory, {
3247
3587
  extras,
3248
- forceMint: true
3588
+ forceMint: true,
3589
+ wizardRequest,
3590
+ saveAttribution
3591
+ });
3592
+ }
3593
+ /** @returns Binding operations restricted to the current management identity. */
3594
+ async workspaceKeyBinding() {
3595
+ const token = await this.#session.credential({ allowBrowser: false });
3596
+ return new WorkspaceKeyBinding({
3597
+ installations: this.#options.installation,
3598
+ token,
3599
+ subject: this.#subject(token),
3600
+ client: this.#client(),
3601
+ now: this.#now(),
3602
+ state: this.#options.state
3249
3603
  });
3250
3604
  }
3251
3605
  /**
@@ -3263,7 +3617,7 @@ var Route33Runtime = class {
3263
3617
  if (attribution === void 0) {
3264
3618
  return void 0;
3265
3619
  }
3266
- const lease = this.#installation(attribution).state.snapshot();
3620
+ const lease = this.#installation(attribution, directory).state.snapshot();
3267
3621
  const keyId = lease?.keyId;
3268
3622
  if (keyId === void 0) {
3269
3623
  return void 0;
@@ -3291,23 +3645,33 @@ var Route33Runtime = class {
3291
3645
  #now() {
3292
3646
  return (this.#options.clock ?? Date.now)();
3293
3647
  }
3294
- async #resolveAttribution() {
3648
+ /** @returns A fresh selection without changing the active budget. */
3649
+ pickAttribution() {
3295
3650
  return resolveAttribution({
3296
3651
  loadProjects: async () => {
3297
3652
  await this.#session.credential();
3298
3653
  return this.listMintableProjects();
3299
3654
  },
3300
- ...this.#options.presenter === void 0 ? {} : { presenter: this.#options.presenter },
3301
- state: this.#options.state
3655
+ ...this.#options.presenter === void 0 ? {} : { presenter: this.#options.presenter }
3302
3656
  });
3303
3657
  }
3304
3658
  async #lease(policy) {
3305
- const attribution = await this.#resolveAttribution();
3306
- return this.#leaseAttribution(attribution, policy);
3659
+ const remembered = readAttribution(this.#options.state);
3660
+ if (remembered !== void 0)
3661
+ return this.#leaseAttribution(remembered, policy);
3662
+ const choice = await this.pickAttribution();
3663
+ const leased = await this.#leaseAttribution(choice, policy);
3664
+ writeAttribution(this.#options.state, choice);
3665
+ return leased;
3307
3666
  }
3308
3667
  async #leaseAttribution(attribution, policy, directory = this.#options.state.directory, request) {
3309
3668
  const installation = this.#installation(attribution, directory);
3310
3669
  await this.#hydrateState(installation);
3670
+ if (attribution.boundKeyId !== void 0) {
3671
+ if (policy?.renewalRatio === Number.EPSILON)
3672
+ throw new TypeError("Automatic rotation is disabled for a shared key.");
3673
+ return this.#boundKey(installation, attribution.boundKeyId);
3674
+ }
3311
3675
  const minted = await leaseForAttribution({
3312
3676
  attribution,
3313
3677
  ...this.#options.clock === void 0 ? {} : { clock: this.#options.clock },
@@ -3323,13 +3687,20 @@ var Route33Runtime = class {
3323
3687
  await this.#persistState(installation, minted.lease);
3324
3688
  return minted;
3325
3689
  }
3690
+ async #boundKey(installation, id) {
3691
+ const key = await installation.secretStore.get();
3692
+ const lease = await installation.secretStore.getLease?.() ?? await installation.stateStore?.get() ?? installation.state.snapshot();
3693
+ if (!key || lease?.keyId !== id || Date.parse(lease.expiresAt) <= this.#now())
3694
+ throw new KeyLeaseError("KEY_LEASE_EXPIRED");
3695
+ return { key, lease };
3696
+ }
3326
3697
  async #hydrateState(installation) {
3327
3698
  const store = installation.stateStore;
3328
- if (store === void 0 || installation.state.snapshot() !== void 0) {
3699
+ if (installation.state.snapshot() !== void 0) {
3329
3700
  return;
3330
3701
  }
3331
3702
  try {
3332
- const persisted = await store.get();
3703
+ const persisted = await installation.secretStore.getLease?.() ?? await store?.get();
3333
3704
  if (persisted !== void 0) {
3334
3705
  installation.state.compareAndSwap(void 0, persisted);
3335
3706
  }
@@ -3343,6 +3714,13 @@ var Route33Runtime = class {
3343
3714
  }
3344
3715
  }
3345
3716
  #installation(attribution, directory = this.#options.state.directory) {
3717
+ if (attribution.boundKeyId !== void 0)
3718
+ return this.#options.installation(
3719
+ deriveScopeId({
3720
+ attribution,
3721
+ folderRealpath: detectWorktreeRoot(directory)
3722
+ })
3723
+ );
3346
3724
  switch (attribution.kind) {
3347
3725
  case "personal":
3348
3726
  return this.#options.installation(deriveScopeId({ attribution }));
@@ -3364,15 +3742,14 @@ var Route33Runtime = class {
3364
3742
  };
3365
3743
 
3366
3744
  // src/v1-entry/unattributed-prompt-gate/unattributed-prompt-gate.ts
3367
- var createUnattributedPromptGate = ({ directory, outsideWorktree }) => (input) => {
3745
+ var CONNECTION_COPY = "Not connected to Route 33. Run /connect, choose Route 33, and complete sign-in before assigning a budget with /r33.";
3746
+ var ATTRIBUTION_COPY = "This folder has no Route 33 budget assigned. Run /r33, choose Route 33, and assign a budget.";
3747
+ var createUnattributedPromptGate = ({ directory, isConnected, outsideWorktree }) => async (input) => {
3368
3748
  if (input.model?.providerID !== "route_33") return Promise.resolve();
3749
+ if (!await isConnected()) throw new Error(CONNECTION_COPY);
3369
3750
  const attribution = readAttribution({ directory, outsideWorktree });
3370
3751
  if (attribution !== void 0) return Promise.resolve();
3371
- return Promise.reject(
3372
- new Error(
3373
- "Route 33 needs a budget for this folder first \u2014 run /r33 in OpenCode, choose Route 33, and assign a budget."
3374
- )
3375
- );
3752
+ throw new Error(ATTRIBUTION_COPY);
3376
3753
  };
3377
3754
 
3378
3755
  // src/v1-entry/workspace-key-headers/workspace-key-headers.ts
@@ -3399,6 +3776,11 @@ var createRoute33Plugin = (options = {}) => {
3399
3776
  };
3400
3777
  const runtimeOptions = options.runtime;
3401
3778
  const installation = runtimeOptions === void 0 ? void 0 : runtimeOptions.installation ?? createLeaseInstallationFactory({
3779
+ listScopes: () => FileSecretStore.scopes(
3780
+ resolveV1SecretStoreDirectory({
3781
+ directory: options.secretStoreDirectory
3782
+ })
3783
+ ),
3402
3784
  createSecretStore: (scopeId) => new FileSecretStore({
3403
3785
  directory: resolveV1SecretStoreDirectory({
3404
3786
  ...options.secretStoreDirectory === void 0 ? {} : { directory: options.secretStoreDirectory }
@@ -3444,6 +3826,14 @@ var createRoute33Plugin = (options = {}) => {
3444
3826
  });
3445
3827
  promptGate = createUnattributedPromptGate({
3446
3828
  directory: input.worktree,
3829
+ isConnected: async () => {
3830
+ try {
3831
+ await runtime2.login({ allowBrowser: false });
3832
+ return true;
3833
+ } catch {
3834
+ return false;
3835
+ }
3836
+ },
3447
3837
  outsideWorktree: "return-undefined"
3448
3838
  });
3449
3839
  }
@@ -3475,12 +3865,6 @@ var drainPages = async (fetchPage) => {
3475
3865
  return { data, page: { ...page, has_more: false, next_cursor: null } };
3476
3866
  };
3477
3867
 
3478
- // src/management/sdk-management-keys/sdk-management-keys.ts
3479
- import {
3480
- createRoute33Client,
3481
- Route33SdkError
3482
- } from "@r-33/sdk";
3483
-
3484
3868
  // src/contract/management-keys/parse-api-key/parse-api-key.ts
3485
3869
  var parseApiKey = (value) => {
3486
3870
  if (!isRecord(value) || !isOwnerType(value["ownership_type"]) || !isNullableString(value["project_id"])) {
@@ -3506,6 +3890,7 @@ var parseApiKey = (value) => {
3506
3890
  name: field("name"),
3507
3891
  org_id: field("org_id"),
3508
3892
  ownership_type: value["ownership_type"],
3893
+ ...typeof value["owner_user_id"] === "string" ? { owner_user_id: value["owner_user_id"] } : {},
3509
3894
  project_id: value["project_id"],
3510
3895
  revoked: value["revoked"] === true,
3511
3896
  status
@@ -3741,6 +4126,32 @@ var parseUserMemberships = (value) => {
3741
4126
  };
3742
4127
  };
3743
4128
 
4129
+ // src/management/key-read-operations/key-read-operations.ts
4130
+ var keyReadOperations = (call) => {
4131
+ const withCursor = (cursor) => ({ request }) => {
4132
+ const url = new URL(request.url);
4133
+ url.searchParams.set("cursor", cursor);
4134
+ return new Request(url, request);
4135
+ };
4136
+ return {
4137
+ get: async (accessToken, id, orgId) => parseApiKey(
4138
+ await call(
4139
+ accessToken,
4140
+ orgId,
4141
+ (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
4142
+ params: { path: { api_key_id: id } }
4143
+ })
4144
+ )
4145
+ ),
4146
+ list: (accessToken, orgId) => drainPages(
4147
+ (cursor) => call(accessToken, orgId, (client) => {
4148
+ if (cursor !== "") client.use({ onRequest: withCursor(cursor) });
4149
+ return client.GET("/api/v1/api-keys", {});
4150
+ }).then((page) => parseCollection(page, parseApiKey))
4151
+ )
4152
+ };
4153
+ };
4154
+
3744
4155
  // src/management/sdk-management-keys/mint-request-body/mint-request-body.ts
3745
4156
  var buildMintRequestBody = (input) => ({
3746
4157
  ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
@@ -3754,10 +4165,134 @@ var buildMintRequestBody = (input) => ({
3754
4165
  ...input.projectId === null ? {} : { project_id: input.projectId }
3755
4166
  });
3756
4167
 
3757
- // src/management/sdk-management-keys/sdk-management-keys.ts
4168
+ // src/management/key-write-operations/key-write-operations.ts
4169
+ var keyWriteOperations = (call) => ({
4170
+ create: async (accessToken, input) => parseKeyMaterial(
4171
+ await call(
4172
+ accessToken,
4173
+ input.activeOrgId,
4174
+ (client) => client.POST("/api/v1/api-keys", {
4175
+ body: buildMintRequestBody(input)
4176
+ })
4177
+ )
4178
+ ),
4179
+ delete: async (accessToken, id) => {
4180
+ await call(
4181
+ accessToken,
4182
+ void 0,
4183
+ (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
4184
+ params: { path: { api_key_id: id } }
4185
+ })
4186
+ );
4187
+ },
4188
+ regenerate: async (accessToken, id, expiresAt, orgId) => parseKeyMaterial(
4189
+ await call(
4190
+ accessToken,
4191
+ orgId,
4192
+ (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
4193
+ body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
4194
+ params: { path: { api_key_id: id } }
4195
+ })
4196
+ )
4197
+ ),
4198
+ update: async (accessToken, id, input) => parseApiKey(
4199
+ await call(
4200
+ accessToken,
4201
+ void 0,
4202
+ (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
4203
+ body: {
4204
+ budget_currency: "EUR",
4205
+ ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
4206
+ ...input.name === void 0 ? {} : { name: input.name }
4207
+ },
4208
+ params: { path: { api_key_id: id } }
4209
+ })
4210
+ )
4211
+ )
4212
+ });
4213
+
4214
+ // src/management/sdk-management-keys/exposed-catalog-ids/exposed-catalog-ids.ts
4215
+ var exposedCatalogIds = async (readPage) => {
4216
+ const ids = /* @__PURE__ */ new Set();
4217
+ let offset = 0;
4218
+ for (; ; ) {
4219
+ const page = await readPage(offset);
4220
+ if (!isRecord(page) || !Array.isArray(page.models) || page.offset !== offset || typeof page.total !== "number" || !Number.isSafeInteger(page.total) || page.total < 0) {
4221
+ throw new ContractParseError("invalid model catalog page");
4222
+ }
4223
+ page.models.forEach((row) => {
4224
+ if (!isRecord(row) || typeof row.id !== "string" || !row.id.trim() || typeof row.status !== "string")
4225
+ throw new ContractParseError("invalid model catalog item");
4226
+ if (row.status === "exposed") ids.add(row.id);
4227
+ });
4228
+ offset += page.models.length;
4229
+ if (offset >= page.total || page.models.length === 0)
4230
+ return [...ids].sort((left, right) => left.localeCompare(right));
4231
+ }
4232
+ };
4233
+
4234
+ // src/management/model-catalog-operations/model-catalog-operations.ts
4235
+ var modelCatalogOperations = (call) => ({
4236
+ listModelIds: (token, { orgId, projectId }) => exposedCatalogIds(
4237
+ (offset) => call(token, orgId, (client) => {
4238
+ const query = { offset };
4239
+ if (projectId !== void 0)
4240
+ return client.GET("/api/v1/projects/{project_id}/model-catalog", {
4241
+ params: { path: { project_id: projectId }, query }
4242
+ });
4243
+ if (orgId !== void 0)
4244
+ return client.GET("/api/v1/orgs/{org_id}/model-catalog", {
4245
+ params: { path: { org_id: orgId }, query }
4246
+ });
4247
+ return client.GET("/api/v1/model-catalog", { params: { query } });
4248
+ })
4249
+ )
4250
+ });
4251
+
4252
+ // src/management/list-sdk-projects/list-sdk-projects.ts
4253
+ var listSdkProjects = async (accessToken, organisationId, call) => {
4254
+ if (organisationId.trim().length === 0) {
4255
+ throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
4256
+ statusCode: 400
4257
+ });
4258
+ }
4259
+ const query = {
4260
+ member_user_id: parseManagementSubject(accessToken),
4261
+ org_id: organisationId
4262
+ };
4263
+ const fetchPage = (cursor) => call(
4264
+ accessToken,
4265
+ void 0,
4266
+ (client) => client.GET("/api/v1/projects", {
4267
+ params: {
4268
+ query: cursor === "" ? query : { ...query, cursor }
4269
+ }
4270
+ })
4271
+ ).then((page) => parseCollection(page, parseProject));
4272
+ return drainPages(fetchPage);
4273
+ };
4274
+
4275
+ // src/management/organization-operations/organization-operations.ts
4276
+ var organizationOperations = (call) => ({
4277
+ listOrganizations: async (accessToken) => parseCollection(
4278
+ await call(
4279
+ accessToken,
4280
+ void 0,
4281
+ (client) => client.GET("/api/v1/orgs", {})
4282
+ ),
4283
+ parseOrganization
4284
+ ),
4285
+ listProjects: (accessToken, organisationId) => listSdkProjects(accessToken, organisationId, call)
4286
+ });
4287
+
4288
+ // src/management/sdk-management-call/sdk-management-call.ts
4289
+ import {
4290
+ createRoute33Client,
4291
+ Route33SdkError
4292
+ } from "@r-33/sdk";
3758
4293
  var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
3759
4294
  var ACTIVE_ORG_HEADER = "X-Active-Org-Id";
3760
- var sdkManagementKeys = (options) => {
4295
+ var createSdkCall = (options) => {
3761
4296
  const baseUrl = options.apiBaseUrl.replace(API_PREFIX_PATTERN, "");
3762
4297
  const timeoutMs = options.timeoutMs ?? 1e4;
3763
4298
  const fetchImpl = options.fetchImpl;
@@ -3796,7 +4331,7 @@ var sdkManagementKeys = (options) => {
3796
4331
  }
3797
4332
  return new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
3798
4333
  };
3799
- const call = async (accessToken, activeOrgId, run) => {
4334
+ return async (accessToken, activeOrgId, run) => {
3800
4335
  try {
3801
4336
  const outcome = await run(callClient(accessToken, activeOrgId));
3802
4337
  const code = outcome.response?.status;
@@ -3811,123 +4346,49 @@ var sdkManagementKeys = (options) => {
3811
4346
  throw mapFailure(cause);
3812
4347
  }
3813
4348
  };
3814
- return {
3815
- create: async (accessToken, input) => parseKeyMaterial(
3816
- await call(
3817
- accessToken,
3818
- input.activeOrgId,
3819
- (client) => client.POST("/api/v1/api-keys", {
3820
- body: buildMintRequestBody(input)
3821
- })
3822
- )
3823
- ),
3824
- delete: async (accessToken, id) => {
3825
- await call(
3826
- accessToken,
3827
- void 0,
3828
- (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
3829
- params: { path: { api_key_id: id } }
3830
- })
3831
- );
3832
- },
3833
- get: async (accessToken, id) => parseApiKey(
3834
- await call(
3835
- accessToken,
3836
- void 0,
3837
- (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
3838
- params: { path: { api_key_id: id } }
3839
- })
3840
- )
3841
- ),
3842
- list: async (accessToken) => parseCollection(
3843
- await call(
3844
- accessToken,
3845
- void 0,
3846
- (client) => client.GET("/api/v1/api-keys", {})
3847
- ),
3848
- parseApiKey
3849
- ),
3850
- listOrganizations: async (accessToken) => parseCollection(
3851
- await call(
3852
- accessToken,
3853
- void 0,
3854
- (client) => client.GET("/api/v1/orgs", {})
3855
- ),
3856
- parseOrganization
3857
- ),
3858
- listMemberships: async (accessToken, userId) => parseUserMemberships(
3859
- await call(
3860
- accessToken,
3861
- void 0,
3862
- (client) => client.GET("/api/v1/users/{user_id}/memberships", {
3863
- params: { path: { user_id: userId } }
3864
- })
3865
- )
3866
- ),
3867
- listBudgetPolicy: async (accessToken, userId, activeOrgId) => parseBudgetPolicy(
3868
- await call(
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,
3880
- (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
3881
- params: { path: { user_id: userId } }
3882
- })
3883
- ),
3884
- parseProjectBudgetState
3885
- ),
3886
- listProjects: async (accessToken, organisationId) => {
3887
- if (organisationId.trim().length === 0) {
3888
- throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
3889
- statusCode: 400
3890
- });
3891
- }
3892
- const query = {
3893
- member_user_id: parseManagementSubject(accessToken),
3894
- org_id: organisationId
3895
- };
3896
- const fetchPage = (cursor) => call(
3897
- accessToken,
3898
- void 0,
3899
- (client) => client.GET("/api/v1/projects", {
3900
- params: {
3901
- query: cursor === "" ? query : { ...query, cursor }
3902
- }
3903
- })
3904
- ).then((page) => parseCollection(page, parseProject));
3905
- return drainPages(fetchPage);
3906
- },
3907
- regenerate: async (accessToken, id, expiresAt) => parseKeyMaterial(
3908
- await call(
3909
- accessToken,
3910
- void 0,
3911
- (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
3912
- body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
3913
- params: { path: { api_key_id: id } }
3914
- })
3915
- )
3916
- ),
3917
- update: async (accessToken, id, input) => parseApiKey(
3918
- await call(
3919
- accessToken,
3920
- void 0,
3921
- (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
3922
- body: {
3923
- budget_currency: "EUR",
3924
- ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
3925
- ...input.name === void 0 ? {} : { name: input.name }
3926
- },
3927
- params: { path: { api_key_id: id } }
3928
- })
3929
- )
4349
+ };
4350
+
4351
+ // src/management/user-context-operations/user-context-operations.ts
4352
+ var userContextOperations = (call) => ({
4353
+ listMemberships: async (accessToken, userId) => parseUserMemberships(
4354
+ await call(
4355
+ accessToken,
4356
+ void 0,
4357
+ (client) => client.GET("/api/v1/users/{user_id}/memberships", {
4358
+ params: { path: { user_id: userId } }
4359
+ })
3930
4360
  )
4361
+ ),
4362
+ listBudgetPolicy: async (accessToken, userId, activeOrgId) => parseBudgetPolicy(
4363
+ await call(
4364
+ accessToken,
4365
+ activeOrgId,
4366
+ (client) => client.GET("/api/v1/users/{user_id}/budget-policy", {
4367
+ params: { path: { user_id: userId } }
4368
+ })
4369
+ )
4370
+ ),
4371
+ listProjectBudgets: async (accessToken, userId, activeOrgId) => parseCollection(
4372
+ await call(
4373
+ accessToken,
4374
+ activeOrgId,
4375
+ (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
4376
+ params: { path: { user_id: userId } }
4377
+ })
4378
+ ),
4379
+ parseProjectBudgetState
4380
+ )
4381
+ });
4382
+
4383
+ // src/management/sdk-management-keys/sdk-management-keys.ts
4384
+ var sdkManagementKeys = (options) => {
4385
+ const call = createSdkCall(options);
4386
+ return {
4387
+ ...keyReadOperations(call),
4388
+ ...keyWriteOperations(call),
4389
+ ...modelCatalogOperations(call),
4390
+ ...organizationOperations(call),
4391
+ ...userContextOperations(call)
3931
4392
  };
3932
4393
  };
3933
4394
 
@@ -4302,14 +4763,16 @@ var readAllowedModels = (answer) => {
4302
4763
  // src/v2-entry/parse-budget-answer/read-budget-cap/read-budget-cap.ts
4303
4764
  var readBudgetCap = (answer) => {
4304
4765
  const value = answer["budget_cap"];
4305
- if (typeof value === "number") {
4306
- return Number.isFinite(value) && value > 0 ? value : null;
4766
+ if (value === void 0 || value === null) return null;
4767
+ if (typeof value !== "string" && typeof value !== "number") {
4768
+ throw new TypeError("Budget cap must be a number or unlimited");
4307
4769
  }
4308
- if (typeof value !== "string") {
4770
+ if (typeof value === "string" && (value.trim() === "" || value.trim().toLowerCase() === "unlimited")) {
4309
4771
  return null;
4310
4772
  }
4311
- const parsed = Number(value.trim());
4312
- return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
4773
+ const parsed = Number(value);
4774
+ if (Number.isFinite(parsed) && parsed > 0) return parsed;
4775
+ throw new RangeError("Budget cap must be a finite positive number");
4313
4776
  };
4314
4777
 
4315
4778
  // src/v2-entry/parse-budget-answer/read-budget-description/read-budget-description.ts
@@ -4358,6 +4821,7 @@ var CONNECT_COPY = {
4358
4821
  failFastWorktree: "Route 33 attributes usage to a project inside a Git worktree. Open a Git repository (or run git init), then connect again.",
4359
4822
  selectionInvalid: "That Route 33 option is no longer available. Connect again and pick another.",
4360
4823
  signedInNextStep: "Signed in to Route 33 \u2713. One more step: connect again, choose Route 33, and assign a budget for this folder.",
4824
+ budgetSelected: "Budget selected. Connect again to configure the key for this budget.",
4361
4825
  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
4826
  };
4363
4827
 
@@ -4367,25 +4831,48 @@ var mapMintFailure = (cause) => cause instanceof KeyLeaseError && cause.statusCo
4367
4831
 
4368
4832
  // src/v2-entry/apply-wizard-answer/apply-wizard-answer.ts
4369
4833
  var applyWizardAnswer = async (deps, answer) => {
4370
- const budget = parseBudgetAnswer(answer);
4371
- const selection = budget?.attribution ?? parseConnectAnswer(answer);
4834
+ const selection = parseConnectAnswer(answer);
4372
4835
  if (selection === void 0) return;
4373
4836
  const choice = deps.getPlan()?.choicesBySelection[selection];
4374
4837
  if (choice === void 0) {
4375
4838
  throw new AttributionPromptError("ATTRIBUTION_SELECTION_INVALID");
4376
4839
  }
4377
- if (choice.orgId !== void 0) {
4378
- deps.onOrgAnswered(choice.orgId);
4379
- }
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);
4840
+ const save = (attribution) => {
4841
+ if (!writeAttribution(deps.state, attribution)) {
4842
+ throw new GatewayCredentialError(
4843
+ "Route 33 could not save the workspace budget."
4844
+ );
4386
4845
  }
4387
- }
4388
- writeAttribution(deps.state, choice);
4846
+ };
4847
+ const acquire = async (existing) => {
4848
+ if (existing === void 0 || existing === "new") {
4849
+ const budget = parseBudgetAnswer(answer);
4850
+ if (budget && deps.mintWorkspaceKey) {
4851
+ try {
4852
+ await deps.mintWorkspaceKey(choice, budget.extras, () => {
4853
+ save(choice);
4854
+ });
4855
+ } catch (cause) {
4856
+ throw mapMintFailure(cause);
4857
+ }
4858
+ } else save(choice);
4859
+ return;
4860
+ }
4861
+ const runtime2 = deps.getRuntime?.();
4862
+ if (!runtime2 || typeof existing !== "string" || !existing)
4863
+ throw new AttributionPromptError("ATTRIBUTION_SELECTION_INVALID");
4864
+ const binding = await runtime2.workspaceKeyBinding();
4865
+ save(
4866
+ await binding.bind(
4867
+ choice,
4868
+ existing,
4869
+ answer["rotation_confirmation"] === existing
4870
+ )
4871
+ );
4872
+ };
4873
+ await acquire(answer[`existing_key:${selection}`] ?? answer["existing_key"]);
4874
+ if (choice.orgId !== void 0) deps.onOrgAnswered?.(choice.orgId);
4875
+ await deps.registerProjectForm?.().catch(() => void 0);
4389
4876
  };
4390
4877
 
4391
4878
  // src/v2-entry/connect-authorize/connect-authorize.ts
@@ -4413,6 +4900,10 @@ var createConnectAuthorize = (deps) => async (answer = {}) => {
4413
4900
  throw new GatewayCredentialError(CONNECT_COPY.signedInNextStep);
4414
4901
  }
4415
4902
  }
4903
+ const selection = parseConnectAnswer(answer);
4904
+ if (selection !== void 0 && await deps.prepareBudget?.(selection, answer) === true) {
4905
+ throw new GatewayCredentialError(CONNECT_COPY.budgetSelected);
4906
+ }
4416
4907
  await applyWizardAnswer(deps, answer);
4417
4908
  if (readAttribution(deps.state) === void 0) {
4418
4909
  throw new GatewayCredentialError(CONNECT_COPY.selectionInvalid);
@@ -4445,7 +4936,7 @@ var EXPIRY_OPTIONS = [
4445
4936
  { label: "180 days", value: "180" },
4446
4937
  { label: "1 year", value: "365" }
4447
4938
  ];
4448
- var buildConnectForm = (plan, modelIds = []) => {
4939
+ var buildConnectForm = (plan, modelIds) => {
4449
4940
  const orgs = plan.orgs ?? [];
4450
4941
  const organisationField = {
4451
4942
  key: ORGANISATION_FIELD_KEY,
@@ -4466,6 +4957,8 @@ var buildConnectForm = (plan, modelIds = []) => {
4466
4957
  title: "Which budget covers Route 33 usage in this folder?",
4467
4958
  type: "string"
4468
4959
  };
4960
+ const budgetFields = orgs.length > 1 ? [organisationField, attributionField] : [attributionField];
4961
+ if (modelIds === void 0) return budgetFields;
4469
4962
  const promptFields = [
4470
4963
  {
4471
4964
  key: BUDGET_NAME_FIELD_KEY,
@@ -4475,7 +4968,7 @@ var buildConnectForm = (plan, modelIds = []) => {
4475
4968
  },
4476
4969
  {
4477
4970
  key: BUDGET_CAP_FIELD_KEY,
4478
- placeholder: "blank = unlimited",
4971
+ placeholder: "e.g. 50; blank or unlimited = no cap",
4479
4972
  title: "Monthly budget cap in EUR",
4480
4973
  type: "string"
4481
4974
  },
@@ -4500,7 +4993,7 @@ var buildConnectForm = (plan, modelIds = []) => {
4500
4993
  type: "string"
4501
4994
  }
4502
4995
  ];
4503
- return orgs.length > 1 ? [organisationField, attributionField, ...promptFields] : [attributionField, ...promptFields];
4996
+ return [...budgetFields, ...promptFields];
4504
4997
  };
4505
4998
 
4506
4999
  // src/v2-entry/direct-key-mode/direct-key-mode.ts
@@ -4576,13 +5069,6 @@ var hostTokenStore = (options) => {
4576
5069
  };
4577
5070
  };
4578
5071
 
4579
- // src/v2-entry/mint-and-refresh/mint-and-refresh.ts
4580
- var mintAndRefresh = async (deps, attribution, extras) => {
4581
- const minted = await deps.mint(attribution, extras);
4582
- await deps.refresh().catch(() => void 0);
4583
- return minted;
4584
- };
4585
-
4586
5072
  // src/v2-entry/model-gate-notify-from/model-gate-notify-from.ts
4587
5073
  var notifyFrom = async (session, sessionID, message) => {
4588
5074
  await session.synthetic?.({ delivery: "queue", sessionID, text: message });
@@ -4646,12 +5132,14 @@ var gateFallback = async (deps, input, directory) => {
4646
5132
  };
4647
5133
 
4648
5134
  // src/v2-entry/v2-unattributed-model-gate/v2-unattributed-model-gate.ts
4649
- var GATE_COPY = "Route 33 needs a budget for this folder first \u2014 finish the setup dialog in the TUI, or run /connect, choose Route 33, and follow the steps.";
5135
+ var CONNECTION_COPY2 = "Not connected to Route 33. Run /connect, choose Route 33, and complete sign-in before assigning a budget in this folder.";
5136
+ var ATTRIBUTION_COPY2 = "This folder has no Route 33 budget assigned. Run /connect, choose Route 33, and complete the budget setup form.";
4650
5137
  var createV2UnattributedModelGate = (deps) => async (input) => {
4651
5138
  if (input.model.providerID !== "route_33") return;
5139
+ if (!await deps.isConnected()) throw new Error(CONNECTION_COPY2);
4652
5140
  const state = await gateDirectory(deps, input.sessionID);
4653
5141
  if (readAttribution(state) === void 0) {
4654
- throw new Error(GATE_COPY);
5142
+ throw new Error(ATTRIBUTION_COPY2);
4655
5143
  }
4656
5144
  await gateFallback(deps, input, state.directory);
4657
5145
  };
@@ -4660,6 +5148,16 @@ var createV2UnattributedModelGate = (deps) => async (input) => {
4660
5148
  var registerRoute33ModelGate = async (deps) => deps.session.hook(
4661
5149
  "model.request",
4662
5150
  createV2UnattributedModelGate({
5151
+ isConnected: async () => {
5152
+ const runtime2 = deps.getRuntime();
5153
+ if (runtime2 === void 0) return false;
5154
+ try {
5155
+ await runtime2.login({ allowBrowser: false });
5156
+ return true;
5157
+ } catch {
5158
+ return false;
5159
+ }
5160
+ },
4663
5161
  allowedModels: (directory) => {
4664
5162
  const runtime2 = deps.getRuntime();
4665
5163
  return runtime2 === void 0 ? Promise.resolve(void 0) : runtime2.workspaceKeyAllowance(directory).then((allowance) => allowance?.allowedModels);
@@ -4695,6 +5193,59 @@ var resolveHostCredential = async (deps) => {
4695
5193
  };
4696
5194
  };
4697
5195
 
5196
+ // src/v2-entry/binding-fields/binding-fields.ts
5197
+ var bindingFields = async (plan, binding) => {
5198
+ const confirmations = /* @__PURE__ */ new Map();
5199
+ const fields = [];
5200
+ for (const [selection, choice] of Object.entries(plan.choicesBySelection)) {
5201
+ const keys = await binding.candidates(choice).catch(() => []);
5202
+ if (!keys.length) continue;
5203
+ for (const key of keys) if (!key.local) confirmations.set(key.id, key.name);
5204
+ fields.push({
5205
+ key: `existing_key:${selection}`,
5206
+ type: "string",
5207
+ title: "Which key should this folder use?",
5208
+ options: [
5209
+ { label: "Mint a new key", value: "new" },
5210
+ ...keys.map((key) => ({
5211
+ label: `Bind ${key.name} (${key.id})`,
5212
+ value: key.id
5213
+ }))
5214
+ ]
5215
+ });
5216
+ }
5217
+ if (confirmations.size)
5218
+ fields.push({
5219
+ key: "rotation_confirmation",
5220
+ type: "string",
5221
+ title: ROTATION_WARNING,
5222
+ options: [
5223
+ { label: "No", value: "no" },
5224
+ ...Array.from(confirmations, ([id, name]) => ({
5225
+ label: `Yes, rotate ${name} (${id})`,
5226
+ value: id
5227
+ }))
5228
+ ]
5229
+ });
5230
+ return fields;
5231
+ };
5232
+
5233
+ // src/v2-entry/selected-budget-form/selected-budget-form.ts
5234
+ var selectedBudgetForm = async (plan, selection, runtime2) => {
5235
+ const option = plan.options.find((row) => row.selection === selection);
5236
+ const choice = plan.choicesBySelection[selection];
5237
+ if (!option || !choice)
5238
+ throw new GatewayCredentialError(CONNECT_COPY.selectionInvalid);
5239
+ const scoped = {
5240
+ title: plan.title,
5241
+ options: [option],
5242
+ choicesBySelection: { [selection]: choice }
5243
+ };
5244
+ const ids = await runtime2.catalogModelIds(choice).catch(() => []);
5245
+ const keys = await bindingFields(scoped, await runtime2.workspaceKeyBinding());
5246
+ return [...buildConnectForm(scoped, ids), ...keys];
5247
+ };
5248
+
4698
5249
  // src/v2-entry/workspace-key-request-hook/workspace-key-request-hook.ts
4699
5250
  var createWorkspaceKeyHook = (deps) => async (input) => {
4700
5251
  const target = new URL(input.request.url);
@@ -4729,6 +5280,7 @@ var createRoute33V2Plugin = (options = {}) => {
4729
5280
  outsideWorktree: "return-undefined"
4730
5281
  };
4731
5282
  const installation = createLeaseInstallationFactory({
5283
+ listScopes: () => HostStorageSecretStore.scopes(context.storage),
4732
5284
  createSecretStore: (scopeId) => new HostStorageSecretStore({
4733
5285
  key: `route33_lease_${scopeId}`,
4734
5286
  storage: context.storage
@@ -4742,7 +5294,7 @@ var createRoute33V2Plugin = (options = {}) => {
4742
5294
  let provider = mapRoute33V2Provider(void 0);
4743
5295
  let connectFields;
4744
5296
  let plan;
4745
- let selectedOrgId;
5297
+ let preparedBudget;
4746
5298
  const runtimeInput = {
4747
5299
  ...options.runtime ?? buildProductionRuntimeOptions({
4748
5300
  apiBaseUrl,
@@ -4777,32 +5329,23 @@ var createRoute33V2Plugin = (options = {}) => {
4777
5329
  });
4778
5330
  const registerProjectForm = async () => {
4779
5331
  const activeRuntime = runtime2;
4780
- if (activeRuntime === void 0) {
4781
- return;
4782
- }
4783
- const [mintableOrgs, modelIds, personalKeyActive] = await Promise.all([
5332
+ if (activeRuntime === void 0) return;
5333
+ const [mintableOrgs, personalKeyActive] = await Promise.all([
4784
5334
  activeRuntime.listMintableOrgs({ allowBrowser: false }).catch(() => void 0),
4785
- activeRuntime.catalogModelIds().catch(() => []),
4786
5335
  activeRuntime.hasPersonalLease().catch(() => false)
4787
5336
  ]);
5337
+ preparedBudget = void 0;
4788
5338
  if (mintableOrgs === void 0) {
4789
5339
  plan = void 0;
4790
5340
  connectFields = void 0;
4791
5341
  await context.integration.reload();
4792
5342
  return;
4793
5343
  }
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
5344
  plan = createAttributionPrompt(
4802
5345
  mintableOrgs.flatMap(({ projects }) => projects),
4803
- { personalKeyActive, orgs }
5346
+ { personalKeyActive, orgs: mintableOrgs }
4804
5347
  );
4805
- connectFields = buildConnectForm(plan, modelIds);
5348
+ connectFields = buildConnectForm(plan);
4806
5349
  await context.integration.reload();
4807
5350
  };
4808
5351
  const authorize = createConnectAuthorize({
@@ -4810,7 +5353,7 @@ var createRoute33V2Plugin = (options = {}) => {
4810
5353
  directory: context.location.directory,
4811
5354
  getPlan: () => plan,
4812
5355
  getRuntime: () => runtime2,
4813
- mintWorkspaceKey: (attribution, extras) => {
5356
+ mintWorkspaceKey: (attribution, extras, save) => {
4814
5357
  const active = runtime2;
4815
5358
  if (active === void 0) {
4816
5359
  return Promise.reject(
@@ -4819,17 +5362,19 @@ var createRoute33V2Plugin = (options = {}) => {
4819
5362
  )
4820
5363
  );
4821
5364
  }
4822
- return mintAndRefresh(
4823
- {
4824
- mint: (choice, extras2) => active.mintWorkspaceKey(choice, extras2),
4825
- refresh: registerProjectForm
4826
- },
4827
- attribution,
4828
- extras
4829
- );
5365
+ return active.mintWorkspaceKey(attribution, extras, void 0, save);
4830
5366
  },
4831
- onOrgAnswered: (orgId) => {
4832
- selectedOrgId = orgId;
5367
+ prepareBudget: async (selection, answer) => {
5368
+ if (preparedBudget === selection && connectFields?.some(
5369
+ (field) => field.key !== "attribution" && Object.hasOwn(answer, field.key)
5370
+ ) === true)
5371
+ return false;
5372
+ if (!runtime2 || !plan)
5373
+ throw new GatewayCredentialError(CONNECT_COPY.selectionInvalid);
5374
+ connectFields = await selectedBudgetForm(plan, selection, runtime2);
5375
+ preparedBudget = selection;
5376
+ await context.integration.reload();
5377
+ return true;
4833
5378
  },
4834
5379
  registerProjectForm,
4835
5380
  resolveCredential,