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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
 
@@ -1845,9 +2148,11 @@ var KeyLeaseError = class extends Error {
1845
2148
  );
1846
2149
  this.code = code;
1847
2150
  this.name = "KeyLeaseError";
2151
+ this.rejection = options?.rejection;
1848
2152
  this.statusCode = options?.statusCode;
1849
2153
  }
1850
2154
  code;
2155
+ rejection;
1851
2156
  statusCode;
1852
2157
  };
1853
2158
 
@@ -1998,9 +2303,62 @@ var buildMintInput = (deps) => {
1998
2303
  };
1999
2304
  };
2000
2305
 
2306
+ // src/key-lease/commit-staged-replacement/commit-staged-replacement.ts
2307
+ var commitStagedReplacement = async (stage, save, persist) => {
2308
+ const storeFailure = (cause) => {
2309
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
2310
+ };
2311
+ const staged = await stage().catch(storeFailure);
2312
+ try {
2313
+ save();
2314
+ await (staged ? staged.commit() : persist()).catch(storeFailure);
2315
+ } finally {
2316
+ await staged?.discard();
2317
+ }
2318
+ };
2319
+
2320
+ // src/management/management-error/management-error.ts
2321
+ var ManagementError = class extends Error {
2322
+ constructor(code, options) {
2323
+ super(
2324
+ "Route 33 management request failed",
2325
+ options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
2326
+ );
2327
+ this.code = code;
2328
+ this.name = "ManagementError";
2329
+ this.rejection = options?.rejection;
2330
+ this.statusCode = options?.statusCode;
2331
+ }
2332
+ code;
2333
+ rejection;
2334
+ statusCode;
2335
+ };
2336
+
2337
+ // src/key-lease/mint-failure/mint-failure.ts
2338
+ var mintFailure = (cause) => {
2339
+ const response = cause instanceof ManagementError ? cause : void 0;
2340
+ return new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
2341
+ cause,
2342
+ ...response?.rejection === void 0 ? {} : { rejection: response.rejection },
2343
+ ...response?.statusCode === void 0 ? {} : { statusCode: response.statusCode }
2344
+ });
2345
+ };
2346
+
2001
2347
  // src/key-lease/mint-fresh-lease/mint-fresh-lease.ts
