@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.
@@ -3964,1333 +3964,1478 @@ var init_default_gateway_key_ttl_ms2 = __esm({
3964
3964
  }
3965
3965
  });
3966
3966
 
3967
- // src/key-lease/file-secret-store/file-secret-store.ts
3968
- import { randomUUID } from "node:crypto";
3969
- import * as fs6 from "node:fs/promises";
3967
+ // src/attribution/detect-worktree-root/detect-worktree-root.ts
3968
+ import * as fs6 from "node:fs";
3970
3969
  import * as path7 from "node:path";
3971
- var FileSecretStore;
3972
- var init_file_secret_store = __esm({
3973
- "src/key-lease/file-secret-store/file-secret-store.ts"() {
3970
+ var detectWorktreeRoot;
3971
+ var init_detect_worktree_root = __esm({
3972
+ "src/attribution/detect-worktree-root/detect-worktree-root.ts"() {
3974
3973
  "use strict";
3975
- init_adapters();
3976
- FileSecretStore = class {
3977
- #directory;
3978
- #file;
3979
- constructor(options) {
3980
- if (options.directory.length === 0) {
3981
- throw new TypeError("File secret store requires a directory");
3982
- }
3983
- if (!/^[a-zA-Z0-9._-]+$/u.test(options.scopeId)) {
3984
- throw new TypeError("File secret store scope is not portable");
3985
- }
3986
- this.#directory = options.directory;
3987
- this.#file = path7.join(options.directory, `lease-${options.scopeId}.json`);
3988
- }
3989
- /** Reads and parses the scoped gateway credential.
3990
- * @returns The persisted credential, when present.
3991
- */
3992
- async get() {
3993
- let contents;
3994
- try {
3995
- contents = await fs6.readFile(this.#file, "utf8");
3996
- } catch (cause) {
3997
- if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
3998
- return void 0;
3974
+ detectWorktreeRoot = (startDirectory) => {
3975
+ let directory = fs6.realpathSync(startDirectory);
3976
+ for (; ; ) {
3977
+ const gitEntry = path7.join(directory, ".git");
3978
+ if (fs6.existsSync(gitEntry)) {
3979
+ const entry = fs6.statSync(gitEntry);
3980
+ if (entry.isDirectory() || entry.isFile()) {
3981
+ return directory;
3999
3982
  }
4000
- throw cause;
4001
- }
4002
- const value = JSON.parse(contents);
4003
- return parseGatewayKey(value);
4004
- }
4005
- /** Writes the scoped gateway credential through an atomic private file.
4006
- * @param key - The credential to persist, or undefined to remove it.
4007
- * @returns A promise that settles after the file write or removal.
4008
- */
4009
- async set(key) {
4010
- if (key === void 0) {
4011
- await fs6.rm(this.#file, { force: true });
4012
- return;
4013
- }
4014
- await fs6.mkdir(this.#directory, { mode: 448, recursive: true });
4015
- await fs6.chmod(this.#directory, 448);
4016
- const temporary = path7.join(this.#directory, `.lease-${randomUUID()}.tmp`);
4017
- try {
4018
- await fs6.writeFile(temporary, `${JSON.stringify(key.value)}
4019
- `, {
4020
- encoding: "utf8",
4021
- flag: "wx",
4022
- mode: 384
4023
- });
4024
- await fs6.rename(temporary, this.#file);
4025
- } finally {
4026
- await fs6.rm(temporary, { force: true });
4027
3983
  }
4028
- }
4029
- };
4030
- }
4031
- });
4032
-
4033
- // src/key-lease/file-secret-store/index.ts
4034
- var init_file_secret_store2 = __esm({
4035
- "src/key-lease/file-secret-store/index.ts"() {
4036
- "use strict";
4037
- init_file_secret_store();
4038
- }
4039
- });
4040
-
4041
- // src/key-lease/host-storage-secret-store/host-storage-secret-store.ts
4042
- var HostStorageSecretStore;
4043
- var init_host_storage_secret_store = __esm({
4044
- "src/key-lease/host-storage-secret-store/host-storage-secret-store.ts"() {
4045
- "use strict";
4046
- init_adapters();
4047
- HostStorageSecretStore = class {
4048
- #key;
4049
- #storage;
4050
- constructor(options) {
4051
- this.#key = options.key;
4052
- this.#storage = options.storage;
4053
- }
4054
- /** Reads and parses the scoped gateway credential.
4055
- * @returns The persisted credential, when present.
4056
- */
4057
- /** Reads the scoped gateway credential out of the box envelope the
4058
- * host's reactive storage uses, so the TUI part reads what the
4059
- * server part wrote at the same plugin key.
4060
- * @returns The persisted credential, when present.
4061
- */
4062
- async get() {
4063
- const value = await this.#storage.get(this.#key);
4064
- if (typeof value === "object" && value !== null && "value" in value && typeof value.value === "string") {
4065
- return parseGatewayKey(value.value);
3984
+ const parent = path7.dirname(directory);
3985
+ if (parent === directory) {
3986
+ return void 0;
4066
3987
  }
4067
- return typeof value === "string" ? parseGatewayKey(value) : void 0;
4068
- }
4069
- /** Writes the scoped gateway credential into the box envelope, through
4070
- * host-owned storage only.
4071
- * @param key - The credential to persist, or undefined to remove it.
4072
- * @returns A promise that settles after the host write or removal.
4073
- */
4074
- set(key) {
4075
- return key === void 0 ? this.#storage.remove(this.#key) : this.#storage.set(this.#key, { value: key.value });
3988
+ directory = parent;
4076
3989
  }
4077
3990
  };
4078
3991
  }
4079
3992
  });
4080
3993
 
4081
- // src/key-lease/host-storage-secret-store/index.ts
4082
- var init_host_storage_secret_store2 = __esm({
4083
- "src/key-lease/host-storage-secret-store/index.ts"() {
3994
+ // src/attribution/detect-worktree-root/index.ts
3995
+ var init_detect_worktree_root2 = __esm({
3996
+ "src/attribution/detect-worktree-root/index.ts"() {
4084
3997
  "use strict";
4085
- init_host_storage_secret_store();
3998
+ init_detect_worktree_root();
4086
3999
  }
4087
4000
  });
4088
4001
 
4089
- // src/key-lease/key-lease-error/key-lease-error.ts
4090
- var REDACTED_CAUSE, KeyLeaseError;
4091
- var init_key_lease_error = __esm({
4092
- "src/key-lease/key-lease-error/key-lease-error.ts"() {
4002
+ // src/attribution/resolve-attribution-file/resolve-attribution-file.ts
4003
+ import * as fs7 from "node:fs";
4004
+ import * as path8 from "node:path";
4005
+ var resolveAttributionFile;
4006
+ var init_resolve_attribution_file = __esm({
4007
+ "src/attribution/resolve-attribution-file/resolve-attribution-file.ts"() {
4093
4008
  "use strict";
4094
- REDACTED_CAUSE = "Route 33 gateway key lease dependency failed";
4095
- KeyLeaseError = class extends Error {
4096
- constructor(code, options) {
4097
- super(
4098
- "Route 33 gateway key lease failed",
4099
- options?.cause === void 0 ? void 0 : { cause: REDACTED_CAUSE }
4100
- );
4101
- this.code = code;
4102
- this.name = "KeyLeaseError";
4103
- this.statusCode = options?.statusCode;
4009
+ init_detect_worktree_root2();
4010
+ resolveAttributionFile = (options) => {
4011
+ const worktreeRoot = detectWorktreeRoot(options.directory);
4012
+ if (worktreeRoot !== void 0) {
4013
+ return path8.join(worktreeRoot, ".opencode", "route33.attribution.json");
4104
4014
  }
4105
- code;
4106
- statusCode;
4015
+ const fallbackRoots = {
4016
+ "return-undefined": void 0,
4017
+ "use-directory": fs7.realpathSync(options.directory)
4018
+ };
4019
+ const fallbackRoot = fallbackRoots[options.outsideWorktree];
4020
+ return fallbackRoot === void 0 ? void 0 : path8.join(fallbackRoot, ".opencode", "route33.attribution.json");
4107
4021
  };
4108
4022
  }
4109
4023
  });
4110
4024
 
4111
- // src/key-lease/key-lease-error/index.ts
4112
- var init_key_lease_error2 = __esm({
4113
- "src/key-lease/key-lease-error/index.ts"() {
4025
+ // src/attribution/resolve-attribution-file/index.ts
4026
+ var init_resolve_attribution_file2 = __esm({
4027
+ "src/attribution/resolve-attribution-file/index.ts"() {
4114
4028
  "use strict";
4115
- init_key_lease_error();
4029
+ init_resolve_attribution_file();
4116
4030
  }
4117
4031
  });
4118
4032
 
4119
- // src/key-lease/is-management-unauthorized/is-management-unauthorized.ts
4120
- var isManagementUnauthorized;
4121
- var init_is_management_unauthorized = __esm({
4122
- "src/key-lease/is-management-unauthorized/is-management-unauthorized.ts"() {
4033
+ // src/attribution/clear-attribution/clear-attribution.ts
4034
+ import * as fs8 from "node:fs";
4035
+ var clearAttribution;
4036
+ var init_clear_attribution = __esm({
4037
+ "src/attribution/clear-attribution/clear-attribution.ts"() {
4123
4038
  "use strict";
4124
- isManagementUnauthorized = (cause) => {
4125
- if (cause instanceof Response) {
4126
- return cause.status === 401;
4127
- }
4128
- if (typeof cause !== "object") {
4129
- return false;
4130
- }
4131
- if (cause === null) {
4039
+ init_resolve_attribution_file2();
4040
+ clearAttribution = (options) => {
4041
+ const file = resolveAttributionFile(options);
4042
+ if (file === void 0) {
4132
4043
  return false;
4133
4044
  }
4134
- if ("status" in cause && cause.status === 401) {
4135
- return true;
4136
- }
4137
- if ("statusCode" in cause && cause.statusCode === 401) {
4138
- return true;
4139
- }
4140
- return "response" in cause && cause.response instanceof Response && cause.response.status === 401;
4045
+ fs8.rmSync(file, { force: true });
4046
+ return true;
4141
4047
  };
4142
4048
  }
4143
4049
  });
4144
4050
 
4145
- // src/key-lease/is-management-unauthorized/index.ts
4146
- var init_is_management_unauthorized2 = __esm({
4147
- "src/key-lease/is-management-unauthorized/index.ts"() {
4051
+ // src/attribution/clear-attribution/index.ts
4052
+ var init_clear_attribution2 = __esm({
4053
+ "src/attribution/clear-attribution/index.ts"() {
4148
4054
  "use strict";
4149
- init_is_management_unauthorized();
4055
+ init_clear_attribution();
4150
4056
  }
4151
4057
  });
4152
4058
 
4153
- // src/key-lease/recover-lease-state/recover-lease-state.ts
4154
- var recoverLeaseState;
4155
- var init_recover_lease_state = __esm({
4156
- "src/key-lease/recover-lease-state/recover-lease-state.ts"() {
4059
+ // src/attribution/read-legacy-key/read-legacy-key.ts
4060
+ import * as fs9 from "node:fs";
4061
+ import * as path9 from "node:path";
4062
+ var LEGACY_KEY_RELATIVE_PATH, readLegacyKey;
4063
+ var init_read_legacy_key = __esm({
4064
+ "src/attribution/read-legacy-key/read-legacy-key.ts"() {
4157
4065
  "use strict";
4158
- init_is_management_unauthorized2();
4159
- init_key_lease_error2();
4160
- recoverLeaseState = async (options) => {
4161
- let keys;
4066
+ LEGACY_KEY_RELATIVE_PATH = path9.join(".opencode", "route33.key");
4067
+ readLegacyKey = (worktree) => {
4068
+ if (worktree.trim() === "") return void 0;
4069
+ let raw;
4162
4070
  try {
4163
- keys = (await options.managementClient.list(options.managementCredential)).data;
4164
- } catch (cause) {
4165
- throw new KeyLeaseError(
4166
- isManagementUnauthorized(cause) ? "KEY_LEASE_UNAUTHORIZED" : "KEY_LEASE_MINT_FAILED",
4167
- { cause }
4071
+ raw = fs9.readFileSync(
4072
+ path9.join(worktree, LEGACY_KEY_RELATIVE_PATH),
4073
+ "utf8"
4168
4074
  );
4075
+ } catch {
4076
+ return void 0;
4169
4077
  }
4170
- const matches = keys.filter((key2) => {
4171
- if (key2.name !== options.keyName || key2.revoked || key2.status !== "active" || !Number.isFinite(Date.parse(key2.expires_at))) {
4172
- return false;
4078
+ try {
4079
+ const parsed = JSON.parse(raw);
4080
+ if (typeof parsed !== "object" || parsed === null || parsed.type !== "api") {
4081
+ return void 0;
4173
4082
  }
4174
- switch (options.attribution.kind) {
4175
- case "personal":
4176
- return key2.ownership_type === "user_personal" && key2.project_id === null;
4177
- case "project":
4178
- return key2.ownership_type === "project" && key2.project_id === options.attribution.projectId;
4179
- default: {
4180
- const unexpected = options.attribution;
4181
- throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
4182
- }
4083
+ const key = parsed.key;
4084
+ if (typeof key !== "string" || key.trim() === "") {
4085
+ return void 0;
4183
4086
  }
4184
- });
4185
- const key = matches.length === 1 ? matches[0] : void 0;
4186
- if (key === void 0) {
4087
+ return { value: key };
4088
+ } catch {
4187
4089
  return void 0;
4188
4090
  }
4189
- const recovered = {
4190
- attribution: options.attribution,
4191
- expiresAt: key.expires_at,
4192
- keyId: key.id
4193
- };
4194
- return options.state.compareAndSwap(void 0, recovered) ? recovered : options.state.snapshot();
4195
4091
  };
4196
4092
  }
4197
4093
  });
4198
4094
 
4199
- // src/key-lease/recover-lease-state/index.ts
4200
- var init_recover_lease_state2 = __esm({
4201
- "src/key-lease/recover-lease-state/index.ts"() {
4095
+ // src/attribution/read-legacy-key/index.ts
4096
+ var init_read_legacy_key2 = __esm({
4097
+ "src/attribution/read-legacy-key/index.ts"() {
4202
4098
  "use strict";
4203
- init_recover_lease_state();
4099
+ init_read_legacy_key();
4204
4100
  }
4205
4101
  });
4206
4102
 
4207
- // src/key-lease/current-lease-state/current-lease-state.ts
4208
- var currentLeaseState;
4209
- var init_current_lease_state = __esm({
4210
- "src/key-lease/current-lease-state/current-lease-state.ts"() {
4103
+ // src/attribution/parse-attribution/read-org-id/read-org-id.ts
4104
+ var readOrgId;
4105
+ var init_read_org_id = __esm({
4106
+ "src/attribution/parse-attribution/read-org-id/read-org-id.ts"() {
4211
4107
  "use strict";
4212
- init_key_lease_error2();
4213
- init_recover_lease_state2();
4214
- currentLeaseState = async (deps) => {
4215
- let current = deps.state.snapshot();
4216
- let storedKey;
4217
- try {
4218
- storedKey = await deps.secretStore.get();
4219
- } catch (cause) {
4220
- throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
4108
+ init_adapters();
4109
+ readOrgId = (value) => {
4110
+ const orgId = value["orgId"];
4111
+ if (orgId === void 0) {
4112
+ return void 0;
4221
4113
  }
4222
- if (current === void 0 && storedKey !== void 0) {
4223
- current = await recoverLeaseState({
4224
- attribution: deps.attribution,
4225
- keyName: deps.keyName,
4226
- managementClient: deps.managementClient,
4227
- managementCredential: deps.credential,
4228
- state: deps.state
4229
- });
4114
+ if (typeof orgId !== "string") {
4115
+ throw new ContractParseError("invalid attribution");
4230
4116
  }
4231
- return { current, storedKey };
4117
+ return orgId;
4232
4118
  };
4233
4119
  }
4234
4120
  });
4235
4121
 
4236
- // src/key-lease/current-lease-state/index.ts
4237
- var init_current_lease_state2 = __esm({
4238
- "src/key-lease/current-lease-state/index.ts"() {
4122
+ // src/attribution/parse-attribution/read-org-id/index.ts
4123
+ var init_read_org_id2 = __esm({
4124
+ "src/attribution/parse-attribution/read-org-id/index.ts"() {
4239
4125
  "use strict";
4240
- init_current_lease_state();
4126
+ init_read_org_id();
4241
4127
  }
4242
4128
  });
4243
4129
 
4244
- // src/key-lease/map-renewal-failure/map-renewal-failure.ts
4245
- var mapRenewalFailure;
4246
- var init_map_renewal_failure = __esm({
4247
- "src/key-lease/map-renewal-failure/map-renewal-failure.ts"() {
4130
+ // src/attribution/parse-attribution/parse-attribution.ts
4131
+ var parseAttribution;
4132
+ var init_parse_attribution = __esm({
4133
+ "src/attribution/parse-attribution/parse-attribution.ts"() {
4248
4134
  "use strict";
4249
- init_key_lease_error2();
4250
- mapRenewalFailure = (options) => {
4251
- if (options.current === void 0) {
4252
- throw options.cause;
4253
- }
4254
- if (options.now < Date.parse(options.current.expiresAt)) {
4255
- throw options.cause;
4135
+ init_adapters();
4136
+ init_predicates();
4137
+ init_read_org_id2();
4138
+ parseAttribution = (value) => {
4139
+ if (!isRecord(value)) {
4140
+ throw new ContractParseError("invalid attribution");
4256
4141
  }
4257
- if (!(options.cause instanceof KeyLeaseError)) {
4258
- throw options.cause;
4142
+ const orgId = readOrgId(value);
4143
+ const binding = (() => {
4144
+ const { boundKeyId, boundScopeId } = value;
4145
+ if (boundKeyId === void 0 && boundScopeId === void 0) return {};
4146
+ if (typeof boundKeyId !== "string" || !boundKeyId)
4147
+ throw new ContractParseError("invalid bound key id");
4148
+ if (boundScopeId === void 0) return { boundKeyId };
4149
+ if (typeof boundScopeId !== "string" || !/^[a-f0-9]{64}$/u.test(boundScopeId))
4150
+ throw new ContractParseError("invalid bound scope id");
4151
+ return { boundKeyId, boundScopeId };
4152
+ })();
4153
+ if (value["kind"] === "personal") {
4154
+ return { ...binding, kind: "personal", orgId };
4259
4155
  }
4260
- if (options.cause.code !== "KEY_LEASE_MINT_FAILED") {
4261
- throw options.cause;
4156
+ if (value["kind"] === "project" && typeof value["projectId"] === "string") {
4157
+ return {
4158
+ ...binding,
4159
+ kind: "project",
4160
+ ...orgId === void 0 ? {} : { orgId },
4161
+ projectId: value["projectId"]
4162
+ };
4262
4163
  }
4263
- throw new KeyLeaseError("KEY_LEASE_EXPIRED", { cause: options.cause });
4164
+ throw new ContractParseError("invalid attribution");
4264
4165
  };
4265
4166
  }
4266
4167
  });
4267
4168
 
4268
- // src/key-lease/map-renewal-failure/index.ts
4269
- var init_map_renewal_failure2 = __esm({
4270
- "src/key-lease/map-renewal-failure/index.ts"() {
4169
+ // src/attribution/parse-attribution/index.ts
4170
+ var init_parse_attribution2 = __esm({
4171
+ "src/attribution/parse-attribution/index.ts"() {
4271
4172
  "use strict";
4272
- init_map_renewal_failure();
4173
+ init_parse_attribution();
4273
4174
  }
4274
4175
  });
4275
4176
 
4276
- // src/key-lease/expiry-ttl-ms/expiry-ttl-ms.ts
4277
- var DAY_MS, expiryTtlMs;
4278
- var init_expiry_ttl_ms = __esm({
4279
- "src/key-lease/expiry-ttl-ms/expiry-ttl-ms.ts"() {
4177
+ // src/attribution/read-attribution/read-attribution.ts
4178
+ import * as fs10 from "node:fs";
4179
+ var readAttribution;
4180
+ var init_read_attribution = __esm({
4181
+ "src/attribution/read-attribution/read-attribution.ts"() {
4280
4182
  "use strict";
4281
- DAY_MS = 864e5;
4282
- expiryTtlMs = (ttlMs, expiryDays) => {
4283
- const explicit = (expiryDays ?? 0) * DAY_MS;
4284
- return explicit > 0 ? explicit : ttlMs;
4183
+ init_parse_attribution2();
4184
+ init_resolve_attribution_file2();
4185
+ readAttribution = (options) => {
4186
+ const file = resolveAttributionFile(options);
4187
+ if (file === void 0) {
4188
+ return void 0;
4189
+ }
4190
+ try {
4191
+ const parsed = JSON.parse(fs10.readFileSync(file, "utf8"));
4192
+ return parseAttribution(parsed);
4193
+ } catch {
4194
+ return void 0;
4195
+ }
4285
4196
  };
4286
4197
  }
4287
4198
  });
4288
4199
 
4289
- // src/key-lease/expiry-ttl-ms/index.ts
4290
- var init_expiry_ttl_ms2 = __esm({
4291
- "src/key-lease/expiry-ttl-ms/index.ts"() {
4200
+ // src/attribution/read-attribution/index.ts
4201
+ var init_read_attribution2 = __esm({
4202
+ "src/attribution/read-attribution/index.ts"() {
4292
4203
  "use strict";
4293
- init_expiry_ttl_ms();
4204
+ init_read_attribution();
4294
4205
  }
4295
4206
  });
4296
4207
 
4297
- // src/key-lease/resolve-key-ownership/resolve-key-ownership.ts
4298
- var resolveKeyOwnership;
4299
- var init_resolve_key_ownership = __esm({
4300
- "src/key-lease/resolve-key-ownership/resolve-key-ownership.ts"() {
4208
+ // src/attribution/remove-legacy-key/remove-legacy-key.ts
4209
+ import * as fs11 from "node:fs";
4210
+ import * as path10 from "node:path";
4211
+ var LEGACY_KEY_RELATIVE_PATH2, removeLegacyKey;
4212
+ var init_remove_legacy_key = __esm({
4213
+ "src/attribution/remove-legacy-key/remove-legacy-key.ts"() {
4301
4214
  "use strict";
4302
- init_key_lease_error2();
4303
- resolveKeyOwnership = (options) => {
4304
- switch (options.attribution.kind) {
4305
- case "personal":
4306
- if (options.managementSubject.length === 0) {
4307
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4308
- }
4309
- return {
4310
- ownerId: options.managementSubject,
4311
- ownerType: "user_personal",
4312
- projectId: null
4313
- };
4314
- case "project":
4315
- return {
4316
- ownerId: options.managementSubject,
4317
- ownerType: "user_project",
4318
- projectId: options.attribution.projectId
4319
- };
4320
- default: {
4321
- const unexpected = options.attribution;
4322
- throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
4323
- }
4215
+ LEGACY_KEY_RELATIVE_PATH2 = path10.join(".opencode", "route33.key");
4216
+ removeLegacyKey = (worktree) => {
4217
+ try {
4218
+ fs11.rmSync(path10.join(worktree, LEGACY_KEY_RELATIVE_PATH2), { force: true });
4219
+ return true;
4220
+ } catch {
4221
+ return false;
4324
4222
  }
4325
4223
  };
4326
4224
  }
4327
4225
  });
4328
4226
 
4329
- // src/key-lease/resolve-key-ownership/index.ts
4330
- var init_resolve_key_ownership2 = __esm({
4331
- "src/key-lease/resolve-key-ownership/index.ts"() {
4227
+ // src/attribution/remove-legacy-key/index.ts
4228
+ var init_remove_legacy_key2 = __esm({
4229
+ "src/attribution/remove-legacy-key/index.ts"() {
4332
4230
  "use strict";
4333
- init_resolve_key_ownership();
4231
+ init_remove_legacy_key();
4334
4232
  }
4335
4233
  });
4336
4234
 
4337
- // src/key-lease/build-mint-input/build-mint-input.ts
4338
- var buildMintInput;
4339
- var init_build_mint_input = __esm({
4340
- "src/key-lease/build-mint-input/build-mint-input.ts"() {
4235
+ // src/attribution/write-attribution/write-attribution.ts
4236
+ import { randomUUID } from "node:crypto";
4237
+ import * as fs12 from "node:fs";
4238
+ import * as path11 from "node:path";
4239
+ var writeAttribution;
4240
+ var init_write_attribution = __esm({
4241
+ "src/attribution/write-attribution/write-attribution.ts"() {
4341
4242
  "use strict";
4342
- init_expiry_ttl_ms2();
4343
- init_resolve_key_ownership2();
4344
- buildMintInput = (deps) => {
4345
- const ownership = resolveKeyOwnership({
4346
- attribution: deps.attribution,
4347
- managementSubject: deps.managementSubject
4348
- });
4349
- return {
4350
- ...deps.attribution.orgId === void 0 ? {} : { activeOrgId: deps.attribution.orgId },
4351
- allowedModels: deps.extras?.allowedModels,
4352
- description: deps.extras?.description,
4353
- expiresAt: new Date(
4354
- deps.now + expiryTtlMs(deps.ttlMs, deps.extras?.expiryDays)
4355
- ).toISOString(),
4356
- maxBudgetAmount: deps.extras?.maxBudgetAmount ?? null,
4357
- name: deps.extras?.name ?? deps.keyName,
4358
- ...ownership
4359
- };
4243
+ init_resolve_attribution_file2();
4244
+ writeAttribution = (options, attribution) => {
4245
+ const file = resolveAttributionFile(options);
4246
+ if (file === void 0) {
4247
+ return false;
4248
+ }
4249
+ fs12.mkdirSync(path11.dirname(file), { recursive: true });
4250
+ const temporaryFile = `${file}.${String(process.pid)}.${randomUUID()}.tmp`;
4251
+ try {
4252
+ fs12.writeFileSync(temporaryFile, `${JSON.stringify(attribution)}
4253
+ `, "utf8");
4254
+ fs12.renameSync(temporaryFile, file);
4255
+ } catch (error) {
4256
+ fs12.rmSync(temporaryFile, { force: true });
4257
+ throw error;
4258
+ }
4259
+ return true;
4360
4260
  };
4361
4261
  }
4362
4262
  });
4363
4263
 
4364
- // src/key-lease/build-mint-input/index.ts
4365
- var init_build_mint_input2 = __esm({
4366
- "src/key-lease/build-mint-input/index.ts"() {
4264
+ // src/attribution/write-attribution/index.ts
4265
+ var init_write_attribution2 = __esm({
4266
+ "src/attribution/write-attribution/index.ts"() {
4367
4267
  "use strict";
4368
- init_build_mint_input();
4268
+ init_write_attribution();
4369
4269
  }
4370
4270
  });
4371
4271
 
4372
- // src/key-lease/mint-fresh-lease/mint-fresh-lease.ts
4373
- var mintFreshLease;
4374
- var init_mint_fresh_lease = __esm({
4375
- "src/key-lease/mint-fresh-lease/mint-fresh-lease.ts"() {
4272
+ // src/attribution/index.ts
4273
+ var init_attribution = __esm({
4274
+ "src/attribution/index.ts"() {
4376
4275
  "use strict";
4377
- init_build_mint_input2();
4378
- init_key_lease_error2();
4379
- mintFreshLease = async (deps) => {
4380
- const now = deps.clock();
4381
- const input = buildMintInput({
4382
- attribution: deps.attribution,
4383
- extras: deps.extras,
4384
- keyName: deps.keyName,
4385
- managementSubject: deps.managementSubject,
4386
- now,
4387
- ttlMs: deps.ttlMs
4388
- });
4389
- let material;
4390
- try {
4391
- material = await deps.managementClient.create(
4392
- deps.managementCredential,
4393
- input
4394
- );
4395
- } catch (cause) {
4396
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", { cause });
4397
- }
4398
- const minted = {
4399
- key: material.key,
4400
- lease: {
4401
- attribution: deps.attribution,
4402
- expiresAt: material.expires_at,
4403
- keyId: material.id
4404
- }
4405
- };
4406
- try {
4407
- await deps.secretStore.set(minted.key);
4408
- } catch (cause) {
4409
- throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
4410
- }
4411
- deps.state.compareAndSwap(deps.state.snapshot(), minted.lease);
4412
- return minted;
4413
- };
4276
+ init_clear_attribution2();
4277
+ init_detect_worktree_root2();
4278
+ init_read_legacy_key2();
4279
+ init_parse_attribution2();
4280
+ init_read_attribution2();
4281
+ init_remove_legacy_key2();
4282
+ init_resolve_attribution_file2();
4283
+ init_write_attribution2();
4414
4284
  }
4415
4285
  });
4416
4286
 
4417
- // src/key-lease/mint-fresh-lease/index.ts
4418
- var init_mint_fresh_lease2 = __esm({
4419
- "src/key-lease/mint-fresh-lease/index.ts"() {
4420
- "use strict";
4421
- init_mint_fresh_lease();
4422
- }
4423
- });
4424
-
4425
- // src/key-lease/orphan-control/orphan-control.ts
4426
- var controlOrphans;
4427
- var init_orphan_control = __esm({
4428
- "src/key-lease/orphan-control/orphan-control.ts"() {
4287
+ // src/key-lease/lease-state/lease-state.ts
4288
+ var LeaseState;
4289
+ var init_lease_state = __esm({
4290
+ "src/key-lease/lease-state/lease-state.ts"() {
4429
4291
  "use strict";
4430
- controlOrphans = async (options) => {
4431
- const now = options.clock();
4432
- if (!Number.isFinite(now) || !Number.isInteger(options.retentionCycles) || options.retentionCycles <= 0 || !Number.isFinite(options.ttlMs) || options.ttlMs <= 0) {
4433
- return { kind: "unavailable" };
4434
- }
4435
- let keys;
4436
- try {
4437
- keys = await options.managementClient.list(options.managementCredential);
4438
- } catch {
4439
- return { kind: "unavailable" };
4292
+ init_attribution();
4293
+ init_adapters();
4294
+ init_predicates();
4295
+ LeaseState = class _LeaseState {
4296
+ /** Current committed snapshot; mutation is limited to compare-and-swap transitions. */
4297
+ #current;
4298
+ constructor(current) {
4299
+ this.#current = current;
4440
4300
  }
4441
- const staleKeys = keys.data.filter(
4442
- (key) => key.name === options.keyName && key.id !== options.currentKeyId && Date.parse(key.expires_at) <= now
4443
- );
4444
- const deletions = await Promise.allSettled(
4445
- staleKeys.map(
4446
- (key) => Promise.resolve().then(
4447
- () => options.managementClient.delete(options.managementCredential, key.id)
4301
+ /** Restores untrusted persisted metadata or an empty lease.
4302
+ * @param value - Persisted metadata, or undefined for a new installation.
4303
+ * @returns A lease-state coordinator.
4304
+ */
4305
+ static restore(value) {
4306
+ if (value === void 0) {
4307
+ return new _LeaseState(void 0);
4308
+ }
4309
+ if (!isRecord(value)) {
4310
+ throw new ContractParseError("invalid gateway key lease state");
4311
+ }
4312
+ const fields = Object.keys(value);
4313
+ if (fields.some(
4314
+ (field) => !["attribution", "expiresAt", "keyId", "wizardRequest"].includes(
4315
+ field
4448
4316
  )
4449
- )
4450
- );
4451
- return {
4452
- attempted: deletions.length,
4453
- deleted: deletions.filter(({ status }) => status === "fulfilled").length,
4454
- kind: "completed"
4455
- };
4317
+ )) {
4318
+ throw new ContractParseError("invalid gateway key lease state");
4319
+ }
4320
+ const expiresAt = value["expiresAt"];
4321
+ const keyId = value["keyId"];
4322
+ const wizardRequest = value["wizardRequest"];
4323
+ if (typeof expiresAt !== "string" || !Number.isFinite(Date.parse(expiresAt)) || typeof keyId !== "string" || keyId.length === 0 || wizardRequest !== void 0 && typeof wizardRequest !== "string") {
4324
+ throw new ContractParseError("invalid gateway key lease state");
4325
+ }
4326
+ return new _LeaseState({
4327
+ attribution: parseAttribution(value["attribution"]),
4328
+ expiresAt,
4329
+ keyId,
4330
+ wizardRequest
4331
+ });
4332
+ }
4333
+ /** Reads the current non-secret metadata.
4334
+ * @returns The current lease metadata, if one is committed.
4335
+ */
4336
+ snapshot() {
4337
+ return this.#current;
4338
+ }
4339
+ /** Checks whether current metadata belongs to an attribution.
4340
+ * @param attribution - The requested ownership choice.
4341
+ * @returns Whether the current lease has the same attribution.
4342
+ */
4343
+ matchesAttribution(attribution) {
4344
+ if (this.#current === void 0) {
4345
+ return false;
4346
+ }
4347
+ switch (this.#current.attribution.kind) {
4348
+ case "personal":
4349
+ return attribution.kind === "personal";
4350
+ case "project":
4351
+ return attribution.kind === "project" && attribution.projectId === this.#current.attribution.projectId;
4352
+ default:
4353
+ return _LeaseState.#unexpectedAttribution(this.#current.attribution);
4354
+ }
4355
+ }
4356
+ /** Atomically swaps metadata when the expected snapshot is still current.
4357
+ * @param expected - Snapshot observed before asynchronous renewal.
4358
+ * @param next - Fresh metadata to commit.
4359
+ * @returns Whether the swap committed.
4360
+ */
4361
+ compareAndSwap(expected, next) {
4362
+ if (this.#current !== expected) {
4363
+ return false;
4364
+ }
4365
+ this.#current = next;
4366
+ return true;
4367
+ }
4368
+ /** Clears metadata only while the expected snapshot remains current.
4369
+ * @param expected - Snapshot whose lease is being invalidated.
4370
+ * @returns Whether the state was cleared.
4371
+ */
4372
+ clear(expected) {
4373
+ if (this.#current !== expected) {
4374
+ return false;
4375
+ }
4376
+ this.#current = void 0;
4377
+ return true;
4378
+ }
4379
+ static #unexpectedAttribution(value) {
4380
+ throw new TypeError(`Unexpected attribution: ${String(value)}`);
4381
+ }
4456
4382
  };
4457
4383
  }
4458
4384
  });
4459
4385
 
4460
- // src/key-lease/orphan-control/index.ts
4461
- var init_orphan_control2 = __esm({
4462
- "src/key-lease/orphan-control/index.ts"() {
4386
+ // src/key-lease/lease-state/index.ts
4387
+ var init_lease_state2 = __esm({
4388
+ "src/key-lease/lease-state/index.ts"() {
4463
4389
  "use strict";
4464
- init_orphan_control();
4390
+ init_lease_state();
4465
4391
  }
4466
4392
  });
4467
4393
 
4468
- // src/key-lease/reject-lease/reject-lease.ts
4469
- var rejectLease;
4470
- var init_reject_lease = __esm({
4471
- "src/key-lease/reject-lease/reject-lease.ts"() {
4394
+ // src/key-lease/file-secret-store/file-secret-store.ts
4395
+ import { randomUUID as randomUUID2 } from "node:crypto";
4396
+ import * as fs13 from "node:fs/promises";
4397
+ import * as path12 from "node:path";
4398
+ var FileSecretStore;
4399
+ var init_file_secret_store = __esm({
4400
+ "src/key-lease/file-secret-store/file-secret-store.ts"() {
4472
4401
  "use strict";
4473
- init_key_lease_error2();
4474
- rejectLease = async (options) => {
4475
- const shouldClear = options.storedKey === void 0 || options.storedKey.value === options.rejection.key.value;
4476
- if (shouldClear) {
4402
+ init_adapters();
4403
+ init_predicates();
4404
+ init_lease_state2();
4405
+ FileSecretStore = class {
4406
+ #directory;
4407
+ #file;
4408
+ /** Lists only lease files, never opening a secret to discover its scope.
4409
+ * @param directory - Machine-local private lease directory.
4410
+ * @returns Known scope ids, or none before the first lease.
4411
+ */
4412
+ static async scopes(directory) {
4477
4413
  try {
4478
- await options.secretStore.set(void 0);
4414
+ return (await fs13.readdir(directory)).flatMap(
4415
+ (name) => /^lease-([a-f0-9]{64})\.json$/u.exec(name)?.slice(1) ?? []
4416
+ );
4479
4417
  } catch (cause) {
4480
- throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
4418
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
4419
+ return [];
4420
+ throw cause;
4481
4421
  }
4482
- if (!options.state.clear(options.current)) {
4483
- throw new KeyLeaseError("KEY_LEASE_RENEWAL_RACE");
4422
+ }
4423
+ constructor(options) {
4424
+ if (options.directory.length === 0) {
4425
+ throw new TypeError("File secret store requires a directory");
4484
4426
  }
4427
+ if (!/^[a-zA-Z0-9._-]+$/u.test(options.scopeId)) {
4428
+ throw new TypeError("File secret store scope is not portable");
4429
+ }
4430
+ this.#directory = options.directory;
4431
+ this.#file = path12.join(options.directory, `lease-${options.scopeId}.json`);
4485
4432
  }
4486
- switch (options.rejection.kind) {
4487
- case "expired":
4488
- throw new KeyLeaseError("KEY_LEASE_EXPIRED");
4489
- case "unauthorized":
4490
- throw new KeyLeaseError("KEY_LEASE_UNAUTHORIZED");
4491
- default: {
4492
- const unexpected = options.rejection;
4493
- throw new TypeError(`Unexpected lease rejection: ${String(unexpected)}`);
4433
+ /** Reads and parses the scoped gateway credential.
4434
+ * @returns The persisted credential, when present.
4435
+ */
4436
+ async get() {
4437
+ const value = await this.#read();
4438
+ if (value === void 0) return void 0;
4439
+ return parseGatewayKey(isRecord(value) ? value["key"] : value);
4440
+ }
4441
+ /** @returns Metadata saved with the key, absent for legacy key-only files. */
4442
+ async getLease() {
4443
+ const value = await this.#read();
4444
+ return isRecord(value) ? LeaseState.restore(value["lease"]).snapshot() : void 0;
4445
+ }
4446
+ async #read() {
4447
+ let contents;
4448
+ try {
4449
+ contents = await fs13.readFile(this.#file, "utf8");
4450
+ } catch (cause) {
4451
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
4452
+ return void 0;
4453
+ }
4454
+ throw cause;
4494
4455
  }
4456
+ const value = JSON.parse(contents);
4457
+ return value;
4458
+ }
4459
+ /** Writes the scoped gateway credential through an atomic private file.
4460
+ * @param key - The credential to persist, or undefined to remove it.
4461
+ * @param lease - Metadata to commit in the same atomic write as the wizard key.
4462
+ * @returns A promise that settles after the file write or removal.
4463
+ */
4464
+ async set(key, lease) {
4465
+ if (key === void 0) {
4466
+ await fs13.rm(this.#file, { force: true });
4467
+ return;
4468
+ }
4469
+ const staged = await this.stage(key, lease);
4470
+ try {
4471
+ await staged.commit();
4472
+ } finally {
4473
+ await staged.discard();
4474
+ }
4475
+ }
4476
+ /** Prepares a private file without changing the credential visible to readers.
4477
+ * @param key - Replacement credential.
4478
+ * @param lease - Metadata promoted with the credential.
4479
+ * @returns Operations to publish the file or remove the temporary copy.
4480
+ */
4481
+ async stage(key, lease) {
4482
+ await fs13.mkdir(this.#directory, { mode: 448, recursive: true });
4483
+ await fs13.chmod(this.#directory, 448);
4484
+ const temporary = path12.join(this.#directory, `.lease-${randomUUID2()}.tmp`);
4485
+ try {
4486
+ const record = lease === void 0 ? key.value : { key: key.value, lease };
4487
+ await fs13.writeFile(temporary, `${JSON.stringify(record)}
4488
+ `, {
4489
+ encoding: "utf8",
4490
+ flag: "wx",
4491
+ mode: 384
4492
+ });
4493
+ } catch (cause) {
4494
+ await fs13.rm(temporary, { force: true });
4495
+ throw cause;
4496
+ }
4497
+ return {
4498
+ commit: () => fs13.rename(temporary, this.#file),
4499
+ discard: () => fs13.rm(temporary, { force: true })
4500
+ };
4495
4501
  }
4496
4502
  };
4497
4503
  }
4498
4504
  });
4499
4505
 
4500
- // src/key-lease/reject-lease/index.ts
4501
- var init_reject_lease2 = __esm({
4502
- "src/key-lease/reject-lease/index.ts"() {
4506
+ // src/key-lease/file-secret-store/index.ts
4507
+ var init_file_secret_store2 = __esm({
4508
+ "src/key-lease/file-secret-store/index.ts"() {
4503
4509
  "use strict";
4504
- init_reject_lease();
4510
+ init_file_secret_store();
4505
4511
  }
4506
4512
  });
4507
4513
 
4508
- // src/key-lease/mint-key/mint-key.ts
4509
- var mintKey;
4510
- var init_mint_key = __esm({
4511
- "src/key-lease/mint-key/mint-key.ts"() {
4514
+ // src/key-lease/host-storage-secret-store/host-storage-secret-store.ts
4515
+ var HostStorageSecretStore;
4516
+ var init_host_storage_secret_store = __esm({
4517
+ "src/key-lease/host-storage-secret-store/host-storage-secret-store.ts"() {
4512
4518
  "use strict";
4513
- init_management_error2();
4514
- init_build_mint_input2();
4515
- init_is_management_unauthorized2();
4516
- init_key_lease_error2();
4517
- mintKey = async (options) => {
4518
- const now = options.clock();
4519
- if (!Number.isFinite(now)) {
4520
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4519
+ init_adapters();
4520
+ init_lease_state2();
4521
+ HostStorageSecretStore = class {
4522
+ #key;
4523
+ #storage;
4524
+ /** @param storage - Plugin-owned host storage.
4525
+ * @returns The persisted lease scopes across all result pages.
4526
+ */
4527
+ static async scopes(storage) {
4528
+ const scopes = [];
4529
+ let after;
4530
+ do {
4531
+ const page = await storage.scan({
4532
+ prefix: "route33_lease_",
4533
+ ...after === void 0 ? {} : { after }
4534
+ });
4535
+ for (const { key } of page.entries)
4536
+ scopes.push(
4537
+ .../^route33_lease_([a-f0-9]{64})$/u.exec(key)?.slice(1) ?? []
4538
+ );
4539
+ after = page.next;
4540
+ } while (after !== void 0);
4541
+ return scopes;
4521
4542
  }
4522
- if (!Number.isFinite(options.installation.ttlMs)) {
4523
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4543
+ /** @returns Metadata written atomically with this secret, if available. */
4544
+ async getLease() {
4545
+ const entry = await this.#storage.get(this.#key);
4546
+ return typeof entry === "object" && entry !== null && "lease" in entry && typeof entry.lease === "string" ? LeaseState.restore(JSON.parse(entry.lease)).snapshot() : void 0;
4524
4547
  }
4525
- if (options.installation.ttlMs <= 0) {
4526
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4548
+ constructor(options) {
4549
+ this.#key = options.key;
4550
+ this.#storage = options.storage;
4527
4551
  }
4528
- if (options.installation.keyName.length === 0) {
4529
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4552
+ /** Reads and parses the scoped gateway credential.
4553
+ * @returns The persisted credential, when present.
4554
+ */
4555
+ /** Reads the scoped gateway credential out of the box envelope the
4556
+ * host's reactive storage uses, so the TUI part reads what the
4557
+ * server part wrote at the same plugin key.
4558
+ * @returns The persisted credential, when present.
4559
+ */
4560
+ async get() {
4561
+ const value = await this.#storage.get(this.#key);
4562
+ if (typeof value === "object" && value !== null && "value" in value && typeof value.value === "string") {
4563
+ return parseGatewayKey(value.value);
4564
+ }
4565
+ return typeof value === "string" ? parseGatewayKey(value) : void 0;
4530
4566
  }
4531
- const input = buildMintInput({
4532
- attribution: options.attribution,
4533
- extras: options.extras,
4534
- keyName: options.installation.keyName,
4535
- managementSubject: options.identity.subject,
4536
- now,
4537
- ttlMs: options.installation.ttlMs
4538
- });
4539
- let material;
4567
+ /** Writes the scoped gateway credential into the box envelope, through
4568
+ * host-owned storage only.
4569
+ * @param key - The credential to persist, or undefined to remove it.
4570
+ * @param lease
4571
+ * @returns A promise that settles after the host write or removal.
4572
+ */
4573
+ set(key, lease) {
4574
+ return key === void 0 ? this.#storage.remove(this.#key) : this.#storage.set(this.#key, {
4575
+ value: key.value,
4576
+ ...lease ? { lease: JSON.stringify(lease) } : {}
4577
+ });
4578
+ }
4579
+ };
4580
+ }
4581
+ });
4582
+
4583
+ // src/key-lease/host-storage-secret-store/index.ts
4584
+ var init_host_storage_secret_store2 = __esm({
4585
+ "src/key-lease/host-storage-secret-store/index.ts"() {
4586
+ "use strict";
4587
+ init_host_storage_secret_store();
4588
+ }
4589
+ });
4590
+
4591
+ // src/key-lease/key-lease-error/key-lease-error.ts
4592
+ var REDACTED_CAUSE, KeyLeaseError;
4593
+ var init_key_lease_error = __esm({
4594
+ "src/key-lease/key-lease-error/key-lease-error.ts"() {
4595
+ "use strict";
4596
+ REDACTED_CAUSE = "Route 33 gateway key lease dependency failed";
4597
+ KeyLeaseError = class extends Error {
4598
+ constructor(code, options) {
4599
+ super(
4600
+ "Route 33 gateway key lease failed",
4601
+ options?.cause === void 0 ? void 0 : { cause: REDACTED_CAUSE }
4602
+ );
4603
+ this.code = code;
4604
+ this.name = "KeyLeaseError";
4605
+ this.statusCode = options?.statusCode;
4606
+ }
4607
+ code;
4608
+ statusCode;
4609
+ };
4610
+ }
4611
+ });
4612
+
4613
+ // src/key-lease/key-lease-error/index.ts
4614
+ var init_key_lease_error2 = __esm({
4615
+ "src/key-lease/key-lease-error/index.ts"() {
4616
+ "use strict";
4617
+ init_key_lease_error();
4618
+ }
4619
+ });
4620
+
4621
+ // src/key-lease/is-management-unauthorized/is-management-unauthorized.ts
4622
+ var isManagementUnauthorized;
4623
+ var init_is_management_unauthorized = __esm({
4624
+ "src/key-lease/is-management-unauthorized/is-management-unauthorized.ts"() {
4625
+ "use strict";
4626
+ isManagementUnauthorized = (cause) => {
4627
+ if (cause instanceof Response) {
4628
+ return cause.status === 401;
4629
+ }
4630
+ if (typeof cause !== "object") {
4631
+ return false;
4632
+ }
4633
+ if (cause === null) {
4634
+ return false;
4635
+ }
4636
+ if ("status" in cause && cause.status === 401) {
4637
+ return true;
4638
+ }
4639
+ if ("statusCode" in cause && cause.statusCode === 401) {
4640
+ return true;
4641
+ }
4642
+ return "response" in cause && cause.response instanceof Response && cause.response.status === 401;
4643
+ };
4644
+ }
4645
+ });
4646
+
4647
+ // src/key-lease/is-management-unauthorized/index.ts
4648
+ var init_is_management_unauthorized2 = __esm({
4649
+ "src/key-lease/is-management-unauthorized/index.ts"() {
4650
+ "use strict";
4651
+ init_is_management_unauthorized();
4652
+ }
4653
+ });
4654
+
4655
+ // src/key-lease/recover-lease-state/recover-lease-state.ts
4656
+ var recoverLeaseState;
4657
+ var init_recover_lease_state = __esm({
4658
+ "src/key-lease/recover-lease-state/recover-lease-state.ts"() {
4659
+ "use strict";
4660
+ init_is_management_unauthorized2();
4661
+ init_key_lease_error2();
4662
+ recoverLeaseState = async (options) => {
4663
+ let keys;
4540
4664
  try {
4541
- material = await options.managementClient.create(
4542
- options.identity.credential,
4543
- input
4665
+ keys = (await options.managementClient.list(options.managementCredential)).data;
4666
+ } catch (cause) {
4667
+ throw new KeyLeaseError(
4668
+ isManagementUnauthorized(cause) ? "KEY_LEASE_UNAUTHORIZED" : "KEY_LEASE_MINT_FAILED",
4669
+ { cause }
4544
4670
  );
4545
- } catch (cause) {
4546
- if (isManagementUnauthorized(cause)) {
4547
- throw new KeyLeaseError("KEY_LEASE_UNAUTHORIZED", { cause });
4548
- }
4549
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
4550
- cause,
4551
- ...cause instanceof ManagementError && cause.statusCode !== void 0 ? { statusCode: cause.statusCode } : {}
4552
- });
4553
4671
  }
4554
- return {
4555
- key: material.key,
4556
- lease: {
4557
- attribution: options.attribution,
4558
- expiresAt: material.expires_at,
4559
- keyId: material.id
4672
+ const matches = keys.filter((key2) => {
4673
+ if (key2.name !== options.keyName || key2.revoked || key2.status !== "active" || !Number.isFinite(Date.parse(key2.expires_at))) {
4674
+ return false;
4675
+ }
4676
+ switch (options.attribution.kind) {
4677
+ case "personal":
4678
+ return key2.ownership_type === "user_personal" && key2.project_id === null;
4679
+ case "project":
4680
+ return key2.ownership_type === "project" && key2.project_id === options.attribution.projectId;
4681
+ default: {
4682
+ const unexpected = options.attribution;
4683
+ throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
4684
+ }
4560
4685
  }
4686
+ });
4687
+ const key = matches.length === 1 ? matches[0] : void 0;
4688
+ if (key === void 0) {
4689
+ return void 0;
4690
+ }
4691
+ const recovered = {
4692
+ attribution: options.attribution,
4693
+ expiresAt: key.expires_at,
4694
+ keyId: key.id
4561
4695
  };
4696
+ return options.state.compareAndSwap(void 0, recovered) ? recovered : options.state.snapshot();
4562
4697
  };
4563
4698
  }
4564
4699
  });
4565
4700
 
4566
- // src/key-lease/mint-key/index.ts
4567
- var init_mint_key2 = __esm({
4568
- "src/key-lease/mint-key/index.ts"() {
4701
+ // src/key-lease/recover-lease-state/index.ts
4702
+ var init_recover_lease_state2 = __esm({
4703
+ "src/key-lease/recover-lease-state/index.ts"() {
4569
4704
  "use strict";
4570
- init_mint_key();
4705
+ init_recover_lease_state();
4571
4706
  }
4572
4707
  });
4573
4708
 
4574
- // src/key-lease/renew-key/renew-key.ts
4575
- var renewals, renewKey;
4576
- var init_renew_key = __esm({
4577
- "src/key-lease/renew-key/renew-key.ts"() {
4709
+ // src/key-lease/current-lease-state/current-lease-state.ts
4710
+ var currentLeaseState;
4711
+ var init_current_lease_state = __esm({
4712
+ "src/key-lease/current-lease-state/current-lease-state.ts"() {
4578
4713
  "use strict";
4579
- init_is_management_unauthorized2();
4580
4714
  init_key_lease_error2();
4581
- init_mint_key2();
4582
- renewals = /* @__PURE__ */ new WeakMap();
4583
- renewKey = async (options) => {
4584
- const inFlight = renewals.get(options.leaseState);
4585
- if (inFlight !== void 0) {
4586
- return inFlight;
4587
- }
4588
- const expected = options.leaseState.snapshot();
4589
- const renewal = (async () => {
4590
- const discard = async (keyId) => {
4591
- const cleared = options.leaseState.clear(expected);
4592
- await Promise.allSettled([
4593
- Promise.resolve().then(() => options.secretStore.set(void 0)),
4594
- Promise.resolve().then(
4595
- () => options.mint.managementClient.delete(
4596
- options.mint.identity.credential,
4597
- keyId
4598
- )
4599
- )
4600
- ]);
4601
- return cleared;
4602
- };
4603
- let renewed;
4604
- if (expected === void 0) {
4605
- renewed = await mintKey(options.mint);
4606
- } else {
4607
- try {
4608
- const material = await options.mint.managementClient.regenerate(
4609
- options.mint.identity.credential,
4610
- expected.keyId,
4611
- new Date(
4612
- options.mint.clock() + options.mint.installation.ttlMs
4613
- ).toISOString()
4614
- );
4615
- renewed = {
4616
- key: material.key,
4617
- lease: {
4618
- attribution: options.mint.attribution,
4619
- expiresAt: material.expires_at,
4620
- keyId: expected.keyId
4621
- }
4622
- };
4623
- } catch (cause) {
4624
- const cleared = await discard(expected.keyId);
4625
- if (!cleared) {
4626
- throw new KeyLeaseError("KEY_LEASE_RENEWAL_RACE", { cause });
4627
- }
4628
- throw new KeyLeaseError(
4629
- isManagementUnauthorized(cause) ? "KEY_LEASE_UNAUTHORIZED" : "KEY_LEASE_MINT_FAILED",
4630
- { cause }
4631
- );
4632
- }
4633
- }
4634
- try {
4635
- await options.secretStore.set(renewed.key);
4636
- } catch (cause) {
4637
- const cleared = await discard(renewed.lease.keyId);
4638
- if (!cleared) {
4639
- throw new KeyLeaseError("KEY_LEASE_RENEWAL_RACE", { cause });
4640
- }
4641
- throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
4642
- }
4643
- if (!options.leaseState.compareAndSwap(expected, renewed.lease)) {
4644
- await discard(renewed.lease.keyId);
4645
- throw new KeyLeaseError("KEY_LEASE_RENEWAL_RACE");
4646
- }
4647
- return renewed;
4648
- })();
4649
- renewals.set(options.leaseState, renewal);
4715
+ init_recover_lease_state2();
4716
+ currentLeaseState = async (deps) => {
4717
+ let current = deps.state.snapshot();
4718
+ let storedKey;
4650
4719
  try {
4651
- return await renewal;
4652
- } finally {
4653
- if (renewals.get(options.leaseState) === renewal) {
4654
- renewals.delete(options.leaseState);
4655
- }
4720
+ storedKey = await deps.secretStore.get();
4721
+ } catch (cause) {
4722
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
4723
+ }
4724
+ if (current === void 0 && storedKey !== void 0) {
4725
+ current = await recoverLeaseState({
4726
+ attribution: deps.attribution,
4727
+ keyName: deps.keyName,
4728
+ managementClient: deps.managementClient,
4729
+ managementCredential: deps.credential,
4730
+ state: deps.state
4731
+ });
4656
4732
  }
4733
+ return { current, storedKey };
4657
4734
  };
4658
4735
  }
4659
4736
  });
4660
4737
 
4661
- // src/key-lease/renew-key/index.ts
4662
- var init_renew_key2 = __esm({
4663
- "src/key-lease/renew-key/index.ts"() {
4738
+ // src/key-lease/current-lease-state/index.ts
4739
+ var init_current_lease_state2 = __esm({
4740
+ "src/key-lease/current-lease-state/index.ts"() {
4664
4741
  "use strict";
4665
- init_renew_key();
4742
+ init_current_lease_state();
4666
4743
  }
4667
4744
  });
4668
4745
 
4669
- // src/key-lease/resolve-lease-policy/resolve-lease-policy.ts
4670
- var resolveLeasePolicy;
4671
- var init_resolve_lease_policy = __esm({
4672
- "src/key-lease/resolve-lease-policy/resolve-lease-policy.ts"() {
4746
+ // src/key-lease/map-renewal-failure/map-renewal-failure.ts
4747
+ var mapRenewalFailure;
4748
+ var init_map_renewal_failure = __esm({
4749
+ "src/key-lease/map-renewal-failure/map-renewal-failure.ts"() {
4673
4750
  "use strict";
4674
- init_default_gateway_key_renewal_ratio2();
4675
- init_default_gateway_key_ttl_ms2();
4676
4751
  init_key_lease_error2();
4677
- resolveLeasePolicy = (policy) => {
4678
- const resolved = {
4679
- deletePreviousKey: false,
4680
- renewalRatio: DEFAULT_GATEWAY_KEY_RENEWAL_RATIO,
4681
- ttlMs: DEFAULT_GATEWAY_KEY_TTL_MS,
4682
- ...policy
4683
- };
4684
- if (!Number.isFinite(resolved.ttlMs)) {
4685
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4686
- }
4687
- if (resolved.ttlMs <= 0) {
4688
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4689
- }
4690
- if (!Number.isFinite(resolved.renewalRatio)) {
4691
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4692
- }
4693
- if (resolved.renewalRatio <= 0) {
4694
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4695
- }
4696
- if (resolved.renewalRatio >= 1) {
4697
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4752
+ mapRenewalFailure = (options) => {
4753
+ if (options.current === void 0) {
4754
+ throw options.cause;
4698
4755
  }
4699
- if (resolved.orphanRetentionCycles === void 0) {
4700
- return resolved;
4756
+ if (options.now < Date.parse(options.current.expiresAt)) {
4757
+ throw options.cause;
4701
4758
  }
4702
- if (!Number.isInteger(resolved.orphanRetentionCycles)) {
4703
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4759
+ if (!(options.cause instanceof KeyLeaseError)) {
4760
+ throw options.cause;
4704
4761
  }
4705
- if (resolved.orphanRetentionCycles <= 0) {
4706
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4762
+ if (options.cause.code !== "KEY_LEASE_MINT_FAILED") {
4763
+ throw options.cause;
4707
4764
  }
4708
- return resolved;
4765
+ throw new KeyLeaseError("KEY_LEASE_EXPIRED", { cause: options.cause });
4709
4766
  };
4710
4767
  }
4711
4768
  });
4712
4769
 
4713
- // src/key-lease/resolve-lease-policy/index.ts
4714
- var init_resolve_lease_policy2 = __esm({
4715
- "src/key-lease/resolve-lease-policy/index.ts"() {
4770
+ // src/key-lease/map-renewal-failure/index.ts
4771
+ var init_map_renewal_failure2 = __esm({
4772
+ "src/key-lease/map-renewal-failure/index.ts"() {
4716
4773
  "use strict";
4717
- init_resolve_lease_policy();
4774
+ init_map_renewal_failure();
4718
4775
  }
4719
4776
  });
4720
4777
 
4721
- // src/key-lease/resolve-seam-value/resolve-seam-value.ts
4722
- var resolveSeamValue;
4723
- var init_resolve_seam_value = __esm({
4724
- "src/key-lease/resolve-seam-value/resolve-seam-value.ts"() {
4778
+ // src/key-lease/expiry-ttl-ms/expiry-ttl-ms.ts
4779
+ var DAY_MS, expiryTtlMs;
4780
+ var init_expiry_ttl_ms = __esm({
4781
+ "src/key-lease/expiry-ttl-ms/expiry-ttl-ms.ts"() {
4725
4782
  "use strict";
4726
- resolveSeamValue = async (value) => typeof value === "function" ? value() : value;
4783
+ DAY_MS = 864e5;
4784
+ expiryTtlMs = (ttlMs, expiryDays) => {
4785
+ const explicit = (expiryDays ?? 0) * DAY_MS;
4786
+ return explicit > 0 ? explicit : ttlMs;
4787
+ };
4788
+ }
4789
+ });
4790
+
4791
+ // src/key-lease/expiry-ttl-ms/index.ts
4792
+ var init_expiry_ttl_ms2 = __esm({
4793
+ "src/key-lease/expiry-ttl-ms/index.ts"() {
4794
+ "use strict";
4795
+ init_expiry_ttl_ms();
4796
+ }
4797
+ });
4798
+
4799
+ // src/key-lease/resolve-key-ownership/resolve-key-ownership.ts
4800
+ var resolveKeyOwnership;
4801
+ var init_resolve_key_ownership = __esm({
4802
+ "src/key-lease/resolve-key-ownership/resolve-key-ownership.ts"() {
4803
+ "use strict";
4804
+ init_key_lease_error2();
4805
+ resolveKeyOwnership = (options) => {
4806
+ switch (options.attribution.kind) {
4807
+ case "personal":
4808
+ if (options.managementSubject.length === 0) {
4809
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4810
+ }
4811
+ return {
4812
+ ownerId: options.managementSubject,
4813
+ ownerType: "user_personal",
4814
+ projectId: null
4815
+ };
4816
+ case "project":
4817
+ return {
4818
+ ownerId: options.managementSubject,
4819
+ ownerType: "user_project",
4820
+ projectId: options.attribution.projectId
4821
+ };
4822
+ default: {
4823
+ const unexpected = options.attribution;
4824
+ throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
4825
+ }
4826
+ }
4827
+ };
4727
4828
  }
4728
4829
  });
4729
4830
 
4730
- // src/key-lease/resolve-seam-value/index.ts
4731
- var init_resolve_seam_value2 = __esm({
4732
- "src/key-lease/resolve-seam-value/index.ts"() {
4831
+ // src/key-lease/resolve-key-ownership/index.ts
4832
+ var init_resolve_key_ownership2 = __esm({
4833
+ "src/key-lease/resolve-key-ownership/index.ts"() {
4733
4834
  "use strict";
4734
- init_resolve_seam_value();
4835
+ init_resolve_key_ownership();
4735
4836
  }
4736
4837
  });
4737
4838
 
4738
- // src/key-lease/reusable-lease/reusable-lease.ts
4739
- var reusableLease;
4740
- var init_reusable_lease = __esm({
4741
- "src/key-lease/reusable-lease/reusable-lease.ts"() {
4839
+ // src/key-lease/build-mint-input/build-mint-input.ts
4840
+ var buildMintInput;
4841
+ var init_build_mint_input = __esm({
4842
+ "src/key-lease/build-mint-input/build-mint-input.ts"() {
4742
4843
  "use strict";
4743
- reusableLease = (options) => {
4744
- if (options.current === void 0) {
4745
- return void 0;
4746
- }
4747
- if (options.storedKey === void 0) {
4748
- return void 0;
4749
- }
4750
- if (!options.state.matchesAttribution(options.attribution)) {
4751
- return void 0;
4752
- }
4753
- const renewalAt = Date.parse(options.current.expiresAt) - options.policy.ttlMs * (1 - options.policy.renewalRatio);
4754
- if (options.now >= renewalAt) {
4755
- return void 0;
4756
- }
4757
- return { key: options.storedKey, lease: options.current };
4844
+ init_expiry_ttl_ms2();
4845
+ init_resolve_key_ownership2();
4846
+ buildMintInput = (deps) => {
4847
+ const ownership = resolveKeyOwnership({
4848
+ attribution: deps.attribution,
4849
+ managementSubject: deps.managementSubject
4850
+ });
4851
+ return {
4852
+ ...deps.attribution.orgId === void 0 ? {} : { activeOrgId: deps.attribution.orgId },
4853
+ allowedModels: deps.extras?.allowedModels,
4854
+ description: deps.extras?.description,
4855
+ expiresAt: new Date(
4856
+ deps.now + expiryTtlMs(deps.ttlMs, deps.extras?.expiryDays)
4857
+ ).toISOString(),
4858
+ maxBudgetAmount: deps.extras?.maxBudgetAmount ?? null,
4859
+ name: deps.extras?.name ?? deps.keyName,
4860
+ ...ownership
4861
+ };
4758
4862
  };
4759
4863
  }
4760
4864
  });
4761
4865
 
4762
- // src/key-lease/reusable-lease/index.ts
4763
- var init_reusable_lease2 = __esm({
4764
- "src/key-lease/reusable-lease/index.ts"() {
4866
+ // src/key-lease/build-mint-input/index.ts
4867
+ var init_build_mint_input2 = __esm({
4868
+ "src/key-lease/build-mint-input/index.ts"() {
4765
4869
  "use strict";
4766
- init_reusable_lease();
4870
+ init_build_mint_input();
4767
4871
  }
4768
4872
  });
4769
4873
 
4770
- // src/key-lease/lease-for-attribution/lease-for-attribution.ts
4771
- var leaseForAttribution;
4772
- var init_lease_for_attribution = __esm({
4773
- "src/key-lease/lease-for-attribution/lease-for-attribution.ts"() {
4874
+ // src/key-lease/commit-staged-replacement/commit-staged-replacement.ts
4875
+ var commitStagedReplacement;
4876
+ var init_commit_staged_replacement = __esm({
4877
+ "src/key-lease/commit-staged-replacement/commit-staged-replacement.ts"() {
4774
4878
  "use strict";
4775
- init_current_lease_state2();
4776
4879
  init_key_lease_error2();
4777
- init_map_renewal_failure2();
4778
- init_mint_fresh_lease2();
4779
- init_orphan_control2();
4780
- init_reject_lease2();
4781
- init_renew_key2();
4782
- init_resolve_lease_policy2();
4783
- init_resolve_seam_value2();
4784
- init_reusable_lease2();
4785
- leaseForAttribution = async (options) => {
4786
- const policy = resolveLeasePolicy(options.policy);
4787
- const clock = options.clock ?? Date.now;
4788
- const now = clock();
4789
- if (!Number.isFinite(now)) {
4790
- throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
4791
- }
4792
- const { current, storedKey } = await currentLeaseState({
4793
- attribution: options.attribution,
4794
- credential: await resolveSeamValue(options.management.credential),
4795
- keyName: options.installation.keyName,
4796
- managementClient: options.management.client,
4797
- secretStore: options.installation.secretStore,
4798
- state: options.installation.state,
4799
- stateStore: options.installation.stateStore
4800
- });
4801
- if (options.rejection !== void 0) {
4802
- return rejectLease({
4803
- current,
4804
- rejection: options.rejection,
4805
- secretStore: options.installation.secretStore,
4806
- state: options.installation.state,
4807
- storedKey
4808
- });
4809
- }
4810
- if (options.request?.forceMint === true) {
4811
- return mintFreshLease({
4812
- attribution: options.attribution,
4813
- clock,
4814
- extras: options.request.extras,
4815
- keyName: options.installation.keyName,
4816
- managementClient: options.management.client,
4817
- managementCredential: await resolveSeamValue(
4818
- options.management.credential
4819
- ),
4820
- managementSubject: await resolveSeamValue(options.management.subject),
4821
- secretStore: options.installation.secretStore,
4822
- state: options.installation.state,
4823
- stateStore: options.installation.stateStore,
4824
- ttlMs: policy.ttlMs
4825
- });
4826
- }
4827
- const reusable = reusableLease({
4828
- attribution: options.attribution,
4829
- current,
4830
- now,
4831
- policy,
4832
- state: options.installation.state,
4833
- storedKey
4834
- });
4835
- if (reusable !== void 0) {
4836
- return reusable;
4837
- }
4880
+ commitStagedReplacement = async (stage, save, persist) => {
4881
+ const storeFailure = (cause) => {
4882
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
4883
+ };
4884
+ const staged = await stage().catch(storeFailure);
4838
4885
  try {
4839
- const renewed = await renewKey({
4840
- leaseState: options.installation.state,
4841
- mint: {
4842
- attribution: options.attribution,
4843
- clock,
4844
- identity: {
4845
- credential: await resolveSeamValue(options.management.credential),
4846
- subject: await resolveSeamValue(options.management.subject)
4847
- },
4848
- installation: {
4849
- keyName: options.installation.keyName,
4850
- ttlMs: policy.ttlMs
4851
- },
4852
- managementClient: options.management.client
4853
- },
4854
- secretStore: options.installation.secretStore
4855
- });
4856
- if (policy.orphanRetentionCycles !== void 0) {
4857
- await controlOrphans({
4858
- clock,
4859
- currentKeyId: renewed.lease.keyId,
4860
- keyName: options.installation.keyName,
4861
- managementClient: options.management.client,
4862
- managementCredential: await resolveSeamValue(
4863
- options.management.credential
4864
- ),
4865
- retentionCycles: policy.orphanRetentionCycles,
4866
- ttlMs: policy.ttlMs
4867
- });
4868
- }
4869
- return renewed;
4870
- } catch (cause) {
4871
- return mapRenewalFailure({ cause, current, now });
4886
+ save();
4887
+ await (staged ? staged.commit() : persist()).catch(storeFailure);
4888
+ } finally {
4889
+ await staged?.discard();
4872
4890
  }
4873
4891
  };
4874
4892
  }
4875
4893
  });
4876
4894
 
4877
- // src/key-lease/lease-for-attribution/index.ts
4878
- var init_lease_for_attribution2 = __esm({
4879
- "src/key-lease/lease-for-attribution/index.ts"() {
4895
+ // src/key-lease/commit-staged-replacement/index.ts
4896
+ var init_commit_staged_replacement2 = __esm({
4897
+ "src/key-lease/commit-staged-replacement/index.ts"() {
4880
4898
  "use strict";
4881
- init_lease_for_attribution();
4899
+ init_commit_staged_replacement();
4882
4900
  }
4883
4901
  });
4884
4902
 
4885
- // src/attribution/detect-worktree-root/detect-worktree-root.ts
4886
- import * as fs7 from "node:fs";
4887
- import * as path8 from "node:path";
4888
- var detectWorktreeRoot;
4889
- var init_detect_worktree_root = __esm({
4890
- "src/attribution/detect-worktree-root/detect-worktree-root.ts"() {
4903
+ // src/key-lease/mint-fresh-lease/mint-fresh-lease.ts
4904
+ var mintFreshLease;
4905
+ var init_mint_fresh_lease = __esm({
4906
+ "src/key-lease/mint-fresh-lease/mint-fresh-lease.ts"() {
4891
4907
  "use strict";
4892
- detectWorktreeRoot = (startDirectory) => {
4893
- let directory = fs7.realpathSync(startDirectory);
4894
- for (; ; ) {
4895
- const gitEntry = path8.join(directory, ".git");
4896
- if (fs7.existsSync(gitEntry)) {
4897
- const entry = fs7.statSync(gitEntry);
4898
- if (entry.isDirectory() || entry.isFile()) {
4899
- return directory;
4900
- }
4901
- }
4902
- const parent = path8.dirname(directory);
4903
- if (parent === directory) {
4904
- return void 0;
4908
+ init_build_mint_input2();
4909
+ init_commit_staged_replacement2();
4910
+ init_key_lease_error2();
4911
+ mintFreshLease = async (deps) => {
4912
+ const now = deps.clock();
4913
+ const current = deps.state.snapshot();
4914
+ const reusable = () => {
4915
+ if (deps.wizardRequest !== void 0 && current?.wizardRequest === deps.wizardRequest && deps.storedKey !== void 0 && Date.parse(current.expiresAt) > now) {
4916
+ return { key: deps.storedKey, lease: current };
4905
4917
  }
4906
- directory = parent;
4918
+ return void 0;
4919
+ };
4920
+ const reused = reusable();
4921
+ if (reused !== void 0) {
4922
+ deps.saveAttribution?.();
4923
+ return reused;
4907
4924
  }
4908
- };
4909
- }
4910
- });
4911
-
4912
- // src/attribution/detect-worktree-root/index.ts
4913
- var init_detect_worktree_root2 = __esm({
4914
- "src/attribution/detect-worktree-root/index.ts"() {
4915
- "use strict";
4916
- init_detect_worktree_root();
4917
- }
4918
- });
4919
-
4920
- // src/attribution/resolve-attribution-file/resolve-attribution-file.ts
4921
- import * as fs8 from "node:fs";
4922
- import * as path9 from "node:path";
4923
- var resolveAttributionFile;
4924
- var init_resolve_attribution_file = __esm({
4925
- "src/attribution/resolve-attribution-file/resolve-attribution-file.ts"() {
4926
- "use strict";
4927
- init_detect_worktree_root2();
4928
- resolveAttributionFile = (options) => {
4929
- const worktreeRoot = detectWorktreeRoot(options.directory);
4930
- if (worktreeRoot !== void 0) {
4931
- return path9.join(worktreeRoot, ".opencode", "route33.attribution.json");
4925
+ const input = buildMintInput({
4926
+ attribution: deps.attribution,
4927
+ extras: deps.extras,
4928
+ keyName: deps.keyName,
4929
+ managementSubject: deps.managementSubject,
4930
+ now,
4931
+ ttlMs: deps.ttlMs
4932
+ });
4933
+ let material;
4934
+ try {
4935
+ material = await deps.managementClient.create(
4936
+ deps.managementCredential,
4937
+ input
4938
+ );
4939
+ } catch (cause) {
4940
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", { cause });
4932
4941
  }
4933
- const fallbackRoots = {
4934
- "return-undefined": void 0,
4935
- "use-directory": fs8.realpathSync(options.directory)
4942
+ const minted = {
4943
+ key: material.key,
4944
+ lease: {
4945
+ attribution: deps.attribution,
4946
+ expiresAt: material.expires_at,
4947
+ keyId: material.id,
4948
+ ...deps.wizardRequest === void 0 ? {} : { wizardRequest: deps.wizardRequest }
4949
+ }
4936
4950
  };
4937
- const fallbackRoot = fallbackRoots[options.outsideWorktree];
4938
- return fallbackRoot === void 0 ? void 0 : path9.join(fallbackRoot, ".opencode", "route33.attribution.json");
4951
+ const storeFailure = (cause) => {
4952
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
4953
+ };
4954
+ const persist = () => deps.secretStore.set(minted.key, minted.lease);
4955
+ if (deps.saveAttribution && deps.storedKey !== void 0) {
4956
+ await commitStagedReplacement(
4957
+ () => deps.secretStore.stage?.(minted.key, minted.lease) ?? Promise.resolve(void 0),
4958
+ deps.saveAttribution,
4959
+ persist
4960
+ );
4961
+ } else {
4962
+ await persist().catch(storeFailure);
4963
+ deps.saveAttribution?.();
4964
+ }
4965
+ deps.state.compareAndSwap(deps.state.snapshot(), minted.lease);
4966
+ return minted;
4939
4967
  };
4940
4968
  }
4941
4969
  });
4942
4970
 
4943
- // src/attribution/resolve-attribution-file/index.ts
4944
- var init_resolve_attribution_file2 = __esm({
4945
- "src/attribution/resolve-attribution-file/index.ts"() {
4971
+ // src/key-lease/mint-fresh-lease/index.ts
4972
+ var init_mint_fresh_lease2 = __esm({
4973
+ "src/key-lease/mint-fresh-lease/index.ts"() {
4946
4974
  "use strict";
4947
- init_resolve_attribution_file();
4975
+ init_mint_fresh_lease();
4948
4976
  }
4949
4977
  });
4950
4978
 
4951
- // src/attribution/clear-attribution/clear-attribution.ts
4952
- import * as fs9 from "node:fs";
4953
- var clearAttribution;
4954
- var init_clear_attribution = __esm({
4955
- "src/attribution/clear-attribution/clear-attribution.ts"() {
4979
+ // src/key-lease/orphan-control/orphan-control.ts
4980
+ var controlOrphans;
4981
+ var init_orphan_control = __esm({
4982
+ "src/key-lease/orphan-control/orphan-control.ts"() {
4956
4983
  "use strict";
4957
- init_resolve_attribution_file2();
4958
- clearAttribution = (options) => {
4959
- const file = resolveAttributionFile(options);
4960
- if (file === void 0) {
4961
- return false;
4984
+ controlOrphans = async (options) => {
4985
+ const now = options.clock();
4986
+ if (!Number.isFinite(now) || !Number.isInteger(options.retentionCycles) || options.retentionCycles <= 0 || !Number.isFinite(options.ttlMs) || options.ttlMs <= 0) {
4987
+ return { kind: "unavailable" };
4962
4988
  }
4963
- fs9.rmSync(file, { force: true });
4964
- return true;
4989
+ let keys;
4990
+ try {
4991
+ keys = await options.managementClient.list(options.managementCredential);
4992
+ } catch {
4993
+ return { kind: "unavailable" };
4994
+ }
4995
+ const staleKeys = keys.data.filter(
4996
+ (key) => key.name === options.keyName && key.id !== options.currentKeyId && Date.parse(key.expires_at) <= now
4997
+ );
4998
+ const deletions = await Promise.allSettled(
4999
+ staleKeys.map(
5000
+ (key) => Promise.resolve().then(
5001
+ () => options.managementClient.delete(options.managementCredential, key.id)
5002
+ )
5003
+ )
5004
+ );
5005
+ return {
5006
+ attempted: deletions.length,
5007
+ deleted: deletions.filter(({ status }) => status === "fulfilled").length,
5008
+ kind: "completed"
5009
+ };
4965
5010
  };
4966
5011
  }
4967
5012
  });
4968
5013
 
4969
- // src/attribution/clear-attribution/index.ts
4970
- var init_clear_attribution2 = __esm({
4971
- "src/attribution/clear-attribution/index.ts"() {
5014
+ // src/key-lease/orphan-control/index.ts
5015
+ var init_orphan_control2 = __esm({
5016
+ "src/key-lease/orphan-control/index.ts"() {
4972
5017
  "use strict";
4973
- init_clear_attribution();
5018
+ init_orphan_control();
4974
5019
  }
4975
5020
  });
4976
5021
 
4977
- // src/attribution/read-legacy-key/read-legacy-key.ts
4978
- import * as fs10 from "node:fs";
4979
- import * as path10 from "node:path";
4980
- var LEGACY_KEY_RELATIVE_PATH, readLegacyKey;
4981
- var init_read_legacy_key = __esm({
4982
- "src/attribution/read-legacy-key/read-legacy-key.ts"() {
5022
+ // src/key-lease/reject-lease/reject-lease.ts
5023
+ var rejectLease;
5024
+ var init_reject_lease = __esm({
5025
+ "src/key-lease/reject-lease/reject-lease.ts"() {
4983
5026
  "use strict";
4984
- LEGACY_KEY_RELATIVE_PATH = path10.join(".opencode", "route33.key");
4985
- readLegacyKey = (worktree) => {
4986
- if (worktree.trim() === "") return void 0;
4987
- let raw;
4988
- try {
4989
- raw = fs10.readFileSync(
4990
- path10.join(worktree, LEGACY_KEY_RELATIVE_PATH),
4991
- "utf8"
4992
- );
4993
- } catch {
4994
- return void 0;
4995
- }
4996
- try {
4997
- const parsed = JSON.parse(raw);
4998
- if (typeof parsed !== "object" || parsed === null || parsed.type !== "api") {
4999
- return void 0;
5027
+ init_key_lease_error2();
5028
+ rejectLease = async (options) => {
5029
+ const shouldClear = options.storedKey === void 0 || options.storedKey.value === options.rejection.key.value;
5030
+ if (shouldClear) {
5031
+ try {
5032
+ await options.secretStore.set(void 0);
5033
+ } catch (cause) {
5034
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
5000
5035
  }
5001
- const key = parsed.key;
5002
- if (typeof key !== "string" || key.trim() === "") {
5003
- return void 0;
5036
+ if (!options.state.clear(options.current)) {
5037
+ throw new KeyLeaseError("KEY_LEASE_RENEWAL_RACE");
5038
+ }
5039
+ }
5040
+ switch (options.rejection.kind) {
5041
+ case "expired":
5042
+ throw new KeyLeaseError("KEY_LEASE_EXPIRED");
5043
+ case "unauthorized":
5044
+ throw new KeyLeaseError("KEY_LEASE_UNAUTHORIZED");
5045
+ default: {
5046
+ const unexpected = options.rejection;
5047
+ throw new TypeError(`Unexpected lease rejection: ${String(unexpected)}`);
5004
5048
  }
5005
- return { value: key };
5006
- } catch {
5007
- return void 0;
5008
5049
  }
5009
5050
  };
5010
5051
  }
5011
5052
  });
5012
5053
 
5013
- // src/attribution/read-legacy-key/index.ts
5014
- var init_read_legacy_key2 = __esm({
5015
- "src/attribution/read-legacy-key/index.ts"() {
5054
+ // src/key-lease/reject-lease/index.ts
5055
+ var init_reject_lease2 = __esm({
5056
+ "src/key-lease/reject-lease/index.ts"() {
5016
5057
  "use strict";
5017
- init_read_legacy_key();
5058
+ init_reject_lease();
5018
5059
  }
5019
5060
  });
5020
5061
 
5021
- // src/attribution/parse-attribution/read-org-id/read-org-id.ts
5022
- var readOrgId;
5023
- var init_read_org_id = __esm({
5024
- "src/attribution/parse-attribution/read-org-id/read-org-id.ts"() {
5062
+ // src/key-lease/mint-key/mint-key.ts
5063
+ var mintKey;
5064
+ var init_mint_key = __esm({
5065
+ "src/key-lease/mint-key/mint-key.ts"() {
5025
5066
  "use strict";
5026
- init_adapters();
5027
- readOrgId = (value) => {
5028
- const orgId = value["orgId"];
5029
- if (orgId === void 0) {
5030
- return void 0;
5067
+ init_management_error2();
5068
+ init_build_mint_input2();
5069
+ init_is_management_unauthorized2();
5070
+ init_key_lease_error2();
5071
+ mintKey = async (options) => {
5072
+ const now = options.clock();
5073
+ if (!Number.isFinite(now)) {
5074
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
5031
5075
  }
5032
- if (typeof orgId !== "string") {
5033
- throw new ContractParseError("invalid attribution");
5076
+ if (!Number.isFinite(options.installation.ttlMs)) {
5077
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
5034
5078
  }
5035
- return orgId;
5079
+ if (options.installation.ttlMs <= 0) {
5080
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
5081
+ }
5082
+ if (options.installation.keyName.length === 0) {
5083
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
5084
+ }
5085
+ const input = buildMintInput({
5086
+ attribution: options.attribution,
5087
+ extras: options.extras,
5088
+ keyName: options.installation.keyName,
5089
+ managementSubject: options.identity.subject,
5090
+ now,
5091
+ ttlMs: options.installation.ttlMs
5092
+ });
5093
+ let material;
5094
+ try {
5095
+ material = await options.managementClient.create(
5096
+ options.identity.credential,
5097
+ input
5098
+ );
5099
+ } catch (cause) {
5100
+ if (isManagementUnauthorized(cause)) {
5101
+ throw new KeyLeaseError("KEY_LEASE_UNAUTHORIZED", { cause });
5102
+ }
5103
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED", {
5104
+ cause,
5105
+ ...cause instanceof ManagementError && cause.statusCode !== void 0 ? { statusCode: cause.statusCode } : {}
5106
+ });
5107
+ }
5108
+ return {
5109
+ key: material.key,
5110
+ lease: {
5111
+ attribution: options.attribution,
5112
+ expiresAt: material.expires_at,
5113
+ keyId: material.id
5114
+ }
5115
+ };
5036
5116
  };
5037
5117
  }
5038
5118
  });
5039
5119
 
5040
- // src/attribution/parse-attribution/read-org-id/index.ts
5041
- var init_read_org_id2 = __esm({
5042
- "src/attribution/parse-attribution/read-org-id/index.ts"() {
5120
+ // src/key-lease/mint-key/index.ts
5121
+ var init_mint_key2 = __esm({
5122
+ "src/key-lease/mint-key/index.ts"() {
5043
5123
  "use strict";
5044
- init_read_org_id();
5124
+ init_mint_key();
5045
5125
  }
5046
5126
  });
5047
5127
 
5048
- // src/attribution/parse-attribution/parse-attribution.ts
5049
- var parseAttribution;
5050
- var init_parse_attribution = __esm({
5051
- "src/attribution/parse-attribution/parse-attribution.ts"() {
5128
+ // src/key-lease/renew-key/renew-key.ts
5129
+ var renewals, renewKey;
5130
+ var init_renew_key = __esm({
5131
+ "src/key-lease/renew-key/renew-key.ts"() {
5052
5132
  "use strict";
5053
- init_adapters();
5054
- init_predicates();
5055
- init_read_org_id2();
5056
- parseAttribution = (value) => {
5057
- if (!isRecord(value)) {
5058
- throw new ContractParseError("invalid attribution");
5059
- }
5060
- const orgId = readOrgId(value);
5061
- if (value["kind"] === "personal") {
5062
- return { kind: "personal", ...orgId === void 0 ? {} : { orgId } };
5133
+ init_is_management_unauthorized2();
5134
+ init_key_lease_error2();
5135
+ init_mint_key2();
5136
+ renewals = /* @__PURE__ */ new WeakMap();
5137
+ renewKey = async (options) => {
5138
+ const inFlight = renewals.get(options.leaseState);
5139
+ if (inFlight !== void 0) {
5140
+ return inFlight;
5063
5141
  }
5064
- if (value["kind"] === "project" && typeof value["projectId"] === "string") {
5065
- return {
5066
- kind: "project",
5067
- ...orgId === void 0 ? {} : { orgId },
5068
- projectId: value["projectId"]
5142
+ const expected = options.leaseState.snapshot();
5143
+ const renewal = (async () => {
5144
+ const discard = async (keyId) => {
5145
+ const cleared = options.leaseState.clear(expected);
5146
+ await Promise.allSettled([
5147
+ Promise.resolve().then(() => options.secretStore.set(void 0)),
5148
+ Promise.resolve().then(
5149
+ () => options.mint.managementClient.delete(
5150
+ options.mint.identity.credential,
5151
+ keyId
5152
+ )
5153
+ )
5154
+ ]);
5155
+ return cleared;
5069
5156
  };
5157
+ let renewed;
5158
+ if (expected === void 0) {
5159
+ renewed = await mintKey(options.mint);
5160
+ } else {
5161
+ try {
5162
+ const material = await options.mint.managementClient.regenerate(
5163
+ options.mint.identity.credential,
5164
+ expected.keyId,
5165
+ new Date(
5166
+ options.mint.clock() + options.mint.installation.ttlMs
5167
+ ).toISOString()
5168
+ );
5169
+ renewed = {
5170
+ key: material.key,
5171
+ lease: {
5172
+ attribution: options.mint.attribution,
5173
+ expiresAt: material.expires_at,
5174
+ keyId: expected.keyId
5175
+ }
5176
+ };
5177
+ } catch (cause) {
5178
+ const cleared = await discard(expected.keyId);
5179
+ if (!cleared) {
5180
+ throw new KeyLeaseError("KEY_LEASE_RENEWAL_RACE", { cause });
5181
+ }
5182
+ throw new KeyLeaseError(
5183
+ isManagementUnauthorized(cause) ? "KEY_LEASE_UNAUTHORIZED" : "KEY_LEASE_MINT_FAILED",
5184
+ { cause }
5185
+ );
5186
+ }
5187
+ }
5188
+ try {
5189
+ await options.secretStore.set(renewed.key, renewed.lease);
5190
+ } catch (cause) {
5191
+ const cleared = await discard(renewed.lease.keyId);
5192
+ if (!cleared) {
5193
+ throw new KeyLeaseError("KEY_LEASE_RENEWAL_RACE", { cause });
5194
+ }
5195
+ throw new KeyLeaseError("KEY_LEASE_STORE_UNAVAILABLE", { cause });
5196
+ }
5197
+ if (!options.leaseState.compareAndSwap(expected, renewed.lease)) {
5198
+ await discard(renewed.lease.keyId);
5199
+ throw new KeyLeaseError("KEY_LEASE_RENEWAL_RACE");
5200
+ }
5201
+ return renewed;
5202
+ })();
5203
+ renewals.set(options.leaseState, renewal);
5204
+ try {
5205
+ return await renewal;
5206
+ } finally {
5207
+ if (renewals.get(options.leaseState) === renewal) {
5208
+ renewals.delete(options.leaseState);
5209
+ }
5070
5210
  }
5071
- throw new ContractParseError("invalid attribution");
5072
5211
  };
5073
5212
  }
5074
5213
  });
5075
5214
 
5076
- // src/attribution/parse-attribution/index.ts
5077
- var init_parse_attribution2 = __esm({
5078
- "src/attribution/parse-attribution/index.ts"() {
5215
+ // src/key-lease/renew-key/index.ts
5216
+ var init_renew_key2 = __esm({
5217
+ "src/key-lease/renew-key/index.ts"() {
5079
5218
  "use strict";
5080
- init_parse_attribution();
5219
+ init_renew_key();
5081
5220
  }
5082
5221
  });
5083
5222
 
5084
- // src/attribution/read-attribution/read-attribution.ts
5085
- import * as fs11 from "node:fs";
5086
- var readAttribution;
5087
- var init_read_attribution = __esm({
5088
- "src/attribution/read-attribution/read-attribution.ts"() {
5223
+ // src/key-lease/resolve-lease-policy/resolve-lease-policy.ts
5224
+ var resolveLeasePolicy;
5225
+ var init_resolve_lease_policy = __esm({
5226
+ "src/key-lease/resolve-lease-policy/resolve-lease-policy.ts"() {
5089
5227
  "use strict";
5090
- init_parse_attribution2();
5091
- init_resolve_attribution_file2();
5092
- readAttribution = (options) => {
5093
- const file = resolveAttributionFile(options);
5094
- if (file === void 0) {
5095
- return void 0;
5228
+ init_default_gateway_key_renewal_ratio2();
5229
+ init_default_gateway_key_ttl_ms2();
5230
+ init_key_lease_error2();
5231
+ resolveLeasePolicy = (policy) => {
5232
+ const resolved = {
5233
+ deletePreviousKey: false,
5234
+ renewalRatio: DEFAULT_GATEWAY_KEY_RENEWAL_RATIO,
5235
+ ttlMs: DEFAULT_GATEWAY_KEY_TTL_MS,
5236
+ ...policy
5237
+ };
5238
+ if (!Number.isFinite(resolved.ttlMs)) {
5239
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
5096
5240
  }
5097
- try {
5098
- const parsed = JSON.parse(fs11.readFileSync(file, "utf8"));
5099
- return parseAttribution(parsed);
5100
- } catch {
5101
- return void 0;
5241
+ if (resolved.ttlMs <= 0) {
5242
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
5243
+ }
5244
+ if (!Number.isFinite(resolved.renewalRatio)) {
5245
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
5246
+ }
5247
+ if (resolved.renewalRatio <= 0) {
5248
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
5249
+ }
5250
+ if (resolved.renewalRatio >= 1) {
5251
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
5252
+ }
5253
+ if (resolved.orphanRetentionCycles === void 0) {
5254
+ return resolved;
5102
5255
  }
5256
+ if (!Number.isInteger(resolved.orphanRetentionCycles)) {
5257
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
5258
+ }
5259
+ if (resolved.orphanRetentionCycles <= 0) {
5260
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
5261
+ }
5262
+ return resolved;
5103
5263
  };
5104
5264
  }
5105
5265
  });
5106
5266
 
5107
- // src/attribution/read-attribution/index.ts
5108
- var init_read_attribution2 = __esm({
5109
- "src/attribution/read-attribution/index.ts"() {
5267
+ // src/key-lease/resolve-lease-policy/index.ts
5268
+ var init_resolve_lease_policy2 = __esm({
5269
+ "src/key-lease/resolve-lease-policy/index.ts"() {
5110
5270
  "use strict";
5111
- init_read_attribution();
5271
+ init_resolve_lease_policy();
5112
5272
  }
5113
5273
  });
5114
5274
 
5115
- // src/attribution/remove-legacy-key/remove-legacy-key.ts
5116
- import * as fs12 from "node:fs";
5117
- import * as path11 from "node:path";
5118
- var LEGACY_KEY_RELATIVE_PATH2, removeLegacyKey;
5119
- var init_remove_legacy_key = __esm({
5120
- "src/attribution/remove-legacy-key/remove-legacy-key.ts"() {
5275
+ // src/key-lease/resolve-seam-value/resolve-seam-value.ts
5276
+ var resolveSeamValue;
5277
+ var init_resolve_seam_value = __esm({
5278
+ "src/key-lease/resolve-seam-value/resolve-seam-value.ts"() {
5121
5279
  "use strict";
5122
- LEGACY_KEY_RELATIVE_PATH2 = path11.join(".opencode", "route33.key");
5123
- removeLegacyKey = (worktree) => {
5124
- try {
5125
- fs12.rmSync(path11.join(worktree, LEGACY_KEY_RELATIVE_PATH2), { force: true });
5126
- return true;
5127
- } catch {
5128
- return false;
5129
- }
5130
- };
5280
+ resolveSeamValue = async (value) => typeof value === "function" ? value() : value;
5131
5281
  }
5132
5282
  });
5133
5283
 
5134
- // src/attribution/remove-legacy-key/index.ts
5135
- var init_remove_legacy_key2 = __esm({
5136
- "src/attribution/remove-legacy-key/index.ts"() {
5284
+ // src/key-lease/resolve-seam-value/index.ts
5285
+ var init_resolve_seam_value2 = __esm({
5286
+ "src/key-lease/resolve-seam-value/index.ts"() {
5137
5287
  "use strict";
5138
- init_remove_legacy_key();
5288
+ init_resolve_seam_value();
5139
5289
  }
5140
5290
  });
5141
5291
 
5142
- // src/attribution/write-attribution/write-attribution.ts
5143
- import { randomUUID as randomUUID2 } from "node:crypto";
5144
- import * as fs13 from "node:fs";
5145
- import * as path12 from "node:path";
5146
- var writeAttribution;
5147
- var init_write_attribution = __esm({
5148
- "src/attribution/write-attribution/write-attribution.ts"() {
5292
+ // src/key-lease/reusable-lease/reusable-lease.ts
5293
+ var reusableLease;
5294
+ var init_reusable_lease = __esm({
5295
+ "src/key-lease/reusable-lease/reusable-lease.ts"() {
5149
5296
  "use strict";
5150
- init_resolve_attribution_file2();
5151
- writeAttribution = (options, attribution) => {
5152
- const file = resolveAttributionFile(options);
5153
- if (file === void 0) {
5154
- return false;
5297
+ reusableLease = (options) => {
5298
+ if (options.current === void 0) {
5299
+ return void 0;
5155
5300
  }
5156
- fs13.mkdirSync(path12.dirname(file), { recursive: true });
5157
- const temporaryFile = `${file}.${String(process.pid)}.${randomUUID2()}.tmp`;
5158
- try {
5159
- fs13.writeFileSync(temporaryFile, `${JSON.stringify(attribution)}
5160
- `, "utf8");
5161
- fs13.renameSync(temporaryFile, file);
5162
- } catch (error) {
5163
- fs13.rmSync(temporaryFile, { force: true });
5164
- throw error;
5301
+ if (options.storedKey === void 0) {
5302
+ return void 0;
5165
5303
  }
5166
- return true;
5304
+ if (!options.state.matchesAttribution(options.attribution)) {
5305
+ return void 0;
5306
+ }
5307
+ const renewalAt = Date.parse(options.current.expiresAt) - options.policy.ttlMs * (1 - options.policy.renewalRatio);
5308
+ if (options.now >= renewalAt) {
5309
+ return void 0;
5310
+ }
5311
+ return { key: options.storedKey, lease: options.current };
5167
5312
  };
5168
5313
  }
5169
5314
  });
5170
5315
 
5171
- // src/attribution/write-attribution/index.ts
5172
- var init_write_attribution2 = __esm({
5173
- "src/attribution/write-attribution/index.ts"() {
5174
- "use strict";
5175
- init_write_attribution();
5176
- }
5177
- });
5178
-
5179
- // src/attribution/index.ts
5180
- var init_attribution = __esm({
5181
- "src/attribution/index.ts"() {
5316
+ // src/key-lease/reusable-lease/index.ts
5317
+ var init_reusable_lease2 = __esm({
5318
+ "src/key-lease/reusable-lease/index.ts"() {
5182
5319
  "use strict";
5183
- init_clear_attribution2();
5184
- init_detect_worktree_root2();
5185
- init_read_legacy_key2();
5186
- init_parse_attribution2();
5187
- init_read_attribution2();
5188
- init_remove_legacy_key2();
5189
- init_resolve_attribution_file2();
5190
- init_write_attribution2();
5320
+ init_reusable_lease();
5191
5321
  }
5192
5322
  });
5193
5323
 
5194
- // src/key-lease/lease-state/lease-state.ts
5195
- var LeaseState;
5196
- var init_lease_state = __esm({
5197
- "src/key-lease/lease-state/lease-state.ts"() {
5324
+ // src/key-lease/lease-for-attribution/lease-for-attribution.ts
5325
+ var leaseForAttribution;
5326
+ var init_lease_for_attribution = __esm({
5327
+ "src/key-lease/lease-for-attribution/lease-for-attribution.ts"() {
5198
5328
  "use strict";
5199
- init_attribution();
5200
- init_adapters();
5201
- init_predicates();
5202
- LeaseState = class _LeaseState {
5203
- /** Current committed snapshot; mutation is limited to compare-and-swap transitions. */
5204
- #current;
5205
- constructor(current) {
5206
- this.#current = current;
5329
+ init_current_lease_state2();
5330
+ init_key_lease_error2();
5331
+ init_map_renewal_failure2();
5332
+ init_mint_fresh_lease2();
5333
+ init_orphan_control2();
5334
+ init_reject_lease2();
5335
+ init_renew_key2();
5336
+ init_resolve_lease_policy2();
5337
+ init_resolve_seam_value2();
5338
+ init_reusable_lease2();
5339
+ leaseForAttribution = async (options) => {
5340
+ const policy = resolveLeasePolicy(options.policy);
5341
+ const clock = options.clock ?? Date.now;
5342
+ const now = clock();
5343
+ if (!Number.isFinite(now)) {
5344
+ throw new KeyLeaseError("KEY_LEASE_MINT_FAILED");
5207
5345
  }
5208
- /** Restores untrusted persisted metadata or an empty lease.
5209
- * @param value - Persisted metadata, or undefined for a new installation.
5210
- * @returns A lease-state coordinator.
5211
- */
5212
- static restore(value) {
5213
- if (value === void 0) {
5214
- return new _LeaseState(void 0);
5215
- }
5216
- if (!isRecord(value)) {
5217
- throw new ContractParseError("invalid gateway key lease state");
5218
- }
5219
- const fields = Object.keys(value);
5220
- if (fields.length !== 3 || fields.some(
5221
- (field) => field !== "attribution" && field !== "expiresAt" && field !== "keyId"
5222
- )) {
5223
- throw new ContractParseError("invalid gateway key lease state");
5224
- }
5225
- const expiresAt = value["expiresAt"];
5226
- const keyId = value["keyId"];
5227
- if (typeof expiresAt !== "string" || !Number.isFinite(Date.parse(expiresAt)) || typeof keyId !== "string" || keyId.length === 0) {
5228
- throw new ContractParseError("invalid gateway key lease state");
5229
- }
5230
- return new _LeaseState({
5231
- attribution: parseAttribution(value["attribution"]),
5232
- expiresAt,
5233
- keyId
5346
+ const { current, storedKey } = await currentLeaseState({
5347
+ attribution: options.attribution,
5348
+ credential: await resolveSeamValue(options.management.credential),
5349
+ keyName: options.installation.keyName,
5350
+ managementClient: options.management.client,
5351
+ secretStore: options.installation.secretStore,
5352
+ state: options.installation.state,
5353
+ stateStore: options.installation.stateStore
5354
+ });
5355
+ if (options.rejection !== void 0) {
5356
+ return rejectLease({
5357
+ current,
5358
+ rejection: options.rejection,
5359
+ secretStore: options.installation.secretStore,
5360
+ state: options.installation.state,
5361
+ storedKey
5362
+ });
5363
+ }
5364
+ if (options.request?.forceMint === true) {
5365
+ return mintFreshLease({
5366
+ attribution: options.attribution,
5367
+ clock,
5368
+ extras: options.request.extras,
5369
+ keyName: options.installation.keyName,
5370
+ managementClient: options.management.client,
5371
+ managementCredential: await resolveSeamValue(
5372
+ options.management.credential
5373
+ ),
5374
+ managementSubject: await resolveSeamValue(options.management.subject),
5375
+ secretStore: options.installation.secretStore,
5376
+ state: options.installation.state,
5377
+ stateStore: options.installation.stateStore,
5378
+ ttlMs: policy.ttlMs,
5379
+ wizardRequest: options.request.wizardRequest,
5380
+ saveAttribution: options.request.saveAttribution,
5381
+ storedKey
5234
5382
  });
5235
5383
  }
5236
- /** Reads the current non-secret metadata.
5237
- * @returns The current lease metadata, if one is committed.
5238
- */
5239
- snapshot() {
5240
- return this.#current;
5241
- }
5242
- /** Checks whether current metadata belongs to an attribution.
5243
- * @param attribution - The requested ownership choice.
5244
- * @returns Whether the current lease has the same attribution.
5245
- */
5246
- matchesAttribution(attribution) {
5247
- if (this.#current === void 0) {
5248
- return false;
5249
- }
5250
- switch (this.#current.attribution.kind) {
5251
- case "personal":
5252
- return attribution.kind === "personal";
5253
- case "project":
5254
- return attribution.kind === "project" && attribution.projectId === this.#current.attribution.projectId;
5255
- default:
5256
- return _LeaseState.#unexpectedAttribution(this.#current.attribution);
5257
- }
5258
- }
5259
- /** Atomically swaps metadata when the expected snapshot is still current.
5260
- * @param expected - Snapshot observed before asynchronous renewal.
5261
- * @param next - Fresh metadata to commit.
5262
- * @returns Whether the swap committed.
5263
- */
5264
- compareAndSwap(expected, next) {
5265
- if (this.#current !== expected) {
5266
- return false;
5267
- }
5268
- this.#current = next;
5269
- return true;
5384
+ const reusable = reusableLease({
5385
+ attribution: options.attribution,
5386
+ current,
5387
+ now,
5388
+ policy,
5389
+ state: options.installation.state,
5390
+ storedKey
5391
+ });
5392
+ if (reusable !== void 0) {
5393
+ return reusable;
5270
5394
  }
5271
- /** Clears metadata only while the expected snapshot remains current.
5272
- * @param expected - Snapshot whose lease is being invalidated.
5273
- * @returns Whether the state was cleared.
5274
- */
5275
- clear(expected) {
5276
- if (this.#current !== expected) {
5277
- return false;
5395
+ try {
5396
+ const renewed = await renewKey({
5397
+ leaseState: options.installation.state,
5398
+ mint: {
5399
+ attribution: options.attribution,
5400
+ clock,
5401
+ identity: {
5402
+ credential: await resolveSeamValue(options.management.credential),
5403
+ subject: await resolveSeamValue(options.management.subject)
5404
+ },
5405
+ installation: {
5406
+ keyName: options.installation.keyName,
5407
+ ttlMs: policy.ttlMs
5408
+ },
5409
+ managementClient: options.management.client
5410
+ },
5411
+ secretStore: options.installation.secretStore
5412
+ });
5413
+ if (policy.orphanRetentionCycles !== void 0) {
5414
+ await controlOrphans({
5415
+ clock,
5416
+ currentKeyId: renewed.lease.keyId,
5417
+ keyName: options.installation.keyName,
5418
+ managementClient: options.management.client,
5419
+ managementCredential: await resolveSeamValue(
5420
+ options.management.credential
5421
+ ),
5422
+ retentionCycles: policy.orphanRetentionCycles,
5423
+ ttlMs: policy.ttlMs
5424
+ });
5278
5425
  }
5279
- this.#current = void 0;
5280
- return true;
5281
- }
5282
- static #unexpectedAttribution(value) {
5283
- throw new TypeError(`Unexpected attribution: ${String(value)}`);
5426
+ return renewed;
5427
+ } catch (cause) {
5428
+ return mapRenewalFailure({ cause, current, now });
5284
5429
  }
5285
5430
  };
5286
5431
  }
5287
5432
  });
5288
5433
 
5289
- // src/key-lease/lease-state/index.ts
5290
- var init_lease_state2 = __esm({
5291
- "src/key-lease/lease-state/index.ts"() {
5434
+ // src/key-lease/lease-for-attribution/index.ts
5435
+ var init_lease_for_attribution2 = __esm({
5436
+ "src/key-lease/lease-for-attribution/index.ts"() {
5292
5437
  "use strict";
5293
- init_lease_state();
5438
+ init_lease_for_attribution();
5294
5439
  }
5295
5440
  });
5296
5441
 
@@ -5302,7 +5447,7 @@ var init_lease_installation_factory = __esm({
5302
5447
  init_lease_state2();
5303
5448
  createLeaseInstallationFactory = (options) => {
5304
5449
  const installations = /* @__PURE__ */ new Map();
5305
- return (scopeId) => {
5450
+ const open = (scopeId) => {
5306
5451
  const existing = installations.get(scopeId);
5307
5452
  if (existing !== void 0) {
5308
5453
  return existing;
@@ -5316,6 +5461,14 @@ var init_lease_installation_factory = __esm({
5316
5461
  installations.set(scopeId, installation);
5317
5462
  return installation;
5318
5463
  };
5464
+ return Object.assign(open, {
5465
+ scopes: async () => [
5466
+ .../* @__PURE__ */ new Set([
5467
+ ...installations.keys(),
5468
+ ...await options.listScopes?.() ?? []
5469
+ ])
5470
+ ]
5471
+ });
5319
5472
  };
5320
5473
  }
5321
5474
  });
@@ -5356,6 +5509,19 @@ var init_scope_id = __esm({
5356
5509
  throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
5357
5510
  }
5358
5511
  }
5512
+ if (input.attribution.boundKeyId !== void 0) {
5513
+ if (input.folderRealpath === void 0)
5514
+ throw new TypeError("Bound keys require a worktree");
5515
+ if (input.attribution.boundScopeId !== void 0)
5516
+ return input.attribution.boundScopeId;
5517
+ identity = [
5518
+ ...identity,
5519
+ "binding",
5520
+ input.folderRealpath,
5521
+ input.attribution.orgId ?? "",
5522
+ input.attribution.boundKeyId
5523
+ ];
5524
+ }
5359
5525
  return createHash2("sha256").update(JSON.stringify(identity)).digest("hex");
5360
5526
  };
5361
5527
  }
@@ -5424,8 +5590,9 @@ var init_change_attribution = __esm({
5424
5590
  "src/commands/change-attribution/change-attribution.ts"() {
5425
5591
  "use strict";
5426
5592
  changeAttribution = async (options) => {
5427
- await options.clear();
5428
- return options.prompt();
5593
+ const choice = await options.prompt();
5594
+ await options.commit(choice);
5595
+ return choice;
5429
5596
  };
5430
5597
  }
5431
5598
  });
@@ -5512,6 +5679,131 @@ var init_commands = __esm({
5512
5679
  }
5513
5680
  });
5514
5681
 
5682
+ // src/key-lease/workspace-key-binding/workspace-key-binding.ts
5683
+ import { mkdir as mkdir2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
5684
+ import { dirname as dirname4 } from "node:path";
5685
+ var ROTATION_WARNING, pending, WorkspaceKeyBinding;
5686
+ var init_workspace_key_binding = __esm({
5687
+ "src/key-lease/workspace-key-binding/workspace-key-binding.ts"() {
5688
+ "use strict";
5689
+ init_attribution();
5690
+ init_config();
5691
+ init_scope_id2();
5692
+ ROTATION_WARNING = "This key will be rotated. Existing consumers will break. Continue?";
5693
+ pending = /* @__PURE__ */ new Map();
5694
+ WorkspaceKeyBinding = class {
5695
+ constructor(deps) {
5696
+ this.deps = deps;
5697
+ }
5698
+ deps;
5699
+ #listings = /* @__PURE__ */ new Map();
5700
+ /** @param choice - The budget selected by the user.
5701
+ * @returns Secret-free options; local options do not need destructive consent.
5702
+ */
5703
+ async candidates(choice) {
5704
+ const listing = this.#listings.get(choice.orgId) ?? this.deps.client.list(this.deps.token, choice.orgId);
5705
+ this.#listings.set(choice.orgId, listing);
5706
+ const rows = await listing;
5707
+ const keys = rows.data.filter((row) => this.matches(row, choice));
5708
+ if (keys.length === 0) return [];
5709
+ const local = await this.localKeys(new Set(keys.map((row) => row.id)));
5710
+ return keys.map((row) => ({
5711
+ id: row.id,
5712
+ name: row.name,
5713
+ local: local.has(row.id)
5714
+ }));
5715
+ }
5716
+ matches(row, choice) {
5717
+ 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");
5718
+ }
5719
+ async localKeys(ids) {
5720
+ const found = /* @__PURE__ */ new Map();
5721
+ for (const scope of await this.deps.installations.scopes?.() ?? []) {
5722
+ const store = this.deps.installations(scope);
5723
+ const lease = await this.metadata(store);
5724
+ if (!lease || !ids.has(lease.keyId) || Date.parse(lease.expiresAt) <= this.deps.now)
5725
+ continue;
5726
+ const key = await store.secretStore.get();
5727
+ if (key && (await this.metadata(store))?.keyId === lease.keyId)
5728
+ found.set(lease.keyId, scope);
5729
+ }
5730
+ return found;
5731
+ }
5732
+ async metadata(store) {
5733
+ return await store.secretStore.getLease?.() ?? await store.stateStore?.get() ?? store.state.snapshot();
5734
+ }
5735
+ /** @param choice - Selected attribution; the live key must still belong to it.
5736
+ * @param id - Selected management key id, never its secret.
5737
+ * @param confirmed - Explicit consent to rotate this id if plaintext is unavailable.
5738
+ * @returns The attribution to commit after saving the secret.
5739
+ */
5740
+ async bind(choice, id, confirmed) {
5741
+ const row = await this.deps.client.get(this.deps.token, id, choice.orgId);
5742
+ if (row.id !== id || !this.matches(row, choice))
5743
+ throw new GatewayCredentialError(
5744
+ "This key is not available for the selected budget."
5745
+ );
5746
+ const file = resolveAttributionFile(this.deps.state);
5747
+ if (file === void 0)
5748
+ throw new GatewayCredentialError("Key binding requires a worktree.");
5749
+ const bound = { ...choice, boundKeyId: id };
5750
+ const scope = deriveScopeId({
5751
+ attribution: bound,
5752
+ folderRealpath: detectWorktreeRoot(this.deps.state.directory)
5753
+ });
5754
+ const marker = `${file}.${scope}.rotation`;
5755
+ const retry = pending.get(marker);
5756
+ const localScope = retry === void 0 ? (await this.localKeys(/* @__PURE__ */ new Set([id]))).get(id) : void 0;
5757
+ if (localScope !== void 0) return { ...bound, boundScopeId: localScope };
5758
+ const target = this.deps.installations(scope);
5759
+ const { key, lease } = retry ?? await this.rotate(bound, marker, confirmed);
5760
+ await target.secretStore.set(key, lease);
5761
+ await target.stateStore?.set(lease);
5762
+ target.state.compareAndSwap(target.state.snapshot(), lease);
5763
+ await rm2(marker, { force: true });
5764
+ pending.delete(marker);
5765
+ return bound;
5766
+ }
5767
+ async rotate(bound, marker, confirmed) {
5768
+ if (!confirmed) throw new GatewayCredentialError(ROTATION_WARNING);
5769
+ const id = bound.boundKeyId;
5770
+ await mkdir2(dirname4(marker), { recursive: true });
5771
+ try {
5772
+ await writeFile2(marker, "pending\n", { flag: "wx", mode: 384 });
5773
+ } catch (cause) {
5774
+ if (cause instanceof Error && "code" in cause && cause.code === "EEXIST")
5775
+ throw new GatewayCredentialError(
5776
+ "Rotation is already pending. Retry saving in the original session or choose a new key."
5777
+ );
5778
+ throw cause;
5779
+ }
5780
+ const rotated = await this.deps.client.regenerate(
5781
+ this.deps.token,
5782
+ id,
5783
+ void 0,
5784
+ bound.orgId
5785
+ );
5786
+ if (rotated.id !== id)
5787
+ throw new GatewayCredentialError("Rotation returned a different key.");
5788
+ const material = {
5789
+ key: rotated.key,
5790
+ lease: { attribution: bound, expiresAt: rotated.expires_at, keyId: id }
5791
+ };
5792
+ pending.set(marker, material);
5793
+ return material;
5794
+ }
5795
+ };
5796
+ }
5797
+ });
5798
+
5799
+ // src/key-lease/workspace-key-binding/index.ts
5800
+ var init_workspace_key_binding2 = __esm({
5801
+ "src/key-lease/workspace-key-binding/index.ts"() {
5802
+ "use strict";
5803
+ init_workspace_key_binding();
5804
+ }
5805
+ });
5806
+
5515
5807
  // src/ux/attribution-prompt/org-selection-prefix/org-selection-prefix.ts
5516
5808
  var orgSelectionPrefix;
5517
5809
  var init_org_selection_prefix = __esm({
@@ -5662,6 +5954,7 @@ var init_attribution_prompt_error = __esm({
5662
5954
  "use strict";
5663
5955
  init_config();
5664
5956
  MESSAGES = {
5957
+ ATTRIBUTION_BACK: "Left budget selection without changing attribution.",
5665
5958
  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.",
5666
5959
  ATTRIBUTION_SELECTION_INVALID: "That Route 33 option is no longer available. Connect again and pick another."
5667
5960
  };
@@ -5685,15 +5978,16 @@ var init_attribution_prompt_error2 = __esm({
5685
5978
  });
5686
5979
 
5687
5980
  // src/ux/prompt-flow/prompt-flow.ts
5688
- var resolveAttribution;
5981
+ var BACK_SELECTION, resolveAttribution;
5689
5982
  var init_prompt_flow = __esm({
5690
5983
  "src/ux/prompt-flow/prompt-flow.ts"() {
5691
5984
  "use strict";
5692
5985
  init_attribution();
5693
5986
  init_attribution_prompt2();
5694
5987
  init_attribution_prompt_error2();
5988
+ BACK_SELECTION = "/back";
5695
5989
  resolveAttribution = async (options) => {
5696
- const remembered = readAttribution(options.state);
5990
+ const remembered = options.state && readAttribution(options.state);
5697
5991
  if (remembered !== void 0) {
5698
5992
  return remembered;
5699
5993
  }
@@ -5701,12 +5995,16 @@ var init_prompt_flow = __esm({
5701
5995
  throw new AttributionPromptError("ATTRIBUTION_PRESENTER_UNAVAILABLE");
5702
5996
  }
5703
5997
  const plan = createAttributionPrompt(await options.loadProjects());
5704
- const selection = await options.presenter.pick(plan);
5998
+ const selection = await options.presenter.pick({
5999
+ ...plan,
6000
+ options: [...plan.options, { label: "Back", selection: BACK_SELECTION }]
6001
+ });
6002
+ if (selection === BACK_SELECTION)
6003
+ throw new AttributionPromptError("ATTRIBUTION_BACK");
5705
6004
  const attribution = plan.choicesBySelection[selection];
5706
6005
  if (attribution === void 0) {
5707
6006
  throw new AttributionPromptError("ATTRIBUTION_SELECTION_INVALID");
5708
6007
  }
5709
- writeAttribution(options.state, attribution);
5710
6008
  return attribution;
5711
6009
  };
5712
6010
  }
@@ -5774,6 +6072,80 @@ var init_ux = __esm({
5774
6072
  }
5775
6073
  });
5776
6074
 
6075
+ // src/route33-runtime/enrich-inspection/enrich-inspection.ts
6076
+ var enrichInspection;
6077
+ var init_enrich_inspection = __esm({
6078
+ "src/route33-runtime/enrich-inspection/enrich-inspection.ts"() {
6079
+ "use strict";
6080
+ enrichInspection = async ({
6081
+ attribution,
6082
+ client,
6083
+ credential,
6084
+ keyId,
6085
+ subject
6086
+ }) => {
6087
+ const key = await client.get(credential, keyId);
6088
+ const orgId = key.org_id;
6089
+ if (attribution.orgId !== void 0 && attribution.orgId !== orgId) {
6090
+ return {};
6091
+ }
6092
+ const keyDetails = {
6093
+ name: key.name,
6094
+ organisationName: null,
6095
+ projectName: null
6096
+ };
6097
+ switch (attribution.kind) {
6098
+ case "personal": {
6099
+ if (key.project_id !== null) {
6100
+ return {};
6101
+ }
6102
+ return client.listBudgetPolicy(credential, subject(), orgId).then(
6103
+ ({ cap }) => cap === null ? { key: keyDetails } : {
6104
+ key: keyDetails,
6105
+ budget: { amount: String(cap), currency: null }
6106
+ }
6107
+ ).catch(() => ({ key: keyDetails }));
6108
+ }
6109
+ case "project": {
6110
+ const { projectId } = attribution;
6111
+ if (key.project_id !== projectId) {
6112
+ return {};
6113
+ }
6114
+ return Promise.all([
6115
+ client.listProjects(credential, orgId).then(
6116
+ ({ data }) => data.find(({ id, org_id }) => id === projectId && org_id === orgId)
6117
+ ).catch(() => void 0),
6118
+ client.listOrganizations(credential).then(({ data }) => data.find(({ id }) => id === orgId)?.name ?? null).catch(() => null)
6119
+ ]).then(([project, organisationName]) => {
6120
+ const title = project?.name.trim() ?? "";
6121
+ const budget = project?.effective_budget ?? project?.max_budget;
6122
+ return {
6123
+ key: {
6124
+ ...keyDetails,
6125
+ organisationName,
6126
+ projectName: title === "" ? null : title
6127
+ },
6128
+ ...budget == null ? {} : { budget }
6129
+ };
6130
+ });
6131
+ }
6132
+ default: {
6133
+ const unexpected = attribution;
6134
+ throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
6135
+ }
6136
+ }
6137
+ };
6138
+ }
6139
+ });
6140
+
6141
+ // src/route33-runtime/enrich-inspection/index.ts
6142
+ var init_enrich_inspection2 = __esm({
6143
+ "src/route33-runtime/enrich-inspection/index.ts"() {
6144
+ "use strict";
6145
+ init_enrich_inspection();
6146
+ }
6147
+ });
6148
+
5777
6149
  // src/requested-scopes/requested-scopes.ts
5778
6150
  var REQUESTED_OAUTH_SCOPES;
5779
6151
  var init_requested_scopes = __esm({
@@ -5955,6 +6327,8 @@ var init_login_session2 = __esm({
5955
6327
  });
5956
6328
 
5957
6329
  // src/route33-runtime/route33-runtime.ts
6330
+ import { createHash as createHash3 } from "node:crypto";
6331
+ import { statSync as statSync2 } from "node:fs";
5958
6332
  var Route33Runtime;
5959
6333
  var init_route33_runtime = __esm({
5960
6334
  "src/route33-runtime/route33-runtime.ts"() {
@@ -5965,8 +6339,11 @@ var init_route33_runtime = __esm({
5965
6339
  init_commands();
5966
6340
  init_adapters();
5967
6341
  init_key_lease();
6342
+ init_key_lease();
6343
+ init_workspace_key_binding2();
5968
6344
  init_default_base_url2();
5969
6345
  init_ux();
6346
+ init_enrich_inspection2();
5970
6347
  init_login_session2();
5971
6348
  Route33Runtime = class {
5972
6349
  #options;
@@ -6118,6 +6495,8 @@ var init_route33_runtime = __esm({
6118
6495
  }
6119
6496
  const installation = this.#installation(attribution);
6120
6497
  await this.#hydrateState(installation);
6498
+ if (attribution.boundKeyId !== void 0)
6499
+ return this.#boundKey(installation, attribution.boundKeyId);
6121
6500
  const storedKey = await installation.secretStore.get();
6122
6501
  return reusableLease({
6123
6502
  attribution,
@@ -6175,24 +6554,14 @@ var init_route33_runtime = __esm({
6175
6554
  commandHandlers() {
6176
6555
  return {
6177
6556
  "change-attribution": () => changeAttribution({
6178
- clear: () => {
6179
- clearAttribution(this.#options.state);
6557
+ commit: async (choice) => {
6558
+ await this.#leaseAttribution(choice, this.#options.policy);
6559
+ if (!writeAttribution(this.#options.state, choice))
6560
+ throw new TypeError("Workspace attribution requires a worktree");
6180
6561
  },
6181
- prompt: () => this.#resolveAttribution()
6562
+ prompt: () => this.pickAttribution()
6182
6563
  }),
6183
- "inspect-session": async () => {
6184
- try {
6185
- return await this.#inspectSession();
6186
- } catch {
6187
- return inspectSession({
6188
- readAttribution: () => readAttribution(this.#options.state),
6189
- readLease: () => {
6190
- const attribution = readAttribution(this.#options.state);
6191
- return attribution === void 0 ? void 0 : this.#installation(attribution).state.snapshot();
6192
- }
6193
- });
6194
- }
6195
- },
6564
+ "inspect-session": () => this.#inspectSession(),
6196
6565
  "reset-attribution": () => resetAttribution({
6197
6566
  clear: () => {
6198
6567
  clearAttribution(this.#options.state);
@@ -6204,53 +6573,58 @@ var init_route33_runtime = __esm({
6204
6573
  })
6205
6574
  };
6206
6575
  }
6207
- /** Enriched session inspection: the plain report plus the key's name and organisation/project.
6576
+ /** Adds fresh display metadata without prompting for sign-in or changing attribution.
6208
6577
  * @returns A safe session report that cannot carry gateway plaintext.
6209
6578
  */
6210
6579
  async #inspectSession() {
6580
+ const attribution = readAttribution(this.#options.state);
6581
+ const installation = attribution === void 0 ? void 0 : this.#installation(attribution);
6582
+ if (installation !== void 0) {
6583
+ await this.#hydrateState(installation);
6584
+ }
6211
6585
  const base = inspectSession({
6212
- readAttribution: () => readAttribution(this.#options.state),
6213
- readLease: () => {
6214
- const attribution = readAttribution(this.#options.state);
6215
- return attribution === void 0 ? void 0 : this.#installation(attribution).state.snapshot();
6216
- }
6586
+ readAttribution: () => attribution,
6587
+ readLease: () => installation?.state.snapshot()
6217
6588
  });
6218
6589
  const keyId = base.lease?.keyId;
6219
- if (keyId === void 0) {
6590
+ if (attribution === void 0 || keyId === void 0) {
6220
6591
  return base;
6221
6592
  }
6222
- const credential = await this.#session.credential();
6223
- const client = this.#client();
6224
- const [keys, projects] = await Promise.all([
6225
- client.list(credential).then((collection) => collection.data).catch(() => []),
6226
- this.listProjects().catch(() => [])
6227
- ]);
6228
- const key = keys.find((item) => item.id === keyId);
6229
- if (key === void 0) {
6593
+ try {
6594
+ const credential = await this.#session.credential({
6595
+ allowBrowser: false
6596
+ });
6597
+ const details = await enrichInspection({
6598
+ attribution,
6599
+ client: this.#client(),
6600
+ credential,
6601
+ keyId,
6602
+ subject: () => this.#subject(credential)
6603
+ });
6604
+ return { ...base, ...details };
6605
+ } catch {
6230
6606
  return base;
6231
6607
  }
6232
- const projectId = key.project_id ?? null;
6233
- const project = projectId === null ? void 0 : projects.find((item) => item.id === projectId);
6234
- return {
6235
- ...base,
6236
- key: {
6237
- name: key.name,
6238
- organisationName: project?.organisation.name ?? null,
6239
- projectName: project?.name ?? null
6240
- }
6241
- };
6242
6608
  }
6243
6609
  /**
6244
- * Lists the gateway catalog's model ids under the current stored key —
6245
- * the connect form's allowed-models picker offers exactly these.
6246
- * @returns Catalog model ids, empty while no key or catalog exists.
6610
+ * @param scope - The budget being configured. Omit to discover models for the current key.
6611
+ * @returns The management catalog for a budget, or the current key's gateway catalog.
6247
6612
  */
6248
- async catalogModelIds() {
6613
+ async catalogModelIds(scope) {
6614
+ if (scope !== void 0) {
6615
+ const credential = await this.#session.credential({
6616
+ allowBrowser: false
6617
+ });
6618
+ return this.#client().listModelIds(credential, scope);
6619
+ }
6249
6620
  const workspace = await this.storedReusableKey();
6250
6621
  const personal = workspace === void 0 ? await this.#storedPersonalKey() : void 0;
6251
6622
  const value = workspace?.key.value ?? personal?.value;
6252
6623
  if (value === void 0) {
6253
- return [];
6624
+ const credential = await this.#session.credential({
6625
+ allowBrowser: false
6626
+ });
6627
+ return this.#client().listModelIds(credential, {});
6254
6628
  }
6255
6629
  return gatewayModelIds({
6256
6630
  baseURL: readEnvBaseUrl() ?? DEFAULT_BASE_URL,
@@ -6269,12 +6643,41 @@ var init_route33_runtime = __esm({
6269
6643
  * @param attribution - The budget the wizard selected.
6270
6644
  * @param extras - The wizard's key-creation answers.
6271
6645
  * @param directory - Optional worktree override for project leases.
6646
+ * @param saveAttribution - Wizard save that must succeed before replacing a live key.
6272
6647
  * @returns The fresh key material with its lease metadata.
6273
6648
  */
6274
- async mintWorkspaceKey(attribution, extras, directory = this.#options.state.directory) {
6649
+ async mintWorkspaceKey(attribution, extras, directory = this.#options.state.directory, saveAttribution) {
6650
+ const file = resolveAttributionFile({ ...this.#options.state, directory });
6651
+ if (file === void 0)
6652
+ throw new TypeError("Workspace attribution requires a worktree");
6653
+ const previous = statSync2(file, { bigint: true, throwIfNoEntry: false });
6654
+ const wizardRequest = createHash3("sha256").update(
6655
+ JSON.stringify([
6656
+ file,
6657
+ previous?.ino.toString(),
6658
+ previous?.mtimeNs.toString(),
6659
+ attribution,
6660
+ extras,
6661
+ this.#subject(await this.#session.credential())
6662
+ ])
6663
+ ).digest("hex");
6275
6664
  return this.#leaseAttribution(attribution, void 0, directory, {
6276
6665
  extras,
6277
- forceMint: true
6666
+ forceMint: true,
6667
+ wizardRequest,
6668
+ saveAttribution
6669
+ });
6670
+ }
6671
+ /** @returns Binding operations restricted to the current management identity. */
6672
+ async workspaceKeyBinding() {
6673
+ const token = await this.#session.credential({ allowBrowser: false });
6674
+ return new WorkspaceKeyBinding({
6675
+ installations: this.#options.installation,
6676
+ token,
6677
+ subject: this.#subject(token),
6678
+ client: this.#client(),
6679
+ now: this.#now(),
6680
+ state: this.#options.state
6278
6681
  });
6279
6682
  }
6280
6683
  /**
@@ -6292,7 +6695,7 @@ var init_route33_runtime = __esm({
6292
6695
  if (attribution === void 0) {
6293
6696
  return void 0;
6294
6697
  }
6295
- const lease = this.#installation(attribution).state.snapshot();
6698
+ const lease = this.#installation(attribution, directory).state.snapshot();
6296
6699
  const keyId = lease?.keyId;
6297
6700
  if (keyId === void 0) {
6298
6701
  return void 0;
@@ -6320,23 +6723,33 @@ var init_route33_runtime = __esm({
6320
6723
  #now() {
6321
6724
  return (this.#options.clock ?? Date.now)();
6322
6725
  }
6323
- async #resolveAttribution() {
6726
+ /** @returns A fresh selection without changing the active budget. */
6727
+ pickAttribution() {
6324
6728
  return resolveAttribution({
6325
6729
  loadProjects: async () => {
6326
6730
  await this.#session.credential();
6327
6731
  return this.listMintableProjects();
6328
6732
  },
6329
- ...this.#options.presenter === void 0 ? {} : { presenter: this.#options.presenter },
6330
- state: this.#options.state
6733
+ ...this.#options.presenter === void 0 ? {} : { presenter: this.#options.presenter }
6331
6734
  });
6332
6735
  }
6333
6736
  async #lease(policy) {
6334
- const attribution = await this.#resolveAttribution();
6335
- return this.#leaseAttribution(attribution, policy);
6737
+ const remembered = readAttribution(this.#options.state);
6738
+ if (remembered !== void 0)
6739
+ return this.#leaseAttribution(remembered, policy);
6740
+ const choice = await this.pickAttribution();
6741
+ const leased = await this.#leaseAttribution(choice, policy);
6742
+ writeAttribution(this.#options.state, choice);
6743
+ return leased;
6336
6744
  }
6337
6745
  async #leaseAttribution(attribution, policy, directory = this.#options.state.directory, request) {
6338
6746
  const installation = this.#installation(attribution, directory);
6339
6747
  await this.#hydrateState(installation);
6748
+ if (attribution.boundKeyId !== void 0) {
6749
+ if (policy?.renewalRatio === Number.EPSILON)
6750
+ throw new TypeError("Automatic rotation is disabled for a shared key.");
6751
+ return this.#boundKey(installation, attribution.boundKeyId);
6752
+ }
6340
6753
  const minted = await leaseForAttribution({
6341
6754
  attribution,
6342
6755
  ...this.#options.clock === void 0 ? {} : { clock: this.#options.clock },
@@ -6352,13 +6765,20 @@ var init_route33_runtime = __esm({
6352
6765
  await this.#persistState(installation, minted.lease);
6353
6766
  return minted;
6354
6767
  }
6768
+ async #boundKey(installation, id) {
6769
+ const key = await installation.secretStore.get();
6770
+ const lease = await installation.secretStore.getLease?.() ?? await installation.stateStore?.get() ?? installation.state.snapshot();
6771
+ if (!key || lease?.keyId !== id || Date.parse(lease.expiresAt) <= this.#now())
6772
+ throw new KeyLeaseError("KEY_LEASE_EXPIRED");
6773
+ return { key, lease };
6774
+ }
6355
6775
  async #hydrateState(installation) {
6356
6776
  const store = installation.stateStore;
6357
- if (store === void 0 || installation.state.snapshot() !== void 0) {
6777
+ if (installation.state.snapshot() !== void 0) {
6358
6778
  return;
6359
6779
  }
6360
6780
  try {
6361
- const persisted = await store.get();
6781
+ const persisted = await installation.secretStore.getLease?.() ?? await store?.get();
6362
6782
  if (persisted !== void 0) {
6363
6783
  installation.state.compareAndSwap(void 0, persisted);
6364
6784
  }
@@ -6372,6 +6792,13 @@ var init_route33_runtime = __esm({
6372
6792
  }
6373
6793
  }
6374
6794
  #installation(attribution, directory = this.#options.state.directory) {
6795
+ if (attribution.boundKeyId !== void 0)
6796
+ return this.#options.installation(
6797
+ deriveScopeId({
6798
+ attribution,
6799
+ folderRealpath: detectWorktreeRoot(directory)
6800
+ })
6801
+ );
6375
6802
  switch (attribution.kind) {
6376
6803
  case "personal":
6377
6804
  return this.#options.installation(deriveScopeId({ attribution }));
@@ -6403,20 +6830,19 @@ var init_route33_runtime2 = __esm({
6403
6830
  });
6404
6831
 
6405
6832
  // src/v1-entry/unattributed-prompt-gate/unattributed-prompt-gate.ts
6406
- var createUnattributedPromptGate;
6833
+ var CONNECTION_COPY, ATTRIBUTION_COPY, createUnattributedPromptGate;
6407
6834
  var init_unattributed_prompt_gate = __esm({
6408
6835
  "src/v1-entry/unattributed-prompt-gate/unattributed-prompt-gate.ts"() {
6409
6836
  "use strict";
6410
6837
  init_attribution();
6411
- createUnattributedPromptGate = ({ directory, outsideWorktree }) => (input) => {
6838
+ CONNECTION_COPY = "Not connected to Route 33. Run /connect, choose Route 33, and complete sign-in before assigning a budget with /r33.";
6839
+ ATTRIBUTION_COPY = "This folder has no Route 33 budget assigned. Run /r33, choose Route 33, and assign a budget.";
6840
+ createUnattributedPromptGate = ({ directory, isConnected, outsideWorktree }) => async (input) => {
6412
6841
  if (input.model?.providerID !== "route_33") return Promise.resolve();
6842
+ if (!await isConnected()) throw new Error(CONNECTION_COPY);
6413
6843
  const attribution = readAttribution({ directory, outsideWorktree });
6414
6844
  if (attribution !== void 0) return Promise.resolve();
6415
- return Promise.reject(
6416
- new Error(
6417
- "Route 33 needs a budget for this folder first \u2014 run /r33 in OpenCode, choose Route 33, and assign a budget."
6418
- )
6419
- );
6845
+ throw new Error(ATTRIBUTION_COPY);
6420
6846
  };
6421
6847
  }
6422
6848
  });
@@ -6488,6 +6914,11 @@ var init_create_route33_plugin = __esm({
6488
6914
  };
6489
6915
  const runtimeOptions = options.runtime;
6490
6916
  const installation = runtimeOptions === void 0 ? void 0 : runtimeOptions.installation ?? createLeaseInstallationFactory({
6917
+ listScopes: () => FileSecretStore.scopes(
6918
+ resolveV1SecretStoreDirectory({
6919
+ directory: options.secretStoreDirectory
6920
+ })
6921
+ ),
6491
6922
  createSecretStore: (scopeId) => new FileSecretStore({
6492
6923
  directory: resolveV1SecretStoreDirectory({
6493
6924
  ...options.secretStoreDirectory === void 0 ? {} : { directory: options.secretStoreDirectory }
@@ -6533,6 +6964,14 @@ var init_create_route33_plugin = __esm({
6533
6964
  });
6534
6965
  promptGate = createUnattributedPromptGate({
6535
6966
  directory: input.worktree,
6967
+ isConnected: async () => {
6968
+ try {
6969
+ await runtime.login({ allowBrowser: false });
6970
+ return true;
6971
+ } catch {
6972
+ return false;
6973
+ }
6974
+ },
6536
6975
  outsideWorktree: "return-undefined"
6537
6976
  });
6538
6977
  }
@@ -6587,13 +7026,6 @@ var drainPages = async (fetchPage) => {
6587
7026
  // src/management/index.ts
6588
7027
  init_management_error2();
6589
7028
 
6590
- // src/management/sdk-management-keys/sdk-management-keys.ts
6591
- init_adapters();
6592
- import {
6593
- createRoute33Client,
6594
- Route33SdkError
6595
- } from "@r-33/sdk";
6596
-
6597
7029
  // src/contract/management-keys/parse-api-key/parse-api-key.ts
6598
7030
  init_adapters();
6599
7031
  init_predicates();
@@ -6621,6 +7053,7 @@ var parseApiKey = (value) => {
6621
7053
  name: field("name"),
6622
7054
  org_id: field("org_id"),
6623
7055
  ownership_type: value["ownership_type"],
7056
+ ...typeof value["owner_user_id"] === "string" ? { owner_user_id: value["owner_user_id"] } : {},
6624
7057
  project_id: value["project_id"],
6625
7058
  revoked: value["revoked"] === true,
6626
7059
  status
@@ -6868,31 +7301,184 @@ var parseUserMemberships = (value) => {
6868
7301
  if (typeof orgId !== "string" || typeof orgName !== "string") {
6869
7302
  throw new ContractParseError("invalid user memberships");
6870
7303
  }
6871
- return { org_id: orgId, org_name: orgName };
7304
+ return { org_id: orgId, org_name: orgName };
7305
+ })
7306
+ };
7307
+ };
7308
+
7309
+ // src/management/key-read-operations/key-read-operations.ts
7310
+ var keyReadOperations = (call) => {
7311
+ const withCursor = (cursor) => ({ request }) => {
7312
+ const url = new URL(request.url);
7313
+ url.searchParams.set("cursor", cursor);
7314
+ return new Request(url, request);
7315
+ };
7316
+ return {
7317
+ get: async (accessToken, id, orgId) => parseApiKey(
7318
+ await call(
7319
+ accessToken,
7320
+ orgId,
7321
+ (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
7322
+ params: { path: { api_key_id: id } }
7323
+ })
7324
+ )
7325
+ ),
7326
+ list: (accessToken, orgId) => drainPages(
7327
+ (cursor) => call(accessToken, orgId, (client) => {
7328
+ if (cursor !== "") client.use({ onRequest: withCursor(cursor) });
7329
+ return client.GET("/api/v1/api-keys", {});
7330
+ }).then((page) => parseCollection(page, parseApiKey))
7331
+ )
7332
+ };
7333
+ };
7334
+
7335
+ // src/management/sdk-management-keys/mint-request-body/mint-request-body.ts
7336
+ var buildMintRequestBody = (input) => ({
7337
+ ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
7338
+ budget_currency: "EUR",
7339
+ ...input.description === void 0 ? {} : { description: input.description },
7340
+ expires_at: input.expiresAt,
7341
+ ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
7342
+ name: input.name,
7343
+ ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
7344
+ owner_type: input.ownerType,
7345
+ ...input.projectId === null ? {} : { project_id: input.projectId }
7346
+ });
7347
+
7348
+ // src/management/key-write-operations/key-write-operations.ts
7349
+ var keyWriteOperations = (call) => ({
7350
+ create: async (accessToken, input) => parseKeyMaterial(
7351
+ await call(
7352
+ accessToken,
7353
+ input.activeOrgId,
7354
+ (client) => client.POST("/api/v1/api-keys", {
7355
+ body: buildMintRequestBody(input)
7356
+ })
7357
+ )
7358
+ ),
7359
+ delete: async (accessToken, id) => {
7360
+ await call(
7361
+ accessToken,
7362
+ void 0,
7363
+ (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
7364
+ params: { path: { api_key_id: id } }
7365
+ })
7366
+ );
7367
+ },
7368
+ regenerate: async (accessToken, id, expiresAt, orgId) => parseKeyMaterial(
7369
+ await call(
7370
+ accessToken,
7371
+ orgId,
7372
+ (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
7373
+ body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
7374
+ params: { path: { api_key_id: id } }
7375
+ })
7376
+ )
7377
+ ),
7378
+ update: async (accessToken, id, input) => parseApiKey(
7379
+ await call(
7380
+ accessToken,
7381
+ void 0,
7382
+ (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
7383
+ body: {
7384
+ budget_currency: "EUR",
7385
+ ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
7386
+ ...input.name === void 0 ? {} : { name: input.name }
7387
+ },
7388
+ params: { path: { api_key_id: id } }
7389
+ })
7390
+ )
7391
+ )
7392
+ });
7393
+
7394
+ // src/management/sdk-management-keys/exposed-catalog-ids/exposed-catalog-ids.ts
7395
+ init_adapters();
7396
+ init_predicates();
7397
+ var exposedCatalogIds = async (readPage) => {
7398
+ const ids = /* @__PURE__ */ new Set();
7399
+ let offset = 0;
7400
+ for (; ; ) {
7401
+ const page = await readPage(offset);
7402
+ if (!isRecord(page) || !Array.isArray(page.models) || page.offset !== offset || typeof page.total !== "number" || !Number.isSafeInteger(page.total) || page.total < 0) {
7403
+ throw new ContractParseError("invalid model catalog page");
7404
+ }
7405
+ page.models.forEach((row) => {
7406
+ if (!isRecord(row) || typeof row.id !== "string" || !row.id.trim() || typeof row.status !== "string")
7407
+ throw new ContractParseError("invalid model catalog item");
7408
+ if (row.status === "exposed") ids.add(row.id);
7409
+ });
7410
+ offset += page.models.length;
7411
+ if (offset >= page.total || page.models.length === 0)
7412
+ return [...ids].sort((left, right) => left.localeCompare(right));
7413
+ }
7414
+ };
7415
+
7416
+ // src/management/model-catalog-operations/model-catalog-operations.ts
7417
+ var modelCatalogOperations = (call) => ({
7418
+ listModelIds: (token, { orgId, projectId }) => exposedCatalogIds(
7419
+ (offset) => call(token, orgId, (client) => {
7420
+ const query = { offset };
7421
+ if (projectId !== void 0)
7422
+ return client.GET("/api/v1/projects/{project_id}/model-catalog", {
7423
+ params: { path: { project_id: projectId }, query }
7424
+ });
7425
+ if (orgId !== void 0)
7426
+ return client.GET("/api/v1/orgs/{org_id}/model-catalog", {
7427
+ params: { path: { org_id: orgId }, query }
7428
+ });
7429
+ return client.GET("/api/v1/model-catalog", { params: { query } });
7430
+ })
7431
+ )
7432
+ });
7433
+
7434
+ // src/management/list-sdk-projects/list-sdk-projects.ts
7435
+ init_adapters();
7436
+ init_management_error2();
7437
+ var listSdkProjects = async (accessToken, organisationId, call) => {
7438
+ if (organisationId.trim().length === 0) {
7439
+ throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
7440
+ statusCode: 400
7441
+ });
7442
+ }
7443
+ const query = {
7444
+ member_user_id: parseManagementSubject(accessToken),
7445
+ org_id: organisationId
7446
+ };
7447
+ const fetchPage = (cursor) => call(
7448
+ accessToken,
7449
+ void 0,
7450
+ (client) => client.GET("/api/v1/projects", {
7451
+ params: {
7452
+ query: cursor === "" ? query : { ...query, cursor }
7453
+ }
6872
7454
  })
6873
- };
7455
+ ).then((page) => parseCollection(page, parseProject));
7456
+ return drainPages(fetchPage);
6874
7457
  };
6875
7458
 
6876
- // src/management/sdk-management-keys/sdk-management-keys.ts
6877
- init_management_error2();
6878
-
6879
- // src/management/sdk-management-keys/mint-request-body/mint-request-body.ts
6880
- var buildMintRequestBody = (input) => ({
6881
- ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
6882
- budget_currency: "EUR",
6883
- ...input.description === void 0 ? {} : { description: input.description },
6884
- expires_at: input.expiresAt,
6885
- ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
6886
- name: input.name,
6887
- ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
6888
- owner_type: input.ownerType,
6889
- ...input.projectId === null ? {} : { project_id: input.projectId }
7459
+ // src/management/organization-operations/organization-operations.ts
7460
+ var organizationOperations = (call) => ({
7461
+ listOrganizations: async (accessToken) => parseCollection(
7462
+ await call(
7463
+ accessToken,
7464
+ void 0,
7465
+ (client) => client.GET("/api/v1/orgs", {})
7466
+ ),
7467
+ parseOrganization
7468
+ ),
7469
+ listProjects: (accessToken, organisationId) => listSdkProjects(accessToken, organisationId, call)
6890
7470
  });
6891
7471
 
6892
- // src/management/sdk-management-keys/sdk-management-keys.ts
7472
+ // src/management/sdk-management-call/sdk-management-call.ts
7473
+ init_adapters();
7474
+ init_management_error2();
7475
+ import {
7476
+ createRoute33Client,
7477
+ Route33SdkError
7478
+ } from "@r-33/sdk";
6893
7479
  var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
6894
7480
  var ACTIVE_ORG_HEADER = "X-Active-Org-Id";
6895
- var sdkManagementKeys = (options) => {
7481
+ var createSdkCall = (options) => {
6896
7482
  const baseUrl = options.apiBaseUrl.replace(API_PREFIX_PATTERN, "");
6897
7483
  const timeoutMs = options.timeoutMs ?? 1e4;
6898
7484
  const fetchImpl = options.fetchImpl;
@@ -6931,7 +7517,7 @@ var sdkManagementKeys = (options) => {
6931
7517
  }
6932
7518
  return new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
6933
7519
  };
6934
- const call = async (accessToken, activeOrgId, run) => {
7520
+ return async (accessToken, activeOrgId, run) => {
6935
7521
  try {
6936
7522
  const outcome = await run(callClient(accessToken, activeOrgId));
6937
7523
  const code = outcome.response?.status;
@@ -6946,123 +7532,49 @@ var sdkManagementKeys = (options) => {
6946
7532
  throw mapFailure(cause);
6947
7533
  }
6948
7534
  };
6949
- return {
6950
- create: async (accessToken, input) => parseKeyMaterial(
6951
- await call(
6952
- accessToken,
6953
- input.activeOrgId,
6954
- (client) => client.POST("/api/v1/api-keys", {
6955
- body: buildMintRequestBody(input)
6956
- })
6957
- )
6958
- ),
6959
- delete: async (accessToken, id) => {
6960
- await call(
6961
- accessToken,
6962
- void 0,
6963
- (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
6964
- params: { path: { api_key_id: id } }
6965
- })
6966
- );
6967
- },
6968
- get: async (accessToken, id) => parseApiKey(
6969
- await call(
6970
- accessToken,
6971
- void 0,
6972
- (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
6973
- params: { path: { api_key_id: id } }
6974
- })
6975
- )
6976
- ),
6977
- list: async (accessToken) => parseCollection(
6978
- await call(
6979
- accessToken,
6980
- void 0,
6981
- (client) => client.GET("/api/v1/api-keys", {})
6982
- ),
6983
- parseApiKey
6984
- ),
6985
- listOrganizations: async (accessToken) => parseCollection(
6986
- await call(
6987
- accessToken,
6988
- void 0,
6989
- (client) => client.GET("/api/v1/orgs", {})
6990
- ),
6991
- parseOrganization
6992
- ),
6993
- listMemberships: async (accessToken, userId) => parseUserMemberships(
6994
- await call(
6995
- accessToken,
6996
- void 0,
6997
- (client) => client.GET("/api/v1/users/{user_id}/memberships", {
6998
- params: { path: { user_id: userId } }
6999
- })
7000
- )
7001
- ),
7002
- listBudgetPolicy: async (accessToken, userId, activeOrgId) => parseBudgetPolicy(
7003
- await call(
7004
- accessToken,
7005
- activeOrgId,
7006
- (client) => client.GET("/api/v1/users/{user_id}/budget-policy", {
7007
- params: { path: { user_id: userId } }
7008
- })
7009
- )
7010
- ),
7011
- listProjectBudgets: async (accessToken, userId, activeOrgId) => parseCollection(
7012
- await call(
7013
- accessToken,
7014
- activeOrgId,
7015
- (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
7016
- params: { path: { user_id: userId } }
7017
- })
7018
- ),
7019
- parseProjectBudgetState
7020
- ),
7021
- listProjects: async (accessToken, organisationId) => {
7022
- if (organisationId.trim().length === 0) {
7023
- throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
7024
- statusCode: 400
7025
- });
7026
- }
7027
- const query = {
7028
- member_user_id: parseManagementSubject(accessToken),
7029
- org_id: organisationId
7030
- };
7031
- const fetchPage = (cursor) => call(
7032
- accessToken,
7033
- void 0,
7034
- (client) => client.GET("/api/v1/projects", {
7035
- params: {
7036
- query: cursor === "" ? query : { ...query, cursor }
7037
- }
7038
- })
7039
- ).then((page) => parseCollection(page, parseProject));
7040
- return drainPages(fetchPage);
7041
- },
7042
- regenerate: async (accessToken, id, expiresAt) => parseKeyMaterial(
7043
- await call(
7044
- accessToken,
7045
- void 0,
7046
- (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
7047
- body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
7048
- params: { path: { api_key_id: id } }
7049
- })
7050
- )
7051
- ),
7052
- update: async (accessToken, id, input) => parseApiKey(
7053
- await call(
7054
- accessToken,
7055
- void 0,
7056
- (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
7057
- body: {
7058
- budget_currency: "EUR",
7059
- ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
7060
- ...input.name === void 0 ? {} : { name: input.name }
7061
- },
7062
- params: { path: { api_key_id: id } }
7063
- })
7064
- )
7535
+ };
7536
+
7537
+ // src/management/user-context-operations/user-context-operations.ts
7538
+ var userContextOperations = (call) => ({
7539
+ listMemberships: async (accessToken, userId) => parseUserMemberships(
7540
+ await call(
7541
+ accessToken,
7542
+ void 0,
7543
+ (client) => client.GET("/api/v1/users/{user_id}/memberships", {
7544
+ params: { path: { user_id: userId } }
7545
+ })
7546
+ )
7547
+ ),
7548
+ listBudgetPolicy: async (accessToken, userId, activeOrgId) => parseBudgetPolicy(
7549
+ await call(
7550
+ accessToken,
7551
+ activeOrgId,
7552
+ (client) => client.GET("/api/v1/users/{user_id}/budget-policy", {
7553
+ params: { path: { user_id: userId } }
7554
+ })
7065
7555
  )
7556
+ ),
7557
+ listProjectBudgets: async (accessToken, userId, activeOrgId) => parseCollection(
7558
+ await call(
7559
+ accessToken,
7560
+ activeOrgId,
7561
+ (client) => client.GET("/api/v1/users/{user_id}/project-budgets", {
7562
+ params: { path: { user_id: userId } }
7563
+ })
7564
+ ),
7565
+ parseProjectBudgetState
7566
+ )
7567
+ });
7568
+
7569
+ // src/management/sdk-management-keys/sdk-management-keys.ts
7570
+ var sdkManagementKeys = (options) => {
7571
+ const call = createSdkCall(options);
7572
+ return {
7573
+ ...keyReadOperations(call),
7574
+ ...keyWriteOperations(call),
7575
+ ...modelCatalogOperations(call),
7576
+ ...organizationOperations(call),
7577
+ ...userContextOperations(call)
7066
7578
  };
7067
7579
  };
7068
7580
 
@@ -7131,15 +7643,32 @@ init_create_route33_plugin2();
7131
7643
  // src/v2-entry/format-inspect-reply/format-inspect-reply.ts
7132
7644
  var formatInspectReply = (inspection) => {
7133
7645
  const lines = [];
7134
- if (inspection.attribution === void 0) {
7646
+ const { attribution, budget, key } = inspection;
7647
+ if (attribution === void 0) {
7135
7648
  return "Route 33 is not connected in this folder \u2014 run /connect or /r33 to set a budget.";
7136
7649
  }
7137
- lines.push(
7138
- inspection.attribution.kind === "personal" ? "Budget: Personal" : `Budget: Project ${inspection.attribution.projectId}`
7139
- );
7140
- if (inspection.key !== void 0) {
7141
- const scope = inspection.key.projectName === null ? "your personal budget" : `${inspection.key.organisationName ?? "unknown organisation"} \xB7 ${inspection.key.projectName}`;
7142
- lines.push(`Key: ${inspection.key.name} on ${scope}`);
7650
+ const { organisationName, projectName } = key ?? {};
7651
+ let label;
7652
+ let keyScope;
7653
+ switch (attribution.kind) {
7654
+ case "personal":
7655
+ label = "Personal";
7656
+ keyScope = "your personal budget";
7657
+ break;
7658
+ case "project":
7659
+ label = `Project ${projectName ?? attribution.projectId}`;
7660
+ keyScope = [organisationName, projectName].filter(Boolean).join(" \xB7 ");
7661
+ break;
7662
+ default: {
7663
+ const unexpected = attribution;
7664
+ throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
7665
+ }
7666
+ }
7667
+ const cap = budget === void 0 ? "" : [" \u2014 cap", budget.amount, budget.currency].filter((part) => part !== null).join(" ");
7668
+ lines.push(`Budget: ${label}${cap}`);
7669
+ if (key !== void 0) {
7670
+ const scope = keyScope === "" ? "" : ` on ${keyScope}`;
7671
+ lines.push(`Key: ${key.name}${scope}`);
7143
7672
  }
7144
7673
  if (inspection.lease !== void 0) {
7145
7674
  lines.push(`Expires: ${inspection.lease.expiresAt}`);
@@ -7207,10 +7736,12 @@ var r33CommandReply = (deps) => async (subcommand) => {
7207
7736
 
7208
7737
  // src/tui-entry/run-connect/run-connect.ts
7209
7738
  init_attribution();
7739
+ init_cli();
7210
7740
  init_config();
7211
7741
 
7212
7742
  // src/tui-entry/run-connect/budget-pick/budget-pick.ts
7213
7743
  init_config();
7744
+ init_ux();
7214
7745
  var budgetPick = (api) => {
7215
7746
  let captured;
7216
7747
  const capture = (plan, selection) => {
@@ -7238,7 +7769,7 @@ var budgetPick = (api) => {
7238
7769
  "Route 33 connect cancelled \u2014 run /r33 again when ready."
7239
7770
  );
7240
7771
  }
7241
- captured = capture(plan, selection);
7772
+ captured = selection === BACK_SELECTION ? void 0 : capture(plan, selection);
7242
7773
  return selection;
7243
7774
  }
7244
7775
  };
@@ -7282,6 +7813,26 @@ var changeGuard = async (api) => {
7282
7813
  return confirmed === true;
7283
7814
  };
7284
7815
 
7816
+ // src/tui-entry/run-connect/v1-budget-round/v1-budget-round.ts
7817
+ init_ux();
7818
+
7819
+ // src/tui-entry/v2-budget-picker/select-with-back/select-with-back.ts
7820
+ var BACK = /* @__PURE__ */ Symbol("Back");
7821
+ var selectWithBack = async (dialog, input) => {
7822
+ let value = "/back";
7823
+ while (input.options.some((row) => row.value === value)) value += "/";
7824
+ const selected = await dialog.select({
7825
+ ...input,
7826
+ options: [...input.options, { title: "Back", value }]
7827
+ });
7828
+ return selected === value ? BACK : selected;
7829
+ };
7830
+
7831
+ // src/tui-entry/run-connect/finish-connect/finish-connect.ts
7832
+ init_attribution();
7833
+ init_config();
7834
+ init_workspace_key_binding2();
7835
+
7285
7836
  // src/tui-entry/dialog-alert/dialog-alert.ts
7286
7837
  var alertFromDialog = (api, input) => new Promise((resolve2) => {
7287
7838
  let settled = false;
@@ -7307,6 +7858,24 @@ var alertFromDialog = (api, input) => new Promise((resolve2) => {
7307
7858
  );
7308
7859
  });
7309
7860
 
7861
+ // src/v2-entry/parse-connect-answer/parse-connect-answer.ts
7862
+ var ATTRIBUTION_FIELD_KEY = "attribution";
7863
+
7864
+ // src/v2-entry/parse-budget-answer/read-budget-cap/read-budget-cap.ts
7865
+ var readBudgetCap = (answer) => {
7866
+ const value = answer["budget_cap"];
7867
+ if (value === void 0 || value === null) return null;
7868
+ if (typeof value !== "string" && typeof value !== "number") {
7869
+ throw new TypeError("Budget cap must be a number or unlimited");
7870
+ }
7871
+ if (typeof value === "string" && (value.trim() === "" || value.trim().toLowerCase() === "unlimited")) {
7872
+ return null;
7873
+ }
7874
+ const parsed = Number(value);
7875
+ if (Number.isFinite(parsed) && parsed > 0) return parsed;
7876
+ throw new RangeError("Budget cap must be a finite positive number");
7877
+ };
7878
+
7310
7879
  // src/tui-entry/dialog-prompt/dialog-prompt.ts
7311
7880
  var promptFromDialog = (api, input) => new Promise((resolve2) => {
7312
7881
  let settled = false;
@@ -7343,35 +7912,46 @@ var EXPIRY_OPTIONS = [
7343
7912
  { title: "1 year", value: "365" }
7344
7913
  ];
7345
7914
  var v1KeyPrompts = async (deps) => {
7346
- const name = await promptFromDialog(deps.api, {
7347
- placeholder: "e.g. opencode-desk",
7348
- title: "Name for the new Route 33 key"
7349
- }) ?? "opencode";
7350
- const capText = await promptFromDialog(deps.api, {
7351
- placeholder: "blank = unlimited",
7352
- title: "Monthly budget cap in EUR"
7353
- });
7354
- const cap = Number(capText);
7355
- const description = await promptFromDialog(deps.api, {
7356
- title: "Description (optional)"
7357
- });
7915
+ const prompt = async (title, hint) => {
7916
+ const text = await promptFromDialog(deps.api, {
7917
+ title,
7918
+ placeholder: `${hint}/back for budget`
7919
+ });
7920
+ return text === "/back" ? BACK : text;
7921
+ };
7922
+ const name = await prompt(
7923
+ "Name for the new Route 33 key",
7924
+ "e.g. opencode-desk, or "
7925
+ );
7926
+ if (typeof name !== "string") return name;
7927
+ const capText = await prompt(
7928
+ "Monthly budget cap in EUR",
7929
+ "blank = unlimited, or "
7930
+ );
7931
+ if (typeof capText !== "string") return capText;
7932
+ const cap = readBudgetCap({ budget_cap: capText });
7933
+ const description = await prompt("Description (optional)", "");
7934
+ if (typeof description !== "string") return description;
7358
7935
  const expiry = await selectFromDialog(deps.api, {
7359
- options: EXPIRY_OPTIONS,
7936
+ options: [...EXPIRY_OPTIONS, { title: "Back", value: BACK }],
7360
7937
  title: "When should the key expire?"
7361
- }) ?? "90";
7938
+ });
7939
+ if (typeof expiry !== "string") return expiry;
7362
7940
  const allowedModels = await selectFromDialog(deps.api, {
7363
7941
  options: [
7364
7942
  { title: "All models (inherit)", value: "all" },
7365
- ...deps.modelIds.map((id) => ({ title: id, value: id }))
7943
+ ...deps.modelIds.map((id) => ({ title: id, value: id })),
7944
+ { title: "Back", value: BACK }
7366
7945
  ],
7367
7946
  title: "Which models may this key use?"
7368
- }) ?? "all";
7947
+ });
7948
+ if (typeof allowedModels !== "string") return allowedModels;
7369
7949
  return {
7370
7950
  ...allowedModels === "all" ? {} : { allowedModels: [allowedModels] },
7371
- ...description === void 0 ? {} : { description },
7951
+ description,
7372
7952
  expiryDays: Number(expiry),
7373
- ...Number.isFinite(cap) && cap > 0 ? { maxBudgetAmount: cap } : {},
7374
- name
7953
+ maxBudgetAmount: cap,
7954
+ name: name || "opencode"
7375
7955
  };
7376
7956
  };
7377
7957
 
@@ -7380,25 +7960,125 @@ var finishConnect = async (deps) => {
7380
7960
  const runtime = deps.runtime;
7381
7961
  const picked = deps.picked;
7382
7962
  if (runtime === void 0 || picked === void 0) {
7383
- return;
7963
+ return false;
7384
7964
  }
7385
- const modelIds = await runtime.catalogModelIds().catch(() => []);
7386
- const extras = await v1KeyPrompts({
7387
- api: deps.api,
7388
- modelIds
7389
- });
7390
- await runtime.mintWorkspaceKey(picked.choice, extras, deps.directory);
7391
- const keyName = extras.name ?? "opencode";
7965
+ const save = (choice) => {
7966
+ if (!writeAttribution(
7967
+ { directory: deps.directory, outsideWorktree: "return-undefined" },
7968
+ choice
7969
+ )) {
7970
+ throw new GatewayCredentialError(
7971
+ "Route 33 could not save the workspace budget."
7972
+ );
7973
+ }
7974
+ };
7975
+ const mint = async () => {
7976
+ const modelIds = await runtime.catalogModelIds(picked.choice).catch(() => []);
7977
+ const extras = await v1KeyPrompts({ api: deps.api, modelIds });
7978
+ if (typeof extras !== "object") return extras;
7979
+ await runtime.mintWorkspaceKey(
7980
+ picked.choice,
7981
+ extras,
7982
+ deps.directory,
7983
+ () => {
7984
+ save(picked.choice);
7985
+ }
7986
+ );
7987
+ return `Route 33 key "${extras.name ?? "opencode"}" created \u2713 \u2014 ${picked.label}.`;
7988
+ };
7989
+ const acquire = async () => {
7990
+ const binding = await runtime.workspaceKeyBinding();
7991
+ const keys = await binding.candidates(picked.choice);
7992
+ const chooseKey = async () => keys.length === 0 ? "new" : await selectFromDialog(deps.api, {
7993
+ title: "Which key should this folder use?",
7994
+ options: [
7995
+ { title: "Mint a new key", value: "new" },
7996
+ ...keys.map((key) => ({
7997
+ title: `Bind ${key.name} (${key.id})`,
7998
+ value: key.id
7999
+ })),
8000
+ { title: "Back", value: BACK }
8001
+ ]
8002
+ });
8003
+ for (; ; ) {
8004
+ const selection = await chooseKey();
8005
+ if (typeof selection !== "string") return selection;
8006
+ if (selection === "new") return mint();
8007
+ const selected = keys.find((key) => key.id === selection);
8008
+ if (!selected) return void 0;
8009
+ if (!selected.local) {
8010
+ const decision = await selectFromDialog(deps.api, {
8011
+ title: ROTATION_WARNING,
8012
+ options: [
8013
+ { title: "Back", value: "back" },
8014
+ { title: "Rotate key", value: "rotate" }
8015
+ ]
8016
+ });
8017
+ if (decision === "back") continue;
8018
+ if (decision !== "rotate") return void 0;
8019
+ }
8020
+ save(await binding.bind(picked.choice, selected.id, !selected.local));
8021
+ return `Route 33 key "${selected.name}" bound \u2014 ${picked.label}.`;
8022
+ }
8023
+ };
8024
+ const result = await acquire();
8025
+ if (result === void 0) return false;
8026
+ if (result === BACK) return BACK;
7392
8027
  await alertFromDialog(deps.api, {
7393
- message: `Route 33 key "${keyName}" created \u2713 \u2014 ${picked.label}.`,
8028
+ message: result,
7394
8029
  title: "Route 33"
7395
8030
  });
8031
+ return true;
8032
+ };
8033
+
8034
+ // src/tui-entry/run-connect/v1-budget-round/v1-budget-round.ts
8035
+ var v1BudgetRound = async (api, runtime, picker) => {
8036
+ const chooseBudget = async (plan) => {
8037
+ for (; ; ) {
8038
+ const selection = await picker.pick({
8039
+ ...plan,
8040
+ options: [
8041
+ ...plan.options,
8042
+ { label: "Back", selection: BACK_SELECTION }
8043
+ ]
8044
+ });
8045
+ if (selection === BACK_SELECTION) return BACK;
8046
+ const result = await finishConnect({
8047
+ api,
8048
+ directory: api.state.path.directory,
8049
+ runtime,
8050
+ picked: picker.captured()
8051
+ });
8052
+ if (result !== BACK) return result;
8053
+ }
8054
+ };
8055
+ const orgs = await runtime.listMintableOrgs();
8056
+ if (orgs.length <= 1) {
8057
+ const projects = orgs[0]?.projects ?? await runtime.listMintableProjects();
8058
+ return await chooseBudget(createAttributionPrompt(projects)) === true;
8059
+ }
8060
+ for (; ; ) {
8061
+ const selection = await selectFromDialog(api, {
8062
+ title: "Choose an organisation",
8063
+ options: [
8064
+ ...orgs.map(({ id, name }) => ({ title: name, value: id })),
8065
+ { title: "Back", value: BACK }
8066
+ ]
8067
+ });
8068
+ const org = orgs.find(({ id }) => id === selection);
8069
+ if (!org) return false;
8070
+ const result = await chooseBudget(
8071
+ createAttributionPrompt(org.projects, { orgs: [org] })
8072
+ );
8073
+ if (result !== BACK) return result;
8074
+ }
7396
8075
  };
7397
8076
 
7398
8077
  // src/tui-entry/run-connect/run-connect.ts
7399
8078
  var runConnect = async (api, composeOptions) => {
7400
8079
  const directory = api.state.path.directory;
7401
8080
  const state = { directory, outsideWorktree: "return-undefined" };
8081
+ if (readEnvDirectApiKey() !== void 0) return;
7402
8082
  try {
7403
8083
  const composed = composeOptions();
7404
8084
  if (composed.clientId === "") {
@@ -7415,14 +8095,11 @@ var runConnect = async (api, composeOptions) => {
7415
8095
  if (!change) {
7416
8096
  return;
7417
8097
  }
7418
- clearAttribution(state);
7419
8098
  }
7420
8099
  let instance;
7421
- let picked;
7422
- let pickedLabel;
7423
8100
  const picker = budgetPick(api);
7424
8101
  const { createRoute33Plugin: createRoute33Plugin2 } = await Promise.resolve().then(() => (init_create_route33_plugin2(), create_route33_plugin_exports));
7425
- const hooks = await createRoute33Plugin2({
8102
+ await createRoute33Plugin2({
7426
8103
  ...composed,
7427
8104
  bindRuntime: (bound) => {
7428
8105
  instance = bound;
@@ -7430,13 +8107,7 @@ var runConnect = async (api, composeOptions) => {
7430
8107
  runtime: {
7431
8108
  ...runtime,
7432
8109
  presenter: {
7433
- pick: async (plan) => {
7434
- const selection = await picker.pick(plan);
7435
- const captured = picker.captured();
7436
- picked = captured?.choice;
7437
- pickedLabel = captured?.label;
7438
- return selection;
7439
- },
8110
+ pick: picker.pick,
7440
8111
  present: (copy) => {
7441
8112
  api.ui.toast({
7442
8113
  message: copy.message,
@@ -7448,18 +8119,15 @@ var runConnect = async (api, composeOptions) => {
7448
8119
  }
7449
8120
  }
7450
8121
  })({ worktree: directory });
7451
- await hooks.config({});
7452
- await finishConnect({
7453
- api,
7454
- directory,
7455
- picked: picked === void 0 ? void 0 : { choice: picked, label: pickedLabel ?? "your budget" },
7456
- runtime: instance
7457
- });
7458
- api.ui.toast({
7459
- message: "Route 33 connected \u2713 \u2014 pick a route_33 model and start prompting.",
7460
- title: "Route 33",
7461
- variant: "success"
7462
- });
8122
+ if (instance === void 0)
8123
+ throw new TypeError("Route 33 runtime expected");
8124
+ if (await v1BudgetRound(api, instance, picker)) {
8125
+ api.ui.toast({
8126
+ message: "Route 33 connected \u2713 \u2014 pick a route_33 model and start prompting.",
8127
+ title: "Route 33",
8128
+ variant: "success"
8129
+ });
8130
+ }
7463
8131
  } catch (error) {
7464
8132
  api.ui.toast({
7465
8133
  message: error instanceof Error ? error.message : String(error),
@@ -7599,6 +8267,7 @@ init_ux();
7599
8267
 
7600
8268
  // src/tui-entry/show-r33-menu/show-r33-menu.ts
7601
8269
  init_attribution();
8270
+ init_cli();
7602
8271
 
7603
8272
  // src/tui-entry/v2-autoconnect/v2-autoconnect.ts
7604
8273
  init_attribution();
@@ -7633,6 +8302,7 @@ var CONNECT_COPY = {
7633
8302
  failFastWorktree: "Route 33 attributes usage to a project inside a Git worktree. Open a Git repository (or run git init), then connect again.",
7634
8303
  selectionInvalid: "That Route 33 option is no longer available. Connect again and pick another.",
7635
8304
  signedInNextStep: "Signed in to Route 33 \u2713. One more step: connect again, choose Route 33, and assign a budget for this folder.",
8305
+ budgetSelected: "Budget selected. Connect again to configure the key for this budget.",
7636
8306
  mintNoBudget: "Route 33 could not create the key \u2014 its cap exceeds this budget. Ask an owner to raise the budget, or pick another."
7637
8307
  };
7638
8308
 
@@ -7663,6 +8333,14 @@ var v2CompletionNotice = ({ dialog, expiryDays, keyName, label }) => () => dialo
7663
8333
  // src/tui-entry/v2-budget-picker/show-completion/show-completion.ts
7664
8334
  var showCompletion = (dialog, options, selection, extras) => {
7665
8335
  const label = options.find((option) => option.value === selection)?.label ?? selection;
8336
+ const bound = extras[`existing_key:${selection}`];
8337
+ if (bound !== void 0 && bound !== "new") {
8338
+ void dialog.alert({
8339
+ title: "Route 33",
8340
+ message: `Key ${bound} bound \u2014 ${label}.`
8341
+ });
8342
+ return;
8343
+ }
7666
8344
  void v2CompletionNotice({
7667
8345
  dialog,
7668
8346
  expiryDays: extras["budget_expiry"],
@@ -7690,6 +8368,9 @@ var answerPass = async (deps) => {
7690
8368
  }
7691
8369
  const settled = await deps.pollTerminal(second.data.attemptID);
7692
8370
  if (settled.kind !== "complete") {
8371
+ if (settled.kind === "failed" && settled.message?.includes(CONNECT_COPY.budgetSelected) === true) {
8372
+ return "budget-selected";
8373
+ }
7693
8374
  if (settled.kind === "failed" && (settled.message ?? "").includes(CONNECT_COPY.mintNoBudget)) {
7694
8375
  return "no-budgets";
7695
8376
  }
@@ -7702,11 +8383,9 @@ var answerPass = async (deps) => {
7702
8383
  };
7703
8384
 
7704
8385
  // src/v2-entry/connect-form/connect-form.ts
7705
- var ATTRIBUTION_FIELD_KEY = "attribution";
7706
- var ORGANISATION_FIELD_KEY = "organisation";
7707
-
7708
- // src/v2-entry/parse-connect-answer/parse-connect-answer.ts
7709
8386
  var ATTRIBUTION_FIELD_KEY2 = "attribution";
8387
+ var ORGANISATION_FIELD_KEY = "organisation";
8388
+ var BUDGET_CAP_FIELD_KEY = "budget_cap";
7710
8389
 
7711
8390
  // src/tui-entry/v2-integration-surface/v2-integration-surface.ts
7712
8391
  var v2IntegrationSurface = (context) => context.client?.integration ?? context.client?.api?.integration;
@@ -7726,30 +8405,70 @@ var v2FormFields = async (context) => {
7726
8405
  };
7727
8406
 
7728
8407
  // src/v2-entry/v2-key-prompts/ask-field/ask-field.ts
7729
- var askField = (dialog, field) => {
8408
+ var askField = async (dialog, field, previous) => {
7730
8409
  const title = field.title ?? field.key;
7731
8410
  const options = field.options ?? [];
7732
8411
  if (options.length === 0) {
7733
- return dialog.prompt({ placeholder: field.placeholder, title });
8412
+ const text = await dialog.prompt({
8413
+ description: "Enter /back to return to the previous step, or Esc to cancel.",
8414
+ placeholder: field.placeholder,
8415
+ title,
8416
+ value: previous
8417
+ });
8418
+ return text === "/back" ? BACK : text;
7734
8419
  }
7735
- return dialog.select({
8420
+ const selected = await selectWithBack(dialog, {
8421
+ current: options.some(({ value }) => value === previous) ? previous : void 0,
7736
8422
  options: options.map((option) => ({
7737
8423
  title: option.label,
7738
8424
  value: option.value
7739
8425
  })),
7740
8426
  title
7741
8427
  });
8428
+ if (typeof selected === "string" && !options.some((row) => row.value === selected))
8429
+ return void 0;
8430
+ return selected;
7742
8431
  };
7743
8432
 
7744
8433
  // src/v2-entry/v2-key-prompts/v2-key-prompts.ts
7745
8434
  var v2KeyPrompts = async (deps) => {
7746
8435
  const answer = {};
7747
- for (const field of deps.fields) {
7748
- const value = await askField(deps.dialog, field);
7749
- if (value === void 0) {
7750
- return void 0;
8436
+ const collect = async (field) => {
8437
+ for (; ; ) {
8438
+ const value = await askField(
8439
+ deps.dialog,
8440
+ field,
8441
+ answer[field.key] ?? deps.draft?.get(field.key)
8442
+ );
8443
+ if (value === BACK || value === void 0) return value;
8444
+ if (field.key === BUDGET_CAP_FIELD_KEY) {
8445
+ try {
8446
+ readBudgetCap({ [field.key]: value });
8447
+ } catch (error) {
8448
+ if (!(error instanceof RangeError)) throw error;
8449
+ await deps.dialog.alert({
8450
+ title: field.title ?? field.key,
8451
+ message: error.message
8452
+ });
8453
+ continue;
8454
+ }
8455
+ }
8456
+ return value;
8457
+ }
8458
+ };
8459
+ let index = 0;
8460
+ while (index < deps.fields.length) {
8461
+ const field = deps.fields[index];
8462
+ if (!field) break;
8463
+ const value = await collect(field);
8464
+ if (value === BACK && index > 0) {
8465
+ index--;
8466
+ continue;
7751
8467
  }
8468
+ if (typeof value !== "string") return value;
8469
+ deps.draft?.set(field.key, value);
7752
8470
  answer[field.key] = value;
8471
+ index++;
7753
8472
  }
7754
8473
  return answer;
7755
8474
  };
@@ -7761,11 +8480,68 @@ var showNoBudgets = (dialog, multi) => dialog.alert({
7761
8480
  });
7762
8481
 
7763
8482
  // src/tui-entry/v2-budget-picker/answer-step/answer-step.ts
7764
- var runAnswerStep = async (deps) => {
7765
- const fields = (await v2FormFields(deps.context)).filter(
7766
- (field) => field.key !== ATTRIBUTION_FIELD_KEY && field.key !== ORGANISATION_FIELD_KEY
7767
- );
7768
- const extras = await v2KeyPrompts({ dialog: deps.dialog, fields });
8483
+ var runAnswerStep = async (deps, budgetPrepared = false) => {
8484
+ const loadFields = async () => {
8485
+ const registered = await v2FormFields(deps.context);
8486
+ const budgets = registered.find(
8487
+ (field) => field.key === ATTRIBUTION_FIELD_KEY2
8488
+ )?.options;
8489
+ const matches = budgets === void 0 || budgets.some((row) => row.value === deps.selection);
8490
+ return (matches ? registered : []).filter(
8491
+ (field) => field.key !== ATTRIBUTION_FIELD_KEY2 && field.key !== ORGANISATION_FIELD_KEY
8492
+ );
8493
+ };
8494
+ const fields = await loadFields();
8495
+ if (budgetPrepared && fields.length === 0) {
8496
+ deps.toast({ message: V2_CONNECT_COPY.setupIncomplete, variant: "error" });
8497
+ return "done";
8498
+ }
8499
+ const confirmBinding = async (key) => {
8500
+ const field = fields.find((row) => row.key === "rotation_confirmation");
8501
+ if (field?.options?.some((option) => option.value === key) !== true)
8502
+ return {};
8503
+ if (field.title === void 0) return void 0;
8504
+ const consent = await deps.dialog.confirm({
8505
+ title: "Rotate key? (No: Back to key selection)",
8506
+ message: field.title
8507
+ });
8508
+ if (consent === false) return BACK;
8509
+ return consent ? { rotation_confirmation: key } : void 0;
8510
+ };
8511
+ const collect = async () => {
8512
+ const selector = fields.find(
8513
+ (field) => field.key === `existing_key:${deps.selection}`
8514
+ );
8515
+ const create = () => v2KeyPrompts({
8516
+ dialog: deps.dialog,
8517
+ draft: deps.draft,
8518
+ fields: fields.filter(
8519
+ (field) => !field.key.startsWith("existing_key:") && field.key !== "rotation_confirmation"
8520
+ )
8521
+ });
8522
+ if (!selector) return create();
8523
+ const select = () => selectWithBack(deps.dialog, {
8524
+ title: selector.title ?? "Choose a key",
8525
+ options: (selector.options ?? []).map((option) => ({
8526
+ title: option.label,
8527
+ value: option.value
8528
+ }))
8529
+ });
8530
+ for (; ; ) {
8531
+ const selection = await select();
8532
+ if (typeof selection !== "string") return selection;
8533
+ if (selection === "new") {
8534
+ const extras2 = await create();
8535
+ if (extras2 === BACK) continue;
8536
+ return extras2;
8537
+ }
8538
+ const confirmation = await confirmBinding(selection);
8539
+ if (confirmation === BACK) continue;
8540
+ return confirmation && { [selector.key]: selection, ...confirmation };
8541
+ }
8542
+ };
8543
+ const extras = await collect();
8544
+ if (extras === BACK) return "back";
7769
8545
  if (extras === void 0) {
7770
8546
  deps.toast({ message: V2_CONNECT_COPY.dismissed });
7771
8547
  return "done";
@@ -7781,6 +8557,9 @@ var runAnswerStep = async (deps) => {
7781
8557
  selection: deps.selection,
7782
8558
  toast: deps.toast
7783
8559
  });
8560
+ if (outcome === "budget-selected" && !budgetPrepared) {
8561
+ return runAnswerStep(deps, true);
8562
+ }
7784
8563
  if (outcome === "no-budgets") {
7785
8564
  await showNoBudgets(deps.dialog, deps.multi);
7786
8565
  return deps.multi ? "retry" : "done";
@@ -7790,7 +8569,8 @@ var runAnswerStep = async (deps) => {
7790
8569
 
7791
8570
  // src/tui-entry/v2-budget-picker/pick-budget/pick-budget.ts
7792
8571
  var pickBudget = async (deps) => {
7793
- const selection = await deps.dialog.select({
8572
+ const selection = await selectWithBack(deps.dialog, {
8573
+ current: deps.current,
7794
8574
  options: deps.options.map((option) => ({
7795
8575
  description: option.description,
7796
8576
  title: option.label,
@@ -7798,11 +8578,12 @@ var pickBudget = async (deps) => {
7798
8578
  })),
7799
8579
  title: deps.title
7800
8580
  });
8581
+ if (selection === BACK) return BACK;
7801
8582
  if (selection === void 0) {
7802
8583
  deps.toast({ message: V2_CONNECT_COPY.dismissed });
7803
8584
  return void 0;
7804
8585
  }
7805
- if (!deps.budgetOptions.some((option) => option.value === selection)) {
8586
+ if (!deps.options.some((option) => option.value === selection)) {
7806
8587
  deps.toast({ message: V2_CONNECT_COPY.stale, variant: "error" });
7807
8588
  return void 0;
7808
8589
  }
@@ -7814,13 +8595,14 @@ var pickOrg = async (deps) => {
7814
8595
  if (deps.orgs.length <= 1) {
7815
8596
  return { kind: "picked", orgId: deps.orgs[0]?.value };
7816
8597
  }
7817
- const orgId = await deps.dialog.select({
8598
+ const orgId = await selectWithBack(deps.dialog, {
7818
8599
  options: deps.orgs.map((option) => ({
7819
8600
  title: option.label,
7820
8601
  value: option.value
7821
8602
  })),
7822
8603
  title: deps.title
7823
8604
  });
8605
+ if (orgId === BACK) return { kind: "back" };
7824
8606
  if (orgId === void 0) {
7825
8607
  deps.toast({ message: V2_CONNECT_COPY.dismissed });
7826
8608
  return { kind: "dismissed" };
@@ -7837,46 +8619,65 @@ var scopeBudgetOptions = (orgId, options) => orgId === void 0 ? options : option
7837
8619
  // src/tui-entry/v2-budget-picker/budget-round/budget-round.ts
7838
8620
  var runBudgetRound = async (deps) => {
7839
8621
  const multi = deps.orgs.length > 1;
7840
- const org = await pickOrg({
7841
- dialog: deps.dialog,
7842
- orgs: deps.orgs,
7843
- title: deps.orgTitle ?? V2_CONNECT_COPY.orgPickerTitle,
7844
- toast: deps.toast
7845
- });
7846
- if (org.kind === "dismissed") {
7847
- return "done";
7848
- }
7849
- const scoped = scopeBudgetOptions(org.orgId, deps.budgetOptions);
7850
- if (scoped.length === 0) {
7851
- await showNoBudgets(deps.dialog, multi);
7852
- return multi ? "retry" : "done";
7853
- }
7854
- const selection = await pickBudget({
7855
- budgetOptions: deps.budgetOptions,
7856
- dialog: deps.dialog,
7857
- options: scoped,
7858
- title: deps.budgetTitle ?? V2_CONNECT_COPY.pickerTitle,
7859
- toast: deps.toast
7860
- });
7861
- if (selection === void 0) {
7862
- return "done";
7863
- }
7864
- if (!deps.unattributed()) {
7865
- deps.toast({ message: V2_CONNECT_COPY.success, variant: "success" });
7866
- return "done";
8622
+ const draft = /* @__PURE__ */ new Map();
8623
+ let previousOrg;
8624
+ let current;
8625
+ const chooseBudget = async (scoped) => {
8626
+ if (scoped.length === 0) {
8627
+ await showNoBudgets(deps.dialog, multi);
8628
+ return multi ? "retry" : "done";
8629
+ }
8630
+ for (; ; ) {
8631
+ const selection = await pickBudget({
8632
+ current,
8633
+ dialog: deps.dialog,
8634
+ options: scoped,
8635
+ title: deps.budgetTitle ?? V2_CONNECT_COPY.pickerTitle,
8636
+ toast: deps.toast
8637
+ });
8638
+ if (selection === BACK) return multi ? "back" : "done";
8639
+ if (selection === void 0) {
8640
+ return "done";
8641
+ }
8642
+ if (!deps.unattributed()) {
8643
+ deps.toast({ message: V2_CONNECT_COPY.success, variant: "success" });
8644
+ return "done";
8645
+ }
8646
+ current = selection;
8647
+ const result = await runAnswerStep({
8648
+ attributionFieldKey: "attribution",
8649
+ budgetOptions: scoped,
8650
+ draft,
8651
+ connect: deps.connect,
8652
+ context: deps.context,
8653
+ dialog: deps.dialog,
8654
+ locationInput: deps.locationInput,
8655
+ multi,
8656
+ pollTerminal: deps.pollTerminal,
8657
+ selection,
8658
+ toast: deps.toast
8659
+ });
8660
+ if (result !== "back") return result;
8661
+ }
8662
+ };
8663
+ for (; ; ) {
8664
+ const org = await pickOrg({
8665
+ dialog: deps.dialog,
8666
+ orgs: deps.orgs,
8667
+ title: deps.orgTitle ?? V2_CONNECT_COPY.orgPickerTitle,
8668
+ toast: deps.toast
8669
+ });
8670
+ if (org.kind !== "picked") return "done";
8671
+ if (org.orgId !== previousOrg) {
8672
+ draft.clear();
8673
+ current = void 0;
8674
+ previousOrg = org.orgId;
8675
+ }
8676
+ const outcome = await chooseBudget(
8677
+ scopeBudgetOptions(org.orgId, deps.budgetOptions)
8678
+ );
8679
+ if (outcome !== "back") return outcome;
7867
8680
  }
7868
- return runAnswerStep({
7869
- attributionFieldKey: "attribution",
7870
- budgetOptions: deps.budgetOptions,
7871
- connect: deps.connect,
7872
- context: deps.context,
7873
- dialog: deps.dialog,
7874
- locationInput: deps.locationInput,
7875
- multi,
7876
- pollTerminal: deps.pollTerminal,
7877
- selection,
7878
- toast: deps.toast
7879
- });
7880
8681
  };
7881
8682
 
7882
8683
  // src/tui-entry/v2-budget-picker/v2-budget-picker.ts
@@ -7886,7 +8687,7 @@ var v2BudgetPicker = async (deps) => {
7886
8687
  return;
7887
8688
  }
7888
8689
  const attributionField = deps.formFields.find(
7889
- (field) => field.key === ATTRIBUTION_FIELD_KEY2
8690
+ (field) => field.key === ATTRIBUTION_FIELD_KEY
7890
8691
  );
7891
8692
  if (attributionField === void 0) {
7892
8693
  deps.toast({ message: V2_CONNECT_COPY.manualFallback, variant: "error" });
@@ -7976,7 +8777,8 @@ var v2StatusSurface = (context) => v2IntegrationSurface(context)?.oauth?.status;
7976
8777
  var v2GuidedSurfaceTry = (deps) => {
7977
8778
  const integration = v2IntegrationSurface(deps.context);
7978
8779
  if (integration === void 0) {
7979
- return { kind: "quiet" };
8780
+ deps.toast({ message: V2_CONNECT_COPY.manualFallback });
8781
+ return { kind: "manual" };
7980
8782
  }
7981
8783
  const connect = v2ConnectSurface(deps.context);
7982
8784
  const status = v2StatusSurface(deps.context);
@@ -8167,13 +8969,15 @@ var showR33Menu = async (context, deps) => {
8167
8969
  if (selection === void 0) return;
8168
8970
  if (selection === "attribute") {
8169
8971
  const location = context.location ?? context.data?.location.default();
8170
- if (location !== void 0) {
8171
- clearAttribution({
8172
- directory: location.directory,
8173
- outsideWorktree: "return-undefined"
8174
- });
8972
+ if (location === void 0 || readEnvDirectApiKey() !== void 0) return;
8973
+ if (readAttribution({
8974
+ directory: location.directory,
8975
+ outsideWorktree: "return-undefined"
8976
+ }) === void 0) {
8977
+ await v2Autoconnect(context);
8978
+ } else {
8979
+ await v2GuidedConnect({ context, unattributed: () => true });
8175
8980
  }
8176
- await v2Autoconnect(context);
8177
8981
  return;
8178
8982
  }
8179
8983
  await runR33MenuAction(context, selection, deps);
@@ -8302,6 +9106,25 @@ var registerV2BootReentry = (deps) => {
8302
9106
  });
8303
9107
  };
8304
9108
 
9109
+ // src/tui-entry/v2-boot-session-probe/v2-boot-session-probe.ts
9110
+ var v2BootSessionProbe = async (deps) => {
9111
+ const get = deps.integrationGet;
9112
+ if (get !== void 0) {
9113
+ const info = await get().then(
9114
+ (value) => value,
9115
+ () => void 0
9116
+ );
9117
+ if ((info?.data.connections?.length ?? 0) > 0) {
9118
+ return "alive";
9119
+ }
9120
+ }
9121
+ const token = await deps.readStoredToken().then(
9122
+ (value) => value,
9123
+ () => void 0
9124
+ );
9125
+ return token !== void 0 ? "alive" : "dead";
9126
+ };
9127
+
8305
9128
  // src/tui-entry/v2-session-watch/v2-session-watch.ts
8306
9129
  init_abortable_sleep2();
8307
9130
  var watchV2SessionBecomeAlive = (deps) => {
@@ -8310,7 +9133,7 @@ var watchV2SessionBecomeAlive = (deps) => {
8310
9133
  const deadline = now() + (deps.watchMs ?? 12e4);
8311
9134
  let stopped = false;
8312
9135
  const isStopped = () => stopped;
8313
- const pending = () => {
9136
+ const pending2 = () => {
8314
9137
  try {
8315
9138
  return deps.pending();
8316
9139
  } catch {
@@ -8319,12 +9142,12 @@ var watchV2SessionBecomeAlive = (deps) => {
8319
9142
  };
8320
9143
  const poll = async () => {
8321
9144
  while (!isStopped()) {
8322
- if (!pending()) return;
9145
+ if (!pending2()) return;
8323
9146
  if (now() >= deadline) return;
8324
9147
  const alive = await deps.probe().catch(() => false);
8325
9148
  if (isStopped()) return;
8326
9149
  if (alive) {
8327
- if (!pending()) return;
9150
+ if (!pending2()) return;
8328
9151
  await deps.onAlive().catch(() => void 0);
8329
9152
  return;
8330
9153
  }
@@ -8550,16 +9373,30 @@ var createV2Tui = () => ({
8550
9373
  directory,
8551
9374
  outsideWorktree: "return-undefined"
8552
9375
  }) !== void 0;
9376
+ const storedRoute33Token = () => {
9377
+ const box = context.storage?.store("route33_auth", {
9378
+ initial: {}
9379
+ })[0];
9380
+ const value = box?.value;
9381
+ if (typeof value === "string") {
9382
+ return Promise.resolve(value);
9383
+ }
9384
+ if (typeof value === "object" && value !== null && "value" in value && typeof value.value === "string") {
9385
+ return Promise.resolve(value.value);
9386
+ }
9387
+ return Promise.resolve(void 0);
9388
+ };
8553
9389
  const sessionProbe = async () => {
8554
9390
  const get = context.client?.integration?.get;
8555
- if (get === void 0) {
8556
- return "alive";
8557
- }
8558
- const info = await get({
8559
- integrationID: "route33",
8560
- ...location === void 0 ? {} : { location }
8561
- }).catch(() => void 0);
8562
- return (info?.data.connections?.length ?? 0) > 0 ? "alive" : "dead";
9391
+ return v2BootSessionProbe({
9392
+ ...get === void 0 ? {} : {
9393
+ integrationGet: async () => get({
9394
+ integrationID: "route33",
9395
+ ...location === void 0 ? {} : { location }
9396
+ })
9397
+ },
9398
+ readStoredToken: storedRoute33Token
9399
+ });
8563
9400
  };
8564
9401
  const globalFallback = async () => {
8565
9402
  if (detectWorktreeRoot(directory) !== void 0) return false;