@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.
package/dist/index.js CHANGED
@@ -1744,12 +1744,293 @@ 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 fs13 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 fs9 from "node:fs";
1805
+ import * as path9 from "node:path";
1806
+ var LEGACY_KEY_RELATIVE_PATH = path9.join(".opencode", "route33.key");
1807
+ var readLegacyKey = (worktree) => {
1808
+ if (worktree.trim() === "") return void 0;
1809
+ let raw;
1810
+ try {
1811
+ raw = fs9.readFileSync(
1812
+ path9.join(worktree, LEGACY_KEY_RELATIVE_PATH),
1813
+ "utf8"
1814
+ );
1815
+ } catch {
1816
+ return void 0;
1817
+ }
1818
+ try {
1819
+ const parsed = JSON.parse(raw);
1820
+ if (typeof parsed !== "object" || parsed === null || parsed.type !== "api") {
1821
+ return void 0;
1822
+ }
1823
+ const key = parsed.key;
1824
+ if (typeof key !== "string" || key.trim() === "") {
1825
+ return void 0;
1826
+ }
1827
+ return { value: key };
1828
+ } catch {
1829
+ return void 0;
1830
+ }
1831
+ };
1832
+
1833
+ // src/attribution/parse-attribution/read-org-id/read-org-id.ts
1834
+ var readOrgId = (value) => {
1835
+ const orgId = value["orgId"];
1836
+ if (orgId === void 0) {
1837
+ return void 0;
1838
+ }
1839
+ if (typeof orgId !== "string") {
1840
+ throw new ContractParseError("invalid attribution");
1841
+ }
1842
+ return orgId;
1843
+ };
1844
+
1845
+ // src/attribution/parse-attribution/parse-attribution.ts
1846
+ var parseAttribution = (value) => {
1847
+ if (!isRecord(value)) {
1848
+ throw new ContractParseError("invalid attribution");
1849
+ }
1850
+ const orgId = readOrgId(value);
1851
+ const binding = (() => {
1852
+ const { boundKeyId, boundScopeId } = value;
1853
+ if (boundKeyId === void 0 && boundScopeId === void 0) return {};
1854
+ if (typeof boundKeyId !== "string" || !boundKeyId)
1855
+ throw new ContractParseError("invalid bound key id");
1856
+ if (boundScopeId === void 0) return { boundKeyId };
1857
+ if (typeof boundScopeId !== "string" || !/^[a-f0-9]{64}$/u.test(boundScopeId))
1858
+ throw new ContractParseError("invalid bound scope id");
1859
+ return { boundKeyId, boundScopeId };
1860
+ })();
1861
+ if (value["kind"] === "personal") {
1862
+ return { ...binding, kind: "personal", orgId };
1863
+ }
1864
+ if (value["kind"] === "project" && typeof value["projectId"] === "string") {
1865
+ return {
1866
+ ...binding,
1867
+ kind: "project",
1868
+ ...orgId === void 0 ? {} : { orgId },
1869
+ projectId: value["projectId"]
1870
+ };
1871
+ }
1872
+ throw new ContractParseError("invalid attribution");
1873
+ };
1874
+
1875
+ // src/attribution/read-attribution/read-attribution.ts
1876
+ import * as fs10 from "node:fs";
1877
+ var readAttribution = (options) => {
1878
+ const file = resolveAttributionFile(options);
1879
+ if (file === void 0) {
1880
+ return void 0;
1881
+ }
1882
+ try {
1883
+ const parsed = JSON.parse(fs10.readFileSync(file, "utf8"));
1884
+ return parseAttribution(parsed);
1885
+ } catch {
1886
+ return void 0;
1887
+ }
1888
+ };
1889
+
1890
+ // src/attribution/remove-legacy-key/remove-legacy-key.ts
1891
+ import * as fs11 from "node:fs";
1892
+ import * as path10 from "node:path";
1893
+ var LEGACY_KEY_RELATIVE_PATH2 = path10.join(".opencode", "route33.key");
1894
+ var removeLegacyKey = (worktree) => {
1895
+ try {
1896
+ fs11.rmSync(path10.join(worktree, LEGACY_KEY_RELATIVE_PATH2), { force: true });
1897
+ return true;
1898
+ } catch {
1899
+ return false;
1900
+ }
1901
+ };
1902
+
1903
+ // src/attribution/write-attribution/write-attribution.ts
1904
+ import { randomUUID } from "node:crypto";
1905
+ import * as fs12 from "node:fs";
1906
+ import * as path11 from "node:path";
1907
+ var writeAttribution = (options, attribution) => {
1908
+ const file = resolveAttributionFile(options);
1909
+ if (file === void 0) {
1910
+ return false;
1911
+ }
1912
+ fs12.mkdirSync(path11.dirname(file), { recursive: true });
1913
+ const temporaryFile = `${file}.${String(process.pid)}.${randomUUID()}.tmp`;
1914
+ try {
1915
+ fs12.writeFileSync(temporaryFile, `${JSON.stringify(attribution)}
1916
+ `, "utf8");
1917
+ fs12.renameSync(temporaryFile, file);
1918
+ } catch (error) {
1919
+ fs12.rmSync(temporaryFile, { force: true });
1920
+ throw error;
1921
+ }
1922
+ return true;
1923
+ };
1924
+
1925
+ // src/key-lease/lease-state/lease-state.ts
1926
+ var LeaseState = class _LeaseState {
1927
+ /** Current committed snapshot; mutation is limited to compare-and-swap transitions. */
1928
+ #current;
1929
+ constructor(current) {
1930
+ this.#current = current;
1931
+ }
1932
+ /** Restores untrusted persisted metadata or an empty lease.
1933
+ * @param value - Persisted metadata, or undefined for a new installation.
1934
+ * @returns A lease-state coordinator.
1935
+ */
1936
+ static restore(value) {
1937
+ if (value === void 0) {
1938
+ return new _LeaseState(void 0);
1939
+ }
1940
+ if (!isRecord(value)) {
1941
+ throw new ContractParseError("invalid gateway key lease state");
1942
+ }
1943
+ const fields = Object.keys(value);
1944
+ if (fields.some(
1945
+ (field) => !["attribution", "expiresAt", "keyId", "wizardRequest"].includes(
1946
+ field
1947
+ )
1948
+ )) {
1949
+ throw new ContractParseError("invalid gateway key lease state");
1950
+ }
1951
+ const expiresAt = value["expiresAt"];
1952
+ const keyId = value["keyId"];
1953
+ const wizardRequest = value["wizardRequest"];
1954
+ if (typeof expiresAt !== "string" || !Number.isFinite(Date.parse(expiresAt)) || typeof keyId !== "string" || keyId.length === 0 || wizardRequest !== void 0 && typeof wizardRequest !== "string") {
1955
+ throw new ContractParseError("invalid gateway key lease state");
1956
+ }
1957
+ return new _LeaseState({
1958
+ attribution: parseAttribution(value["attribution"]),
1959
+ expiresAt,
1960
+ keyId,
1961
+ wizardRequest
1962
+ });
1963
+ }
1964
+ /** Reads the current non-secret metadata.
1965
+ * @returns The current lease metadata, if one is committed.
1966
+ */
1967
+ snapshot() {
1968
+ return this.#current;
1969
+ }
1970
+ /** Checks whether current metadata belongs to an attribution.
1971
+ * @param attribution - The requested ownership choice.
1972
+ * @returns Whether the current lease has the same attribution.
1973
+ */
1974
+ matchesAttribution(attribution) {
1975
+ if (this.#current === void 0) {
1976
+ return false;
1977
+ }
1978
+ switch (this.#current.attribution.kind) {
1979
+ case "personal":
1980
+ return attribution.kind === "personal";
1981
+ case "project":
1982
+ return attribution.kind === "project" && attribution.projectId === this.#current.attribution.projectId;
1983
+ default:
1984
+ return _LeaseState.#unexpectedAttribution(this.#current.attribution);
1985
+ }
1986
+ }
1987
+ /** Atomically swaps metadata when the expected snapshot is still current.
1988
+ * @param expected - Snapshot observed before asynchronous renewal.
1989
+ * @param next - Fresh metadata to commit.
1990
+ * @returns Whether the swap committed.
1991
+ */
1992
+ compareAndSwap(expected, next) {
1993
+ if (this.#current !== expected) {
1994
+ return false;
1995
+ }
1996
+ this.#current = next;
1997
+ return true;
1998
+ }
1999
+ /** Clears metadata only while the expected snapshot remains current.
2000
+ * @param expected - Snapshot whose lease is being invalidated.
2001
+ * @returns Whether the state was cleared.
2002
+ */
2003
+ clear(expected) {
2004
+ if (this.#current !== expected) {
2005
+ return false;
2006
+ }
2007
+ this.#current = void 0;
2008
+ return true;
2009
+ }
2010
+ static #unexpectedAttribution(value) {
2011
+ throw new TypeError(`Unexpected attribution: ${String(value)}`);
2012
+ }
2013
+ };
2014
+
2015
+ // src/key-lease/file-secret-store/file-secret-store.ts
1750
2016
  var FileSecretStore = class {
1751
2017
  #directory;
1752
2018
  #file;
2019
+ /** Lists only lease files, never opening a secret to discover its scope.
2020
+ * @param directory - Machine-local private lease directory.
2021
+ * @returns Known scope ids, or none before the first lease.
2022
+ */
2023
+ static async scopes(directory) {
2024
+ try {
2025
+ return (await fs13.readdir(directory)).flatMap(
2026
+ (name) => /^lease-([a-f0-9]{64})\.json$/u.exec(name)?.slice(1) ?? []
2027
+ );
2028
+ } catch (cause) {
2029
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
2030
+ return [];
2031
+ throw cause;
2032
+ }
2033
+ }
1753
2034
  constructor(options) {
1754
2035
  if (options.directory.length === 0) {
1755
2036
  throw new TypeError("File secret store requires a directory");
@@ -1758,15 +2039,25 @@ var FileSecretStore = class {
1758
2039
  throw new TypeError("File secret store scope is not portable");
1759
2040
  }
1760
2041
  this.#directory = options.directory;
1761
- this.#file = path7.join(options.directory, `lease-${options.scopeId}.json`);
2042
+ this.#file = path12.join(options.directory, `lease-${options.scopeId}.json`);
1762
2043
  }
1763
2044
  /** Reads and parses the scoped gateway credential.
1764
2045
  * @returns The persisted credential, when present.
1765
2046
  */
1766
2047
  async get() {
2048
+ const value = await this.#read();
2049
+ if (value === void 0) return void 0;
2050
+ return parseGatewayKey(isRecord(value) ? value["key"] : value);
2051
+ }
2052
+ /** @returns Metadata saved with the key, absent for legacy key-only files. */
2053
+ async getLease() {
2054
+ const value = await this.#read();
2055
+ return isRecord(value) ? LeaseState.restore(value["lease"]).snapshot() : void 0;
2056
+ }
2057
+ async #read() {
1767
2058
  let contents;
1768
2059
  try {
1769
- contents = await fs6.readFile(this.#file, "utf8");
2060
+ contents = await fs13.readFile(this.#file, "utf8");
1770
2061
  } catch (cause) {
1771
2062
  if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
1772
2063
  return void 0;
@@ -1774,31 +2065,50 @@ var FileSecretStore = class {
1774
2065
  throw cause;
1775
2066
  }
1776
2067
  const value = JSON.parse(contents);
1777
- return parseGatewayKey(value);
2068
+ return value;
1778
2069
  }
1779
2070
  /** Writes the scoped gateway credential through an atomic private file.
1780
2071
  * @param key - The credential to persist, or undefined to remove it.
2072
+ * @param lease - Metadata to commit in the same atomic write as the wizard key.
1781
2073
  * @returns A promise that settles after the file write or removal.
1782
2074
  */
1783
- async set(key) {
2075
+ async set(key, lease) {
1784
2076
  if (key === void 0) {
1785
- await fs6.rm(this.#file, { force: true });
2077
+ await fs13.rm(this.#file, { force: true });
1786
2078
  return;
1787
2079
  }
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`);
2080
+ const staged = await this.stage(key, lease);
2081
+ try {
2082
+ await staged.commit();
2083
+ } finally {
2084
+ await staged.discard();
2085
+ }
2086
+ }
2087
+ /** Prepares a private file without changing the credential visible to readers.
2088
+ * @param key - Replacement credential.
2089
+ * @param lease - Metadata promoted with the credential.
2090
+ * @returns Operations to publish the file or remove the temporary copy.
2091
+ */
2092
+ async stage(key, lease) {
2093
+ await fs13.mkdir(this.#directory, { mode: 448, recursive: true });
2094
+ await fs13.chmod(this.#directory, 448);
2095
+ const temporary = path12.join(this.#directory, `.lease-${randomUUID2()}.tmp`);
1791
2096
  try {
1792
- await fs6.writeFile(temporary, `${JSON.stringify(key.value)}
2097
+ const record = lease === void 0 ? key.value : { key: key.value, lease };
2098
+ await fs13.writeFile(temporary, `${JSON.stringify(record)}
1793
2099
  `, {
1794
2100
  encoding: "utf8",
1795
2101
  flag: "wx",
1796
2102
  mode: 384
1797
2103
  });
1798
- await fs6.rename(temporary, this.#file);
1799
- } finally {
1800
- await fs6.rm(temporary, { force: true });
2104
+ } catch (cause) {
2105
+ await fs13.rm(temporary, { force: true });
2106
+ throw cause;
1801
2107
  }
2108
+ return {
2109
+ commit: () => fs13.rename(temporary, this.#file),
2110
+ discard: () => fs13.rm(temporary, { force: true })
2111
+ };
1802
2112
  }
1803
2113
  };
1804
2114
 
@@ -1806,6 +2116,30 @@ var FileSecretStore = class {
1806
2116
  var HostStorageSecretStore = class {
1807
2117
  #key;
1808
2118
  #storage;
2119
+ /** @param storage - Plugin-owned host storage.
2120
+ * @returns The persisted lease scopes across all result pages.
2121
+ */
2122
+ static async scopes(storage) {
2123
+ const scopes = [];
2124
+ let after;
2125
+ do {
2126
+ const page = await storage.scan({
2127
+ prefix: "route33_lease_",
2128
+ ...after === void 0 ? {} : { after }
2129
+ });
2130
+ for (const { key } of page.entries)
2131
+ scopes.push(
2132
+ .../^route33_lease_([a-f0-9]{64})$/u.exec(key)?.slice(1) ?? []
2133
+ );
2134
+ after = page.next;
2135
+ } while (after !== void 0);
2136
+ return scopes;
2137
+ }
2138
+ /** @returns Metadata written atomically with this secret, if available. */
2139
+ async getLease() {
2140
+ const entry = await this.#storage.get(this.#key);
2141
+ return typeof entry === "object" && entry !== null && "lease" in entry && typeof entry.lease === "string" ? LeaseState.restore(JSON.parse(entry.lease)).snapshot() : void 0;
2142
+ }
1809
2143
  constructor(options) {
1810
2144
  this.#key = options.key;
1811
2145
  this.#storage = options.storage;
@@ -1828,10 +2162,14 @@ var HostStorageSecretStore = class {
1828
2162
  /** Writes the scoped gateway credential into the box envelope, through
1829
2163
  * host-owned storage only.
1830
2164
  * @param key - The credential to persist, or undefined to remove it.
2165
+ * @param lease
1831
2166
  * @returns A promise that settles after the host write or removal.
1832
2167
  */
1833
- set(key) {
1834
- return key === void 0 ? this.#storage.remove(this.#key) : this.#storage.set(this.#key, { value: key.value });
2168
+ set(key, lease) {
2169
+ return key === void 0 ? this.#storage.remove(this.#key) : this.#storage.set(this.#key, {
2170
+ value: key.value,
2171
+ ...lease ? { lease: JSON.stringify(lease) } : {}
2172
+ });
1835
2173
  }
1836
2174
  };
1837
2175
 
@@ -1845,9 +2183,11 @@ var KeyLeaseError = class extends Error {
1845
2183
  );
1846
2184
  this.code = code;
1847
2185
  this.name = "KeyLeaseError";
2186
+ this.rejection = options?.rejection;
1848
2187
  this.statusCode = options?.statusCode;
1849
2188
  }
1850
2189
  code;
2190
+ rejection;
1851
2191
  statusCode;
1852
2192
  };
1853
2193
 
@@ -1998,9 +2338,62 @@ var buildMintInput = (deps) => {
1998
2338
  };
1999
2339
  };
2000
2340
 
2341
+ // src/key-lease/commit-staged-replacement/commit-staged-replacement.ts
2342
+ var commitStagedReplacement = async (stage, save, persist) => {
2343
+ const storeFailure = (cause) => {
2344
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
2345
+ };
2346
+ const staged = await stage().catch(storeFailure);
2347
+ try {
2348
+ save();
2349
+ await (staged ? staged.commit() : persist()).catch(storeFailure);
2350
+ } finally {
2351
+ await staged?.discard();
2352
+ }
2353
+ };
2354
+
2355
+ // src/management/management-error/management-error.ts
2356
+ var ManagementError = class extends Error {
2357
+ constructor(code, options) {
2358
+ super(
2359
+ "Route 33 management request failed",
2360
+ options?.cause === void 0 ? void 0 : { cause: "Route 33 management dependency failed" }
2361
+ );
2362
+ this.code = code;
2363
+ this.name = "ManagementError";
2364
+ this.rejection = options?.rejection;
2365
+ this.statusCode = options?.statusCode;
2366
+ }
2367
+ code;
2368
+ rejection;
2369
+ statusCode;
2370
+ };
2371
+
2372
+ // src/key-lease/mint-failure/mint-failure.ts
2373
+ var mintFailure = (cause) => {
2374
+ const response = cause instanceof ManagementError ? cause : void 0;
2375
+ return new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
2376
+ cause,
2377
+ ...response?.rejection === void 0 ? {} : { rejection: response.rejection },
2378
+ ...response?.statusCode === void 0 ? {} : { statusCode: response.statusCode }
2379
+ });
2380
+ };
2381
+
2001
2382
  // src/key-lease/mint-fresh-lease/mint-fresh-lease.ts
2002
2383
  var mintFreshLease = async (deps) => {
2003
2384
  const now = deps.clock();
2385
+ const current = deps.state.snapshot();
2386
+ const reusable = () => {
2387
+ if (deps.wizardRequest !== void 0 && current?.wizardRequest === deps.wizardRequest && deps.storedKey !== void 0 && Date.parse(current.expiresAt) > now) {
2388
+ return { key: deps.storedKey, lease: current };
2389
+ }
2390
+ return void 0;
2391
+ };
2392
+ const reused = reusable();
2393
+ if (reused !== void 0) {
2394
+ deps.saveAttribution?.();
2395
+ return reused;
2396
+ }
2004
2397
  const input = buildMintInput({
2005
2398
  attribution: deps.attribution,
2006
2399
  extras: deps.extras,
@@ -2016,20 +2409,30 @@ var mintFreshLease = async (deps) => {
2016
2409
  input
2017
2410
  );
2018
2411
  } catch (cause) {
2019
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", { cause });
2412
+ throw mintFailure(cause);
2020
2413
  }
2021
2414
  const minted = {
2022
2415
  key: material.key,
2023
2416
  lease: {
2024
2417
  attribution: deps.attribution,
2025
2418
  expiresAt: material.expires_at,
2026
- keyId: material.id
2419
+ keyId: material.id,
2420
+ ...deps.wizardRequest === void 0 ? {} : { wizardRequest: deps.wizardRequest }
2027
2421
  }
2028
2422
  };
2029
- try {
2030
- await deps.secretStore.set(minted.key);
2031
- } catch (cause) {
2423
+ const storeFailure = (cause) => {
2032
2424
  throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
2425
+ };
2426
+ const persist = () => deps.secretStore.set(minted.key, minted.lease);
2427
+ if (deps.saveAttribution && deps.storedKey !== void 0) {
2428
+ await commitStagedReplacement(
2429
+ () => deps.secretStore.stage?.(minted.key, minted.lease) ?? Promise.resolve(void 0),
2430
+ deps.saveAttribution,
2431
+ persist
2432
+ );
2433
+ } else {
2434
+ await persist().catch(storeFailure);
2435
+ deps.saveAttribution?.();
2033
2436
  }
2034
2437
  deps.state.compareAndSwap(deps.state.snapshot(), minted.lease);
2035
2438
  return minted;
@@ -2089,21 +2492,6 @@ var rejectLease = async (options) => {
2089
2492
  }
2090
2493
  };
2091
2494
 
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
2495
  // src/key-lease/mint-key/mint-key.ts
2108
2496
  var mintKey = async (options) => {
2109
2497
  const now = options.clock();
@@ -2137,10 +2525,7 @@ var mintKey = async (options) => {
2137
2525
  if (isManagementUnauthorized(cause)) {
2138
2526
  throw new KeyLeaseError("KEY_LEASE_UNAUTHORIZED", { cause });
2139
2527
  }
2140
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
2141
- cause,
2142
- ...cause instanceof ManagementError && cause.statusCode !== void 0 ? { statusCode: cause.statusCode } : {}
2143
- });
2528
+ throw mintFailure(cause);
2144
2529
  }
2145
2530
  return {
2146
2531
  key: material.key,
@@ -2206,7 +2591,7 @@ var renewKey = async (options) => {
2206
2591
  }
2207
2592
  }
2208
2593
  try {
2209
- await options.secretStore.set(renewed.key);
2594
+ await options.secretStore.set(renewed.key, renewed.lease);
2210
2595
  } catch (cause) {
2211
2596
  const cleared = await discard(renewed.lease.keyId);
2212
2597
  if (!cleared) {
@@ -2326,7 +2711,10 @@ var leaseForAttribution = async (options) => {
2326
2711
  secretStore: options.installation.secretStore,
2327
2712
  state: options.installation.state,
2328
2713
  stateStore: options.installation.stateStore,
2329
- ttlMs: policy.ttlMs
2714
+ ttlMs: policy.ttlMs,
2715
+ wizardRequest: options.request.wizardRequest,
2716
+ saveAttribution: options.request.saveAttribution,
2717
+ storedKey
2330
2718
  });
2331
2719
  }
2332
2720
  const reusable = reusableLease({
@@ -2377,259 +2765,10 @@ var leaseForAttribution = async (options) => {
2377
2765
  }
2378
2766
  };
2379
2767
 
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 fs10 from "node:fs";
2434
- import * as path10 from "node:path";
2435
- var LEGACY_KEY_RELATIVE_PATH = path10.join(".opencode", "route33.key");
2436
- var readLegacyKey = (worktree) => {
2437
- if (worktree.trim() === "") return void 0;
2438
- let raw;
2439
- try {
2440
- raw = fs10.readFileSync(
2441
- path10.join(worktree, LEGACY_KEY_RELATIVE_PATH),
2442
- "utf8"
2443
- );
2444
- } catch {
2445
- return void 0;
2446
- }
2447
- try {
2448
- const parsed = JSON.parse(raw);
2449
- if (typeof parsed !== "object" || parsed === null || parsed.type !== "api") {
2450
- return void 0;
2451
- }
2452
- const key = parsed.key;
2453
- if (typeof key !== "string" || key.trim() === "") {
2454
- return void 0;
2455
- }
2456
- return { value: key };
2457
- } catch {
2458
- return void 0;
2459
- }
2460
- };
2461
-
2462
- // src/attribution/parse-attribution/read-org-id/read-org-id.ts
2463
- var readOrgId = (value) => {
2464
- const orgId = value["orgId"];
2465
- if (orgId === void 0) {
2466
- return void 0;
2467
- }
2468
- if (typeof orgId !== "string") {
2469
- throw new ContractParseError("invalid attribution");
2470
- }
2471
- return orgId;
2472
- };
2473
-
2474
- // src/attribution/parse-attribution/parse-attribution.ts
2475
- var parseAttribution = (value) => {
2476
- if (!isRecord(value)) {
2477
- throw new ContractParseError("invalid attribution");
2478
- }
2479
- const orgId = readOrgId(value);
2480
- if (value["kind"] === "personal") {
2481
- return { kind: "personal", ...orgId === void 0 ? {} : { orgId } };
2482
- }
2483
- if (value["kind"] === "project" && typeof value["projectId"] === "string") {
2484
- return {
2485
- kind: "project",
2486
- ...orgId === void 0 ? {} : { orgId },
2487
- projectId: value["projectId"]
2488
- };
2489
- }
2490
- throw new ContractParseError("invalid attribution");
2491
- };
2492
-
2493
- // src/attribution/read-attribution/read-attribution.ts
2494
- import * as fs11 from "node:fs";
2495
- var readAttribution = (options) => {
2496
- const file = resolveAttributionFile(options);
2497
- if (file === void 0) {
2498
- return void 0;
2499
- }
2500
- try {
2501
- const parsed = JSON.parse(fs11.readFileSync(file, "utf8"));
2502
- return parseAttribution(parsed);
2503
- } catch {
2504
- return void 0;
2505
- }
2506
- };
2507
-
2508
- // src/attribution/remove-legacy-key/remove-legacy-key.ts
2509
- import * as fs12 from "node:fs";
2510
- import * as path11 from "node:path";
2511
- var LEGACY_KEY_RELATIVE_PATH2 = path11.join(".opencode", "route33.key");
2512
- var removeLegacyKey = (worktree) => {
2513
- try {
2514
- fs12.rmSync(path11.join(worktree, LEGACY_KEY_RELATIVE_PATH2), { force: true });
2515
- return true;
2516
- } catch {
2517
- return false;
2518
- }
2519
- };
2520
-
2521
- // src/attribution/write-attribution/write-attribution.ts
2522
- import { randomUUID as randomUUID2 } from "node:crypto";
2523
- import * as fs13 from "node:fs";
2524
- import * as path12 from "node:path";
2525
- var writeAttribution = (options, attribution) => {
2526
- const file = resolveAttributionFile(options);
2527
- if (file === void 0) {
2528
- return false;
2529
- }
2530
- fs13.mkdirSync(path12.dirname(file), { recursive: true });
2531
- const temporaryFile = `${file}.${String(process.pid)}.${randomUUID2()}.tmp`;
2532
- try {
2533
- fs13.writeFileSync(temporaryFile, `${JSON.stringify(attribution)}
2534
- `, "utf8");
2535
- fs13.renameSync(temporaryFile, file);
2536
- } catch (error) {
2537
- fs13.rmSync(temporaryFile, { force: true });
2538
- throw error;
2539
- }
2540
- return true;
2541
- };
2542
-
2543
- // src/key-lease/lease-state/lease-state.ts
2544
- var LeaseState = class _LeaseState {
2545
- /** Current committed snapshot; mutation is limited to compare-and-swap transitions. */
2546
- #current;
2547
- constructor(current) {
2548
- this.#current = current;
2549
- }
2550
- /** Restores untrusted persisted metadata or an empty lease.
2551
- * @param value - Persisted metadata, or undefined for a new installation.
2552
- * @returns A lease-state coordinator.
2553
- */
2554
- static restore(value) {
2555
- if (value === void 0) {
2556
- return new _LeaseState(void 0);
2557
- }
2558
- if (!isRecord(value)) {
2559
- throw new ContractParseError("invalid gateway key lease state");
2560
- }
2561
- const fields = Object.keys(value);
2562
- if (fields.length !== 3 || fields.some(
2563
- (field) => field !== "attribution" && field !== "expiresAt" && field !== "keyId"
2564
- )) {
2565
- throw new ContractParseError("invalid gateway key lease state");
2566
- }
2567
- const expiresAt = value["expiresAt"];
2568
- const keyId = value["keyId"];
2569
- if (typeof expiresAt !== "string" || !Number.isFinite(Date.parse(expiresAt)) || typeof keyId !== "string" || keyId.length === 0) {
2570
- throw new ContractParseError("invalid gateway key lease state");
2571
- }
2572
- return new _LeaseState({
2573
- attribution: parseAttribution(value["attribution"]),
2574
- expiresAt,
2575
- keyId
2576
- });
2577
- }
2578
- /** Reads the current non-secret metadata.
2579
- * @returns The current lease metadata, if one is committed.
2580
- */
2581
- snapshot() {
2582
- return this.#current;
2583
- }
2584
- /** Checks whether current metadata belongs to an attribution.
2585
- * @param attribution - The requested ownership choice.
2586
- * @returns Whether the current lease has the same attribution.
2587
- */
2588
- matchesAttribution(attribution) {
2589
- if (this.#current === void 0) {
2590
- return false;
2591
- }
2592
- switch (this.#current.attribution.kind) {
2593
- case "personal":
2594
- return attribution.kind === "personal";
2595
- case "project":
2596
- return attribution.kind === "project" && attribution.projectId === this.#current.attribution.projectId;
2597
- default:
2598
- return _LeaseState.#unexpectedAttribution(this.#current.attribution);
2599
- }
2600
- }
2601
- /** Atomically swaps metadata when the expected snapshot is still current.
2602
- * @param expected - Snapshot observed before asynchronous renewal.
2603
- * @param next - Fresh metadata to commit.
2604
- * @returns Whether the swap committed.
2605
- */
2606
- compareAndSwap(expected, next) {
2607
- if (this.#current !== expected) {
2608
- return false;
2609
- }
2610
- this.#current = next;
2611
- return true;
2612
- }
2613
- /** Clears metadata only while the expected snapshot remains current.
2614
- * @param expected - Snapshot whose lease is being invalidated.
2615
- * @returns Whether the state was cleared.
2616
- */
2617
- clear(expected) {
2618
- if (this.#current !== expected) {
2619
- return false;
2620
- }
2621
- this.#current = void 0;
2622
- return true;
2623
- }
2624
- static #unexpectedAttribution(value) {
2625
- throw new TypeError(`Unexpected attribution: ${String(value)}`);
2626
- }
2627
- };
2628
-
2629
2768
  // src/key-lease/lease-installation-factory/lease-installation-factory.ts
2630
2769
  var createLeaseInstallationFactory = (options) => {
2631
2770
  const installations = /* @__PURE__ */ new Map();
2632
- return (scopeId) => {
2771
+ const open = (scopeId) => {
2633
2772
  const existing = installations.get(scopeId);
2634
2773
  if (existing !== void 0) {
2635
2774
  return existing;
@@ -2643,6 +2782,14 @@ var createLeaseInstallationFactory = (options) => {
2643
2782
  installations.set(scopeId, installation);
2644
2783
  return installation;
2645
2784
  };
2785
+ return Object.assign(open, {
2786
+ scopes: async () => [
2787
+ .../* @__PURE__ */ new Set([
2788
+ ...installations.keys(),
2789
+ ...await options.listScopes?.() ?? []
2790
+ ])
2791
+ ]
2792
+ });
2646
2793
  };
2647
2794
 
2648
2795
  // src/key-lease/scope-id/scope-id.ts
@@ -2669,12 +2816,29 @@ var deriveScopeId = (input) => {
2669
2816
  throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
2670
2817
  }
2671
2818
  }
2819
+ if (input.attribution.boundKeyId !== void 0) {
2820
+ if (input.folderRealpath === void 0)
2821
+ throw new TypeError("Bound keys require a worktree");
2822
+ if (input.attribution.boundScopeId !== void 0)
2823
+ return input.attribution.boundScopeId;
2824
+ identity = [
2825
+ ...identity,
2826
+ "binding",
2827
+ input.folderRealpath,
2828
+ input.attribution.orgId ?? "",
2829
+ input.attribution.boundKeyId
2830
+ ];
2831
+ }
2672
2832
  return createHash2("sha256").update(JSON.stringify(identity)).digest("hex");
2673
2833
  };
2674
2834
 
2675
2835
  // src/requested-client-id/requested-client-id.ts
2676
2836
  var DEFAULT_ROUTE33_CLIENT_ID = false ? "" : "oa_platform_203623de";
2677
2837
 
2838
+ // src/route33-runtime/route33-runtime.ts
2839
+ import { createHash as createHash3 } from "node:crypto";
2840
+ import { statSync as statSync2 } from "node:fs";
2841
+
2678
2842
  // src/catalog/gateway-model-ids/gateway-model-ids.ts
2679
2843
  var gatewayModelIds = async (deps) => {
2680
2844
  const { baseURL, gatewayKey, ...rest } = deps;
@@ -2688,8 +2852,9 @@ var gatewayModelIds = async (deps) => {
2688
2852
 
2689
2853
  // src/commands/change-attribution/change-attribution.ts
2690
2854
  var changeAttribution = async (options) => {
2691
- await options.clear();
2692
- return options.prompt();
2855
+ const choice = await options.prompt();
2856
+ await options.commit(choice);
2857
+ return choice;
2693
2858
  };
2694
2859
 
2695
2860
  // src/commands/inspect-session/inspect-session.ts
@@ -2698,6 +2863,7 @@ var inspectSession = (options) => {
2698
2863
  const lease = options.readLease();
2699
2864
  return {
2700
2865
  attribution,
2866
+ connected: options.connected,
2701
2867
  ...lease === void 0 ? {} : { lease: { expiresAt: lease.expiresAt, keyId: lease.keyId } }
2702
2868
  };
2703
2869
  };
@@ -2713,6 +2879,124 @@ var rotateNow = async (options) => {
2713
2879
  return rotated.lease;
2714
2880
  };
2715
2881
 
2882
+ // src/key-lease/workspace-key-binding/workspace-key-binding.ts
2883
+ import { mkdir as mkdir2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
2884
+ import { dirname as dirname4 } from "node:path";
2885
+ var ROTATION_WARNING = "This key will be rotated. Existing consumers will break. Continue?";
2886
+ var pending = /* @__PURE__ */ new Map();
2887
+ var WorkspaceKeyBinding = class {
2888
+ constructor(deps) {
2889
+ this.deps = deps;
2890
+ }
2891
+ deps;
2892
+ #listings = /* @__PURE__ */ new Map();
2893
+ /** @param choice - The budget selected by the user.
2894
+ * @returns Secret-free options; local options do not need destructive consent.
2895
+ */
2896
+ async candidates(choice) {
2897
+ const listing = this.#listings.get(choice.orgId) ?? this.listKeys(choice.orgId);
2898
+ this.#listings.set(choice.orgId, listing);
2899
+ const rows = await listing;
2900
+ const keys = rows.filter((row) => this.matches(row, choice));
2901
+ if (keys.length === 0) return [];
2902
+ const local = await this.localKeys(new Set(keys.map((row) => row.id)));
2903
+ return keys.map((row) => ({
2904
+ id: row.id,
2905
+ name: row.name,
2906
+ local: local.has(row.id)
2907
+ }));
2908
+ }
2909
+ async listKeys(orgId) {
2910
+ try {
2911
+ return (await this.deps.client.list(this.deps.token, orgId)).data;
2912
+ } catch {
2913
+ logger.warn(
2914
+ "Existing keys could not be listed; only new keys can be offered."
2915
+ );
2916
+ return [];
2917
+ }
2918
+ }
2919
+ matches(row, choice) {
2920
+ 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");
2921
+ }
2922
+ async localKeys(ids) {
2923
+ const found = /* @__PURE__ */ new Map();
2924
+ for (const scope of await this.deps.installations.scopes?.() ?? []) {
2925
+ const store = this.deps.installations(scope);
2926
+ const lease = await this.metadata(store);
2927
+ if (!lease || !ids.has(lease.keyId) || Date.parse(lease.expiresAt) <= this.deps.now)
2928
+ continue;
2929
+ const key = await store.secretStore.get();
2930
+ if (key && (await this.metadata(store))?.keyId === lease.keyId)
2931
+ found.set(lease.keyId, scope);
2932
+ }
2933
+ return found;
2934
+ }
2935
+ async metadata(store) {
2936
+ return await store.secretStore.getLease?.() ?? await store.stateStore?.get() ?? store.state.snapshot();
2937
+ }
2938
+ /** @param choice - Selected attribution; the live key must still belong to it.
2939
+ * @param id - Selected management key id, never its secret.
2940
+ * @param confirmed - Explicit consent to rotate this id if plaintext is unavailable.
2941
+ * @returns The attribution to commit after saving the secret.
2942
+ */
2943
+ async bind(choice, id, confirmed) {
2944
+ const row = await this.deps.client.get(this.deps.token, id, choice.orgId);
2945
+ if (row.id !== id || !this.matches(row, choice))
2946
+ throw new GatewayCredentialError(
2947
+ "This key is not available for the selected budget."
2948
+ );
2949
+ const file = resolveAttributionFile(this.deps.state);
2950
+ if (file === void 0)
2951
+ throw new GatewayCredentialError("Key binding requires a worktree.");
2952
+ const bound = { ...choice, boundKeyId: id };
2953
+ const scope = deriveScopeId({
2954
+ attribution: bound,
2955
+ folderRealpath: detectWorktreeRoot(this.deps.state.directory)
2956
+ });
2957
+ const marker = `${file}.${scope}.rotation`;
2958
+ const retry = pending.get(marker);
2959
+ const localScope = retry === void 0 ? (await this.localKeys(/* @__PURE__ */ new Set([id]))).get(id) : void 0;
2960
+ if (localScope !== void 0) return { ...bound, boundScopeId: localScope };
2961
+ const target = this.deps.installations(scope);
2962
+ const { key, lease } = retry ?? await this.rotate(bound, marker, confirmed);
2963
+ await target.secretStore.set(key, lease);
2964
+ await target.stateStore?.set(lease);
2965
+ target.state.compareAndSwap(target.state.snapshot(), lease);
2966
+ await rm2(marker, { force: true });
2967
+ pending.delete(marker);
2968
+ return bound;
2969
+ }
2970
+ async rotate(bound, marker, confirmed) {
2971
+ if (!confirmed) throw new GatewayCredentialError(ROTATION_WARNING);
2972
+ const id = bound.boundKeyId;
2973
+ await mkdir2(dirname4(marker), { recursive: true });
2974
+ try {
2975
+ await writeFile2(marker, "pending\n", { flag: "wx", mode: 384 });
2976
+ } catch (cause) {
2977
+ if (cause instanceof Error && "code" in cause && cause.code === "EEXIST")
2978
+ throw new GatewayCredentialError(
2979
+ "Rotation is already pending. Retry saving in the original session or choose a new key."
2980
+ );
2981
+ throw cause;
2982
+ }
2983
+ const rotated = await this.deps.client.regenerate(
2984
+ this.deps.token,
2985
+ id,
2986
+ void 0,
2987
+ bound.orgId
2988
+ );
2989
+ if (rotated.id !== id)
2990
+ throw new GatewayCredentialError("Rotation returned a different key.");
2991
+ const material = {
2992
+ key: rotated.key,
2993
+ lease: { attribution: bound, expiresAt: rotated.expires_at, keyId: id }
2994
+ };
2995
+ pending.set(marker, material);
2996
+ return material;
2997
+ }
2998
+ };
2999
+
2716
3000
  // src/ux/attribution-prompt/org-selection-prefix/org-selection-prefix.ts
2717
3001
  var orgSelectionPrefix = (orgId) => `org:${orgId}:`;
2718
3002
 
@@ -2732,6 +3016,8 @@ var createAttributionPrompt = (projects, options = {}) => {
2732
3016
  return `Personal \u2014 your own key${marker}${orgSuffix}`;
2733
3017
  };
2734
3018
  const budgetAllowance = (project) => {
3019
+ if (project.memberCap !== void 0)
3020
+ return `cap ${String(project.memberCap)} EUR`;
2735
3021
  const budget = project.effective_budget ?? project.max_budget;
2736
3022
  return budget === null ? "no cap set" : `cap ${budget.amount} ${budget.currency}`;
2737
3023
  };
@@ -2746,6 +3032,7 @@ var createAttributionPrompt = (projects, options = {}) => {
2746
3032
  };
2747
3033
  return {
2748
3034
  label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${budgetAllowance(project)}`,
3035
+ maximum: project.memberCap,
2749
3036
  selection
2750
3037
  };
2751
3038
  });
@@ -2765,6 +3052,7 @@ var createAttributionPrompt = (projects, options = {}) => {
2765
3052
  choicesBySelection[personal] = { kind: "personal", orgId: org.id };
2766
3053
  promptOptions.push({
2767
3054
  label: personalLabel(options.orgs.length > 1 ? org.name : void 0),
3055
+ maximum: org.personalBudget?.cap ?? void 0,
2768
3056
  selection: personal
2769
3057
  });
2770
3058
  }
@@ -2780,6 +3068,7 @@ var createAttributionPrompt = (projects, options = {}) => {
2780
3068
  };
2781
3069
  promptOptions.push({
2782
3070
  label: `${project.organisation.name} \xB7 ${project.name} \u2014 ${budgetAllowance(project)}`,
3071
+ maximum: project.memberCap,
2783
3072
  selection
2784
3073
  });
2785
3074
  }
@@ -2798,8 +3087,9 @@ var isPersonalSelection = (selection) => selection === "personal" || selection.e
2798
3087
 
2799
3088
  // src/ux/attribution-prompt-error/attribution-prompt-error.ts
2800
3089
  var MESSAGES = {
2801
- 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.",
2802
- ATTRIBUTION_SELECTION_INVALID: "That Route 33 option is no longer available. Connect again and pick another."
3090
+ ATTRIBUTION_BACK: "Left budget selection without changing attribution.",
3091
+ ATTRIBUTION_PRESENTER_UNAVAILABLE: "Update to OpenCode v2 to assign a Route 33 budget in this folder.",
3092
+ ATTRIBUTION_SELECTION_INVALID: "That Route 33 option is no longer available; choose another budget."
2803
3093
  };
2804
3094
  var AttributionPromptError = class extends GatewayCredentialError {
2805
3095
  code;
@@ -2811,8 +3101,9 @@ var AttributionPromptError = class extends GatewayCredentialError {
2811
3101
  };
2812
3102
 
2813
3103
  // src/ux/prompt-flow/prompt-flow.ts
3104
+ var BACK_SELECTION = "/back";
2814
3105
  var resolveAttribution = async (options) => {
2815
- const remembered = readAttribution(options.state);
3106
+ const remembered = options.state && readAttribution(options.state);
2816
3107
  if (remembered !== void 0) {
2817
3108
  return remembered;
2818
3109
  }
@@ -2820,12 +3111,16 @@ var resolveAttribution = async (options) => {
2820
3111
  throw new AttributionPromptError("ATTRIBUTION_PRESENTER_UNAVAILABLE");
2821
3112
  }
2822
3113
  const plan = createAttributionPrompt(await options.loadProjects());
2823
- const selection = await options.presenter.pick(plan);
3114
+ const selection = await options.presenter.pick({
3115
+ ...plan,
3116
+ options: [...plan.options, { label: "Back", selection: BACK_SELECTION }]
3117
+ });
3118
+ if (selection === BACK_SELECTION)
3119
+ throw new AttributionPromptError("ATTRIBUTION_BACK");
2824
3120
  const attribution = plan.choicesBySelection[selection];
2825
3121
  if (attribution === void 0) {
2826
3122
  throw new AttributionPromptError("ATTRIBUTION_SELECTION_INVALID");
2827
3123
  }
2828
- writeAttribution(options.state, attribution);
2829
3124
  return attribution;
2830
3125
  };
2831
3126
 
@@ -2843,6 +3138,66 @@ var CALLBACK_PAGE_COPY = {
2843
3138
  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."
2844
3139
  };
2845
3140
 
3141
+ // src/route33-runtime/enrich-inspection/enrich-inspection.ts
3142
+ var enrichInspection = async ({
3143
+ attribution,
3144
+ client,
3145
+ credential,
3146
+ keyId,
3147
+ subject
3148
+ }) => {
3149
+ const key = await client.get(credential, keyId);
3150
+ const orgId = key.org_id;
3151
+ if (attribution.orgId !== void 0 && attribution.orgId !== orgId) {
3152
+ return {};
3153
+ }
3154
+ const keyDetails = {
3155
+ name: key.name,
3156
+ organisationName: null,
3157
+ projectName: null
3158
+ };
3159
+ switch (attribution.kind) {
3160
+ case "personal": {
3161
+ if (key.project_id !== null) {
3162
+ return {};
3163
+ }
3164
+ return client.listBudgetPolicy(credential, subject(), orgId).then(
3165
+ ({ cap }) => cap === null ? { key: keyDetails } : {
3166
+ key: keyDetails,
3167
+ budget: { amount: String(cap), currency: null }
3168
+ }
3169
+ ).catch(() => ({ key: keyDetails }));
3170
+ }
3171
+ case "project": {
3172
+ const { projectId } = attribution;
3173
+ if (key.project_id !== projectId) {
3174
+ return {};
3175
+ }
3176
+ return Promise.all([
3177
+ client.listProjects(credential, orgId).then(
3178
+ ({ data }) => data.find(({ id, org_id }) => id === projectId && org_id === orgId)
3179
+ ).catch(() => void 0),
3180
+ client.listOrganizations(credential).then(({ data }) => data.find(({ id }) => id === orgId)?.name ?? null).catch(() => null)
3181
+ ]).then(([project, organisationName]) => {
3182
+ const title = project?.name.trim() ?? "";
3183
+ const budget = project?.effective_budget ?? project?.max_budget;
3184
+ return {
3185
+ key: {
3186
+ ...keyDetails,
3187
+ organisationName,
3188
+ projectName: title === "" ? null : title
3189
+ },
3190
+ ...budget == null ? {} : { budget }
3191
+ };
3192
+ });
3193
+ }
3194
+ default: {
3195
+ const unexpected = attribution;
3196
+ throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
3197
+ }
3198
+ }
3199
+ };
3200
+
2846
3201
  // src/route33-runtime/login-session/login-session.ts
2847
3202
  import { AuthError as AuthError2 } from "@r-33/auth-browser";
2848
3203
 
@@ -2853,7 +3208,7 @@ import {
2853
3208
  } from "@r-33/auth-browser";
2854
3209
 
2855
3210
  // src/requested-scopes/requested-scopes.ts
2856
- var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read profile projects:read users:read keys:read keys:write";
3211
+ var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read profile projects:read users:read keys:read keys:write models:read";
2857
3212
 
2858
3213
  // src/route33-login/route33-login.ts
2859
3214
  var route33Login = async (options) => {
@@ -2882,20 +3237,34 @@ var LoginSession = class {
2882
3237
  #options;
2883
3238
  #result;
2884
3239
  #expiresAt;
3240
+ #clears = 0;
2885
3241
  constructor(options) {
2886
3242
  this.#options = options;
2887
3243
  }
2888
3244
  /**
2889
3245
  * Clears the session: the cached login result and the stored refresh
2890
3246
  * token. The next login starts from scratch — /r33 logout and the
2891
- * auto-reconnect path both land here.
3247
+ * auto-reconnect path both land here. A refresh still on its way to the
3248
+ * auth server is disowned: its rotated token is never stored.
2892
3249
  * @returns Resolved once the session and the stored refresh token are gone.
2893
3250
  */
2894
3251
  async clear() {
3252
+ this.#clears += 1;
2895
3253
  this.#result = void 0;
2896
3254
  this.#expiresAt = void 0;
2897
3255
  await this.#options.tokenStore?.set(void 0);
2898
3256
  }
3257
+ /**
3258
+ * Whether a session exists, judged without using it: a login resolved or
3259
+ * in flight in this process, or a stored refresh token. Read-only — the
3260
+ * token is never presented, so asking cannot rotate or revoke anything.
3261
+ * @returns True when there is a session to sign in with.
3262
+ */
3263
+ async hasSession() {
3264
+ if (this.#result !== void 0) return true;
3265
+ const stored = await this.#options.tokenStore?.get().catch(() => void 0);
3266
+ return stored !== void 0 && stored !== "";
3267
+ }
2899
3268
  /**
2900
3269
  * Resolves the login once per process, sharing in-flight attempts.
2901
3270
  * @param policy - Whether this attempt may start a browser login; an in-flight attempt is always shared.
@@ -2904,11 +3273,15 @@ var LoginSession = class {
2904
3273
  result(policy = {}) {
2905
3274
  if (this.#result !== void 0 && this.#expiresAt !== void 0 && Date.now() >= this.#expiresAt - EXPIRY_SKEW_MS) {
2906
3275
  this.#result = void 0;
3276
+ this.#expiresAt = void 0;
3277
+ }
3278
+ if (this.#result === void 0) {
3279
+ const attempt = this.#start(policy).catch((cause) => {
3280
+ if (this.#result === attempt) this.#result = void 0;
3281
+ throw cause;
3282
+ });
3283
+ this.#result = attempt;
2907
3284
  }
2908
- this.#result ??= this.#start(policy).catch((cause) => {
2909
- this.#result = void 0;
2910
- throw cause;
2911
- });
2912
3285
  return this.#result;
2913
3286
  }
2914
3287
  /**
@@ -2938,6 +3311,7 @@ var LoginSession = class {
2938
3311
  if (tokenStore === void 0) {
2939
3312
  return void 0;
2940
3313
  }
3314
+ const clears = this.#clears;
2941
3315
  const stored = await tokenStore.get();
2942
3316
  if (stored === void 0 || stored === "") {
2943
3317
  return void 0;
@@ -2946,6 +3320,9 @@ var LoginSession = class {
2946
3320
  if (tokenSet === void 0) {
2947
3321
  return void 0;
2948
3322
  }
3323
+ if (clears !== this.#clears) {
3324
+ throw new AuthError2("AUTH_REAUTHENTICATION_REQUIRED");
3325
+ }
2949
3326
  let credential;
2950
3327
  try {
2951
3328
  credential = parseManagementJwt(tokenSet.access_token);
@@ -3079,7 +3456,7 @@ var Route33Runtime = class {
3079
3456
  const projectsById = new Map(
3080
3457
  listings.flatMap(({ data }) => data).map((project) => [project.id, project])
3081
3458
  );
3082
- return rows.flatMap(({ org_id, project_id }) => {
3459
+ return rows.flatMap(({ org_id, project_id, cap }) => {
3083
3460
  const project = projectsById.get(project_id);
3084
3461
  if (project === void 0) {
3085
3462
  return [];
@@ -3087,6 +3464,7 @@ var Route33Runtime = class {
3087
3464
  return [
3088
3465
  {
3089
3466
  ...project,
3467
+ memberCap: cap,
3090
3468
  organisation: {
3091
3469
  id: org_id,
3092
3470
  name: organisationNames.get(org_id) ?? org_id
@@ -3128,6 +3506,8 @@ var Route33Runtime = class {
3128
3506
  }
3129
3507
  const installation = this.#installation(attribution);
3130
3508
  await this.#hydrateState(installation);
3509
+ if (attribution.boundKeyId !== void 0)
3510
+ return this.#boundKey(installation, attribution.boundKeyId);
3131
3511
  const storedKey = await installation.secretStore.get();
3132
3512
  return reusableLease({
3133
3513
  attribution,
@@ -3185,24 +3565,14 @@ var Route33Runtime = class {
3185
3565
  commandHandlers() {
3186
3566
  return {
3187
3567
  "change-attribution": () => changeAttribution({
3188
- clear: () => {
3189
- clearAttribution(this.#options.state);
3568
+ commit: async (choice) => {
3569
+ await this.#leaseAttribution(choice, this.#options.policy);
3570
+ if (!writeAttribution(this.#options.state, choice))
3571
+ throw new TypeError("Workspace attribution requires a worktree");
3190
3572
  },
3191
- prompt: () => this.#resolveAttribution()
3573
+ prompt: () => this.pickAttribution()
3192
3574
  }),
3193
- "inspect-session": async () => {
3194
- try {
3195
- return await this.#inspectSession();
3196
- } catch {
3197
- return inspectSession({
3198
- readAttribution: () => readAttribution(this.#options.state),
3199
- readLease: () => {
3200
- const attribution = readAttribution(this.#options.state);
3201
- return attribution === void 0 ? void 0 : this.#installation(attribution).state.snapshot();
3202
- }
3203
- });
3204
- }
3205
- },
3575
+ "inspect-session": () => this.#inspectSession(),
3206
3576
  "reset-attribution": () => resetAttribution({
3207
3577
  clear: () => {
3208
3578
  clearAttribution(this.#options.state);
@@ -3214,53 +3584,67 @@ var Route33Runtime = class {
3214
3584
  })
3215
3585
  };
3216
3586
  }
3217
- /** Enriched session inspection: the plain report plus the key's name and organisation/project.
3587
+ /** Adds fresh display metadata without prompting for sign-in or changing attribution.
3218
3588
  * @returns A safe session report that cannot carry gateway plaintext.
3219
3589
  */
3220
3590
  async #inspectSession() {
3591
+ const attribution = readAttribution(this.#options.state);
3592
+ const installation = attribution === void 0 ? void 0 : this.#installation(attribution);
3593
+ if (installation !== void 0) {
3594
+ await this.#hydrateState(installation);
3595
+ }
3221
3596
  const base = inspectSession({
3222
- readAttribution: () => readAttribution(this.#options.state),
3223
- readLease: () => {
3224
- const attribution = readAttribution(this.#options.state);
3225
- return attribution === void 0 ? void 0 : this.#installation(attribution).state.snapshot();
3226
- }
3597
+ connected: await this.#session.hasSession(),
3598
+ readAttribution: () => attribution,
3599
+ readLease: () => installation?.state.snapshot()
3227
3600
  });
3228
3601
  const keyId = base.lease?.keyId;
3229
- if (keyId === void 0) {
3602
+ if (attribution === void 0 || keyId === void 0) {
3230
3603
  return base;
3231
3604
  }
3232
- const credential = await this.#session.credential();
3233
- const client = this.#client();
3234
- const [keys, projects] = await Promise.all([
3235
- client.list(credential).then((collection) => collection.data).catch(() => []),
3236
- this.listProjects().catch(() => [])
3237
- ]);
3238
- const key = keys.find((item) => item.id === keyId);
3239
- if (key === void 0) {
3605
+ const credential = await this.#session.credential({ allowBrowser: false }).catch(() => void 0);
3606
+ if (credential === void 0) return { ...base, connected: false };
3607
+ try {
3608
+ const details = await enrichInspection({
3609
+ attribution,
3610
+ client: this.#client(),
3611
+ credential,
3612
+ keyId,
3613
+ subject: () => this.#subject(credential)
3614
+ });
3615
+ return { ...base, ...details };
3616
+ } catch {
3240
3617
  return base;
3241
3618
  }
3242
- const projectId = key.project_id ?? null;
3243
- const project = projectId === null ? void 0 : projects.find((item) => item.id === projectId);
3244
- return {
3245
- ...base,
3246
- key: {
3247
- name: key.name,
3248
- organisationName: project?.organisation.name ?? null,
3249
- projectName: project?.name ?? null
3250
- }
3251
- };
3252
3619
  }
3253
3620
  /**
3254
- * Lists the gateway catalog's model ids under the current stored key —
3255
- * the connect form's allowed-models picker offers exactly these.
3256
- * @returns Catalog model ids, empty while no key or catalog exists.
3621
+ * Lists the models a key on this budget may be limited to. Never opens a
3622
+ * browser; an organisation-level (personal) catalog needs the `models:read`
3623
+ * grant, so sessions signed in before that grant reject here.
3624
+ * @param scope - The budget being configured.
3625
+ * @returns Key-facing model ids with their readable names.
3257
3626
  */
3258
- async catalogModelIds() {
3627
+ async catalogModelChoices(scope) {
3628
+ const credential = await this.#session.credential({ allowBrowser: false });
3629
+ return this.#client().listModelChoices(credential, scope);
3630
+ }
3631
+ /**
3632
+ * @param scope - The budget being configured. Omit to discover models for the current key.
3633
+ * @returns The management catalog for a budget, or the current key's gateway catalog.
3634
+ */
3635
+ async catalogModelIds(scope) {
3636
+ if (scope !== void 0) {
3637
+ return (await this.catalogModelChoices(scope)).map(({ id }) => id);
3638
+ }
3259
3639
  const workspace = await this.storedReusableKey();
3260
3640
  const personal = workspace === void 0 ? await this.#storedPersonalKey() : void 0;
3261
3641
  const value = workspace?.key.value ?? personal?.value;
3262
3642
  if (value === void 0) {
3263
- return [];
3643
+ const credential = await this.#session.credential({
3644
+ allowBrowser: false
3645
+ });
3646
+ const choices = await this.#client().listModelChoices(credential, {});
3647
+ return choices.map(({ id }) => id);
3264
3648
  }
3265
3649
  return gatewayModelIds({
3266
3650
  baseURL: readEnvBaseUrl() ?? DEFAULT_BASE_URL,
@@ -3279,12 +3663,41 @@ var Route33Runtime = class {
3279
3663
  * @param attribution - The budget the wizard selected.
3280
3664
  * @param extras - The wizard's key-creation answers.
3281
3665
  * @param directory - Optional worktree override for project leases.
3666
+ * @param saveAttribution - Wizard save that must succeed before replacing a live key.
3282
3667
  * @returns The fresh key material with its lease metadata.
3283
3668
  */
3284
- async mintWorkspaceKey(attribution, extras, directory = this.#options.state.directory) {
3669
+ async mintWorkspaceKey(attribution, extras, directory = this.#options.state.directory, saveAttribution) {
3670
+ const file = resolveAttributionFile({ ...this.#options.state, directory });
3671
+ if (file === void 0)
3672
+ throw new TypeError("Workspace attribution requires a worktree");
3673
+ const previous = statSync2(file, { bigint: true, throwIfNoEntry: false });
3674
+ const wizardRequest = createHash3("sha256").update(
3675
+ JSON.stringify([
3676
+ file,
3677
+ previous?.ino.toString(),
3678
+ previous?.mtimeNs.toString(),
3679
+ attribution,
3680
+ extras,
3681
+ this.#subject(await this.#session.credential())
3682
+ ])
3683
+ ).digest("hex");
3285
3684
  return this.#leaseAttribution(attribution, void 0, directory, {
3286
3685
  extras,
3287
- forceMint: true
3686
+ forceMint: true,
3687
+ wizardRequest,
3688
+ saveAttribution
3689
+ });
3690
+ }
3691
+ /** @returns Binding operations restricted to the current management identity. */
3692
+ async workspaceKeyBinding() {
3693
+ const token = await this.#session.credential({ allowBrowser: false });
3694
+ return new WorkspaceKeyBinding({
3695
+ installations: this.#options.installation,
3696
+ token,
3697
+ subject: this.#subject(token),
3698
+ client: this.#client(),
3699
+ now: this.#now(),
3700
+ state: this.#options.state
3288
3701
  });
3289
3702
  }
3290
3703
  /**
@@ -3302,7 +3715,7 @@ var Route33Runtime = class {
3302
3715
  if (attribution === void 0) {
3303
3716
  return void 0;
3304
3717
  }
3305
- const lease = this.#installation(attribution).state.snapshot();
3718
+ const lease = this.#installation(attribution, directory).state.snapshot();
3306
3719
  const keyId = lease?.keyId;
3307
3720
  if (keyId === void 0) {
3308
3721
  return void 0;
@@ -3312,6 +3725,29 @@ var Route33Runtime = class {
3312
3725
  const key = keys.find((item) => item.id === keyId);
3313
3726
  return key === void 0 ? void 0 : { allowedModels: key.allowed_models };
3314
3727
  }
3728
+ /** V1 captures only the choice, not the plan; read only that owner's policy.
3729
+ * @param choice - The selected budget and its active organisation.
3730
+ * @returns The effective EUR cap, if the owner has a readable allowance.
3731
+ */
3732
+ async ownerBudgetCap(choice) {
3733
+ const token = await this.#session.credential({ allowBrowser: false });
3734
+ const subject = this.#subject(token);
3735
+ const client = this.#client();
3736
+ if (choice.kind === "personal") {
3737
+ const policy = await client.listBudgetPolicy(
3738
+ token,
3739
+ subject,
3740
+ choice.orgId
3741
+ );
3742
+ return policy.cap ?? void 0;
3743
+ }
3744
+ const budgets = await client.listProjectBudgets(
3745
+ token,
3746
+ subject,
3747
+ choice.orgId
3748
+ );
3749
+ return budgets.data.find((row) => row.project_id === choice.projectId)?.cap;
3750
+ }
3315
3751
  #client() {
3316
3752
  const client = this.#options.management.client;
3317
3753
  if (typeof client !== "function") {
@@ -3330,23 +3766,33 @@ var Route33Runtime = class {
3330
3766
  #now() {
3331
3767
  return (this.#options.clock ?? Date.now)();
3332
3768
  }
3333
- async #resolveAttribution() {
3769
+ /** @returns A fresh selection without changing the active budget. */
3770
+ pickAttribution() {
3334
3771
  return resolveAttribution({
3335
3772
  loadProjects: async () => {
3336
3773
  await this.#session.credential();
3337
3774
  return this.listMintableProjects();
3338
3775
  },
3339
- ...this.#options.presenter === void 0 ? {} : { presenter: this.#options.presenter },
3340
- state: this.#options.state
3776
+ ...this.#options.presenter === void 0 ? {} : { presenter: this.#options.presenter }
3341
3777
  });
3342
3778
  }
3343
3779
  async #lease(policy) {
3344
- const attribution = await this.#resolveAttribution();
3345
- return this.#leaseAttribution(attribution, policy);
3780
+ const remembered = readAttribution(this.#options.state);
3781
+ if (remembered !== void 0)
3782
+ return this.#leaseAttribution(remembered, policy);
3783
+ const choice = await this.pickAttribution();
3784
+ const leased = await this.#leaseAttribution(choice, policy);
3785
+ writeAttribution(this.#options.state, choice);
3786
+ return leased;
3346
3787
  }
3347
3788
  async #leaseAttribution(attribution, policy, directory = this.#options.state.directory, request) {
3348
3789
  const installation = this.#installation(attribution, directory);
3349
3790
  await this.#hydrateState(installation);
3791
+ if (attribution.boundKeyId !== void 0) {
3792
+ if (policy?.renewalRatio === Number.EPSILON)
3793
+ throw new TypeError("Automatic rotation is disabled for a shared key.");
3794
+ return this.#boundKey(installation, attribution.boundKeyId);
3795
+ }
3350
3796
  const minted = await leaseForAttribution({
3351
3797
  attribution,
3352
3798
  ...this.#options.clock === void 0 ? {} : { clock: this.#options.clock },
@@ -3362,13 +3808,20 @@ var Route33Runtime = class {
3362
3808
  await this.#persistState(installation, minted.lease);
3363
3809
  return minted;
3364
3810
  }
3811
+ async #boundKey(installation, id) {
3812
+ const key = await installation.secretStore.get();
3813
+ const lease = await installation.secretStore.getLease?.() ?? await installation.stateStore?.get() ?? installation.state.snapshot();
3814
+ if (!key || lease?.keyId !== id || Date.parse(lease.expiresAt) <= this.#now())
3815
+ throw new KeyLeaseError("KEY_LEASE_EXPIRED");
3816
+ return { key, lease };
3817
+ }
3365
3818
  async #hydrateState(installation) {
3366
3819
  const store = installation.stateStore;
3367
- if (store === void 0 || installation.state.snapshot() !== void 0) {
3820
+ if (installation.state.snapshot() !== void 0) {
3368
3821
  return;
3369
3822
  }
3370
3823
  try {
3371
- const persisted = await store.get();
3824
+ const persisted = await installation.secretStore.getLease?.() ?? await store?.get();
3372
3825
  if (persisted !== void 0) {
3373
3826
  installation.state.compareAndSwap(void 0, persisted);
3374
3827
  }
@@ -3382,6 +3835,13 @@ var Route33Runtime = class {
3382
3835
  }
3383
3836
  }
3384
3837
  #installation(attribution, directory = this.#options.state.directory) {
3838
+ if (attribution.boundKeyId !== void 0)
3839
+ return this.#options.installation(
3840
+ deriveScopeId({
3841
+ attribution,
3842
+ folderRealpath: detectWorktreeRoot(directory)
3843
+ })
3844
+ );
3385
3845
  switch (attribution.kind) {
3386
3846
  case "personal":
3387
3847
  return this.#options.installation(deriveScopeId({ attribution }));
@@ -3403,15 +3863,14 @@ var Route33Runtime = class {
3403
3863
  };
3404
3864
 
3405
3865
  // src/v1-entry/unattributed-prompt-gate/unattributed-prompt-gate.ts
3406
- var createUnattributedPromptGate = ({ directory, outsideWorktree }) => (input) => {
3866
+ var CONNECTION_COPY = "To sign in, run /connect and choose Route 33.";
3867
+ var ATTRIBUTION_COPY = "This folder has no Route 33 budget; open /r33 and choose Change budget.";
3868
+ var createUnattributedPromptGate = ({ directory, isConnected, outsideWorktree }) => async (input) => {
3407
3869
  if (input.model?.providerID !== "route_33") return Promise.resolve();
3870
+ if (!await isConnected()) throw new Error(CONNECTION_COPY);
3408
3871
  const attribution = readAttribution({ directory, outsideWorktree });
3409
3872
  if (attribution !== void 0) return Promise.resolve();
3410
- return Promise.reject(
3411
- new Error(
3412
- "Route 33 needs a budget for this folder first \u2014 run /r33 in OpenCode, choose Route 33, and assign a budget."
3413
- )
3414
- );
3873
+ throw new Error(ATTRIBUTION_COPY);
3415
3874
  };
3416
3875
 
3417
3876
  // src/v1-entry/workspace-key-headers/workspace-key-headers.ts
@@ -3438,6 +3897,11 @@ var createRoute33Plugin = (options = {}) => {
3438
3897
  };
3439
3898
  const runtimeOptions = options.runtime;
3440
3899
  const installation = runtimeOptions === void 0 ? void 0 : runtimeOptions.installation ?? createLeaseInstallationFactory({
3900
+ listScopes: () => FileSecretStore.scopes(
3901
+ resolveV1SecretStoreDirectory({
3902
+ directory: options.secretStoreDirectory
3903
+ })
3904
+ ),
3441
3905
  createSecretStore: (scopeId) => new FileSecretStore({
3442
3906
  directory: resolveV1SecretStoreDirectory({
3443
3907
  ...options.secretStoreDirectory === void 0 ? {} : { directory: options.secretStoreDirectory }
@@ -3483,6 +3947,14 @@ var createRoute33Plugin = (options = {}) => {
3483
3947
  });
3484
3948
  promptGate = createUnattributedPromptGate({
3485
3949
  directory: input.worktree,
3950
+ isConnected: async () => {
3951
+ try {
3952
+ await runtime2.login({ allowBrowser: false });
3953
+ return true;
3954
+ } catch {
3955
+ return false;
3956
+ }
3957
+ },
3486
3958
  outsideWorktree: "return-undefined"
3487
3959
  });
3488
3960
  }
@@ -3514,12 +3986,6 @@ var drainPages = async (fetchPage) => {
3514
3986
  return { data, page: { ...page, has_more: false, next_cursor: null } };
3515
3987
  };
3516
3988
 
3517
- // src/management/sdk-management-keys/sdk-management-keys.ts
3518
- import {
3519
- createRoute33Client,
3520
- Route33SdkError
3521
- } from "@r-33/sdk";
3522
-
3523
3989
  // src/contract/management-keys/parse-api-key/parse-api-key.ts
3524
3990
  var parseApiKey = (value) => {
3525
3991
  if (!isRecord(value) || !isOwnerType(value["ownership_type"]) || !isNullableString(value["project_id"])) {
@@ -3545,6 +4011,7 @@ var parseApiKey = (value) => {
3545
4011
  name: field("name"),
3546
4012
  org_id: field("org_id"),
3547
4013
  ownership_type: value["ownership_type"],
4014
+ ...isNullableString(value["user_id"]) ? { user_id: value["user_id"] } : {},
3548
4015
  project_id: value["project_id"],
3549
4016
  revoked: value["revoked"] === true,
3550
4017
  status
@@ -3780,6 +4247,44 @@ var parseUserMemberships = (value) => {
3780
4247
  };
3781
4248
  };
3782
4249
 
4250
+ // src/management/key-read-operations/key-read-operations.ts
4251
+ var keyReadOperations = (call) => {
4252
+ const withCursor = (cursor) => ({ request }) => {
4253
+ const url = new URL(request.url);
4254
+ url.searchParams.set("cursor", cursor);
4255
+ return new Request(url, request);
4256
+ };
4257
+ const parsePage = (page) => {
4258
+ const collection = parseCollection(page, (row) => row);
4259
+ const data = collection.data.flatMap((row) => {
4260
+ try {
4261
+ return [parseApiKey(row)];
4262
+ } catch (error) {
4263
+ if (error instanceof ContractParseError) return [];
4264
+ throw error;
4265
+ }
4266
+ });
4267
+ return { ...collection, data };
4268
+ };
4269
+ return {
4270
+ get: async (accessToken, id, orgId) => parseApiKey(
4271
+ await call(
4272
+ accessToken,
4273
+ orgId,
4274
+ (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
4275
+ params: { path: { api_key_id: id } }
4276
+ })
4277
+ )
4278
+ ),
4279
+ list: (accessToken, orgId) => drainPages(
4280
+ (cursor) => call(accessToken, orgId, (client) => {
4281
+ if (cursor !== "") client.use({ onRequest: withCursor(cursor) });
4282
+ return client.GET("/api/v1/api-keys", {});
4283
+ }).then(parsePage)
4284
+ )
4285
+ };
4286
+ };
4287
+
3783
4288
  // src/management/sdk-management-keys/mint-request-body/mint-request-body.ts
3784
4289
  var buildMintRequestBody = (input) => ({
3785
4290
  ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
@@ -3793,10 +4298,183 @@ var buildMintRequestBody = (input) => ({
3793
4298
  ...input.projectId === null ? {} : { project_id: input.projectId }
3794
4299
  });
3795
4300
 
3796
- // src/management/sdk-management-keys/sdk-management-keys.ts
4301
+ // src/management/key-write-operations/key-write-operations.ts
4302
+ var keyWriteOperations = (call) => ({
4303
+ create: async (accessToken, input) => parseKeyMaterial(
4304
+ await call(
4305
+ accessToken,
4306
+ input.activeOrgId,
4307
+ (client) => client.POST("/api/v1/api-keys", {
4308
+ body: buildMintRequestBody(input)
4309
+ })
4310
+ )
4311
+ ),
4312
+ delete: async (accessToken, id) => {
4313
+ await call(
4314
+ accessToken,
4315
+ void 0,
4316
+ (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
4317
+ params: { path: { api_key_id: id } }
4318
+ })
4319
+ );
4320
+ },
4321
+ regenerate: async (accessToken, id, expiresAt, orgId) => parseKeyMaterial(
4322
+ await call(
4323
+ accessToken,
4324
+ orgId,
4325
+ (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
4326
+ body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
4327
+ params: { path: { api_key_id: id } }
4328
+ })
4329
+ )
4330
+ ),
4331
+ update: async (accessToken, id, input) => parseApiKey(
4332
+ await call(
4333
+ accessToken,
4334
+ void 0,
4335
+ (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
4336
+ body: {
4337
+ budget_currency: "EUR",
4338
+ ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
4339
+ ...input.name === void 0 ? {} : { name: input.name }
4340
+ },
4341
+ params: { path: { api_key_id: id } }
4342
+ })
4343
+ )
4344
+ )
4345
+ });
4346
+
4347
+ // src/management/client-model-id/client-model-id.ts
4348
+ var clientModelId = (offeringId) => {
4349
+ const [provider, region, scope, vendor, ...modelParts] = offeringId.split(":");
4350
+ const slugParts = modelParts.at(-1) === "zdr" ? modelParts.slice(0, -1) : modelParts;
4351
+ const parts = [provider, region, scope, vendor, slugParts.join(":")];
4352
+ return parts.some((part) => part === void 0 || part === "") || /[\s,]/u.test(offeringId) ? void 0 : `${vendor ?? ""}/${slugParts.join(":")}`;
4353
+ };
4354
+
4355
+ // src/management/exposed-catalog-models/catalog-row-choices/catalog-row-choices.ts
4356
+ var catalogRowChoices = (row) => {
4357
+ if (!isRecord(row) || typeof row.id !== "string" || !row.id.trim() || typeof row.status !== "string")
4358
+ throw new ContractParseError("invalid model catalog item");
4359
+ if (row.status !== "exposed" || !Array.isArray(row.offerings)) return [];
4360
+ const label = typeof row.name === "string" && row.name.trim() !== "" ? row.name.trim() : void 0;
4361
+ return row.offerings.flatMap((offering) => {
4362
+ if (!isRecord(offering) || typeof offering.id !== "string" || offering.enabled !== true)
4363
+ return [];
4364
+ const id = clientModelId(offering.id);
4365
+ return id === void 0 ? [] : [{ id, name: label ?? id }];
4366
+ });
4367
+ };
4368
+
4369
+ // src/management/exposed-catalog-models/exposed-catalog-models.ts
4370
+ var exposedCatalogModels = async (readPage) => {
4371
+ const readRows = async (offset2) => {
4372
+ const page = await readPage(offset2);
4373
+ if (!isRecord(page) || !Array.isArray(page.models) || page.offset !== offset2 || typeof page.total !== "number" || !Number.isSafeInteger(page.total) || page.total < 0) {
4374
+ throw new ContractParseError("invalid model catalog page");
4375
+ }
4376
+ return { rows: page.models, total: page.total };
4377
+ };
4378
+ const names = /* @__PURE__ */ new Map();
4379
+ let offset = 0;
4380
+ for (; ; ) {
4381
+ const { rows, total } = await readRows(offset);
4382
+ for (const { id, name } of rows.flatMap(catalogRowChoices)) {
4383
+ names.set(id, name);
4384
+ }
4385
+ offset += rows.length;
4386
+ if (offset >= total || rows.length === 0) break;
4387
+ }
4388
+ return [...names].map(([id, name]) => ({ id, name })).sort(
4389
+ (left, right) => left.name.localeCompare(right.name) || left.id.localeCompare(right.id)
4390
+ );
4391
+ };
4392
+
4393
+ // src/management/model-catalog-operations/model-catalog-operations.ts
4394
+ var modelCatalogOperations = (call) => ({
4395
+ listModelChoices: (token, { orgId, projectId }) => exposedCatalogModels(
4396
+ (offset) => call(token, orgId, (client) => {
4397
+ const query = { offset };
4398
+ if (projectId !== void 0)
4399
+ return client.GET("/api/v1/projects/{project_id}/model-catalog", {
4400
+ params: { path: { project_id: projectId }, query }
4401
+ });
4402
+ if (orgId !== void 0)
4403
+ return client.GET("/api/v1/orgs/{org_id}/model-catalog", {
4404
+ params: { path: { org_id: orgId }, query }
4405
+ });
4406
+ return client.GET("/api/v1/model-catalog", { params: { query } });
4407
+ })
4408
+ )
4409
+ });
4410
+
4411
+ // src/management/list-sdk-projects/list-sdk-projects.ts
4412
+ var listSdkProjects = async (accessToken, organisationId, call) => {
4413
+ if (organisationId.trim().length === 0) {
4414
+ throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
4415
+ statusCode: 400
4416
+ });
4417
+ }
4418
+ const query = {
4419
+ member_user_id: parseManagementSubject(accessToken),
4420
+ org_id: organisationId
4421
+ };
4422
+ const fetchPage = (cursor) => call(
4423
+ accessToken,
4424
+ void 0,
4425
+ (client) => client.GET("/api/v1/projects", {
4426
+ params: {
4427
+ query: cursor === "" ? query : { ...query, cursor }
4428
+ }
4429
+ })
4430
+ ).then((page) => parseCollection(page, parseProject));
4431
+ return drainPages(fetchPage);
4432
+ };
4433
+
4434
+ // src/management/organization-operations/organization-operations.ts
4435
+ var organizationOperations = (call) => ({
4436
+ listOrganizations: async (accessToken) => parseCollection(
4437
+ await call(
4438
+ accessToken,
4439
+ void 0,
4440
+ (client) => client.GET("/api/v1/orgs", {})
4441
+ ),
4442
+ parseOrganization
4443
+ ),
4444
+ listProjects: (accessToken, organisationId) => listSdkProjects(accessToken, organisationId, call)
4445
+ });
4446
+
4447
+ // src/management/sdk-management-call/sdk-management-call.ts
4448
+ import {
4449
+ createRoute33Client,
4450
+ Route33SdkError
4451
+ } from "@r-33/sdk";
4452
+
4453
+ // src/management/sdk-management-call/rejection-of/rejection-of.ts
4454
+ var REFUSED = 422;
4455
+ var REJECTION_MAX_LENGTH = 200;
4456
+ var CONTROL = /\p{Cc}+/gu;
4457
+ var SECRET_PREFIXES = ["r33_", "eyj", "bearer "];
4458
+ var OPAQUE_MIN_LENGTH = 20;
4459
+ var rejectionOf = (outcome) => {
4460
+ const body = outcome.error;
4461
+ if (outcome.response?.status !== REFUSED || !isRecord(body)) return void 0;
4462
+ const raw = body["error"];
4463
+ if (typeof raw !== "string" || raw.length > REJECTION_MAX_LENGTH) {
4464
+ return void 0;
4465
+ }
4466
+ const sentence = raw.replaceAll(CONTROL, " ").replaceAll(/\s+/gu, " ").trim();
4467
+ const lower = sentence.toLowerCase();
4468
+ const secretShaped = SECRET_PREFIXES.some((prefix) => lower.includes(prefix)) || lower.split(" ").some(
4469
+ (word) => word.length >= OPAQUE_MIN_LENGTH && /\d/u.test(word) && /[a-z]/u.test(word)
4470
+ );
4471
+ return sentence === "" || secretShaped ? void 0 : sentence;
4472
+ };
4473
+
4474
+ // src/management/sdk-management-call/sdk-management-call.ts
3797
4475
  var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
3798
4476
  var ACTIVE_ORG_HEADER = "X-Active-Org-Id";
3799
- var sdkManagementKeys = (options) => {
4477
+ var createSdkCall = (options) => {
3800
4478
  const baseUrl = options.apiBaseUrl.replace(API_PREFIX_PATTERN, "");
3801
4479
  const timeoutMs = options.timeoutMs ?? 1e4;
3802
4480
  const fetchImpl = options.fetchImpl;
@@ -3835,14 +4513,18 @@ var sdkManagementKeys = (options) => {
3835
4513
  }
3836
4514
  return new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
3837
4515
  };
3838
- const call = async (accessToken, activeOrgId, run) => {
4516
+ return async (accessToken, activeOrgId, run) => {
3839
4517
  try {
3840
4518
  const outcome = await run(callClient(accessToken, activeOrgId));
3841
4519
  const code = outcome.response?.status;
3842
4520
  if (code === void 0 || code < 200 || code >= 300) {
4521
+ const rejection = rejectionOf(outcome);
3843
4522
  throw new ManagementError(
3844
4523
  code === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
3845
- { statusCode: code }
4524
+ {
4525
+ ...rejection === void 0 ? {} : { rejection },
4526
+ statusCode: code
4527
+ }
3846
4528
  );
3847
4529
  }
3848
4530
  return outcome.data;
@@ -3850,123 +4532,49 @@ var sdkManagementKeys = (options) => {
3850
4532
  throw mapFailure(cause);
3851
4533
  }
3852
4534
  };
3853
- return {
3854
- create: async (accessToken, input) => parseKeyMaterial(
3855
- await call(
3856
- accessToken,
3857
- input.activeOrgId,
3858
- (client) => client.POST("/api/v1/api-keys", {
3859
- body: buildMintRequestBody(input)
3860
- })
3861
- )
3862
- ),
3863
- delete: async (accessToken, id) => {
3864
- await call(
3865
- accessToken,
3866
- void 0,
3867
- (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
3868
- params: { path: { api_key_id: id } }
3869
- })
3870
- );
3871
- },
3872
- get: async (accessToken, id) => parseApiKey(
3873
- await call(
3874
- accessToken,
3875
- void 0,
3876
- (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
3877
- params: { path: { api_key_id: id } }
3878
- })
3879
- )
3880
- ),
3881
- list: async (accessToken) => parseCollection(
3882
- await call(
3883
- accessToken,
3884
- void 0,
3885
- (client) => client.GET("/api/v1/api-keys", {})
3886
- ),
3887
- parseApiKey
3888
- ),
3889
- listOrganizations: async (accessToken) => parseCollection(
3890
- await call(
3891
- accessToken,
3892
- void 0,
3893
- (client) => client.GET("/api/v1/orgs", {})
3894
- ),
3895
- parseOrganization
3896
- ),
3897
- listMemberships: async (accessToken, userId) => parseUserMemberships(
3898
- await call(
3899
- accessToken,
3900
- void 0,
3901
- (client) => client.GET("/api/v1/users/{user_id}/memberships", {
3902
- params: { path: { user_id: userId } }
3903
- })
3904
- )
3905
- ),
3906
- listBudgetPolicy: async (accessToken, userId, activeOrgId) => parseBudgetPolicy(
3907
- await call(
3908
- accessToken,
3909
- activeOrgId,
3910
- (client) => client.GET("/api/v1/users/{user_id}/budget-policy", {
3911
- params: { path: { user_id: userId } }
3912
- })
3913
- )
3914
- ),
3915
- listProjectBudgets: async (accessToken, userId, activeOrgId) => parseCollection(
3916
- await call(
3917
- accessToken,
3918
- activeOrgId,
3919
- (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
3920
- params: { path: { user_id: userId } }
3921
- })
3922
- ),
3923
- parseProjectBudgetState
3924
- ),
3925
- listProjects: async (accessToken, organisationId) => {
3926
- if (organisationId.trim().length === 0) {
3927
- throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
3928
- statusCode: 400
3929
- });
3930
- }
3931
- const query = {
3932
- member_user_id: parseManagementSubject(accessToken),
3933
- org_id: organisationId
3934
- };
3935
- const fetchPage = (cursor) => call(
3936
- accessToken,
3937
- void 0,
3938
- (client) => client.GET("/api/v1/projects", {
3939
- params: {
3940
- query: cursor === "" ? query : { ...query, cursor }
3941
- }
3942
- })
3943
- ).then((page) => parseCollection(page, parseProject));
3944
- return drainPages(fetchPage);
3945
- },
3946
- regenerate: async (accessToken, id, expiresAt) => parseKeyMaterial(
3947
- await call(
3948
- accessToken,
3949
- void 0,
3950
- (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
3951
- body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
3952
- params: { path: { api_key_id: id } }
3953
- })
3954
- )
3955
- ),
3956
- update: async (accessToken, id, input) => parseApiKey(
3957
- await call(
3958
- accessToken,
3959
- void 0,
3960
- (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
3961
- body: {
3962
- budget_currency: "EUR",
3963
- ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
3964
- ...input.name === void 0 ? {} : { name: input.name }
3965
- },
3966
- params: { path: { api_key_id: id } }
3967
- })
3968
- )
4535
+ };
4536
+
4537
+ // src/management/user-context-operations/user-context-operations.ts
4538
+ var userContextOperations = (call) => ({
4539
+ listMemberships: async (accessToken, userId) => parseUserMemberships(
4540
+ await call(
4541
+ accessToken,
4542
+ void 0,
4543
+ (client) => client.GET("/api/v1/users/{user_id}/memberships", {
4544
+ params: { path: { user_id: userId } }
4545
+ })
4546
+ )
4547
+ ),
4548
+ listBudgetPolicy: async (accessToken, userId, activeOrgId) => parseBudgetPolicy(
4549
+ await call(
4550
+ accessToken,
4551
+ activeOrgId,
4552
+ (client) => client.GET("/api/v1/users/{user_id}/budget-policy", {
4553
+ params: { path: { user_id: userId } }
4554
+ })
3969
4555
  )
4556
+ ),
4557
+ listProjectBudgets: async (accessToken, userId, activeOrgId) => parseCollection(
4558
+ await call(
4559
+ accessToken,
4560
+ activeOrgId,
4561
+ (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
4562
+ params: { path: { user_id: userId } }
4563
+ })
4564
+ ),
4565
+ parseProjectBudgetState
4566
+ )
4567
+ });
4568
+
4569
+ // src/management/sdk-management-keys/sdk-management-keys.ts
4570
+ var sdkManagementKeys = (options) => {
4571
+ const call = createSdkCall(options);
4572
+ return {
4573
+ ...keyReadOperations(call),
4574
+ ...keyWriteOperations(call),
4575
+ ...modelCatalogOperations(call),
4576
+ ...organizationOperations(call),
4577
+ ...userContextOperations(call)
3970
4578
  };
3971
4579
  };
3972
4580
 
@@ -4278,6 +4886,7 @@ var Route33Plugin = async (input) => {
4278
4886
  };
4279
4887
  export {
4280
4888
  AttributionPromptError,
4889
+ BACK_SELECTION,
4281
4890
  CALLBACK_PAGE_COPY,
4282
4891
  ContractParseError,
4283
4892
  DEFAULT_GATEWAY_KEY_RENEWAL_RATIO,