2002
2348
  var mintFreshLease = async (deps) => {
2003
2349
  const now = deps.clock();
2350
+ const current = deps.state.snapshot();
2351
+ const reusable = () => {
2352
+ if (deps.wizardRequest !== void 0 && current?.wizardRequest === deps.wizardRequest && deps.storedKey !== void 0 && Date.parse(current.expiresAt) > now) {
2353
+ return { key: deps.storedKey, lease: current };
2354
+ }
2355
+ return void 0;
2356
+ };
2357
+ const reused = reusable();
2358
+ if (reused !== void 0) {
2359
+ deps.saveAttribution?.();
2360
+ return reused;
2361
+ }
2004
2362
  const input = buildMintInput({
2005
2363
  attribution: deps.attribution,
2006
2364
  extras: deps.extras,
@@ -2016,20 +2374,30 @@ var mintFreshLease = async (deps) => {
2016
2374
  input
2017
2375
  );
2018
2376
  } catch (cause) {
2019
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", { cause });
2377
+ throw mintFailure(cause);
2020
2378
  }
2021
2379
  const minted = {
2022
2380
  key: material.key,
2023
2381
  lease: {
2024
2382
  attribution: deps.attribution,
2025
2383
  expiresAt: material.expires_at,
2026
- keyId: material.id
2384
+ keyId: material.id,
2385
+ ...deps.wizardRequest === void 0 ? {} : { wizardRequest: deps.wizardRequest }
2027
2386
  }
2028
2387
  };
2029
- try {
2030
- await deps.secretStore.set(minted.key);
2031
- } catch (cause) {
2388
+ const storeFailure = (cause) => {
2032
2389
  throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
2390
+ };
2391
+ const persist = () => deps.secretStore.set(minted.key, minted.lease);
2392
+ if (deps.saveAttribution && deps.storedKey !== void 0) {
2393
+ await commitStagedReplacement(
2394
+ () => deps.secretStore.stage?.(minted.key, minted.lease) ?? Promise.resolve(void 0),
2395
+ deps.saveAttribution,
2396
+ persist
2397
+ );
2398
+ } else {
2399
+ await persist().catch(storeFailure);
2400
+ deps.saveAttribution?.();
2033
2401
  }
2034
2402
  deps.state.compareAndSwap(deps.state.snapshot(), minted.lease);
2035
2403
  return minted;
@@ -2089,21 +2457,6 @@ var rejectLease = async (options) => {
2089
2457
  }
2090
2458
  };
2091
2459
 
2092
- // src/management/management-error/management-error.ts
2093
- var ManagementError = class extends Error {
2094
- constructor(code, options) {
2095
- super(
2096
- "Route 33 management request failed",
2097
- options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
2098
- );
2099
- this.code = code;
2100
- this.name = "ManagementError";
2101
- this.statusCode = options?.statusCode;
2102
- }
2103
- code;
2104
- statusCode;
2105
- };
2106
-
2107
2460
  // src/key-lease/mint-key/mint-key.ts
2108
2461
  var mintKey = async (options) => {
2109
2462
  const now = options.clock();
@@ -2137,10 +2490,7 @@ var mintKey = async (options) => {
2137
2490
  if (isManagementUnauthorized(cause)) {
2138
2491
  throw new KeyLeaseError("KEY_LEASE_UNAUTHORIZED", { cause });
2139
2492
  }
2140
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
2141
- cause,
2142
- ...cause instanceof ManagementError && cause.statusCode !== void 0 ? { statusCode: cause.statusCode } : {}
2143
- });
2493
+ throw mintFailure(cause);
2144
2494
  }
2145
2495
  return {
2146
2496
  key: material.key,
@@ -2206,7 +2556,7 @@ var renewKey = async (options) => {
2206
2556
  }
2207
2557
  }
2208
2558
  try {
2209
- await options.secretStore.set(renewed.key);
2559
+ await options.secretStore.set(renewed.key, renewed.lease);
2210
2560
  } catch (cause) {
2211
2561
  const cleared = await discard(renewed.lease.keyId);
2212
2562
  if (!cleared) {
@@ -2286,315 +2636,104 @@ var reusableLease = (options) => {
2286
2636
  return { key: options.storedKey, lease: options.current };
2287
2637
  };
2288
2638
 
2289
- // src/key-lease/lease-for-attribution/lease-for-attribution.ts
2290
- var leaseForAttribution = async (options) => {
2291
- const policy = resolveLeasePolicy(options.policy);
2292
- const clock = options.clock ?? Date.now;
2293
- const now = clock();
2294
- if (!Number.isFinite(now)) {
2295
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2296
- }
2297
- const { current, storedKey } = await currentLeaseState({
2298
- attribution: options.attribution,
2299
- credential: await resolveSeamValue(options.management.credential),
2300
- keyName: options.installation.keyName,
2301
- managementClient: options.management.client,
2302
- secretStore: options.installation.secretStore,
2303
- state: options.installation.state,
2304
- stateStore: options.installation.stateStore
2305
- });
2306
- if (options.rejection !== void 0) {
2307
- return rejectLease({
2308
- current,
2309
- rejection: options.rejection,
2310
- secretStore: options.installation.secretStore,
2311
- state: options.installation.state,
2312
- storedKey
2313
- });
2314
- }
2315
- if (options.request?.forceMint === true) {
2316
- return mintFreshLease({
2317
- attribution: options.attribution,
2318
- clock,
2319
- extras: options.request.extras,
2320
- keyName: options.installation.keyName,
2321
- managementClient: options.management.client,
2322
- managementCredential: await resolveSeamValue(
2323
- options.management.credential
2324
- ),
2325
- managementSubject: await resolveSeamValue(options.management.subject),
2326
- secretStore: options.installation.secretStore,
2327
- state: options.installation.state,
2328
- stateStore: options.installation.stateStore,
2329
- ttlMs: policy.ttlMs
2330
- });
2331
- }
2332
- const reusable = reusableLease({
2333
- attribution: options.attribution,
2334
- current,
2335
- now,
2336
- policy,
2337
- state: options.installation.state,
2338
- storedKey
2339
- });
2340
- if (reusable !== void 0) {
2341
- return reusable;
2342
- }
2343
- try {
2344
- const renewed = await renewKey({
2345
- leaseState: options.installation.state,
2346
- mint: {
2347
- attribution: options.attribution,
2348
- clock,
2349
- identity: {
2350
- credential: await resolveSeamValue(options.management.credential),
2351
- subject: await resolveSeamValue(options.management.subject)
2352
- },
2353
- installation: {
2354
- keyName: options.installation.keyName,
2355
- ttlMs: policy.ttlMs
2356
- },
2357
- managementClient: options.management.client
2358
- },
2359
- secretStore: options.installation.secretStore
2360
- });
2361
- if (policy.orphanRetentionCycles !== void 0) {
2362
- await controlOrphans({
2363
- clock,
2364
- currentKeyId: renewed.lease.keyId,
2365
- keyName: options.installation.keyName,
2366
- managementClient: options.management.client,
2367
- managementCredential: await resolveSeamValue(
2368
- options.management.credential
2369
- ),
2370
- retentionCycles: policy.orphanRetentionCycles,
2371
- ttlMs: policy.ttlMs
2372
- });
2373
- }
2374
- 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;
2639
+ // src/key-lease/lease-for-attribution/lease-for-attribution.ts
2640
+ var leaseForAttribution = async (options) => {
2641
+ const policy = resolveLeasePolicy(options.policy);
2642
+ const clock = options.clock ?? Date.now;
2643
+ const now = clock();
2644
+ if (!Number.isFinite(now)) {
2645
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
2514
2646
  }
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
2647
+ const { current, storedKey } = await currentLeaseState({
2648
+ attribution: options.attribution,
2649
+ credential: await resolveSeamValue(options.management.credential),
2650
+ keyName: options.installation.keyName,
2651
+ managementClient: options.management.client,
2652
+ secretStore: options.installation.secretStore,
2653
+ state: options.installation.state,
2654
+ stateStore: options.installation.stateStore
2655
+ });
2656
+ if (options.rejection !== void 0) {
2657
+ return rejectLease({
2658
+ current,
2659
+ rejection: options.rejection,
2660
+ secretStore: options.installation.secretStore,
2661
+ state: options.installation.state,
2662
+ storedKey
2541
2663
  });
2542
2664
  }
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
- }
2665
+ if (options.request?.forceMint === true) {
2666
+ return mintFreshLease({
2667
+ attribution: options.attribution,
2668
+ clock,
2669
+ extras: options.request.extras,
2670
+ keyName: options.installation.keyName,
2671
+ managementClient: options.management.client,
2672
+ managementCredential: await resolveSeamValue(
2673
+ options.management.credential
2674
+ ),
2675
+ managementSubject: await resolveSeamValue(options.management.subject),
2676
+ secretStore: options.installation.secretStore,
2677
+ state: options.installation.state,
2678
+ stateStore: options.installation.stateStore,
2679
+ ttlMs: policy.ttlMs,
2680
+ wizardRequest: options.request.wizardRequest,
2681
+ saveAttribution: options.request.saveAttribution,
2682
+ storedKey
2683
+ });
2565
2684
  }
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;
2685
+ const reusable = reusableLease({
2686
+ attribution: options.attribution,
2687
+ current,
2688
+ now,
2689
+ policy,
2690
+ state: options.installation.state,
2691
+ storedKey
2692
+ });
2693
+ if (reusable !== void 0) {
2694
+ return reusable;
2577
2695
  }
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;
2696
+ try {
2697
+ const renewed = await renewKey({
2698
+ leaseState: options.installation.state,
2699
+ mint: {
2700
+ attribution: options.attribution,
2701
+ clock,
2702
+ identity: {
2703
+ credential: await resolveSeamValue(options.management.credential),
2704
+ subject: await resolveSeamValue(options.management.subject)
2705
+ },
2706
+ installation: {
2707
+ keyName: options.installation.keyName,
2708
+ ttlMs: policy.ttlMs
2709
+ },
2710
+ managementClient: options.management.client
2711
+ },
2712
+ secretStore: options.installation.secretStore
2713
+ });
2714
+ if (policy.orphanRetentionCycles !== void 0) {
2715
+ await controlOrphans({
2716
+ clock,
2717
+ currentKeyId: renewed.lease.keyId,
2718
+ keyName: options.installation.keyName,
2719
+ managementClient: options.management.client,
2720
+ managementCredential: await resolveSeamValue(
2721
+ options.management.credential
2722
+ ),
2723
+ retentionCycles: policy.orphanRetentionCycles,
2724
+ ttlMs: policy.ttlMs
2725
+ });
2585
2726
  }
2586
- this.#current = void 0;
2587
- return true;
2588
- }
2589
- static #unexpectedAttribution(value) {
2590
- throw new TypeError(`Unexpected attribution: ${String(value)}`);
2727
+ return renewed;
2728
+ } catch (cause) {
2729
+ return mapRenewalFailure({ cause, current, now });
2591
2730
  }
2592
2731
  };
2593
2732
 
2594
2733
  // src/key-lease/lease-installation-factory/lease-installation-factory.ts
2595
2734
  var createLeaseInstallationFactory = (options) => {
2596
2735
  const installations = /* @__PURE__ */ new Map();
2597
- return (scopeId) => {
2736
+ const open = (scopeId) => {
2598
2737
  const existing = installations.get(scopeId);
2599
2738
  if (existing !== void 0) {
2600
2739
  return existing;
@@ -2608,6 +2747,14 @@ var createLeaseInstallationFactory = (options) => {
2608
2747
  installations.set(scopeId, installation);
2609
2748
  return installation;
2610
2749
  };
2750
+ return Object.assign(open, {
2751
+ scopes: async () => [
2752
+ .../* @__PURE__ */ new Set([
2753
+ ...installations.keys(),
2754
+ ...await options.listScopes?.() ?? []
2755
+ ])
2756
+ ]
2757
+ });
2611
2758
  };
2612
2759
 
2613
2760
  // src/key-lease/scope-id/scope-id.ts
@@ -2634,12 +2781,29 @@ var deriveScopeId = (input) => {
2634
2781
  throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
2635
2782
  }
2636
2783
  }
2784
+ if (input.attribution.boundKeyId !== void 0) {
2785
+ if (input.folderRealpath === void 0)
2786
+ throw new TypeError("Bound keys require a worktree");
2787
+ if (input.attribution.boundScopeId !== void 0)
2788
+ return input.attribution.boundScopeId;
2789
+ identity = [
2790
+ ...identity,
2791
+ "binding",
2792
+ input.folderRealpath,
2793
+ input.attribution.orgId ?? "",
2794
+ input.attribution.boundKeyId
2795
+ ];
2796
+ }
2637
2797
  return createHash2("sha256").update(JSON.stringify(identity)).digest("hex");
2638
2798
  };
2639
2799
 
2640
2800
  // src/requested-client-id/requested-client-id.ts
2641
2801
  var DEFAULT_ROUTE33_CLIENT_ID = false ? "" : "oa_platform_203623de";
2642
2802
 
2803
+ // src/route33-runtime/route33-runtime.ts
2804
+ import { createHash as createHash3 } from "node:crypto";
2805
+ import { statSync as statSync2 } from "node:fs";
2806
+
2643
2807
  // src/catalog/gateway-model-ids/gateway-model-ids.ts
2644
2808
  var gatewayModelIds = async (deps) => {
2645
2809
  const { baseURL, gatewayKey, ...rest } = deps;
@@ -2653,8 +2817,9 @@ var gatewayModelIds = async (deps) => {
2653
2817
 
2654
2818
  // src/commands/change-attribution/change-attribution.ts
2655
2819
  var changeAttribution = async (options) => {
2656
- await options.clear();
2657
- return options.prompt();
2820
+ const choice = await options.prompt();
2821
+ await options.commit(choice);
2822
+ return choice;
2658
2823
  };
2659
2824
 
2660
2825
  // src/commands/inspect-session/inspect-session.ts
@@ -2663,6 +2828,7 @@ var inspectSession = (options) => {
2663
2828
  const lease = options.readLease();
2664
2829
  return {
2665
2830
  attribution,
2831
+ connected: options.connected,
2666
2832
  ...lease === void 0 ? {} : { lease: { expiresAt: lease.expiresAt, keyId: lease.keyId } }
2667
2833
  };
2668
2834
  };
@@ -2678,6 +2844,124 @@ var rotateNow = async (options) => {
2678
2844
  return rotated.lease;
2679
2845
  };
2680
2846
 
2847
+ // src/key-lease/workspace-key-binding/workspace-key-binding.ts
2848
+ import { mkdir as mkdir2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
2849
+ import { dirname as dirname4 } from "node:path";
2850
+ var ROTATION_WARNING = "This key will be rotated. Existing consumers will break. Continue?";
2851
+ var pending = /* @__PURE__ */ new Map();
2852
+ var WorkspaceKeyBinding = class {
2853
+ constructor(deps) {
2854
+ this.deps = deps;
2855
+ }
2856
+ deps;
2857
+ #listings = /* @__PURE__ */ new Map();
2858
+ /** @param choice - The budget selected by the user.
2859
+ * @returns Secret-free options; local options do not need destructive consent.
2860
+ */
2861
+ async candidates(choice) {
2862
+ const listing = this.#listings.get(choice.orgId) ?? this.listKeys(choice.orgId);
2863
+ this.#listings.set(choice.orgId, listing);
2864
+ const rows = await listing;
2865
+ const keys = rows.filter((row) => this.matches(row, choice));
2866
+ if (keys.length === 0) return [];
2867
+ const local = await this.localKeys(new Set(keys.map((row) => row.id)));
2868
+ return keys.map((row) => ({
2869
+ id: row.id,
2870
+ name: row.name,
2871
+ local: local.has(row.id)
2872
+ }));
2873
+ }
2874
+ async listKeys(orgId) {
2875
+ try {
2876
+ return (await this.deps.client.list(this.deps.token, orgId)).data;
2877
+ } catch {
2878
+ logger.warn(
2879
+ "Existing keys could not be listed; only new keys can be offered."
2880
+ );
2881
+ return [];
2882
+ }
2883
+ }
2884
+ matches(row, choice) {
2885
+ return row.status === "active" && !row.revoked && Date.parse(row.expires_at) > this.deps.now && (choice.orgId === void 0 || row.org_id === choice.orgId) && row.user_id === this.deps.subject && (choice.kind === "project" ? row.project_id === choice.projectId && row.ownership_type === "user_project" : row.project_id === null && row.ownership_type === "user_personal");
2886
+ }
2887
+ async localKeys(ids) {
2888
+ const found = /* @__PURE__ */ new Map();
2889
+ for (const scope of await this.deps.installations.scopes?.() ?? []) {
2890
+ const store = this.deps.installations(scope);
2891
+ const lease = await this.metadata(store);
2892
+ if (!lease || !ids.has(lease.keyId) || Date.parse(lease.expiresAt) <= this.deps.now)
2893
+ continue;
2894
+ const key = await store.secretStore.get();
2895
+ if (key && (await this.metadata(store))?.keyId === lease.keyId)
2896
+ found.set(lease.keyId, scope);
2897
+ }
2898
+ return found;
2899
+ }
2900
+ async metadata(store) {
2901
+ return await store.secretStore.getLease?.() ?? await store.stateStore?.get() ?? store.state.snapshot();
2902
+ }
2903
+ /** @param choice - Selected attribution; the live key must still belong to it.
2904
+ * @param id - Selected management key id, never its secret.
2905
+ * @param confirmed - Explicit consent to rotate this id if plaintext is unavailable.
2906
+ * @returns The attribution to commit after saving the secret.
2907
+ */
2908
+ async bind(choice, id, confirmed) {
2909
+ const row = await this.deps.client.get(this.deps.token, id, choice.orgId);
2910
+ if (row.id !== id || !this.matches(row, choice))
2911
+ throw new GatewayCredentialError(
2912
+ "This key is not available for the selected budget."
2913
+ );
2914
+ const file = resolveAttributionFile(this.deps.state);
2915
+ if (file === void 0)
2916
+ throw new GatewayCredentialError("Key binding requires a worktree.");
2917
+ const bound = { ...choice, boundKeyId: id };
2918
+ const scope = deriveScopeId({
2919
+ attribution: bound,
2920
+ folderRealpath: detectWorktreeRoot(this.deps.state.directory)
2921
+ });
2922
+ const marker = `${file}.${scope}.rotation`;
2923
+ const retry = pending.get(marker);
2924
+ const localScope = retry === void 0 ? (await this.localKeys(/* @__PURE__ */ new Set([id]))).get(id) : void 0;
2925
+ if (localScope !== void 0) return { ...bound, boundScopeId: localScope };
2926
+ const target = this.deps.installations(scope);
2927
+ const { key, lease } = retry ?? await this.rotate(bound, marker, confirmed);
2928
+ await target.secretStore.set(key, lease);
2929
+ await target.stateStore?.set(lease);
2930
+ target.state.compareAndSwap(target.state.snapshot(), lease);
2931
+ await rm2(marker, { force: true });
2932
+ pending.delete(marker);
2933
+ return bound;
2934
+ }
2935
+ async rotate(bound, marker, confirmed) {
2936
+ if (!confirmed) throw new GatewayCredentialError(ROTATION_WARNING);
2937
+ const id = bound.boundKeyId;
2938
+ await mkdir2(dirname4(marker), { recursive: true });
2939
+ try {
2940
+ await writeFile2(marker, "pending\n", { flag: "wx", mode: 384 });
2941
+ } catch (cause) {
2942
+ if (cause instanceof Error && "code" in cause && cause.code === "EEXIST")
2943
+ throw new GatewayCredentialError(
2944
+ "Rotation is already pending. Retry saving in the original session or choose a new key."
2945
+ );
2946
+ throw cause;
2947
+ }
2948
+ const rotated = await this.deps.client.regenerate(
2949
+ this.deps.token,
2950
+ id,
2951
+ void 0,
2952
+ bound.orgId
2953
+ );
2954
+ if (rotated.id !== id)
2955
+ throw new GatewayCredentialError("Rotation returned a different key.");
2956
+ const material = {
2957
+ key: rotated.key,
2958
+ lease: { attribution: bound, expiresAt: rotated.expires_at, keyId: id }
2959
+ };
2960
+ pending.set(marker, material);
2961
+ return material;
2962
+ }
2963
+ };
2964
+
2681
2965
  // src/ux/attribution-prompt/org-selection-prefix/org-selection-prefix.ts
2682
2966
  var orgSelectionPrefix = (orgId) => `org:${orgId}:`;
2683
2967
 
@@ -2697,6 +2981,8 @@ var createAttributionPrompt = (projects, options = {}) => {
2697
2981
  return `Personal \u2014 your own key${marker}${orgSuffix}`;
2698
2982
  };
2699
2983
  const budgetAllowance = (project) => {
2984
+ if (project.memberCap !== void 0)
2985
+ return `cap ${String(project.memberCap)} EUR`;
2700
2986
  const budget = project.effective_budget ?? project.max_budget;
2701
2987
  return budget === null ? "no cap set" : `cap ${budget.amount} ${budget.currency}`;
2702
2988
  };
@@ -2711,6 +2997,7 @@ var createAttributionPrompt = (projects, options = {}) => {
2711
2997
  };
2712
2998
  return {
2713
2999
  label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${budgetAllowance(project)}`,
3000
+ maximum: project.memberCap,
2714
3001
  selection
2715
3002
  };
2716
3003
  });
@@ -2730,6 +3017,7 @@ var createAttributionPrompt = (projects, options = {}) => {
2730
3017
  choicesBySelection[personal] = { kind: "personal", orgId: org.id };
2731
3018
  promptOptions.push({
2732
3019
  label: personalLabel(options.orgs.length > 1 ? org.name : void 0),
3020
+ maximum: org.personalBudget?.cap ?? void 0,
2733
3021
  selection: personal
2734
3022
  });
2735
3023
  }
@@ -2745,6 +3033,7 @@ var createAttributionPrompt = (projects, options = {}) => {
2745
3033
  };
2746
3034
  promptOptions.push({
2747
3035
  label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${budgetAllowance(project)}`,
3036
+ maximum: project.memberCap,
2748
3037
  selection
2749
3038
  });
2750
3039
  }
@@ -2759,8 +3048,9 @@ var createAttributionPrompt = (projects, options = {}) => {
2759
3048
 
2760
3049
  // src/ux/attribution-prompt-error/attribution-prompt-error.ts
2761
3050
  var MESSAGES = {
2762
- 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
- ATTRIBUTION_SELECTION_INVALID: "That Route 33 option is no longer available. Connect again and pick another."
3051
+ ATTRIBUTION_BACK: "Left budget selection without changing attribution.",
3052
+ ATTRIBUTION_PRESENTER_UNAVAILABLE: "Update to OpenCode v2 to assign a Route 33 budget in this folder.",
3053
+ ATTRIBUTION_SELECTION_INVALID: "That Route 33 option is no longer available; choose another budget."
2764
3054
  };
2765
3055
  var AttributionPromptError = class extends GatewayCredentialError {
2766
3056
  code;
@@ -2772,8 +3062,9 @@ var AttributionPromptError = class extends GatewayCredentialError {
2772
3062
  };
2773
3063
 
2774
3064
  // src/ux/prompt-flow/prompt-flow.ts
3065
+ var BACK_SELECTION = "/back";
2775
3066
  var resolveAttribution = async (options) => {
2776
- const remembered = readAttribution(options.state);
3067
+ const remembered = options.state && readAttribution(options.state);
2777
3068
  if (remembered !== void 0) {
2778
3069
  return remembered;
2779
3070
  }
@@ -2781,12 +3072,16 @@ var resolveAttribution = async (options) => {
2781
3072
  throw new AttributionPromptError("ATTRIBUTION_PRESENTER_UNAVAILABLE");
2782
3073
  }
2783
3074
  const plan = createAttributionPrompt(await options.loadProjects());
2784
- const selection = await options.presenter.pick(plan);
3075
+ const selection = await options.presenter.pick({
3076
+ ...plan,
3077
+ options: [...plan.options, { label: "Back", selection: BACK_SELECTION }]
3078
+ });
3079
+ if (selection === BACK_SELECTION)
3080
+ throw new AttributionPromptError("ATTRIBUTION_BACK");
2785
3081
  const attribution = plan.choicesBySelection[selection];
2786
3082
  if (attribution === void 0) {
2787
3083
  throw new AttributionPromptError("ATTRIBUTION_SELECTION_INVALID");
2788
3084
  }
2789
- writeAttribution(options.state, attribution);
2790
3085
  return attribution;
2791
3086
  };
2792
3087
 
@@ -2804,6 +3099,66 @@ var CALLBACK_PAGE_COPY = {
2804
3099
  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
3100
  };
2806
3101
 
3102
+ // src/route33-runtime/enrich-inspection/enrich-inspection.ts
3103
+ var enrichInspection = async ({
3104
+ attribution,
3105
+ client,
3106
+ credential,
3107
+ keyId,
3108
+ subject
3109
+ }) => {
3110
+ const key = await client.get(credential, keyId);
3111
+ const orgId = key.org_id;
3112
+ if (attribution.orgId !== void 0 && attribution.orgId !== orgId) {
3113
+ return {};
3114
+ }
3115
+ const keyDetails = {
3116
+ name: key.name,
3117
+ organisationName: null,
3118
+ projectName: null
3119
+ };
3120
+ switch (attribution.kind) {
3121
+ case "personal": {
3122
+ if (key.project_id !== null) {
3123
+ return {};
3124
+ }
3125
+ return client.listBudgetPolicy(credential, subject(), orgId).then(
3126
+ ({ cap }) => cap === null ? { key: keyDetails } : {
3127
+ key: keyDetails,
3128
+ budget: { amount: String(cap), currency: null }
3129
+ }
3130
+ ).catch(() => ({ key: keyDetails }));
3131
+ }
3132
+ case "project": {
3133
+ const { projectId } = attribution;
3134
+ if (key.project_id !== projectId) {
3135
+ return {};
3136
+ }
3137
+ return Promise.all([
3138
+ client.listProjects(credential, orgId).then(
3139
+ ({ data }) => data.find(({ id, org_id }) => id === projectId && org_id === orgId)
3140
+ ).catch(() => void 0),
3141
+ client.listOrganizations(credential).then(({ data }) => data.find(({ id }) => id === orgId)?.name ?? null).catch(() => null)
3142
+ ]).then(([project, organisationName]) => {
3143
+ const title = project?.name.trim() ?? "";
3144
+ const budget = project?.effective_budget ?? project?.max_budget;
3145
+ return {
3146
+ key: {
3147
+ ...keyDetails,
3148
+ organisationName,
3149
+ projectName: title === "" ? null : title
3150
+ },
3151
+ ...budget == null ? {} : { budget }
3152
+ };
3153
+ });
3154
+ }
3155
+ default: {
3156
+ const unexpected = attribution;
3157
+ throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
3158
+ }
3159
+ }
3160
+ };
3161
+
2807
3162
  // src/route33-runtime/login-session/login-session.ts
2808
3163
  import { AuthError as AuthError2 } from "@r-33/auth-browser";
2809
3164
 
@@ -2814,7 +3169,7 @@ import {
2814
3169
  } from "@r-33/auth-browser";
2815
3170
 
2816
3171
  // src/requested-scopes/requested-scopes.ts
2817
- var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read profile projects:read users:read keys:read keys:write";
3172
+ var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read profile projects:read users:read keys:read keys:write models:read";
2818
3173
 
2819
3174
  // src/route33-login/route33-login.ts
2820
3175
  var route33Login = async (options) => {
@@ -2843,20 +3198,34 @@ var LoginSession = class {
2843
3198
  #options;
2844
3199
  #result;
2845
3200
  #expiresAt;
3201
+ #clears = 0;
2846
3202
  constructor(options) {
2847
3203
  this.#options = options;
2848
3204
  }
2849
3205
  /**
2850
3206
  * Clears the session: the cached login result and the stored refresh
2851
3207
  * token. The next login starts from scratch — /r33 logout and the
2852
- * auto-reconnect path both land here.
3208
+ * auto-reconnect path both land here. A refresh still on its way to the
3209
+ * auth server is disowned: its rotated token is never stored.
2853
3210
  * @returns Resolved once the session and the stored refresh token are gone.
2854
3211
  */
2855
3212
  async clear() {
3213
+ this.#clears += 1;
2856
3214
  this.#result = void 0;
2857
3215
  this.#expiresAt = void 0;
2858
3216
  await this.#options.tokenStore?.set(void 0);
2859
3217
  }
3218
+ /**
3219
+ * Whether a session exists, judged without using it: a login resolved or
3220
+ * in flight in this process, or a stored refresh token. Read-only — the
3221
+ * token is never presented, so asking cannot rotate or revoke anything.
3222
+ * @returns True when there is a session to sign in with.
3223
+ */
3224
+ async hasSession() {
3225
+ if (this.#result !== void 0) return true;
3226
+ const stored = await this.#options.tokenStore?.get().catch(() => void 0);
3227
+ return stored !== void 0 && stored !== "";
3228
+ }
2860
3229
  /**
2861
3230
  * Resolves the login once per process, sharing in-flight attempts.
2862
3231
  * @param policy - Whether this attempt may start a browser login; an in-flight attempt is always shared.
@@ -2865,11 +3234,15 @@ var LoginSession = class {
2865
3234
  result(policy = {}) {
2866
3235
  if (this.#result !== void 0 && this.#expiresAt !== void 0 && Date.now() >= this.#expiresAt - EXPIRY_SKEW_MS) {
2867
3236
  this.#result = void 0;
3237
+ this.#expiresAt = void 0;
3238
+ }
3239
+ if (this.#result === void 0) {
3240
+ const attempt = this.#start(policy).catch((cause) => {
3241
+ if (this.#result === attempt) this.#result = void 0;
3242
+ throw cause;
3243
+ });
3244
+ this.#result = attempt;
2868
3245
  }
2869
- this.#result ??= this.#start(policy).catch((cause) => {
2870
- this.#result = void 0;
2871
- throw cause;
2872
- });
2873
3246
  return this.#result;
2874
3247
  }
2875
3248
  /**
@@ -2899,6 +3272,7 @@ var LoginSession = class {
2899
3272
  if (tokenStore === void 0) {
2900
3273
  return void 0;
2901
3274
  }
3275
+ const clears = this.#clears;
2902
3276
  const stored = await tokenStore.get();
2903
3277
  if (stored === void 0 || stored === "") {
2904
3278
  return void 0;
@@ -2907,6 +3281,9 @@ var LoginSession = class {
2907
3281
  if (tokenSet === void 0) {
2908
3282
  return void 0;
2909
3283
  }
3284
+ if (clears !== this.#clears) {
3285
+ throw new AuthError2("AUTH_REAUTHENTICATION_REQUIRED");
3286
+ }
2910
3287
  let credential;
2911
3288
  try {
2912
3289
  credential = parseManagementJwt(tokenSet.access_token);
@@ -3040,7 +3417,7 @@ var Route33Runtime = class {
3040
3417
  const projectsById = new Map(
3041
3418
  listings.flatMap(({ data }) => data).map((project) => [project.id, project])
3042
3419
  );
3043
- return rows.flatMap(({ org_id, project_id }) => {
3420
+ return rows.flatMap(({ org_id, project_id, cap }) => {
3044
3421
  const project = projectsById.get(project_id);
3045
3422
  if (project === void 0) {
3046
3423
  return [];
@@ -3048,6 +3425,7 @@ var Route33Runtime = class {
3048
3425
  return [
3049
3426
  {
3050
3427
  ...project,
3428
+ memberCap: cap,
3051
3429
  organisation: {
3052
3430
  id: org_id,
3053
3431
  name: organisationNames.get(org_id) ?? org_id
@@ -3089,6 +3467,8 @@ var Route33Runtime = class {
3089
3467
  }
3090
3468
  const installation = this.#installation(attribution);
3091
3469
  await this.#hydrateState(installation);
3470
+ if (attribution.boundKeyId !== void 0)
3471
+ return this.#boundKey(installation, attribution.boundKeyId);
3092
3472
  const storedKey = await installation.secretStore.get();
3093
3473
  return reusableLease({
3094
3474
  attribution,
@@ -3146,24 +3526,14 @@ var Route33Runtime = class {
3146
3526
  commandHandlers() {
3147
3527
  return {
3148
3528
  "change-attribution": () => changeAttribution({
3149
- clear: () => {
3150
- clearAttribution(this.#options.state);
3529
+ commit: async (choice) => {
3530
+ await this.#leaseAttribution(choice, this.#options.policy);
3531
+ if (!writeAttribution(this.#options.state, choice))
3532
+ throw new TypeError("Workspace attribution requires a worktree");
3151
3533
  },
3152
- prompt: () => this.#resolveAttribution()
3534
+ prompt: () => this.pickAttribution()
3153
3535
  }),
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
- },
3536
+ "inspect-session": () => this.#inspectSession(),
3167
3537
  "reset-attribution": () => resetAttribution({
3168
3538
  clear: () => {
3169
3539
  clearAttribution(this.#options.state);
@@ -3175,53 +3545,67 @@ var Route33Runtime = class {
3175
3545
  })
3176
3546
  };
3177
3547
  }
3178
- /** Enriched session inspection: the plain report plus the key's name and organisation/project.
3548
+ /** Adds fresh display metadata without prompting for sign-in or changing attribution.
3179
3549
  * @returns A safe session report that cannot carry gateway plaintext.
3180
3550
  */
3181
3551
  async #inspectSession() {
3552
+ const attribution = readAttribution(this.#options.state);
3553
+ const installation = attribution === void 0 ? void 0 : this.#installation(attribution);
3554
+ if (installation !== void 0) {
3555
+ await this.#hydrateState(installation);
3556
+ }
3182
3557
  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
- }
3558
+ connected: await this.#session.hasSession(),
3559
+ readAttribution: () => attribution,
3560
+ readLease: () => installation?.state.snapshot()
3188
3561
  });
3189
3562
  const keyId = base.lease?.keyId;
3190
- if (keyId === void 0) {
3563
+ if (attribution === void 0 || keyId === void 0) {
3191
3564
  return base;
3192
3565
  }
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) {
3566
+ const credential = await this.#session.credential({ allowBrowser: false }).catch(() => void 0);
3567
+ if (credential === void 0) return { ...base, connected: false };
3568
+ try {
3569
+ const details = await enrichInspection({
3570
+ attribution,
3571
+ client: this.#client(),
3572
+ credential,
3573
+ keyId,
3574
+ subject: () => this.#subject(credential)
3575
+ });
3576
+ return { ...base, ...details };
3577
+ } catch {
3201
3578
  return base;
3202
3579
  }
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
3580
  }
3214
3581
  /**
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.
3582
+ * Lists the models a key on this budget may be limited to. Never opens a
3583
+ * browser; an organisation-level (personal) catalog needs the `models:read`
3584
+ * grant, so sessions signed in before that grant reject here.
3585
+ * @param scope - The budget being configured.
3586
+ * @returns Key-facing model ids with their readable names.
3587
+ */
3588
+ async catalogModelChoices(scope) {
3589
+ const credential = await this.#session.credential({ allowBrowser: false });
3590
+ return this.#client().listModelChoices(credential, scope);
3591
+ }
3592
+ /**
3593
+ * @param scope - The budget being configured. Omit to discover models for the current key.
3594
+ * @returns The management catalog for a budget, or the current key's gateway catalog.
3218
3595
  */
3219
- async catalogModelIds() {
3596
+ async catalogModelIds(scope) {
3597
+ if (scope !== void 0) {
3598
+ return (await this.catalogModelChoices(scope)).map(({ id }) => id);
3599
+ }
3220
3600
  const workspace = await this.storedReusableKey();
3221
3601
  const personal = workspace === void 0 ? await this.#storedPersonalKey() : void 0;
3222
3602
  const value = workspace?.key.value ?? personal?.value;
3223
3603
  if (value === void 0) {
3224
- return [];
3604
+ const credential = await this.#session.credential({
3605
+ allowBrowser: false
3606
+ });
3607
+ const choices = await this.#client().listModelChoices(credential, {});
3608
+ return choices.map(({ id }) => id);
3225
3609
  }
3226
3610
  return gatewayModelIds({
3227
3611
  baseURL: readEnvBaseUrl() ?? DEFAULT_BASE_URL,
@@ -3240,12 +3624,41 @@ var Route33Runtime = class {
3240
3624
  * @param attribution - The budget the wizard selected.
3241
3625
  * @param extras - The wizard's key-creation answers.
3242
3626
  * @param directory - Optional worktree override for project leases.
3627
+ * @param saveAttribution - Wizard save that must succeed before replacing a live key.
3243
3628
  * @returns The fresh key material with its lease metadata.
3244
3629
  */
3245
- async mintWorkspaceKey(attribution, extras, directory = this.#options.state.directory) {
3630
+ async mintWorkspaceKey(attribution, extras, directory = this.#options.state.directory, saveAttribution) {
3631
+ const file = resolveAttributionFile({ ...this.#options.state, directory });
3632
+ if (file === void 0)
3633
+ throw new TypeError("Workspace attribution requires a worktree");
3634
+ const previous = statSync2(file, { bigint: true, throwIfNoEntry: false });
3635
+ const wizardRequest = createHash3("sha256").update(
3636
+ JSON.stringify([
3637
+ file,
3638
+ previous?.ino.toString(),
3639
+ previous?.mtimeNs.toString(),
3640
+ attribution,
3641
+ extras,
3642
+ this.#subject(await this.#session.credential())
3643
+ ])
3644
+ ).digest("hex");
3246
3645
  return this.#leaseAttribution(attribution, void 0, directory, {
3247
3646
  extras,
3248
- forceMint: true
3647
+ forceMint: true,
3648
+ wizardRequest,
3649
+ saveAttribution
3650
+ });
3651
+ }
3652
+ /** @returns Binding operations restricted to the current management identity. */
3653
+ async workspaceKeyBinding() {
3654
+ const token = await this.#session.credential({ allowBrowser: false });
3655
+ return new WorkspaceKeyBinding({
3656
+ installations: this.#options.installation,
3657
+ token,
3658
+ subject: this.#subject(token),
3659
+ client: this.#client(),
3660
+ now: this.#now(),
3661
+ state: this.#options.state
3249
3662
  });
3250
3663
  }
3251
3664
  /**
@@ -3263,7 +3676,7 @@ var Route33Runtime = class {
3263
3676
  if (attribution === void 0) {
3264
3677
  return void 0;
3265
3678
  }
3266
- const lease = this.#installation(attribution).state.snapshot();
3679
+ const lease = this.#installation(attribution, directory).state.snapshot();
3267
3680
  const keyId = lease?.keyId;
3268
3681
  if (keyId === void 0) {
3269
3682
  return void 0;
@@ -3273,6 +3686,29 @@ var Route33Runtime = class {
3273
3686
  const key = keys.find((item) => item.id === keyId);
3274
3687
  return key === void 0 ? void 0 : { allowedModels: key.allowed_models };
3275
3688
  }
3689
+ /** V1 captures only the choice, not the plan; read only that owner's policy.
3690
+ * @param choice - The selected budget and its active organisation.
3691
+ * @returns The effective EUR cap, if the owner has a readable allowance.
3692
+ */
3693
+ async ownerBudgetCap(choice) {
3694
+ const token = await this.#session.credential({ allowBrowser: false });
3695
+ const subject = this.#subject(token);
3696
+ const client = this.#client();
3697
+ if (choice.kind === "personal") {
3698
+ const policy = await client.listBudgetPolicy(
3699
+ token,
3700
+ subject,
3701
+ choice.orgId
3702
+ );
3703
+ return policy.cap ?? void 0;
3704
+ }
3705
+ const budgets = await client.listProjectBudgets(
3706
+ token,
3707
+ subject,
3708
+ choice.orgId
3709
+ );
3710
+ return budgets.data.find((row) => row.project_id === choice.projectId)?.cap;
3711
+ }
3276
3712
  #client() {
3277
3713
  const client = this.#options.management.client;
3278
3714
  if (typeof client !== "function") {
@@ -3291,23 +3727,33 @@ var Route33Runtime = class {
3291
3727
  #now() {
3292
3728
  return (this.#options.clock ?? Date.now)();
3293
3729
  }
3294
- async #resolveAttribution() {
3730
+ /** @returns A fresh selection without changing the active budget. */
3731
+ pickAttribution() {
3295
3732
  return resolveAttribution({
3296
3733
  loadProjects: async () => {
3297
3734
  await this.#session.credential();
3298
3735
  return this.listMintableProjects();
3299
3736
  },
3300
- ...this.#options.presenter === void 0 ? {} : { presenter: this.#options.presenter },
3301
- state: this.#options.state
3737
+ ...this.#options.presenter === void 0 ? {} : { presenter: this.#options.presenter }
3302
3738
  });
3303
3739
  }
3304
3740
  async #lease(policy) {
3305
- const attribution = await this.#resolveAttribution();
3306
- return this.#leaseAttribution(attribution, policy);
3741
+ const remembered = readAttribution(this.#options.state);
3742
+ if (remembered !== void 0)
3743
+ return this.#leaseAttribution(remembered, policy);
3744
+ const choice = await this.pickAttribution();
3745
+ const leased = await this.#leaseAttribution(choice, policy);
3746
+ writeAttribution(this.#options.state, choice);
3747
+ return leased;
3307
3748
  }
3308
3749
  async #leaseAttribution(attribution, policy, directory = this.#options.state.directory, request) {
3309
3750
  const installation = this.#installation(attribution, directory);
3310
3751
  await this.#hydrateState(installation);
3752
+ if (attribution.boundKeyId !== void 0) {
3753
+ if (policy?.renewalRatio === Number.EPSILON)
3754
+ throw new TypeError("Automatic rotation is disabled for a shared key.");
3755
+ return this.#boundKey(installation, attribution.boundKeyId);
3756
+ }
3311
3757
  const minted = await leaseForAttribution({
3312
3758
  attribution,
3313
3759
  ...this.#options.clock === void 0 ? {} : { clock: this.#options.clock },
@@ -3323,13 +3769,20 @@ var Route33Runtime = class {
3323
3769
  await this.#persistState(installation, minted.lease);
3324
3770
  return minted;
3325
3771
  }
3772
+ async #boundKey(installation, id) {
3773
+ const key = await installation.secretStore.get();
3774
+ const lease = await installation.secretStore.getLease?.() ?? await installation.stateStore?.get() ?? installation.state.snapshot();
3775
+ if (!key || lease?.keyId !== id || Date.parse(lease.expiresAt) <= this.#now())
3776
+ throw new KeyLeaseError("KEY_LEASE_EXPIRED");
3777
+ return { key, lease };
3778
+ }
3326
3779
  async #hydrateState(installation) {
3327
3780
  const store = installation.stateStore;
3328
- if (store === void 0 || installation.state.snapshot() !== void 0) {
3781
+ if (installation.state.snapshot() !== void 0) {
3329
3782
  return;
3330
3783
  }
3331
3784
  try {
3332
- const persisted = await store.get();
3785
+ const persisted = await installation.secretStore.getLease?.() ?? await store?.get();
3333
3786
  if (persisted !== void 0) {
3334
3787
  installation.state.compareAndSwap(void 0, persisted);
3335
3788
  }
@@ -3343,6 +3796,13 @@ var Route33Runtime = class {
3343
3796
  }
3344
3797
  }
3345
3798
  #installation(attribution, directory = this.#options.state.directory) {
3799
+ if (attribution.boundKeyId !== void 0)
3800
+ return this.#options.installation(
3801
+ deriveScopeId({
3802
+ attribution,
3803
+ folderRealpath: detectWorktreeRoot(directory)
3804
+ })
3805
+ );
3346
3806
  switch (attribution.kind) {
3347
3807
  case "personal":
3348
3808
  return this.#options.installation(deriveScopeId({ attribution }));
@@ -3364,15 +3824,14 @@ var Route33Runtime = class {
3364
3824
  };
3365
3825
 
3366
3826
  // src/v1-entry/unattributed-prompt-gate/unattributed-prompt-gate.ts
3367
- var createUnattributedPromptGate = ({ directory, outsideWorktree }) => (input) => {
3827
+ var CONNECTION_COPY = "To sign in, run /connect and choose Route 33.";
3828
+ var ATTRIBUTION_COPY = "This folder has no Route 33 budget; open /r33 and choose Change budget.";
3829
+ var createUnattributedPromptGate = ({ directory, isConnected, outsideWorktree }) => async (input) => {
3368
3830
  if (input.model?.providerID !== "route_33") return Promise.resolve();
3831
+ if (!await isConnected()) throw new Error(CONNECTION_COPY);
3369
3832
  const attribution = readAttribution({ directory, outsideWorktree });
3370
3833
  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
- );
3834
+ throw new Error(ATTRIBUTION_COPY);
3376
3835
  };
3377
3836
 
3378
3837
  // src/v1-entry/workspace-key-headers/workspace-key-headers.ts
@@ -3399,6 +3858,11 @@ var createRoute33Plugin = (options = {}) => {
3399
3858
  };
3400
3859
  const runtimeOptions = options.runtime;
3401
3860
  const installation = runtimeOptions === void 0 ? void 0 : runtimeOptions.installation ?? createLeaseInstallationFactory({
3861
+ listScopes: () => FileSecretStore.scopes(
3862
+ resolveV1SecretStoreDirectory({
3863
+ directory: options.secretStoreDirectory
3864
+ })
3865
+ ),
3402
3866
  createSecretStore: (scopeId) => new FileSecretStore({
3403
3867
  directory: resolveV1SecretStoreDirectory({
3404
3868
  ...options.secretStoreDirectory === void 0 ? {} : { directory: options.secretStoreDirectory }
@@ -3444,6 +3908,14 @@ var createRoute33Plugin = (options = {}) => {
3444
3908
  });
3445
3909
  promptGate = createUnattributedPromptGate({
3446
3910
  directory: input.worktree,
3911
+ isConnected: async () => {
3912
+ try {
3913
+ await runtime2.login({ allowBrowser: false });
3914
+ return true;
3915
+ } catch {
3916
+ return false;
3917
+ }
3918
+ },
3447
3919
  outsideWorktree: "return-undefined"
3448
3920
  });
3449
3921
  }
@@ -3475,12 +3947,6 @@ var drainPages = async (fetchPage) => {
3475
3947
  return { data, page: { ...page, has_more: false, next_cursor: null } };
3476
3948
  };
3477
3949
 
3478
- // src/management/sdk-management-keys/sdk-management-keys.ts
3479
- import {
3480
- createRoute33Client,
3481
- Route33SdkError
3482
- } from "@r-33/sdk";
3483
-
3484
3950
  // src/contract/management-keys/parse-api-key/parse-api-key.ts
3485
3951
  var parseApiKey = (value) => {
3486
3952
  if (!isRecord(value) || !isOwnerType(value["ownership_type"]) || !isNullableString(value["project_id"])) {
@@ -3506,6 +3972,7 @@ var parseApiKey = (value) => {
3506
3972
  name: field("name"),
3507
3973
  org_id: field("org_id"),
3508
3974
  ownership_type: value["ownership_type"],
3975
+ ...isNullableString(value["user_id"]) ? { user_id: value["user_id"] } : {},
3509
3976
  project_id: value["project_id"],
3510
3977
  revoked: value["revoked"] === true,
3511
3978
  status
@@ -3741,6 +4208,44 @@ var parseUserMemberships = (value) => {
3741
4208
  };
3742
4209
  };
3743
4210
 
4211
+ // src/management/key-read-operations/key-read-operations.ts
4212
+ var keyReadOperations = (call) => {
4213
+ const withCursor = (cursor) => ({ request }) => {
4214
+ const url = new URL(request.url);
4215
+ url.searchParams.set("cursor", cursor);
4216
+ return new Request(url, request);
4217
+ };
4218
+ const parsePage = (page) => {
4219
+ const collection = parseCollection(page, (row) => row);
4220
+ const data = collection.data.flatMap((row) => {
4221
+ try {
4222
+ return [parseApiKey(row)];
4223
+ } catch (error) {
4224
+ if (error instanceof ContractParseError) return [];
4225
+ throw error;
4226
+ }
4227
+ });
4228
+ return { ...collection, data };
4229
+ };
4230
+ return {
4231
+ get: async (accessToken, id, orgId) => parseApiKey(
4232
+ await call(
4233
+ accessToken,
4234
+ orgId,
4235
+ (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
4236
+ params: { path: { api_key_id: id } }
4237
+ })
4238
+ )
4239
+ ),
4240
+ list: (accessToken, orgId) => drainPages(
4241
+ (cursor) => call(accessToken, orgId, (client) => {
4242
+ if (cursor !== "") client.use({ onRequest: withCursor(cursor) });
4243
+ return client.GET("/api/v1/api-keys", {});
4244
+ }).then(parsePage)
4245
+ )
4246
+ };
4247
+ };
4248
+
3744
4249
  // src/management/sdk-management-keys/mint-request-body/mint-request-body.ts
3745
4250
  var buildMintRequestBody = (input) => ({
3746
4251
  ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
@@ -3754,10 +4259,183 @@ var buildMintRequestBody = (input) => ({
3754
4259
  ...input.projectId === null ? {} : { project_id: input.projectId }
3755
4260
  });
3756
4261
 
3757
- // src/management/sdk-management-keys/sdk-management-keys.ts
4262
+ // src/management/key-write-operations/key-write-operations.ts
4263
+ var keyWriteOperations = (call) => ({
4264
+ create: async (accessToken, input) => parseKeyMaterial(
4265
+ await call(
4266
+ accessToken,
4267
+ input.activeOrgId,
4268
+ (client) => client.POST("/api/v1/api-keys", {
4269
+ body: buildMintRequestBody(input)
4270
+ })
4271
+ )
4272
+ ),
4273
+ delete: async (accessToken, id) => {
4274
+ await call(
4275
+ accessToken,
4276
+ void 0,
4277
+ (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
4278
+ params: { path: { api_key_id: id } }
4279
+ })
4280
+ );
4281
+ },
4282
+ regenerate: async (accessToken, id, expiresAt, orgId) => parseKeyMaterial(
4283
+ await call(
4284
+ accessToken,
4285
+ orgId,
4286
+ (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
4287
+ body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
4288
+ params: { path: { api_key_id: id } }
4289
+ })
4290
+ )
4291
+ ),
4292
+ update: async (accessToken, id, input) => parseApiKey(
4293
+ await call(
4294
+ accessToken,
4295
+ void 0,
4296
+ (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
4297
+ body: {
4298
+ budget_currency: "EUR",
4299
+ ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
4300
+ ...input.name === void 0 ? {} : { name: input.name }
4301
+ },
4302
+ params: { path: { api_key_id: id } }
4303
+ })
4304
+ )
4305
+ )
4306
+ });
4307
+
4308
+ // src/management/client-model-id/client-model-id.ts
4309
+ var clientModelId = (offeringId) => {
4310
+ const [provider, region, scope, vendor, ...modelParts] = offeringId.split(":");
4311
+ const slugParts = modelParts.at(-1) === "zdr" ? modelParts.slice(0, -1) : modelParts;
4312
+ const parts = [provider, region, scope, vendor, slugParts.join(":")];
4313
+ return parts.some((part) => part === void 0 || part === "") || /[\s,]/u.test(offeringId) ? void 0 : `${vendor ?? ""}/${slugParts.join(":")}`;
4314
+ };
4315
+
4316
+ // src/management/exposed-catalog-models/catalog-row-choices/catalog-row-choices.ts
4317
+ var catalogRowChoices = (row) => {
4318
+ if (!isRecord(row) || typeof row.id !== "string" || !row.id.trim() || typeof row.status !== "string")
4319
+ throw new ContractParseError("invalid model catalog item");
4320
+ if (row.status !== "exposed" || !Array.isArray(row.offerings)) return [];
4321
+ const label = typeof row.name === "string" && row.name.trim() !== "" ? row.name.trim() : void 0;
4322
+ return row.offerings.flatMap((offering) => {
4323
+ if (!isRecord(offering) || typeof offering.id !== "string" || offering.enabled !== true)
4324
+ return [];
4325
+ const id = clientModelId(offering.id);
4326
+ return id === void 0 ? [] : [{ id, name: label ?? id }];
4327
+ });
4328
+ };
4329
+
4330
+ // src/management/exposed-catalog-models/exposed-catalog-models.ts
4331
+ var exposedCatalogModels = async (readPage) => {
4332
+ const readRows = async (offset2) => {
4333
+ const page = await readPage(offset2);
4334
+ if (!isRecord(page) || !Array.isArray(page.models) || page.offset !== offset2 || typeof page.total !== "number" || !Number.isSafeInteger(page.total) || page.total < 0) {
4335
+ throw new ContractParseError("invalid model catalog page");
4336
+ }
4337
+ return { rows: page.models, total: page.total };
4338
+ };
4339
+ const names = /* @__PURE__ */ new Map();
4340
+ let offset = 0;
4341
+ for (; ; ) {
4342
+ const { rows, total } = await readRows(offset);
4343
+ for (const { id, name } of rows.flatMap(catalogRowChoices)) {
4344
+ names.set(id, name);
4345
+ }
4346
+ offset += rows.length;
4347
+ if (offset >= total || rows.length === 0) break;
4348
+ }
4349
+ return [...names].map(([id, name]) => ({ id, name })).sort(
4350
+ (left, right) => left.name.localeCompare(right.name) || left.id.localeCompare(right.id)
4351
+ );
4352
+ };
4353
+
4354
+ // src/management/model-catalog-operations/model-catalog-operations.ts
4355
+ var modelCatalogOperations = (call) => ({
4356
+ listModelChoices: (token, { orgId, projectId }) => exposedCatalogModels(
4357
+ (offset) => call(token, orgId, (client) => {
4358
+ const query = { offset };
4359
+ if (projectId !== void 0)
4360
+ return client.GET("/api/v1/projects/{project_id}/model-catalog", {
4361
+ params: { path: { project_id: projectId }, query }
4362
+ });
4363
+ if (orgId !== void 0)
4364
+ return client.GET("/api/v1/orgs/{org_id}/model-catalog", {
4365
+ params: { path: { org_id: orgId }, query }
4366
+ });
4367
+ return client.GET("/api/v1/model-catalog", { params: { query } });
4368
+ })
4369
+ )
4370
+ });
4371
+
4372
+ // src/management/list-sdk-projects/list-sdk-projects.ts
4373
+ var listSdkProjects = async (accessToken, organisationId, call) => {
4374
+ if (organisationId.trim().length === 0) {
4375
+ throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
4376
+ statusCode: 400
4377
+ });
4378
+ }
4379
+ const query = {
4380
+ member_user_id: parseManagementSubject(accessToken),
4381
+ org_id: organisationId
4382
+ };
4383
+ const fetchPage = (cursor) => call(
4384
+ accessToken,
4385
+ void 0,
4386
+ (client) => client.GET("/api/v1/projects", {
4387
+ params: {
4388
+ query: cursor === "" ? query : { ...query, cursor }
4389
+ }
4390
+ })
4391
+ ).then((page) => parseCollection(page, parseProject));
4392
+ return drainPages(fetchPage);
4393
+ };
4394
+
4395
+ // src/management/organization-operations/organization-operations.ts
4396
+ var organizationOperations = (call) => ({
4397
+ listOrganizations: async (accessToken) => parseCollection(
4398
+ await call(
4399
+ accessToken,
4400
+ void 0,
4401
+ (client) => client.GET("/api/v1/orgs", {})
4402
+ ),
4403
+ parseOrganization
4404
+ ),
4405
+ listProjects: (accessToken, organisationId) => listSdkProjects(accessToken, organisationId, call)
4406
+ });
4407
+
4408
+ // src/management/sdk-management-call/sdk-management-call.ts
4409
+ import {
4410
+ createRoute33Client,
4411
+ Route33SdkError
4412
+ } from "@r-33/sdk";
4413
+
4414
+ // src/management/sdk-management-call/rejection-of/rejection-of.ts
4415
+ var REFUSED = 422;
4416
+ var REJECTION_MAX_LENGTH = 200;
4417
+ var CONTROL = /\p{Cc}+/gu;
4418
+ var SECRET_PREFIXES = ["r33_", "eyj", "bearer "];
4419
+ var OPAQUE_MIN_LENGTH = 20;
4420
+ var rejectionOf = (outcome) => {
4421
+ const body = outcome.error;
4422
+ if (outcome.response?.status !== REFUSED || !isRecord(body)) return void 0;
4423
+ const raw = body["error"];
4424
+ if (typeof raw !== "string" || raw.length > REJECTION_MAX_LENGTH) {
4425
+ return void 0;
4426
+ }
4427
+ const sentence = raw.replaceAll(CONTROL, " ").replaceAll(/\s+/gu, " ").trim();
4428
+ const lower = sentence.toLowerCase();
4429
+ const secretShaped = SECRET_PREFIXES.some((prefix) => lower.includes(prefix)) || lower.split(" ").some(
4430
+ (word) => word.length >= OPAQUE_MIN_LENGTH && /\d/u.test(word) && /[a-z]/u.test(word)
4431
+ );
4432
+ return sentence === "" || secretShaped ? void 0 : sentence;
4433
+ };
4434
+
4435
+ // src/management/sdk-management-call/sdk-management-call.ts
3758
4436
  var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
3759
4437
  var ACTIVE_ORG_HEADER = "X-Active-Org-Id";
3760
- var sdkManagementKeys = (options) => {
4438
+ var createSdkCall = (options) => {
3761
4439
  const baseUrl = options.apiBaseUrl.replace(API_PREFIX_PATTERN, "");
3762
4440
  const timeoutMs = options.timeoutMs ?? 1e4;
3763
4441
  const fetchImpl = options.fetchImpl;
@@ -3796,14 +4474,18 @@ var sdkManagementKeys = (options) => {
3796
4474
  }
3797
4475
  return new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
3798
4476
  };
3799
- const call = async (accessToken, activeOrgId, run) => {
4477
+ return async (accessToken, activeOrgId, run) => {
3800
4478
  try {
3801
4479
  const outcome = await run(callClient(accessToken, activeOrgId));
3802
4480
  const code = outcome.response?.status;
3803
4481
  if (code === void 0 || code < 200 || code >= 300) {
4482
+ const rejection = rejectionOf(outcome);
3804
4483
  throw new ManagementError(
3805
4484
  code === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
3806
- { statusCode: code }
4485
+ {
4486
+ ...rejection === void 0 ? {} : { rejection },
4487
+ statusCode: code
4488
+ }
3807
4489
  );
3808
4490
  }
3809
4491
  return outcome.data;
@@ -3811,123 +4493,49 @@ var sdkManagementKeys = (options) => {
3811
4493
  throw mapFailure(cause);
3812
4494
  }
3813
4495
  };
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
- )
4496
+ };
4497
+
4498
+ // src/management/user-context-operations/user-context-operations.ts
4499
+ var userContextOperations = (call) => ({
4500
+ listMemberships: async (accessToken, userId) => parseUserMemberships(
4501
+ await call(
4502
+ accessToken,
4503
+ void 0,
4504
+ (client) => client.GET("/api/v1/users/{user_id}/memberships", {
4505
+ params: { path: { user_id: userId } }
4506
+ })
4507
+ )
4508
+ ),
4509
+ listBudgetPolicy: async (accessToken, userId, activeOrgId) => parseBudgetPolicy(
4510
+ await call(
4511
+ accessToken,
4512
+ activeOrgId,
4513
+ (client) => client.GET("/api/v1/users/{user_id}/budget-policy", {
4514
+ params: { path: { user_id: userId } }
4515
+ })
3930
4516
  )
4517
+ ),
4518
+ listProjectBudgets: async (accessToken, userId, activeOrgId) => parseCollection(
4519
+ await call(
4520
+ accessToken,
4521
+ activeOrgId,
4522
+ (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
4523
+ params: { path: { user_id: userId } }
4524
+ })
4525
+ ),
4526
+ parseProjectBudgetState
4527
+ )
4528
+ });
4529
+
4530
+ // src/management/sdk-management-keys/sdk-management-keys.ts
4531
+ var sdkManagementKeys = (options) => {
4532
+ const call = createSdkCall(options);
4533
+ return {
4534
+ ...keyReadOperations(call),
4535
+ ...keyWriteOperations(call),
4536
+ ...modelCatalogOperations(call),
4537
+ ...organizationOperations(call),
4538
+ ...userContextOperations(call)
3931
4539
  };
3932
4540
  };
3933
4541
 
@@ -4192,10 +4800,43 @@ import { createAuthorizationUrlStash as createAuthorizationUrlStash2 } from "@r-
4192
4800
  import { Integration, Provider } from "@opencode/plugin";
4193
4801
 
4194
4802
  // src/v2-entry/map-route33-model/map-route33-model.ts
4195
- import { Model as Model2 } from "@opencode/plugin";
4803
+ import { Model as Model3 } from "@opencode/plugin";
4196
4804
 
4197
- // src/v2-entry/map-route33-variant/map-route33-variant.ts
4805
+ // src/v2-entry/map-route33-cost/map-route33-cost.ts
4198
4806
  import { Model } from "@opencode/plugin";
4807
+ var LONG_CONTEXT_TOKENS = 2e5;
4808
+ var mapRoute33Cost = (cost) => {
4809
+ const rate = Model.Cost.fields.input;
4810
+ const read = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
4811
+ const tier = (rates) => {
4812
+ if (!isRecord(rates)) return [];
4813
+ const input = read(rates["input"]);
4814
+ const output = read(rates["output"]);
4815
+ if (input === void 0 || output === void 0) return [];
4816
+ return [
4817
+ {
4818
+ cache: {
4819
+ read: rate.make(read(rates["cache_read"]) ?? 0),
4820
+ write: rate.make(read(rates["cache_write"]) ?? 0)
4821
+ },
4822
+ input: rate.make(input),
4823
+ output: rate.make(output)
4824
+ }
4825
+ ];
4826
+ };
4827
+ const base = tier(cost);
4828
+ if (base.length === 0 || !isRecord(cost)) return [];
4829
+ return [
4830
+ ...base,
4831
+ ...tier(cost["context_over_200k"]).map((rates) => ({
4832
+ ...rates,
4833
+ tier: { size: LONG_CONTEXT_TOKENS, type: "context" }
4834
+ }))
4835
+ ];
4836
+ };
4837
+
4838
+ // src/v2-entry/map-route33-variant/map-route33-variant.ts
4839
+ import { Model as Model2 } from "@opencode/plugin";
4199
4840
  var mapRoute33Variant = (variants) => {
4200
4841
  if (variants === void 0) {
4201
4842
  return [];
@@ -4206,7 +4847,7 @@ var mapRoute33Variant = (variants) => {
4206
4847
  continue;
4207
4848
  }
4208
4849
  mapped.push({
4209
- id: Model.VariantID.make(variantID),
4850
+ id: Model2.VariantID.make(variantID),
4210
4851
  settings: structuredClone(overlay)
4211
4852
  });
4212
4853
  }
@@ -4215,8 +4856,9 @@ var mapRoute33Variant = (variants) => {
4215
4856
 
4216
4857
  // src/v2-entry/map-route33-model/map-route33-model.ts
4217
4858
  var mapRoute33Model = (providerID, modelID, model) => ({
4218
- ...Model2.Info.default(providerID, Model2.ID.make(modelID)),
4859
+ ...Model3.Info.default(providerID, Model3.ID.make(modelID)),
4219
4860
  name: typeof model.name === "string" ? model.name : modelID,
4861
+ cost: mapRoute33Cost(model.cost),
4220
4862
  ...model.variants === void 0 ? {} : {
4221
4863
  variants: mapRoute33Variant(
4222
4864
  model.variants
@@ -4260,11 +4902,12 @@ var bootstrapProvider = async (deps, sink) => {
4260
4902
  if (runtime2 === void 0) {
4261
4903
  return;
4262
4904
  }
4263
- try {
4264
- await runtime2.login({ allowBrowser: false });
4265
- } catch {
4266
- }
4905
+ const signedIn = await runtime2.login({ allowBrowser: false }).then(
4906
+ () => true,
4907
+ () => false
4908
+ );
4267
4909
  await deps.registerProjectForm().catch(() => void 0);
4910
+ if (!signedIn) return;
4268
4911
  try {
4269
4912
  const config = {};
4270
4913
  await deps.runConfig(config);
@@ -4300,16 +4943,24 @@ var readAllowedModels = (answer) => {
4300
4943
  };
4301
4944
 
4302
4945
  // src/v2-entry/parse-budget-answer/read-budget-cap/read-budget-cap.ts
4303
- var readBudgetCap = (answer) => {
4304
- const value = answer["budget_cap"];
4305
- if (typeof value === "number") {
4306
- return Number.isFinite(value) && value > 0 ? value : null;
4946
+ var readBudgetCap = (answer, maximum) => {
4947
+ const value = answer["budget_cap"] ?? "";
4948
+ if (typeof value !== "string" && typeof value !== "number") {
4949
+ throw new TypeError("Budget cap must be a number or unlimited");
4307
4950
  }
4308
- if (typeof value !== "string") {
4951
+ if (typeof value === "string" && ["", "unlimited"].includes(value.trim().toLowerCase())) {
4309
4952
  return null;
4310
4953
  }
4311
- const parsed = Number(value.trim());
4312
- return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
4954
+ const parsed = Number(value);
4955
+ if (!Number.isFinite(parsed) || parsed <= 0) {
4956
+ throw new RangeError("Budget cap must be a finite positive number");
4957
+ }
4958
+ if (maximum !== void 0 && parsed > maximum) {
4959
+ throw new RangeError(
4960
+ `Entered ${String(value)} EUR; the selected budget allows at most ${String(maximum)} EUR.`
4961
+ );
4962
+ }
4963
+ return parsed;
4313
4964
  };
4314
4965
 
4315
4966
  // src/v2-entry/parse-budget-answer/read-budget-description/read-budget-description.ts
@@ -4335,7 +4986,7 @@ var readBudgetName = (answer) => {
4335
4986
  };
4336
4987
 
4337
4988
  // src/v2-entry/parse-budget-answer/parse-budget-answer.ts
4338
- var parseBudgetAnswer = (answer) => {
4989
+ var parseBudgetAnswer = (answer, maximum) => {
4339
4990
  const attribution = parseConnectAnswer(answer);
4340
4991
  if (attribution === void 0) {
4341
4992
  return void 0;
@@ -4346,7 +4997,7 @@ var parseBudgetAnswer = (answer) => {
4346
4997
  allowedModels: readAllowedModels(answer),
4347
4998
  description: readBudgetDescription(answer),
4348
4999
  expiryDays: readBudgetExpiry(answer),
4349
- maxBudgetAmount: readBudgetCap(answer),
5000
+ maxBudgetAmount: readBudgetCap(answer, maximum),
4350
5001
  name: readBudgetName(answer)
4351
5002
  }
4352
5003
  };
@@ -4354,38 +5005,74 @@ var parseBudgetAnswer = (answer) => {
4354
5005
 
4355
5006
  // src/v2-entry/connect-copy/connect-copy.ts
4356
5007
  var CONNECT_COPY = {
4357
- failFastClientId: "This Route 33 build has no OAuth client id. Reinstall it from the opencode-dist ref, or set ROUTE33_CLIENT_ID and restart OpenCode.",
4358
- failFastWorktree: "Route 33 attributes usage to a project inside a Git worktree. Open a Git repository (or run git init), then connect again.",
4359
- selectionInvalid: "That Route 33 option is no longer available. Connect again and pick another.",
4360
- signedInNextStep: "Signed in to Route 33 \u2713. One more step: connect again, choose Route 33, and assign a budget for this folder.",
4361
- mintNoBudget: "Route 33 could not create the key \u2014 its cap exceeds this budget. Ask an owner to raise the budget, or pick another."
5008
+ failFastClientId: "This Route 33 build has no OAuth client ID; reinstall it from the opencode-dist ref.",
5009
+ failFastWorktree: "To assign a Route 33 budget, open a Git repository.",
5010
+ selectionInvalid: "That Route 33 option is no longer available; open /r33 and choose Attribute.",
5011
+ signedInNextStep: "Signed in to Route 33; open /r33 and choose Attribute to assign a budget.",
5012
+ budgetSelected: "Budget selected but not assigned; open /r33 and choose Attribute to finish setup."
5013
+ };
5014
+ var KEY_FORM_COPY = {
5015
+ /** Prefix of a key the management API refused; its reason follows. */
5016
+ mintRefused: "Route 33 refused this key:",
5017
+ mintRefusedUnknown: "its settings are not allowed for this budget.",
5018
+ modelsNeedSignIn: "Choosing individual models needs a fresh Route 33 sign-in.",
5019
+ modelsUnavailable: "The model list is unavailable right now."
4362
5020
  };
4363
5021
 
4364
5022
  // src/v2-entry/apply-wizard-answer/map-mint-failure/map-mint-failure.ts
4365
- var MINT_BUDGET_FAILURE_STATUS = 422;
4366
- var mapMintFailure = (cause) => cause instanceof KeyLeaseError && cause.statusCode === MINT_BUDGET_FAILURE_STATUS ? new GatewayCredentialError(CONNECT_COPY.mintNoBudget) : cause;
5023
+ var MINT_REFUSED_STATUS = 422;
5024
+ var mapMintFailure = (cause) => cause instanceof KeyLeaseError && cause.statusCode === MINT_REFUSED_STATUS ? new GatewayCredentialError(
5025
+ `${KEY_FORM_COPY.mintRefused} ${cause.rejection ?? KEY_FORM_COPY.mintRefusedUnknown}`
5026
+ ) : cause;
4367
5027
 
4368
5028
  // src/v2-entry/apply-wizard-answer/apply-wizard-answer.ts
4369
5029
  var applyWizardAnswer = async (deps, answer) => {
4370
- const budget = parseBudgetAnswer(answer);
4371
- const selection = budget?.attribution ?? parseConnectAnswer(answer);
5030
+ const selection = parseConnectAnswer(answer);
4372
5031
  if (selection === void 0) return;
4373
- const choice = deps.getPlan()?.choicesBySelection[selection];
5032
+ const plan = deps.getPlan();
5033
+ const choice = plan?.choicesBySelection[selection];
4374
5034
  if (choice === void 0) {
4375
5035
  throw new AttributionPromptError("ATTRIBUTION_SELECTION_INVALID");
4376
5036
  }
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);
5037
+ const save = (attribution) => {
5038
+ if (!writeAttribution(deps.state, attribution)) {
5039
+ throw new GatewayCredentialError(
5040
+ "Route 33 could not save the workspace budget."
5041
+ );
4386
5042
  }
4387
- }
4388
- writeAttribution(deps.state, choice);
5043
+ };
5044
+ const maximum = plan?.options.find(
5045
+ (option) => option.selection === selection
5046
+ )?.maximum;
5047
+ const acquire = async (existing) => {
5048
+ if (existing === void 0 || existing === "new") {
5049
+ const budget = parseBudgetAnswer(answer, maximum);
5050
+ if (budget && deps.mintWorkspaceKey) {
5051
+ try {
5052
+ await deps.mintWorkspaceKey(choice, budget.extras, () => {
5053
+ save(choice);
5054
+ });
5055
+ } catch (cause) {
5056
+ throw mapMintFailure(cause);
5057
+ }
5058
+ } else save(choice);
5059
+ return;
5060
+ }
5061
+ const runtime2 = deps.getRuntime?.();
5062
+ if (!runtime2 || typeof existing !== "string" || !existing)
5063
+ throw new AttributionPromptError("ATTRIBUTION_SELECTION_INVALID");
5064
+ const binding = await runtime2.workspaceKeyBinding();
5065
+ save(
5066
+ await binding.bind(
5067
+ choice,
5068
+ existing,
5069
+ answer["rotation_confirmation"] === existing
5070
+ )
5071
+ );
5072
+ };
5073
+ await acquire(answer[`existing_key:${selection}`] ?? answer["existing_key"]);
5074
+ if (choice.orgId !== void 0) deps.onOrgAnswered?.(choice.orgId);
5075
+ await deps.registerProjectForm?.().catch(() => void 0);
4389
5076
  };
4390
5077
 
4391
5078
  // src/v2-entry/connect-authorize/connect-authorize.ts
@@ -4398,7 +5085,7 @@ var createConnectAuthorize = (deps) => async (answer = {}) => {
4398
5085
  }
4399
5086
  const callback = (async () => {
4400
5087
  const emptyAnswer = Object.keys(answer).length === 0;
4401
- if (emptyAnswer && readAttribution(deps.state) === void 0) {
5088
+ if (emptyAnswer) {
4402
5089
  const runtime2 = deps.getRuntime();
4403
5090
  if (runtime2 === void 0) {
4404
5091
  throw new GatewayCredentialError(
@@ -4406,18 +5093,26 @@ var createConnectAuthorize = (deps) => async (answer = {}) => {
4406
5093
  );
4407
5094
  }
4408
5095
  await runtime2.login();
4409
- try {
4410
- return await deps.resolveCredential();
4411
- } catch {
4412
- await deps.registerProjectForm();
4413
- throw new GatewayCredentialError(CONNECT_COPY.signedInNextStep);
5096
+ if (readAttribution(deps.state) === void 0) {
5097
+ try {
5098
+ return await deps.resolveCredential();
5099
+ } catch {
5100
+ await deps.registerProjectForm();
5101
+ throw new GatewayCredentialError(CONNECT_COPY.signedInNextStep);
5102
+ }
4414
5103
  }
4415
5104
  }
5105
+ const selection = parseConnectAnswer(answer);
5106
+ if (selection !== void 0 && await deps.prepareBudget?.(selection, answer) === true) {
5107
+ throw new GatewayCredentialError(CONNECT_COPY.budgetSelected);
5108
+ }
4416
5109
  await applyWizardAnswer(deps, answer);
4417
5110
  if (readAttribution(deps.state) === void 0) {
4418
5111
  throw new GatewayCredentialError(CONNECT_COPY.selectionInvalid);
4419
5112
  }
4420
- return deps.resolveCredential();
5113
+ const credential = await deps.resolveCredential();
5114
+ if (emptyAnswer) await deps.registerProjectForm().catch(() => void 0);
5115
+ return credential;
4421
5116
  })();
4422
5117
  const decision = await deps.stash.urlForConnect(
4423
5118
  callback.then(() => void 0)
@@ -4435,9 +5130,14 @@ var ATTRIBUTION_FIELD_KEY2 = "attribution";
4435
5130
  var ORGANISATION_FIELD_KEY = "organisation";
4436
5131
  var BUDGET_NAME_FIELD_KEY = "budget_name";
4437
5132
  var BUDGET_CAP_FIELD_KEY = "budget_cap";
5133
+ var BUDGET_CAP_MAX_FIELD_KEY = "budget_cap_max";
5134
+ var PREPARED_BUDGET_FIELD_KEY = "prepared_budget";
4438
5135
  var BUDGET_DESCRIPTION_FIELD_KEY = "budget_description";
4439
5136
  var BUDGET_EXPIRY_FIELD_KEY = "budget_expiry";
4440
5137
  var ALLOWED_MODELS_FIELD_KEY = "allowed_models";
5138
+ var ALLOWED_MODELS_TITLE = "Which models may this key use?";
5139
+ var ALL_MODELS_VALUE = "all";
5140
+ var ALL_MODELS_LABEL = "All models (inherit)";
4441
5141
  var ORGANISATION_FIELD_TITLE = "Which Route 33 organisation covers this folder?";
4442
5142
  var EXPIRY_OPTIONS = [
4443
5143
  { label: "30 days", value: "30" },
@@ -4445,7 +5145,8 @@ var EXPIRY_OPTIONS = [
4445
5145
  { label: "180 days", value: "180" },
4446
5146
  { label: "1 year", value: "365" }
4447
5147
  ];
4448
- var buildConnectForm = (plan, modelIds = []) => {
5148
+ var buildConnectForm = (plan, key) => {
5149
+ const maximum = key?.maximum;
4449
5150
  const orgs = plan.orgs ?? [];
4450
5151
  const organisationField = {
4451
5152
  key: ORGANISATION_FIELD_KEY,
@@ -4466,6 +5167,8 @@ var buildConnectForm = (plan, modelIds = []) => {
4466
5167
  title: "Which budget covers Route 33 usage in this folder?",
4467
5168
  type: "string"
4468
5169
  };
5170
+ const budgetFields = orgs.length > 1 ? [organisationField, attributionField] : [attributionField];
5171
+ if (key === void 0) return budgetFields;
4469
5172
  const promptFields = [
4470
5173
  {
4471
5174
  key: BUDGET_NAME_FIELD_KEY,
@@ -4475,8 +5178,8 @@ var buildConnectForm = (plan, modelIds = []) => {
4475
5178
  },
4476
5179
  {
4477
5180
  key: BUDGET_CAP_FIELD_KEY,
4478
- placeholder: "blank = unlimited",
4479
- title: "Monthly budget cap in EUR",
5181
+ placeholder: "e.g. 50; blank or unlimited = no cap",
5182
+ title: maximum === void 0 ? "Monthly budget cap in EUR" : `Monthly budget cap in EUR (max ${String(maximum)})`,
4480
5183
  type: "string"
4481
5184
  },
4482
5185
  {
@@ -4490,17 +5193,41 @@ var buildConnectForm = (plan, modelIds = []) => {
4490
5193
  title: "When should the key expire?",
4491
5194
  type: "string"
4492
5195
  },
4493
- {
5196
+ key.models.length === 0 ? {
4494
5197
  key: ALLOWED_MODELS_FIELD_KEY,
4495
5198
  options: [
4496
- { label: "All models (inherit)", value: "all" },
4497
- ...modelIds.map((id) => ({ label: id, value: id }))
5199
+ {
5200
+ ...key.modelsNote === void 0 ? {} : { description: key.modelsNote },
5201
+ label: ALL_MODELS_LABEL,
5202
+ value: ALL_MODELS_VALUE
5203
+ }
4498
5204
  ],
4499
- title: "Which models may this key use?",
5205
+ title: ALLOWED_MODELS_TITLE,
4500
5206
  type: "string"
5207
+ } : {
5208
+ description: "Select none to allow all models.",
5209
+ key: ALLOWED_MODELS_FIELD_KEY,
5210
+ options: key.models.map(({ id, name }) => ({
5211
+ description: id,
5212
+ label: name,
5213
+ value: id
5214
+ })),
5215
+ title: ALLOWED_MODELS_TITLE,
5216
+ type: "multiselect"
4501
5217
  }
4502
5218
  ];
4503
- return orgs.length > 1 ? [organisationField, attributionField, ...promptFields] : [attributionField, ...promptFields];
5219
+ const helper = (name, value) => ({
5220
+ hidden: true,
5221
+ key: name,
5222
+ placeholder: value,
5223
+ type: "string"
5224
+ });
5225
+ return [
5226
+ ...budgetFields,
5227
+ ...promptFields,
5228
+ ...maximum === void 0 ? [] : [helper(BUDGET_CAP_MAX_FIELD_KEY, String(maximum))],
5229
+ ...key.prepared === void 0 ? [] : [helper(PREPARED_BUDGET_FIELD_KEY, key.prepared)]
5230
+ ];
4504
5231
  };
4505
5232
 
4506
5233
  // src/v2-entry/direct-key-mode/direct-key-mode.ts
@@ -4576,13 +5303,6 @@ var hostTokenStore = (options) => {
4576
5303
  };
4577
5304
  };
4578
5305
 
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
5306
  // src/v2-entry/model-gate-notify-from/model-gate-notify-from.ts
4587
5307
  var notifyFrom = async (session, sessionID, message) => {
4588
5308
  await session.synthetic?.({ delivery: "queue", sessionID, text: message });
@@ -4646,12 +5366,14 @@ var gateFallback = async (deps, input, directory) => {
4646
5366
  };
4647
5367
 
4648
5368
  // 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.";
5369
+ var CONNECTION_COPY2 = "To sign in, run /connect and choose Route 33.";
5370
+ var ATTRIBUTION_COPY2 = "This folder has no Route 33 budget; open /r33 and choose Attribute.";
4650
5371
  var createV2UnattributedModelGate = (deps) => async (input) => {
4651
5372
  if (input.model.providerID !== "route_33") return;
5373
+ if (!await deps.isConnected()) throw new Error(CONNECTION_COPY2);
4652
5374
  const state = await gateDirectory(deps, input.sessionID);
4653
5375
  if (readAttribution(state) === void 0) {
4654
- throw new Error(GATE_COPY);
5376
+ throw new Error(ATTRIBUTION_COPY2);
4655
5377
  }
4656
5378
  await gateFallback(deps, input, state.directory);
4657
5379
  };
@@ -4660,6 +5382,16 @@ var createV2UnattributedModelGate = (deps) => async (input) => {
4660
5382
  var registerRoute33ModelGate = async (deps) => deps.session.hook(
4661
5383
  "model.request",
4662
5384
  createV2UnattributedModelGate({
5385
+ isConnected: async () => {
5386
+ const runtime2 = deps.getRuntime();
5387
+ if (runtime2 === void 0) return false;
5388
+ try {
5389
+ await runtime2.login({ allowBrowser: false });
5390
+ return true;
5391
+ } catch {
5392
+ return false;
5393
+ }
5394
+ },
4663
5395
  allowedModels: (directory) => {
4664
5396
  const runtime2 = deps.getRuntime();
4665
5397
  return runtime2 === void 0 ? Promise.resolve(void 0) : runtime2.workspaceKeyAllowance(directory).then((allowance) => allowance?.allowedModels);
@@ -4675,6 +5407,33 @@ var registerRoute33ModelGate = async (deps) => deps.session.hook(
4675
5407
  { providerID: "route_33" }
4676
5408
  );
4677
5409
 
5410
+ // src/v2-entry/session-rpc/session-rpc.ts
5411
+ var ROUTE33_SESSION_RPC = {
5412
+ events: {},
5413
+ id: "route33",
5414
+ methods: {
5415
+ /** Ends the Route 33 session; answers `signedOut: true` once it is gone. */
5416
+ logout: {
5417
+ input: { additionalProperties: false, properties: {}, type: "object" },
5418
+ output: {
5419
+ additionalProperties: false,
5420
+ properties: { signedOut: { type: "boolean" } },
5421
+ required: ["signedOut"],
5422
+ type: "object"
5423
+ }
5424
+ }
5425
+ }
5426
+ };
5427
+
5428
+ // src/v2-entry/register-session-rpc/register-session-rpc.ts
5429
+ var registerSessionRpc = (rpc, deps) => rpc.register(ROUTE33_SESSION_RPC, {
5430
+ logout: async () => {
5431
+ await deps.getRuntime()?.commandHandlers().logout();
5432
+ await deps.registerProjectForm().catch(() => void 0);
5433
+ return { signedOut: true };
5434
+ }
5435
+ });
5436
+
4678
5437
  // src/v2-entry/resolve-host-credential/resolve-host-credential.ts
4679
5438
  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.";
4680
5439
  var resolveHostCredential = async (deps) => {
@@ -4695,6 +5454,81 @@ var resolveHostCredential = async (deps) => {
4695
5454
  };
4696
5455
  };
4697
5456
 
5457
+ // src/v2-entry/binding-fields/binding-fields.ts
5458
+ var bindingFields = async (plan, binding) => {
5459
+ const confirmations = /* @__PURE__ */ new Map();
5460
+ const fields = [];
5461
+ for (const [selection, choice] of Object.entries(plan.choicesBySelection)) {
5462
+ const keys = await binding.candidates(choice);
5463
+ if (!keys.length) continue;
5464
+ for (const key of keys) if (!key.local) confirmations.set(key.id, key.name);
5465
+ fields.push({
5466
+ key: `existing_key:${selection}`,
5467
+ type: "string",
5468
+ title: "Which key should this folder use?",
5469
+ options: [
5470
+ { label: "Mint a new key", value: "new" },
5471
+ ...keys.map((key) => ({
5472
+ label: `Bind ${key.name} (${key.id})`,
5473
+ value: key.id
5474
+ }))
5475
+ ]
5476
+ });
5477
+ }
5478
+ if (confirmations.size)
5479
+ fields.push({
5480
+ key: "rotation_confirmation",
5481
+ type: "string",
5482
+ title: ROTATION_WARNING,
5483
+ options: [
5484
+ { label: "No", value: "no" },
5485
+ ...Array.from(confirmations, ([id, name]) => ({
5486
+ label: `Yes, rotate ${name} (${id})`,
5487
+ value: id
5488
+ }))
5489
+ ]
5490
+ });
5491
+ return fields;
5492
+ };
5493
+
5494
+ // src/v2-entry/selected-budget-form/read-model-choices/read-model-choices.ts
5495
+ var FORBIDDEN = 403;
5496
+ var readModelChoices = async (read) => {
5497
+ try {
5498
+ return { models: await read() };
5499
+ } catch (cause) {
5500
+ return {
5501
+ models: [],
5502
+ modelsNote: cause instanceof ManagementError && cause.statusCode === FORBIDDEN ? KEY_FORM_COPY.modelsNeedSignIn : KEY_FORM_COPY.modelsUnavailable
5503
+ };
5504
+ }
5505
+ };
5506
+
5507
+ // src/v2-entry/selected-budget-form/selected-budget-form.ts
5508
+ var selectedBudgetForm = async (plan, selection, runtime2) => {
5509
+ const option = plan.options.find((row) => row.selection === selection);
5510
+ const choice = plan.choicesBySelection[selection];
5511
+ if (!option || !choice)
5512
+ throw new GatewayCredentialError(CONNECT_COPY.selectionInvalid);
5513
+ const scoped = {
5514
+ title: plan.title,
5515
+ options: [option],
5516
+ choicesBySelection: { [selection]: choice }
5517
+ };
5518
+ const choices = await readModelChoices(
5519
+ () => runtime2.catalogModelChoices(choice)
5520
+ );
5521
+ const keys = await bindingFields(scoped, await runtime2.workspaceKeyBinding());
5522
+ return [
5523
+ ...buildConnectForm(plan, {
5524
+ ...choices,
5525
+ ...option.maximum === void 0 ? {} : { maximum: option.maximum },
5526
+ prepared: selection
5527
+ }),
5528
+ ...keys
5529
+ ];
5530
+ };
5531
+
4698
5532
  // src/v2-entry/workspace-key-request-hook/workspace-key-request-hook.ts
4699
5533
  var createWorkspaceKeyHook = (deps) => async (input) => {
4700
5534
  const target = new URL(input.request.url);
@@ -4729,6 +5563,7 @@ var createRoute33V2Plugin = (options = {}) => {
4729
5563
  outsideWorktree: "return-undefined"
4730
5564
  };
4731
5565
  const installation = createLeaseInstallationFactory({
5566
+ listScopes: () => HostStorageSecretStore.scopes(context.storage),
4732
5567
  createSecretStore: (scopeId) => new HostStorageSecretStore({
4733
5568
  key: `route33_lease_${scopeId}`,
4734
5569
  storage: context.storage
@@ -4742,7 +5577,7 @@ var createRoute33V2Plugin = (options = {}) => {
4742
5577
  let provider = mapRoute33V2Provider(void 0);
4743
5578
  let connectFields;
4744
5579
  let plan;
4745
- let selectedOrgId;
5580
+ let preparedBudget;
4746
5581
  const runtimeInput = {
4747
5582
  ...options.runtime ?? buildProductionRuntimeOptions({
4748
5583
  apiBaseUrl,
@@ -4777,32 +5612,23 @@ var createRoute33V2Plugin = (options = {}) => {
4777
5612
  });
4778
5613
  const registerProjectForm = async () => {
4779
5614
  const activeRuntime = runtime2;
4780
- if (activeRuntime === void 0) {
4781
- return;
4782
- }
4783
- const [mintableOrgs, modelIds, personalKeyActive] = await Promise.all([
5615
+ if (activeRuntime === void 0) return;
5616
+ const [mintableOrgs, personalKeyActive] = await Promise.all([
4784
5617
  activeRuntime.listMintableOrgs({ allowBrowser: false }).catch(() => void 0),
4785
- activeRuntime.catalogModelIds().catch(() => []),
4786
5618
  activeRuntime.hasPersonalLease().catch(() => false)
4787
5619
  ]);
5620
+ preparedBudget = void 0;
4788
5621
  if (mintableOrgs === void 0) {
4789
5622
  plan = void 0;
4790
5623
  connectFields = void 0;
4791
5624
  await context.integration.reload();
4792
5625
  return;
4793
5626
  }
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
5627
  plan = createAttributionPrompt(
4802
5628
  mintableOrgs.flatMap(({ projects }) => projects),
4803
- { personalKeyActive, orgs }
5629
+ { personalKeyActive, orgs: mintableOrgs }
4804
5630
  );
4805
- connectFields = buildConnectForm(plan, modelIds);
5631
+ connectFields = buildConnectForm(plan);
4806
5632
  await context.integration.reload();
4807
5633
  };
4808
5634
  const authorize = createConnectAuthorize({
@@ -4810,7 +5636,7 @@ var createRoute33V2Plugin = (options = {}) => {
4810
5636
  directory: context.location.directory,
4811
5637
  getPlan: () => plan,
4812
5638
  getRuntime: () => runtime2,
4813
- mintWorkspaceKey: (attribution, extras) => {
5639
+ mintWorkspaceKey: (attribution, extras, save) => {
4814
5640
  const active = runtime2;
4815
5641
  if (active === void 0) {
4816
5642
  return Promise.reject(
@@ -4819,17 +5645,19 @@ var createRoute33V2Plugin = (options = {}) => {
4819
5645
  )
4820
5646
  );
4821
5647
  }
4822
- return mintAndRefresh(
4823
- {
4824
- mint: (choice, extras2) => active.mintWorkspaceKey(choice, extras2),
4825
- refresh: registerProjectForm
4826
- },
4827
- attribution,
4828
- extras
4829
- );
5648
+ return active.mintWorkspaceKey(attribution, extras, void 0, save);
4830
5649
  },
4831
- onOrgAnswered: (orgId) => {
4832
- selectedOrgId = orgId;
5650
+ prepareBudget: async (selection, answer) => {
5651
+ if (preparedBudget === selection && connectFields?.some(
5652
+ (field) => field.key !== "attribution" && Object.hasOwn(answer, field.key)
5653
+ ) === true)
5654
+ return false;
5655
+ if (!runtime2 || !plan)
5656
+ throw new GatewayCredentialError(CONNECT_COPY.selectionInvalid);
5657
+ connectFields = await selectedBudgetForm(plan, selection, runtime2);
5658
+ preparedBudget = selection;
5659
+ await context.integration.reload();
5660
+ return true;
4833
5661
  },
4834
5662
  registerProjectForm,
4835
5663
  resolveCredential,
@@ -4858,10 +5686,7 @@ var createRoute33V2Plugin = (options = {}) => {
4858
5686
  "http.request",
4859
5687
  createWorkspaceKeyHook({
4860
5688
  gatewayBase: readEnvBaseUrl() ?? DEFAULT_BASE_URL,
4861
- resolveKey: (directory) => {
4862
- const active = runtime2;
4863
- return active === void 0 ? Promise.resolve(void 0) : active.resolveWorkspaceCredential(directory);
4864
- },
5689
+ resolveKey: (directory) => runtime2?.resolveWorkspaceCredential(directory) ?? Promise.resolve(void 0),
4865
5690
  session: context.session
4866
5691
  })
4867
5692
  );
@@ -4871,6 +5696,10 @@ var createRoute33V2Plugin = (options = {}) => {
4871
5696
  listSessions: async () => (await context.session.list()).data,
4872
5697
  session: context.session
4873
5698
  });
5699
+ const sessionRpc = await registerSessionRpc(context.rpc, {
5700
+ getRuntime: () => runtime2,
5701
+ registerProjectForm
5702
+ });
4874
5703
  await bootstrapProvider(
4875
5704
  {
4876
5705
  getRuntime: () => runtime2,
@@ -4890,7 +5719,8 @@ var createRoute33V2Plugin = (options = {}) => {
4890
5719
  integrationTransform.dispose(),
4891
5720
  providerTransform.dispose(),
4892
5721
  sessionHook.dispose(),
4893
- modelGate.dispose()
5722
+ modelGate.dispose(),
5723
+ sessionRpc.dispose()
4894
5724
  ]);
4895
5725
  };
4896
5726
  }