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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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);
1791
2081
  try {
1792
- await fs6.writeFile(temporary, `${JSON.stringify(key.value)}
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`);
2096
+ try {
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
 
@@ -1998,9 +2336,35 @@ var buildMintInput = (deps) => {
1998
2336
  };
1999
2337
  };
2000
2338
 
2339
+ // src/key-lease/commit-staged-replacement/commit-staged-replacement.ts
2340
+ var commitStagedReplacement = async (stage, save, persist) => {
2341
+ const storeFailure = (cause) => {
2342
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
2343
+ };
2344
+ const staged = await stage().catch(storeFailure);
2345
+ try {
2346
+ save();
2347
+ await (staged ? staged.commit() : persist()).catch(storeFailure);
2348
+ } finally {
2349
+ await staged?.discard();
2350
+ }
2351
+ };
2352
+
2001
2353
  // src/key-lease/mint-fresh-lease/mint-fresh-lease.ts
2002
2354
  var mintFreshLease = async (deps) => {
2003
2355
  const now = deps.clock();
2356
+ const current = deps.state.snapshot();
2357
+ const reusable = () => {
2358
+ if (deps.wizardRequest !== void 0 && current?.wizardRequest === deps.wizardRequest && deps.storedKey !== void 0 && Date.parse(current.expiresAt) > now) {
2359
+ return { key: deps.storedKey, lease: current };
2360
+ }
2361
+ return void 0;
2362
+ };
2363
+ const reused = reusable();
2364
+ if (reused !== void 0) {
2365
+ deps.saveAttribution?.();
2366
+ return reused;
2367
+ }
2004
2368
  const input = buildMintInput({
2005
2369
  attribution: deps.attribution,
2006
2370
  extras: deps.extras,
@@ -2023,13 +2387,23 @@ var mintFreshLease = async (deps) => {
2023
2387
  lease: {
2024
2388
  attribution: deps.attribution,
2025
2389
  expiresAt: material.expires_at,
2026
- keyId: material.id
2390
+ keyId: material.id,
2391
+ ...deps.wizardRequest === void 0 ? {} : { wizardRequest: deps.wizardRequest }
2027
2392
  }
2028
2393
  };
2029
- try {
2030
- await deps.secretStore.set(minted.key);
2031
- } catch (cause) {
2394
+ const storeFailure = (cause) => {
2032
2395
  throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
2396
+ };
2397
+ const persist = () => deps.secretStore.set(minted.key, minted.lease);
2398
+ if (deps.saveAttribution && deps.storedKey !== void 0) {
2399
+ await commitStagedReplacement(
2400
+ () => deps.secretStore.stage?.(minted.key, minted.lease) ?? Promise.resolve(void 0),
2401
+ deps.saveAttribution,
2402
+ persist
2403
+ );
2404
+ } else {
2405
+ await persist().catch(storeFailure);
2406
+ deps.saveAttribution?.();
2033
2407
  }
2034
2408
  deps.state.compareAndSwap(deps.state.snapshot(), minted.lease);
2035
2409
  return minted;
@@ -2206,7 +2580,7 @@ var renewKey = async (options) => {
2206
2580
  }
2207
2581
  }
2208
2582
  try {
2209
- await options.secretStore.set(renewed.key);
2583
+ await options.secretStore.set(renewed.key, renewed.lease);
2210
2584
  } catch (cause) {
2211
2585
  const cleared = await discard(renewed.lease.keyId);
2212
2586
  if (!cleared) {
@@ -2326,310 +2700,64 @@ var leaseForAttribution = async (options) => {
2326
2700
  secretStore: options.installation.secretStore,
2327
2701
  state: options.installation.state,
2328
2702
  stateStore: options.installation.stateStore,
2329
- ttlMs: policy.ttlMs
2703
+ ttlMs: policy.ttlMs,
2704
+ wizardRequest: options.request.wizardRequest,
2705
+ saveAttribution: options.request.saveAttribution,
2706
+ storedKey
2330
2707
  });
2331
2708
  }
2332
2709
  const reusable = reusableLease({
2333
2710
  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 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;
2711
+ current,
2712
+ now,
2713
+ policy,
2714
+ state: options.installation.state,
2715
+ storedKey
2716
+ });
2717
+ if (reusable !== void 0) {
2718
+ return reusable;
2623
2719
  }
2624
- static #unexpectedAttribution(value) {
2625
- throw new TypeError(`Unexpected attribution: ${String(value)}`);
2720
+ try {
2721
+ const renewed = await renewKey({
2722
+ leaseState: options.installation.state,
2723
+ mint: {
2724
+ attribution: options.attribution,
2725
+ clock,
2726
+ identity: {
2727
+ credential: await resolveSeamValue(options.management.credential),
2728
+ subject: await resolveSeamValue(options.management.subject)
2729
+ },
2730
+ installation: {
2731
+ keyName: options.installation.keyName,
2732
+ ttlMs: policy.ttlMs
2733
+ },
2734
+ managementClient: options.management.client
2735
+ },
2736
+ secretStore: options.installation.secretStore
2737
+ });
2738
+ if (policy.orphanRetentionCycles !== void 0) {
2739
+ await controlOrphans({
2740
+ clock,
2741
+ currentKeyId: renewed.lease.keyId,
2742
+ keyName: options.installation.keyName,
2743
+ managementClient: options.management.client,
2744
+ managementCredential: await resolveSeamValue(
2745
+ options.management.credential
2746
+ ),
2747
+ retentionCycles: policy.orphanRetentionCycles,
2748
+ ttlMs: policy.ttlMs
2749
+ });
2750
+ }
2751
+ return renewed;
2752
+ } catch (cause) {
2753
+ return mapRenewalFailure({ cause, current, now });
2626
2754
  }
2627
2755
  };
2628
2756
 
2629
2757
  // src/key-lease/lease-installation-factory/lease-installation-factory.ts
2630
2758
  var createLeaseInstallationFactory = (options) => {
2631
2759
  const installations = /* @__PURE__ */ new Map();
2632
- return (scopeId) => {
2760
+ const open = (scopeId) => {
2633
2761
  const existing = installations.get(scopeId);
2634
2762
  if (existing !== void 0) {
2635
2763
  return existing;
@@ -2643,6 +2771,14 @@ var createLeaseInstallationFactory = (options) => {
2643
2771
  installations.set(scopeId, installation);
2644
2772
  return installation;
2645
2773
  };
2774
+ return Object.assign(open, {
2775
+ scopes: async () => [
2776
+ .../* @__PURE__ */ new Set([
2777
+ ...installations.keys(),
2778
+ ...await options.listScopes?.() ?? []
2779
+ ])
2780
+ ]
2781
+ });
2646
2782
  };
2647
2783
 
2648
2784
  // src/key-lease/scope-id/scope-id.ts
@@ -2669,12 +2805,29 @@ var deriveScopeId = (input) => {
2669
2805
  throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
2670
2806
  }
2671
2807
  }
2808
+ if (input.attribution.boundKeyId !== void 0) {
2809
+ if (input.folderRealpath === void 0)
2810
+ throw new TypeError("Bound keys require a worktree");
2811
+ if (input.attribution.boundScopeId !== void 0)
2812
+ return input.attribution.boundScopeId;
2813
+ identity = [
2814
+ ...identity,
2815
+ "binding",
2816
+ input.folderRealpath,
2817
+ input.attribution.orgId ?? "",
2818
+ input.attribution.boundKeyId
2819
+ ];
2820
+ }
2672
2821
  return createHash2("sha256").update(JSON.stringify(identity)).digest("hex");
2673
2822
  };
2674
2823
 
2675
2824
  // src/requested-client-id/requested-client-id.ts
2676
2825
  var DEFAULT_ROUTE33_CLIENT_ID = false ? "" : "oa_platform_203623de";
2677
2826
 
2827
+ // src/route33-runtime/route33-runtime.ts
2828
+ import { createHash as createHash3 } from "node:crypto";
2829
+ import { statSync as statSync2 } from "node:fs";
2830
+
2678
2831
  // src/catalog/gateway-model-ids/gateway-model-ids.ts
2679
2832
  var gatewayModelIds = async (deps) => {
2680
2833
  const { baseURL, gatewayKey, ...rest } = deps;
@@ -2688,8 +2841,9 @@ var gatewayModelIds = async (deps) => {
2688
2841
 
2689
2842
  // src/commands/change-attribution/change-attribution.ts
2690
2843
  var changeAttribution = async (options) => {
2691
- await options.clear();
2692
- return options.prompt();
2844
+ const choice = await options.prompt();
2845
+ await options.commit(choice);
2846
+ return choice;
2693
2847
  };
2694
2848
 
2695
2849
  // src/commands/inspect-session/inspect-session.ts
@@ -2713,6 +2867,114 @@ var rotateNow = async (options) => {
2713
2867
  return rotated.lease;
2714
2868
  };
2715
2869
 
2870
+ // src/key-lease/workspace-key-binding/workspace-key-binding.ts
2871
+ import { mkdir as mkdir2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
2872
+ import { dirname as dirname4 } from "node:path";
2873
+ var ROTATION_WARNING = "This key will be rotated. Existing consumers will break. Continue?";
2874
+ var pending = /* @__PURE__ */ new Map();
2875
+ var WorkspaceKeyBinding = class {
2876
+ constructor(deps) {
2877
+ this.deps = deps;
2878
+ }
2879
+ deps;
2880
+ #listings = /* @__PURE__ */ new Map();
2881
+ /** @param choice - The budget selected by the user.
2882
+ * @returns Secret-free options; local options do not need destructive consent.
2883
+ */
2884
+ async candidates(choice) {
2885
+ const listing = this.#listings.get(choice.orgId) ?? this.deps.client.list(this.deps.token, choice.orgId);
2886
+ this.#listings.set(choice.orgId, listing);
2887
+ const rows = await listing;
2888
+ const keys = rows.data.filter((row) => this.matches(row, choice));
2889
+ if (keys.length === 0) return [];
2890
+ const local = await this.localKeys(new Set(keys.map((row) => row.id)));
2891
+ return keys.map((row) => ({
2892
+ id: row.id,
2893
+ name: row.name,
2894
+ local: local.has(row.id)
2895
+ }));
2896
+ }
2897
+ matches(row, choice) {
2898
+ return row.status === "active" && !row.revoked && Date.parse(row.expires_at) > this.deps.now && (choice.orgId === void 0 || row.org_id === choice.orgId) && row.owner_user_id === this.deps.subject && (choice.kind === "project" ? row.project_id === choice.projectId && row.ownership_type === "user_project" : row.project_id === null && row.ownership_type === "user_personal");
2899
+ }
2900
+ async localKeys(ids) {
2901
+ const found = /* @__PURE__ */ new Map();
2902
+ for (const scope of await this.deps.installations.scopes?.() ?? []) {
2903
+ const store = this.deps.installations(scope);
2904
+ const lease = await this.metadata(store);
2905
+ if (!lease || !ids.has(lease.keyId) || Date.parse(lease.expiresAt) <= this.deps.now)
2906
+ continue;
2907
+ const key = await store.secretStore.get();
2908
+ if (key && (await this.metadata(store))?.keyId === lease.keyId)
2909
+ found.set(lease.keyId, scope);
2910
+ }
2911
+ return found;
2912
+ }
2913
+ async metadata(store) {
2914
+ return await store.secretStore.getLease?.() ?? await store.stateStore?.get() ?? store.state.snapshot();
2915
+ }
2916
+ /** @param choice - Selected attribution; the live key must still belong to it.
2917
+ * @param id - Selected management key id, never its secret.
2918
+ * @param confirmed - Explicit consent to rotate this id if plaintext is unavailable.
2919
+ * @returns The attribution to commit after saving the secret.
2920
+ */
2921
+ async bind(choice, id, confirmed) {
2922
+ const row = await this.deps.client.get(this.deps.token, id, choice.orgId);
2923
+ if (row.id !== id || !this.matches(row, choice))
2924
+ throw new GatewayCredentialError(
2925
+ "This key is not available for the selected budget."
2926
+ );
2927
+ const file = resolveAttributionFile(this.deps.state);
2928
+ if (file === void 0)
2929
+ throw new GatewayCredentialError("Key binding requires a worktree.");
2930
+ const bound = { ...choice, boundKeyId: id };
2931
+ const scope = deriveScopeId({
2932
+ attribution: bound,
2933
+ folderRealpath: detectWorktreeRoot(this.deps.state.directory)
2934
+ });
2935
+ const marker = `${file}.${scope}.rotation`;
2936
+ const retry = pending.get(marker);
2937
+ const localScope = retry === void 0 ? (await this.localKeys(/* @__PURE__ */ new Set([id]))).get(id) : void 0;
2938
+ if (localScope !== void 0) return { ...bound, boundScopeId: localScope };
2939
+ const target = this.deps.installations(scope);
2940
+ const { key, lease } = retry ?? await this.rotate(bound, marker, confirmed);
2941
+ await target.secretStore.set(key, lease);
2942
+ await target.stateStore?.set(lease);
2943
+ target.state.compareAndSwap(target.state.snapshot(), lease);
2944
+ await rm2(marker, { force: true });
2945
+ pending.delete(marker);
2946
+ return bound;
2947
+ }
2948
+ async rotate(bound, marker, confirmed) {
2949
+ if (!confirmed) throw new GatewayCredentialError(ROTATION_WARNING);
2950
+ const id = bound.boundKeyId;
2951
+ await mkdir2(dirname4(marker), { recursive: true });
2952
+ try {
2953
+ await writeFile2(marker, "pending\n", { flag: "wx", mode: 384 });
2954
+ } catch (cause) {
2955
+ if (cause instanceof Error && "code" in cause && cause.code === "EEXIST")
2956
+ throw new GatewayCredentialError(
2957
+ "Rotation is already pending. Retry saving in the original session or choose a new key."
2958
+ );
2959
+ throw cause;
2960
+ }
2961
+ const rotated = await this.deps.client.regenerate(
2962
+ this.deps.token,
2963
+ id,
2964
+ void 0,
2965
+ bound.orgId
2966
+ );
2967
+ if (rotated.id !== id)
2968
+ throw new GatewayCredentialError("Rotation returned a different key.");
2969
+ const material = {
2970
+ key: rotated.key,
2971
+ lease: { attribution: bound, expiresAt: rotated.expires_at, keyId: id }
2972
+ };
2973
+ pending.set(marker, material);
2974
+ return material;
2975
+ }
2976
+ };
2977
+
2716
2978
  // src/ux/attribution-prompt/org-selection-prefix/org-selection-prefix.ts
2717
2979
  var orgSelectionPrefix = (orgId) => `org:${orgId}:`;
2718
2980
 
@@ -2798,6 +3060,7 @@ var isPersonalSelection = (selection) => selection === "personal" || selection.e
2798
3060
 
2799
3061
  // src/ux/attribution-prompt-error/attribution-prompt-error.ts
2800
3062
  var MESSAGES = {
3063
+ ATTRIBUTION_BACK: "Left budget selection without changing attribution.",
2801
3064
  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
3065
  ATTRIBUTION_SELECTION_INVALID: "That Route 33 option is no longer available. Connect again and pick another."
2803
3066
  };
@@ -2811,8 +3074,9 @@ var AttributionPromptError = class extends GatewayCredentialError {
2811
3074
  };
2812
3075
 
2813
3076
  // src/ux/prompt-flow/prompt-flow.ts
3077
+ var BACK_SELECTION = "/back";
2814
3078
  var resolveAttribution = async (options) => {
2815
- const remembered = readAttribution(options.state);
3079
+ const remembered = options.state && readAttribution(options.state);
2816
3080
  if (remembered !== void 0) {
2817
3081
  return remembered;
2818
3082
  }
@@ -2820,12 +3084,16 @@ var resolveAttribution = async (options) => {
2820
3084
  throw new AttributionPromptError("ATTRIBUTION_PRESENTER_UNAVAILABLE");
2821
3085
  }
2822
3086
  const plan = createAttributionPrompt(await options.loadProjects());
2823
- const selection = await options.presenter.pick(plan);
3087
+ const selection = await options.presenter.pick({
3088
+ ...plan,
3089
+ options: [...plan.options, { label: "Back", selection: BACK_SELECTION }]
3090
+ });
3091
+ if (selection === BACK_SELECTION)
3092
+ throw new AttributionPromptError("ATTRIBUTION_BACK");
2824
3093
  const attribution = plan.choicesBySelection[selection];
2825
3094
  if (attribution === void 0) {
2826
3095
  throw new AttributionPromptError("ATTRIBUTION_SELECTION_INVALID");
2827
3096
  }
2828
- writeAttribution(options.state, attribution);
2829
3097
  return attribution;
2830
3098
  };
2831
3099
 
@@ -2843,6 +3111,66 @@ var CALLBACK_PAGE_COPY = {
2843
3111
  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
3112
  };
2845
3113
 
3114
+ // src/route33-runtime/enrich-inspection/enrich-inspection.ts
3115
+ var enrichInspection = async ({
3116
+ attribution,
3117
+ client,
3118
+ credential,
3119
+ keyId,
3120
+ subject
3121
+ }) => {
3122
+ const key = await client.get(credential, keyId);
3123
+ const orgId = key.org_id;
3124
+ if (attribution.orgId !== void 0 && attribution.orgId !== orgId) {
3125
+ return {};
3126
+ }
3127
+ const keyDetails = {
3128
+ name: key.name,
3129
+ organisationName: null,
3130
+ projectName: null
3131
+ };
3132
+ switch (attribution.kind) {
3133
+ case "personal": {
3134
+ if (key.project_id !== null) {
3135
+ return {};
3136
+ }
3137
+ return client.listBudgetPolicy(credential, subject(), orgId).then(
3138
+ ({ cap }) => cap === null ? { key: keyDetails } : {
3139
+ key: keyDetails,
3140
+ budget: { amount: String(cap), currency: null }
3141
+ }
3142
+ ).catch(() => ({ key: keyDetails }));
3143
+ }
3144
+ case "project": {
3145
+ const { projectId } = attribution;
3146
+ if (key.project_id !== projectId) {
3147
+ return {};
3148
+ }
3149
+ return Promise.all([
3150
+ client.listProjects(credential, orgId).then(
3151
+ ({ data }) => data.find(({ id, org_id }) => id === projectId && org_id === orgId)
3152
+ ).catch(() => void 0),
3153
+ client.listOrganizations(credential).then(({ data }) => data.find(({ id }) => id === orgId)?.name ?? null).catch(() => null)
3154
+ ]).then(([project, organisationName]) => {
3155
+ const title = project?.name.trim() ?? "";
3156
+ const budget = project?.effective_budget ?? project?.max_budget;
3157
+ return {
3158
+ key: {
3159
+ ...keyDetails,
3160
+ organisationName,
3161
+ projectName: title === "" ? null : title
3162
+ },
3163
+ ...budget == null ? {} : { budget }
3164
+ };
3165
+ });
3166
+ }
3167
+ default: {
3168
+ const unexpected = attribution;
3169
+ throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
3170
+ }
3171
+ }
3172
+ };
3173
+
2846
3174
  // src/route33-runtime/login-session/login-session.ts
2847
3175
  import { AuthError as AuthError2 } from "@r-33/auth-browser";
2848
3176
 
@@ -3128,6 +3456,8 @@ var Route33Runtime = class {
3128
3456
  }
3129
3457
  const installation = this.#installation(attribution);
3130
3458
  await this.#hydrateState(installation);
3459
+ if (attribution.boundKeyId !== void 0)
3460
+ return this.#boundKey(installation, attribution.boundKeyId);
3131
3461
  const storedKey = await installation.secretStore.get();
3132
3462
  return reusableLease({
3133
3463
  attribution,
@@ -3185,24 +3515,14 @@ var Route33Runtime = class {
3185
3515
  commandHandlers() {
3186
3516
  return {
3187
3517
  "change-attribution": () => changeAttribution({
3188
- clear: () => {
3189
- clearAttribution(this.#options.state);
3518
+ commit: async (choice) => {
3519
+ await this.#leaseAttribution(choice, this.#options.policy);
3520
+ if (!writeAttribution(this.#options.state, choice))
3521
+ throw new TypeError("Workspace attribution requires a worktree");
3190
3522
  },
3191
- prompt: () => this.#resolveAttribution()
3523
+ prompt: () => this.pickAttribution()
3192
3524
  }),
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
- },
3525
+ "inspect-session": () => this.#inspectSession(),
3206
3526
  "reset-attribution": () => resetAttribution({
3207
3527
  clear: () => {
3208
3528
  clearAttribution(this.#options.state);
@@ -3214,53 +3534,58 @@ var Route33Runtime = class {
3214
3534
  })
3215
3535
  };
3216
3536
  }
3217
- /** Enriched session inspection: the plain report plus the key's name and organisation/project.
3537
+ /** Adds fresh display metadata without prompting for sign-in or changing attribution.
3218
3538
  * @returns A safe session report that cannot carry gateway plaintext.
3219
3539
  */
3220
3540
  async #inspectSession() {
3541
+ const attribution = readAttribution(this.#options.state);
3542
+ const installation = attribution === void 0 ? void 0 : this.#installation(attribution);
3543
+ if (installation !== void 0) {
3544
+ await this.#hydrateState(installation);
3545
+ }
3221
3546
  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
- }
3547
+ readAttribution: () => attribution,
3548
+ readLease: () => installation?.state.snapshot()
3227
3549
  });
3228
3550
  const keyId = base.lease?.keyId;
3229
- if (keyId === void 0) {
3551
+ if (attribution === void 0 || keyId === void 0) {
3230
3552
  return base;
3231
3553
  }
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) {
3554
+ try {
3555
+ const credential = await this.#session.credential({
3556
+ allowBrowser: false
3557
+ });
3558
+ const details = await enrichInspection({
3559
+ attribution,
3560
+ client: this.#client(),
3561
+ credential,
3562
+ keyId,
3563
+ subject: () => this.#subject(credential)
3564
+ });
3565
+ return { ...base, ...details };
3566
+ } catch {
3240
3567
  return base;
3241
3568
  }
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
3569
  }
3253
3570
  /**
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.
3571
+ * @param scope - The budget being configured. Omit to discover models for the current key.
3572
+ * @returns The management catalog for a budget, or the current key's gateway catalog.
3257
3573
  */
3258
- async catalogModelIds() {
3574
+ async catalogModelIds(scope) {
3575
+ if (scope !== void 0) {
3576
+ const credential = await this.#session.credential({
3577
+ allowBrowser: false
3578
+ });
3579
+ return this.#client().listModelIds(credential, scope);
3580
+ }
3259
3581
  const workspace = await this.storedReusableKey();
3260
3582
  const personal = workspace === void 0 ? await this.#storedPersonalKey() : void 0;
3261
3583
  const value = workspace?.key.value ?? personal?.value;
3262
3584
  if (value === void 0) {
3263
- return [];
3585
+ const credential = await this.#session.credential({
3586
+ allowBrowser: false
3587
+ });
3588
+ return this.#client().listModelIds(credential, {});
3264
3589
  }
3265
3590
  return gatewayModelIds({
3266
3591
  baseURL: readEnvBaseUrl() ?? DEFAULT_BASE_URL,
@@ -3279,12 +3604,41 @@ var Route33Runtime = class {
3279
3604
  * @param attribution - The budget the wizard selected.
3280
3605
  * @param extras - The wizard's key-creation answers.
3281
3606
  * @param directory - Optional worktree override for project leases.
3607
+ * @param saveAttribution - Wizard save that must succeed before replacing a live key.
3282
3608
  * @returns The fresh key material with its lease metadata.
3283
3609
  */
3284
- async mintWorkspaceKey(attribution, extras, directory = this.#options.state.directory) {
3610
+ async mintWorkspaceKey(attribution, extras, directory = this.#options.state.directory, saveAttribution) {
3611
+ const file = resolveAttributionFile({ ...this.#options.state, directory });
3612
+ if (file === void 0)
3613
+ throw new TypeError("Workspace attribution requires a worktree");
3614
+ const previous = statSync2(file, { bigint: true, throwIfNoEntry: false });
3615
+ const wizardRequest = createHash3("sha256").update(
3616
+ JSON.stringify([
3617
+ file,
3618
+ previous?.ino.toString(),
3619
+ previous?.mtimeNs.toString(),
3620
+ attribution,
3621
+ extras,
3622
+ this.#subject(await this.#session.credential())
3623
+ ])
3624
+ ).digest("hex");
3285
3625
  return this.#leaseAttribution(attribution, void 0, directory, {
3286
3626
  extras,
3287
- forceMint: true
3627
+ forceMint: true,
3628
+ wizardRequest,
3629
+ saveAttribution
3630
+ });
3631
+ }
3632
+ /** @returns Binding operations restricted to the current management identity. */
3633
+ async workspaceKeyBinding() {
3634
+ const token = await this.#session.credential({ allowBrowser: false });
3635
+ return new WorkspaceKeyBinding({
3636
+ installations: this.#options.installation,
3637
+ token,
3638
+ subject: this.#subject(token),
3639
+ client: this.#client(),
3640
+ now: this.#now(),
3641
+ state: this.#options.state
3288
3642
  });
3289
3643
  }
3290
3644
  /**
@@ -3302,7 +3656,7 @@ var Route33Runtime = class {
3302
3656
  if (attribution === void 0) {
3303
3657
  return void 0;
3304
3658
  }
3305
- const lease = this.#installation(attribution).state.snapshot();
3659
+ const lease = this.#installation(attribution, directory).state.snapshot();
3306
3660
  const keyId = lease?.keyId;
3307
3661
  if (keyId === void 0) {
3308
3662
  return void 0;
@@ -3330,23 +3684,33 @@ var Route33Runtime = class {
3330
3684
  #now() {
3331
3685
  return (this.#options.clock ?? Date.now)();
3332
3686
  }
3333
- async #resolveAttribution() {
3687
+ /** @returns A fresh selection without changing the active budget. */
3688
+ pickAttribution() {
3334
3689
  return resolveAttribution({
3335
3690
  loadProjects: async () => {
3336
3691
  await this.#session.credential();
3337
3692
  return this.listMintableProjects();
3338
3693
  },
3339
- ...this.#options.presenter === void 0 ? {} : { presenter: this.#options.presenter },
3340
- state: this.#options.state
3694
+ ...this.#options.presenter === void 0 ? {} : { presenter: this.#options.presenter }
3341
3695
  });
3342
3696
  }
3343
3697
  async #lease(policy) {
3344
- const attribution = await this.#resolveAttribution();
3345
- return this.#leaseAttribution(attribution, policy);
3698
+ const remembered = readAttribution(this.#options.state);
3699
+ if (remembered !== void 0)
3700
+ return this.#leaseAttribution(remembered, policy);
3701
+ const choice = await this.pickAttribution();
3702
+ const leased = await this.#leaseAttribution(choice, policy);
3703
+ writeAttribution(this.#options.state, choice);
3704
+ return leased;
3346
3705
  }
3347
3706
  async #leaseAttribution(attribution, policy, directory = this.#options.state.directory, request) {
3348
3707
  const installation = this.#installation(attribution, directory);
3349
3708
  await this.#hydrateState(installation);
3709
+ if (attribution.boundKeyId !== void 0) {
3710
+ if (policy?.renewalRatio === Number.EPSILON)
3711
+ throw new TypeError("Automatic rotation is disabled for a shared key.");
3712
+ return this.#boundKey(installation, attribution.boundKeyId);
3713
+ }
3350
3714
  const minted = await leaseForAttribution({
3351
3715
  attribution,
3352
3716
  ...this.#options.clock === void 0 ? {} : { clock: this.#options.clock },
@@ -3362,13 +3726,20 @@ var Route33Runtime = class {
3362
3726
  await this.#persistState(installation, minted.lease);
3363
3727
  return minted;
3364
3728
  }
3729
+ async #boundKey(installation, id) {
3730
+ const key = await installation.secretStore.get();
3731
+ const lease = await installation.secretStore.getLease?.() ?? await installation.stateStore?.get() ?? installation.state.snapshot();
3732
+ if (!key || lease?.keyId !== id || Date.parse(lease.expiresAt) <= this.#now())
3733
+ throw new KeyLeaseError("KEY_LEASE_EXPIRED");
3734
+ return { key, lease };
3735
+ }
3365
3736
  async #hydrateState(installation) {
3366
3737
  const store = installation.stateStore;
3367
- if (store === void 0 || installation.state.snapshot() !== void 0) {
3738
+ if (installation.state.snapshot() !== void 0) {
3368
3739
  return;
3369
3740
  }
3370
3741
  try {
3371
- const persisted = await store.get();
3742
+ const persisted = await installation.secretStore.getLease?.() ?? await store?.get();
3372
3743
  if (persisted !== void 0) {
3373
3744
  installation.state.compareAndSwap(void 0, persisted);
3374
3745
  }
@@ -3382,6 +3753,13 @@ var Route33Runtime = class {
3382
3753
  }
3383
3754
  }
3384
3755
  #installation(attribution, directory = this.#options.state.directory) {
3756
+ if (attribution.boundKeyId !== void 0)
3757
+ return this.#options.installation(
3758
+ deriveScopeId({
3759
+ attribution,
3760
+ folderRealpath: detectWorktreeRoot(directory)
3761
+ })
3762
+ );
3385
3763
  switch (attribution.kind) {
3386
3764
  case "personal":
3387
3765
  return this.#options.installation(deriveScopeId({ attribution }));
@@ -3403,15 +3781,14 @@ var Route33Runtime = class {
3403
3781
  };
3404
3782
 
3405
3783
  // src/v1-entry/unattributed-prompt-gate/unattributed-prompt-gate.ts
3406
- var createUnattributedPromptGate = ({ directory, outsideWorktree }) => (input) => {
3784
+ var CONNECTION_COPY = "Not connected to Route 33. Run /connect, choose Route 33, and complete sign-in before assigning a budget with /r33.";
3785
+ var ATTRIBUTION_COPY = "This folder has no Route 33 budget assigned. Run /r33, choose Route 33, and assign a budget.";
3786
+ var createUnattributedPromptGate = ({ directory, isConnected, outsideWorktree }) => async (input) => {
3407
3787
  if (input.model?.providerID !== "route_33") return Promise.resolve();
3788
+ if (!await isConnected()) throw new Error(CONNECTION_COPY);
3408
3789
  const attribution = readAttribution({ directory, outsideWorktree });
3409
3790
  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
- );
3791
+ throw new Error(ATTRIBUTION_COPY);
3415
3792
  };
3416
3793
 
3417
3794
  // src/v1-entry/workspace-key-headers/workspace-key-headers.ts
@@ -3438,6 +3815,11 @@ var createRoute33Plugin = (options = {}) => {
3438
3815
  };
3439
3816
  const runtimeOptions = options.runtime;
3440
3817
  const installation = runtimeOptions === void 0 ? void 0 : runtimeOptions.installation ?? createLeaseInstallationFactory({
3818
+ listScopes: () => FileSecretStore.scopes(
3819
+ resolveV1SecretStoreDirectory({
3820
+ directory: options.secretStoreDirectory
3821
+ })
3822
+ ),
3441
3823
  createSecretStore: (scopeId) => new FileSecretStore({
3442
3824
  directory: resolveV1SecretStoreDirectory({
3443
3825
  ...options.secretStoreDirectory === void 0 ? {} : { directory: options.secretStoreDirectory }
@@ -3483,6 +3865,14 @@ var createRoute33Plugin = (options = {}) => {
3483
3865
  });
3484
3866
  promptGate = createUnattributedPromptGate({
3485
3867
  directory: input.worktree,
3868
+ isConnected: async () => {
3869
+ try {
3870
+ await runtime2.login({ allowBrowser: false });
3871
+ return true;
3872
+ } catch {
3873
+ return false;
3874
+ }
3875
+ },
3486
3876
  outsideWorktree: "return-undefined"
3487
3877
  });
3488
3878
  }
@@ -3514,12 +3904,6 @@ var drainPages = async (fetchPage) => {
3514
3904
  return { data, page: { ...page, has_more: false, next_cursor: null } };
3515
3905
  };
3516
3906
 
3517
- // src/management/sdk-management-keys/sdk-management-keys.ts
3518
- import {
3519
- createRoute33Client,
3520
- Route33SdkError
3521
- } from "@r-33/sdk";
3522
-
3523
3907
  // src/contract/management-keys/parse-api-key/parse-api-key.ts
3524
3908
  var parseApiKey = (value) => {
3525
3909
  if (!isRecord(value) || !isOwnerType(value["ownership_type"]) || !isNullableString(value["project_id"])) {
@@ -3545,6 +3929,7 @@ var parseApiKey = (value) => {
3545
3929
  name: field("name"),
3546
3930
  org_id: field("org_id"),
3547
3931
  ownership_type: value["ownership_type"],
3932
+ ...typeof value["owner_user_id"] === "string" ? { owner_user_id: value["owner_user_id"] } : {},
3548
3933
  project_id: value["project_id"],
3549
3934
  revoked: value["revoked"] === true,
3550
3935
  status
@@ -3780,6 +4165,32 @@ var parseUserMemberships = (value) => {
3780
4165
  };
3781
4166
  };
3782
4167
 
4168
+ // src/management/key-read-operations/key-read-operations.ts
4169
+ var keyReadOperations = (call) => {
4170
+ const withCursor = (cursor) => ({ request }) => {
4171
+ const url = new URL(request.url);
4172
+ url.searchParams.set("cursor", cursor);
4173
+ return new Request(url, request);
4174
+ };
4175
+ return {
4176
+ get: async (accessToken, id, orgId) => parseApiKey(
4177
+ await call(
4178
+ accessToken,
4179
+ orgId,
4180
+ (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
4181
+ params: { path: { api_key_id: id } }
4182
+ })
4183
+ )
4184
+ ),
4185
+ list: (accessToken, orgId) => drainPages(
4186
+ (cursor) => call(accessToken, orgId, (client) => {
4187
+ if (cursor !== "") client.use({ onRequest: withCursor(cursor) });
4188
+ return client.GET("/api/v1/api-keys", {});
4189
+ }).then((page) => parseCollection(page, parseApiKey))
4190
+ )
4191
+ };
4192
+ };
4193
+
3783
4194
  // src/management/sdk-management-keys/mint-request-body/mint-request-body.ts
3784
4195
  var buildMintRequestBody = (input) => ({
3785
4196
  ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
@@ -3793,10 +4204,134 @@ var buildMintRequestBody = (input) => ({
3793
4204
  ...input.projectId === null ? {} : { project_id: input.projectId }
3794
4205
  });
3795
4206
 
3796
- // src/management/sdk-management-keys/sdk-management-keys.ts
4207
+ // src/management/key-write-operations/key-write-operations.ts
4208
+ var keyWriteOperations = (call) => ({
4209
+ create: async (accessToken, input) => parseKeyMaterial(
4210
+ await call(
4211
+ accessToken,
4212
+ input.activeOrgId,
4213
+ (client) => client.POST("/api/v1/api-keys", {
4214
+ body: buildMintRequestBody(input)
4215
+ })
4216
+ )
4217
+ ),
4218
+ delete: async (accessToken, id) => {
4219
+ await call(
4220
+ accessToken,
4221
+ void 0,
4222
+ (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
4223
+ params: { path: { api_key_id: id } }
4224
+ })
4225
+ );
4226
+ },
4227
+ regenerate: async (accessToken, id, expiresAt, orgId) => parseKeyMaterial(
4228
+ await call(
4229
+ accessToken,
4230
+ orgId,
4231
+ (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
4232
+ body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
4233
+ params: { path: { api_key_id: id } }
4234
+ })
4235
+ )
4236
+ ),
4237
+ update: async (accessToken, id, input) => parseApiKey(
4238
+ await call(
4239
+ accessToken,
4240
+ void 0,
4241
+ (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
4242
+ body: {
4243
+ budget_currency: "EUR",
4244
+ ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
4245
+ ...input.name === void 0 ? {} : { name: input.name }
4246
+ },
4247
+ params: { path: { api_key_id: id } }
4248
+ })
4249
+ )
4250
+ )
4251
+ });
4252
+
4253
+ // src/management/sdk-management-keys/exposed-catalog-ids/exposed-catalog-ids.ts
4254
+ var exposedCatalogIds = async (readPage) => {
4255
+ const ids = /* @__PURE__ */ new Set();
4256
+ let offset = 0;
4257
+ for (; ; ) {
4258
+ const page = await readPage(offset);
4259
+ if (!isRecord(page) || !Array.isArray(page.models) || page.offset !== offset || typeof page.total !== "number" || !Number.isSafeInteger(page.total) || page.total < 0) {
4260
+ throw new ContractParseError("invalid model catalog page");
4261
+ }
4262
+ page.models.forEach((row) => {
4263
+ if (!isRecord(row) || typeof row.id !== "string" || !row.id.trim() || typeof row.status !== "string")
4264
+ throw new ContractParseError("invalid model catalog item");
4265
+ if (row.status === "exposed") ids.add(row.id);
4266
+ });
4267
+ offset += page.models.length;
4268
+ if (offset >= page.total || page.models.length === 0)
4269
+ return [...ids].sort((left, right) => left.localeCompare(right));
4270
+ }
4271
+ };
4272
+
4273
+ // src/management/model-catalog-operations/model-catalog-operations.ts
4274
+ var modelCatalogOperations = (call) => ({
4275
+ listModelIds: (token, { orgId, projectId }) => exposedCatalogIds(
4276
+ (offset) => call(token, orgId, (client) => {
4277
+ const query = { offset };
4278
+ if (projectId !== void 0)
4279
+ return client.GET("/api/v1/projects/{project_id}/model-catalog", {
4280
+ params: { path: { project_id: projectId }, query }
4281
+ });
4282
+ if (orgId !== void 0)
4283
+ return client.GET("/api/v1/orgs/{org_id}/model-catalog", {
4284
+ params: { path: { org_id: orgId }, query }
4285
+ });
4286
+ return client.GET("/api/v1/model-catalog", { params: { query } });
4287
+ })
4288
+ )
4289
+ });
4290
+
4291
+ // src/management/list-sdk-projects/list-sdk-projects.ts
4292
+ var listSdkProjects = async (accessToken, organisationId, call) => {
4293
+ if (organisationId.trim().length === 0) {
4294
+ throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
4295
+ statusCode: 400
4296
+ });
4297
+ }
4298
+ const query = {
4299
+ member_user_id: parseManagementSubject(accessToken),
4300
+ org_id: organisationId
4301
+ };
4302
+ const fetchPage = (cursor) => call(
4303
+ accessToken,
4304
+ void 0,
4305
+ (client) => client.GET("/api/v1/projects", {
4306
+ params: {
4307
+ query: cursor === "" ? query : { ...query, cursor }
4308
+ }
4309
+ })
4310
+ ).then((page) => parseCollection(page, parseProject));
4311
+ return drainPages(fetchPage);
4312
+ };
4313
+
4314
+ // src/management/organization-operations/organization-operations.ts
4315
+ var organizationOperations = (call) => ({
4316
+ listOrganizations: async (accessToken) => parseCollection(
4317
+ await call(
4318
+ accessToken,
4319
+ void 0,
4320
+ (client) => client.GET("/api/v1/orgs", {})
4321
+ ),
4322
+ parseOrganization
4323
+ ),
4324
+ listProjects: (accessToken, organisationId) => listSdkProjects(accessToken, organisationId, call)
4325
+ });
4326
+
4327
+ // src/management/sdk-management-call/sdk-management-call.ts
4328
+ import {
4329
+ createRoute33Client,
4330
+ Route33SdkError
4331
+ } from "@r-33/sdk";
3797
4332
  var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
3798
4333
  var ACTIVE_ORG_HEADER = "X-Active-Org-Id";
3799
- var sdkManagementKeys = (options) => {
4334
+ var createSdkCall = (options) => {
3800
4335
  const baseUrl = options.apiBaseUrl.replace(API_PREFIX_PATTERN, "");
3801
4336
  const timeoutMs = options.timeoutMs ?? 1e4;
3802
4337
  const fetchImpl = options.fetchImpl;
@@ -3835,7 +4370,7 @@ var sdkManagementKeys = (options) => {
3835
4370
  }
3836
4371
  return new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
3837
4372
  };
3838
- const call = async (accessToken, activeOrgId, run) => {
4373
+ return async (accessToken, activeOrgId, run) => {
3839
4374
  try {
3840
4375
  const outcome = await run(callClient(accessToken, activeOrgId));
3841
4376
  const code = outcome.response?.status;
@@ -3850,123 +4385,49 @@ var sdkManagementKeys = (options) => {
3850
4385
  throw mapFailure(cause);
3851
4386
  }
3852
4387
  };
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
- )
4388
+ };
4389
+
4390
+ // src/management/user-context-operations/user-context-operations.ts
4391
+ var userContextOperations = (call) => ({
4392
+ listMemberships: async (accessToken, userId) => parseUserMemberships(
4393
+ await call(
4394
+ accessToken,
4395
+ void 0,
4396
+ (client) => client.GET("/api/v1/users/{user_id}/memberships", {
4397
+ params: { path: { user_id: userId } }
4398
+ })
4399
+ )
4400
+ ),
4401
+ listBudgetPolicy: async (accessToken, userId, activeOrgId) => parseBudgetPolicy(
4402
+ await call(
4403
+ accessToken,
4404
+ activeOrgId,
4405
+ (client) => client.GET("/api/v1/users/{user_id}/budget-policy", {
4406
+ params: { path: { user_id: userId } }
4407
+ })
3969
4408
  )
4409
+ ),
4410
+ listProjectBudgets: async (accessToken, userId, activeOrgId) => parseCollection(
4411
+ await call(
4412
+ accessToken,
4413
+ activeOrgId,
4414
+ (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
4415
+ params: { path: { user_id: userId } }
4416
+ })
4417
+ ),
4418
+ parseProjectBudgetState
4419
+ )
4420
+ });
4421
+
4422
+ // src/management/sdk-management-keys/sdk-management-keys.ts
4423
+ var sdkManagementKeys = (options) => {
4424
+ const call = createSdkCall(options);
4425
+ return {
4426
+ ...keyReadOperations(call),
4427
+ ...keyWriteOperations(call),
4428
+ ...modelCatalogOperations(call),
4429
+ ...organizationOperations(call),
4430
+ ...userContextOperations(call)
3970
4431
  };
3971
4432
  };
3972
4433
 
@@ -4278,6 +4739,7 @@ var Route33Plugin = async (input) => {
4278
4739
  };
4279
4740
  export {
4280
4741
  AttributionPromptError,
4742
+ BACK_SELECTION,
4281
4743
  CALLBACK_PAGE_COPY,
4282
4744
  ContractParseError,
4283
4745
  DEFAULT_GATEWAY_KEY_RENEWAL_RATIO,