@cortexkit/anthropic-auth-core 2.5.5 → 2.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -24048,6 +24048,288 @@ class CacheKeepSessionRegistry {
24048
24048
  } catch {}
24049
24049
  }
24050
24050
  }
24051
+ // src/cachekeep-store.ts
24052
+ import { createHash as createHash20, randomUUID as randomUUID16 } from "node:crypto";
24053
+ import { constants as constants3 } from "node:fs";
24054
+ import { lstat as lstat14, mkdir as mkdir12, open as open10, readdir as readdir4, rm as rm8, writeFile as writeFile5 } from "node:fs/promises";
24055
+ import { tmpdir as tmpdir7 } from "node:os";
24056
+ import { join as join22 } from "node:path";
24057
+ import { promisify } from "node:util";
24058
+ import { gunzip, gzip } from "node:zlib";
24059
+ var compress = promisify(gzip);
24060
+ var decompress = promisify(gunzip);
24061
+ var hash3 = (value) => createHash20("sha256").update(value).digest("hex");
24062
+ var FILE = /^[a-f0-9]{64}\.json\.gz$/;
24063
+ var TEMP = /^[a-f0-9]{64}\.json\.gz\.[a-f0-9-]+\.tmp$/;
24064
+ var MAX_RECORD_BYTES = 2 * CACHE_KEEP_MAX_BODY_BYTES + 64 * 1024;
24065
+ var RECORD_FORMAT_VERSION = 1;
24066
+ function cacheKeepStoreDirectory(storageId, root = getHostDataHome(), host) {
24067
+ return join22(root, "cortexkit", "anthropic-auth", "cachekeep-restore", ...host ? [host] : [], hash3(storageId).slice(0, 16));
24068
+ }
24069
+ function legacyCacheKeepStoreDirectory(storageId, root = tmpdir7()) {
24070
+ return join22(root, `cortexkit-anthropic-auth-cachekeep-${hash3(storageId).slice(0, 16)}`);
24071
+ }
24072
+ function record8(target, pluginVersion) {
24073
+ return {
24074
+ v: RECORD_FORMAT_VERSION,
24075
+ pluginVersion,
24076
+ id: target.id,
24077
+ bodyText: target.bodyText,
24078
+ url: target.url,
24079
+ cacheExpiresAt: target.cacheExpiresAt,
24080
+ nextPrewarmAt: target.nextPrewarmAt,
24081
+ oauthAccountIdentity: target.oauthAccountIdentity,
24082
+ isSubagent: target.isSubagent,
24083
+ ttlMs: target.ttlMs,
24084
+ lastTouchAt: target.lastTouchAt,
24085
+ lastTouchKind: target.lastTouchKind
24086
+ };
24087
+ }
24088
+ function sanitizedBody(text5) {
24089
+ const body = JSON.parse(text5);
24090
+ if (!body || typeof body !== "object" || Array.isArray(body))
24091
+ throw new Error("Invalid restart body");
24092
+ let stripped = false;
24093
+ for (const key of Object.keys(body)) {
24094
+ if (/^(authorization|x-api-key|cookie|set-cookie|headers|credentials|token|access[_-]?token|refresh[_-]?token)$/i.test(key)) {
24095
+ delete body[key];
24096
+ stripped = true;
24097
+ }
24098
+ }
24099
+ return stripped ? JSON.stringify(body) : text5;
24100
+ }
24101
+ function invalidReason(value, name, now) {
24102
+ if (!value || typeof value !== "object" || Array.isArray(value))
24103
+ return "invalid";
24104
+ if (value.v !== RECORD_FORMAT_VERSION)
24105
+ return "format";
24106
+ if (typeof value.id !== "string" || !value.id || `${hash3(value.id)}.json.gz` !== name || typeof value.bodyText !== "string" || Buffer.byteLength(value.bodyText) > CACHE_KEEP_MAX_BODY_BYTES || typeof value.url !== "string" || typeof value.oauthAccountIdentity !== "string" || !value.oauthAccountIdentity || typeof value.isSubagent !== "boolean" || !Number.isFinite(value.cacheExpiresAt) || !Number.isFinite(value.nextPrewarmAt))
24107
+ return "invalid";
24108
+ if (value.cacheExpiresAt <= now)
24109
+ return "expired";
24110
+ if (sanitizedBody(value.bodyText) !== value.bodyText)
24111
+ return "invalid";
24112
+ }
24113
+
24114
+ class CacheKeepStore {
24115
+ options;
24116
+ directory;
24117
+ disabled = false;
24118
+ legacyLoadAttempted = false;
24119
+ chain = Promise.resolve();
24120
+ pending = new Map;
24121
+ timers = new Map;
24122
+ lastWrite = new Map;
24123
+ latest = new Map;
24124
+ constructor(options, previous) {
24125
+ this.options = options;
24126
+ this.directory = cacheKeepStoreDirectory(options.storageId, options.root, options.host);
24127
+ this.chain = previous?.drain() ?? Promise.resolve();
24128
+ }
24129
+ refuse() {
24130
+ if (this.disabled)
24131
+ return;
24132
+ this.disabled = true;
24133
+ for (const timer of this.timers.values())
24134
+ (this.options.clearTimeoutImpl ?? clearTimeout)(timer);
24135
+ this.timers.clear();
24136
+ this.pending.clear();
24137
+ this.latest.clear();
24138
+ this.lastWrite.clear();
24139
+ logger2.warn("cachekeep", "restart storage unavailable; retaining sessions in memory only");
24140
+ }
24141
+ async directoryReady(directory = this.directory) {
24142
+ if (this.disabled)
24143
+ return false;
24144
+ try {
24145
+ if (!await ensureWindowsOwnerOnlyDirectory(directory, this.options.ownerOnly)) {
24146
+ try {
24147
+ await mkdir12(directory, { recursive: true, mode: 448 });
24148
+ } catch (error) {
24149
+ if (error.code !== "EEXIST")
24150
+ throw error;
24151
+ }
24152
+ }
24153
+ const stat11 = await lstat14(directory);
24154
+ if (!stat11.isDirectory() || stat11.isSymbolicLink() || !await isOwnerOnly(directory, () => stat11.uid === process.getuid?.() && (stat11.mode & 511) === 448, this.options.ownerOnly))
24155
+ throw new Error("Unsafe restart directory");
24156
+ return true;
24157
+ } catch {
24158
+ this.refuse();
24159
+ return false;
24160
+ }
24161
+ }
24162
+ enqueue(action) {
24163
+ this.chain = this.chain.then(async () => {
24164
+ if (await this.directoryReady())
24165
+ await action();
24166
+ }).catch(() => this.refuse());
24167
+ }
24168
+ async load(now, accept, claim) {
24169
+ await this.chain;
24170
+ if (!await this.directoryReady())
24171
+ return;
24172
+ let directory = this.directory;
24173
+ const firstLoad = !this.legacyLoadAttempted;
24174
+ this.legacyLoadAttempted = true;
24175
+ if (!this.options.host && firstLoad && (await readdir4(directory)).length === 0) {
24176
+ const legacy = legacyCacheKeepStoreDirectory(this.options.storageId, this.options.legacyRoot ?? this.options.root);
24177
+ try {
24178
+ await lstat14(legacy);
24179
+ if (!await this.directoryReady(legacy))
24180
+ return;
24181
+ directory = legacy;
24182
+ } catch {
24183
+ return;
24184
+ }
24185
+ }
24186
+ let restored = 0;
24187
+ let dropped = 0;
24188
+ try {
24189
+ for (const name of (await readdir4(directory)).sort()) {
24190
+ if (!FILE.test(name) && !TEMP.test(name))
24191
+ continue;
24192
+ const release2 = claim ? await claim(name.slice(0, 64)) : undefined;
24193
+ if (claim && !release2)
24194
+ continue;
24195
+ const path2 = join22(directory, name);
24196
+ let reason = "unreadable";
24197
+ try {
24198
+ if (TEMP.test(name)) {
24199
+ reason = "unfinished-write";
24200
+ throw new Error("Unfinished write");
24201
+ }
24202
+ const stat11 = await lstat14(path2);
24203
+ if (!stat11.isFile() || stat11.isSymbolicLink() || stat11.size > MAX_RECORD_BYTES || !await isOwnerOnly(path2, () => stat11.uid === process.getuid?.() && (stat11.mode & 511) === 384, this.options.ownerOnly)) {
24204
+ reason = "unsafe-file";
24205
+ throw new Error("Unsafe restart file");
24206
+ }
24207
+ let bytes = await readWindowsOwnerOnly(path2, this.options.ownerOnly);
24208
+ if (!bytes) {
24209
+ const file = await open10(path2, constants3.O_RDONLY | constants3.O_NOFOLLOW);
24210
+ try {
24211
+ bytes = await file.readFile();
24212
+ } finally {
24213
+ await file.close();
24214
+ }
24215
+ }
24216
+ const raw = await decompress(bytes, {
24217
+ maxOutputLength: MAX_RECORD_BYTES
24218
+ });
24219
+ reason = "invalid";
24220
+ const entry2 = JSON.parse(raw.toString("utf8"));
24221
+ const invalid = invalidReason(entry2, name, now);
24222
+ const accepted = invalid ?? accept(entry2);
24223
+ if (accepted !== true && accepted !== undefined) {
24224
+ reason = accepted || "invalid";
24225
+ throw new Error("Stale restart file");
24226
+ }
24227
+ if (accepted === true) {
24228
+ if (directory !== this.directory) {
24229
+ try {
24230
+ await this.writeEntry(entry2);
24231
+ } catch {
24232
+ this.refuse();
24233
+ return;
24234
+ }
24235
+ await rm8(path2, { force: true });
24236
+ }
24237
+ restored++;
24238
+ }
24239
+ } catch {
24240
+ logger2.debug("cachekeep", "restart record dropped", {
24241
+ file: name,
24242
+ reason
24243
+ });
24244
+ dropped++;
24245
+ await rm8(path2, { force: true });
24246
+ } finally {
24247
+ await release2?.();
24248
+ }
24249
+ }
24250
+ } catch {
24251
+ this.refuse();
24252
+ } finally {
24253
+ if (restored || dropped)
24254
+ logger2.info("cachekeep", "restart records loaded", {
24255
+ restored,
24256
+ dropped
24257
+ });
24258
+ }
24259
+ }
24260
+ changed(target) {
24261
+ if (this.disabled)
24262
+ return;
24263
+ const entry2 = record8(target, this.options.pluginVersion);
24264
+ const previous = this.latest.get(entry2.id);
24265
+ if (previous && previous.bodyText === entry2.bodyText && previous.url === entry2.url && previous.oauthAccountIdentity === entry2.oauthAccountIdentity && previous.cacheExpiresAt === entry2.cacheExpiresAt && previous.nextPrewarmAt === entry2.nextPrewarmAt && previous.ttlMs === entry2.ttlMs && previous.lastTouchAt === entry2.lastTouchAt && previous.lastTouchKind === entry2.lastTouchKind && previous.isSubagent === entry2.isSubagent)
24266
+ return;
24267
+ this.latest.set(entry2.id, entry2);
24268
+ this.pending.set(entry2.id, entry2);
24269
+ if (this.timers.has(entry2.id))
24270
+ return;
24271
+ const delay3 = Math.max(250, (this.lastWrite.get(entry2.id) ?? 0) + 5000 - (this.options.now?.() ?? Date.now()));
24272
+ const timer = (this.options.setTimeoutImpl ?? setTimeout)(() => this.flush(entry2.id), delay3);
24273
+ timer.unref?.();
24274
+ this.timers.set(entry2.id, timer);
24275
+ }
24276
+ flush(id2) {
24277
+ const timer = this.timers.get(id2);
24278
+ if (timer)
24279
+ (this.options.clearTimeoutImpl ?? clearTimeout)(timer);
24280
+ this.timers.delete(id2);
24281
+ const entry2 = this.pending.get(id2);
24282
+ this.pending.delete(id2);
24283
+ if (!entry2)
24284
+ return this.chain;
24285
+ this.lastWrite.set(id2, this.options.now?.() ?? Date.now());
24286
+ this.enqueue(() => this.writeEntry(entry2));
24287
+ return this.chain;
24288
+ }
24289
+ async writeEntry(entry2) {
24290
+ const path2 = join22(this.directory, `${hash3(entry2.id)}.json.gz`);
24291
+ const temp = `${path2}.${randomUUID16()}.tmp`;
24292
+ try {
24293
+ const safe = { ...entry2, bodyText: sanitizedBody(entry2.bodyText) };
24294
+ const bytes = await compress(JSON.stringify(safe));
24295
+ if (!await createWindowsOwnerOnly(temp, bytes, this.options.ownerOnly))
24296
+ await writeFile5(temp, bytes, { flag: "wx", mode: 384 });
24297
+ await renameWithWindowsSharingRetry(temp, path2, {
24298
+ platform: this.options.ownerOnly?.platform
24299
+ });
24300
+ } finally {
24301
+ await rm8(temp, { force: true });
24302
+ }
24303
+ }
24304
+ removed(id2) {
24305
+ const timer = this.timers.get(id2);
24306
+ if (timer)
24307
+ (this.options.clearTimeoutImpl ?? clearTimeout)(timer);
24308
+ this.timers.delete(id2);
24309
+ this.pending.delete(id2);
24310
+ this.latest.delete(id2);
24311
+ this.lastWrite.delete(id2);
24312
+ this.enqueue(() => rm8(join22(this.directory, `${hash3(id2)}.json.gz`), { force: true }));
24313
+ }
24314
+ clear() {
24315
+ for (const timer of this.timers.values())
24316
+ (this.options.clearTimeoutImpl ?? clearTimeout)(timer);
24317
+ this.timers.clear();
24318
+ this.pending.clear();
24319
+ this.latest.clear();
24320
+ this.lastWrite.clear();
24321
+ this.enqueue(async () => {
24322
+ for (const name of await readdir4(this.directory))
24323
+ if (FILE.test(name) || TEMP.test(name))
24324
+ await rm8(join22(this.directory, name), { force: true });
24325
+ });
24326
+ }
24327
+ async drain() {
24328
+ for (const id2 of this.pending.keys())
24329
+ this.flush(id2);
24330
+ await this.chain;
24331
+ }
24332
+ }
24051
24333
  // src/oauth-profile.ts
24052
24334
  var PROFILE_URL = "https://api.anthropic.com/api/oauth/profile";
24053
24335
  var PROFILE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
@@ -24802,13 +25084,13 @@ function executeLoggingCommand(input) {
24802
25084
  `);
24803
25085
  }
24804
25086
  // src/message-threads.ts
24805
- import { createHash as createHash20 } from "node:crypto";
25087
+ import { createHash as createHash21 } from "node:crypto";
24806
25088
  var MESSAGE_THREADS_BETA = "message-threads-2026-08-12";
24807
25089
  var MAX_AGE_MS = 5 * 60000;
24808
25090
  var MAX_SESSIONS = 2048;
24809
25091
  var MAX_MESSAGE_HASHES = 131072;
24810
- function hash3(value) {
24811
- return createHash20("sha256").update(JSON.stringify(value)).digest("hex");
25092
+ function hash4(value) {
25093
+ return createHash21("sha256").update(JSON.stringify(value)).digest("hex");
24812
25094
  }
24813
25095
  function normalizedReplyName(name) {
24814
25096
  const bare = name.startsWith("mcp_") ? name.slice(4) : name;
@@ -24854,7 +25136,7 @@ class ReplyFingerprint {
24854
25136
  layout = new Map;
24855
25137
  textBlocks = new Map;
24856
25138
  signatures = new Map;
24857
- text = createHash20("sha256");
25139
+ text = createHash21("sha256");
24858
25140
  committedText = this.text.copy();
24859
25141
  hasText = false;
24860
25142
  activeText;
@@ -24876,7 +25158,7 @@ class ReplyFingerprint {
24876
25158
  this.text.update(part.slice(visible.length));
24877
25159
  }
24878
25160
  appendBlockText(state, value) {
24879
- state.text ??= createHash20("sha256");
25161
+ state.text ??= createHash21("sha256");
24880
25162
  state.committedText ??= state.text.copy();
24881
25163
  const part = state.textHasContent ? value : value.trimStart();
24882
25164
  const visible = part.trimEnd();
@@ -24923,7 +25205,7 @@ class ReplyFingerprint {
24923
25205
  state.input = block.input;
24924
25206
  }
24925
25207
  if (block.type === "thinking" || block.type === "redacted_thinking") {
24926
- state.signature = createHash20("sha256");
25208
+ state.signature = createHash21("sha256");
24927
25209
  const signature = block.type === "redacted_thinking" ? block.data : block.signature;
24928
25210
  if (typeof signature === "string") {
24929
25211
  state.signature.update(signature);
@@ -25001,7 +25283,7 @@ class ReplyFingerprint {
25001
25283
  this.tools.set(index, [
25002
25284
  state.id,
25003
25285
  state.name,
25004
- hash3(canonicalValue(input))
25286
+ hash4(canonicalValue(input))
25005
25287
  ]);
25006
25288
  } catch {
25007
25289
  this.invalid = true;
@@ -25013,7 +25295,7 @@ class ReplyFingerprint {
25013
25295
  return;
25014
25296
  const ordered = [...this.layout].sort(([a], [b]) => a - b);
25015
25297
  const kept = withoutTrailingToolWhitespace(ordered.map(([, block]) => block));
25016
- return hash3({
25298
+ return hash4({
25017
25299
  blocks: kept.map((block) => block.type),
25018
25300
  texts: ordered.slice(0, kept.length).filter(([, block]) => block.type === "text").map(([index]) => this.textBlocks.get(index)),
25019
25301
  tools: [...this.tools].sort(([a], [b]) => a - b).map(([, tool]) => tool),
@@ -25120,7 +25402,7 @@ function fixedThreadFingerprint(input) {
25120
25402
  "tool_choice",
25121
25403
  "context_management"
25122
25404
  ].map((key) => [key, body[key]]));
25123
- return hash3(canonicalValue({
25405
+ return hash4(canonicalValue({
25124
25406
  ...fixed,
25125
25407
  tools: JSON.stringify(body.tools),
25126
25408
  system: JSON.stringify(system),
@@ -25129,9 +25411,9 @@ function fixedThreadFingerprint(input) {
25129
25411
  betas: input.betas
25130
25412
  }));
25131
25413
  }
25132
- function messageThreadSnapshot(input, identity3 = hash3([input.account, input.credential]), fingerprint = fixedThreadFingerprint(input)) {
25133
- const messages = (Array.isArray(input.body.messages) ? input.body.messages : []).map((message) => hash3(canonicalValue(withoutMessageCache(message))));
25134
- return { identity: identity3, fingerprint, messages, prefix: hash3(messages) };
25414
+ function messageThreadSnapshot(input, identity3 = hash4([input.account, input.credential]), fingerprint = fixedThreadFingerprint(input)) {
25415
+ const messages = (Array.isArray(input.body.messages) ? input.body.messages : []).map((message) => hash4(canonicalValue(withoutMessageCache(message))));
25416
+ return { identity: identity3, fingerprint, messages, prefix: hash4(messages) };
25135
25417
  }
25136
25418
  function canContinueFrom(anchor, input, identity3, now) {
25137
25419
  if (!anchor || !identity3 || anchor.identity !== identity3 || now < anchor.completedAt || now - anchor.completedAt >= MAX_AGE_MS)
@@ -25140,7 +25422,7 @@ function canContinueFrom(anchor, input, identity3, now) {
25140
25422
  return messages.length >= anchor.messages.length + 2 && messages[anchor.messages.length]?.role === "assistant" && !messages.slice(anchor.messages.length + 1).some((message) => message?.role === "assistant") && assistantReplyFingerprint(messages[anchor.messages.length], replyToolNameResolver(input)) === anchor.replyFingerprint;
25141
25423
  }
25142
25424
  function decideMessageThread(anchor, input, snapshot, now) {
25143
- if (!canContinueFrom(anchor, input, snapshot.identity, now) || anchor.fingerprint !== snapshot.fingerprint || hash3(snapshot.messages.slice(0, anchor.messages.length)) !== anchor.prefix)
25425
+ if (!canContinueFrom(anchor, input, snapshot.identity, now) || anchor.fingerprint !== snapshot.fingerprint || hash4(snapshot.messages.slice(0, anchor.messages.length)) !== anchor.prefix)
25144
25426
  return { type: "create" };
25145
25427
  const messages = Array.isArray(input.body.messages) ? input.body.messages : [];
25146
25428
  return {
@@ -25184,7 +25466,7 @@ class MessageThreadTracker {
25184
25466
  const previous = this.sessions.get(input.session);
25185
25467
  const anchor = previous?.anchor;
25186
25468
  const now = this.now();
25187
- const identity3 = anchor && now >= anchor.completedAt && now - anchor.completedAt < MAX_AGE_MS ? hash3([input.account, input.credential]) : undefined;
25469
+ const identity3 = anchor && now >= anchor.completedAt && now - anchor.completedAt < MAX_AGE_MS ? hash4([input.account, input.credential]) : undefined;
25188
25470
  let snapshot;
25189
25471
  if (canContinueFrom(anchor, input, identity3, now)) {
25190
25472
  const fingerprint = fixedThreadFingerprint(input);
@@ -25443,7 +25725,7 @@ function disableThreadsForAccount(key) {
25443
25725
  if (disabledThreadAccounts.has(key))
25444
25726
  return;
25445
25727
  disabledThreadAccounts.add(key);
25446
- logger2.warn("message-threads", "Anthropic rejected message threads; using full stateless requests for this account until restart", { account: hash3(key).slice(0, 12) });
25728
+ logger2.warn("message-threads", "Anthropic rejected message threads; using full stateless requests for this account until restart", { account: hash4(key).slice(0, 12) });
25447
25729
  }
25448
25730
  function ignoreThreadFailure() {}
25449
25731
  function threadFailureState(initial) {
@@ -25733,7 +26015,7 @@ function remapRequestBodyModel(parsed) {
25733
26015
  return true;
25734
26016
  }
25735
26017
  // src/native-account-runtime.ts
25736
- import { randomUUID as randomUUID17 } from "node:crypto";
26018
+ import { randomUUID as randomUUID18 } from "node:crypto";
25737
26019
 
25738
26020
  // src/native-account-view.ts
25739
26021
  import { types as types2 } from "node:util";
@@ -26498,7 +26780,7 @@ function createNativeLocalRuntimeReaders(options) {
26498
26780
  }
26499
26781
 
26500
26782
  // src/native-refresh-coordinator.ts
26501
- import { createHash as createHash21 } from "node:crypto";
26783
+ import { createHash as createHash22 } from "node:crypto";
26502
26784
 
26503
26785
  // src/native-transient-account.ts
26504
26786
  var TRANSIENT_ACCOUNT_MESSAGE = "Anthropic account update in progress; retry the request";
@@ -26600,7 +26882,7 @@ function pause(ms, signals) {
26600
26882
  var NATIVE_REFRESH_MAX_ATTEMPTS = 3;
26601
26883
  var NATIVE_REFRESH_JOIN_BUDGET_MS = 2000;
26602
26884
  function nativeAccountProviderLock(paths, identity3) {
26603
- const key = createHash21("sha256").update(JSON.stringify([paths.storageId, identity3])).digest("hex");
26885
+ const key = createHash22("sha256").update(JSON.stringify([paths.storageId, identity3])).digest("hex");
26604
26886
  return {
26605
26887
  path: paths.state,
26606
26888
  name: `native-account-provider-${key}`,
@@ -27400,9 +27682,9 @@ function createNativeRefreshCoordinator(options) {
27400
27682
  import { isAbsolute as isAbsolute5, normalize, parse as parse3, sep } from "node:path";
27401
27683
 
27402
27684
  // src/migration-source.ts
27403
- import { createHash as createHash22 } from "node:crypto";
27404
- import { constants as constants3 } from "node:fs";
27405
- import { lstat as lstat14, open as open10 } from "node:fs/promises";
27685
+ import { createHash as createHash23 } from "node:crypto";
27686
+ import { constants as constants4 } from "node:fs";
27687
+ import { lstat as lstat15, open as open11 } from "node:fs/promises";
27406
27688
  class NativeMigrationSourceError extends Error {
27407
27689
  role;
27408
27690
  code;
@@ -27445,7 +27727,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27445
27727
  });
27446
27728
  let initial;
27447
27729
  try {
27448
- initial = await lstat14(path2, { bigint: true });
27730
+ initial = await lstat15(path2, { bigint: true });
27449
27731
  } catch (error) {
27450
27732
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
27451
27733
  return missing2;
@@ -27455,7 +27737,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27455
27737
  throw new NativeMigrationSourceError(role, "unsafe-source");
27456
27738
  let handle;
27457
27739
  try {
27458
- handle = await open10(path2, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0) | (constants3.O_NONBLOCK ?? 0));
27740
+ handle = await open11(path2, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0) | (constants4.O_NONBLOCK ?? 0));
27459
27741
  const before = await handle.stat({ bigint: true });
27460
27742
  if (!before.isFile() || before.dev !== initial.dev || before.ino !== initial.ino) {
27461
27743
  throw new NativeMigrationSourceError(role, "source-changed");
@@ -27483,7 +27765,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27483
27765
  chunks.push(chunk.subarray(0, read.bytesRead));
27484
27766
  }
27485
27767
  const after = await handle.stat({ bigint: true });
27486
- const current = await lstat14(path2, { bigint: true });
27768
+ const current = await lstat15(path2, { bigint: true });
27487
27769
  if (before.uid !== after.uid || before.gid !== after.gid || before.mode !== after.mode || current.uid !== before.uid || current.gid !== before.gid || current.mode !== before.mode || before.dev !== after.dev || before.ino !== after.ino || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs || before.size !== after.size || current.dev !== before.dev || current.ino !== before.ino || current.isSymbolicLink() || current.mtimeNs !== before.mtimeNs || current.ctimeNs !== before.ctimeNs || current.size !== before.size || BigInt(bytes) !== before.size) {
27488
27770
  throw new NativeMigrationSourceError(role, "source-changed");
27489
27771
  }
@@ -27499,7 +27781,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27499
27781
  return sourceSnapshot({
27500
27782
  role,
27501
27783
  path: path2,
27502
- digest: createHash22("sha256").update(content).digest("hex"),
27784
+ digest: createHash23("sha256").update(content).digest("hex"),
27503
27785
  data: freezeJson(data),
27504
27786
  metadata: Object.freeze({
27505
27787
  uid: Number(before.uid),
@@ -28524,11 +28806,11 @@ class NativeRuntimeRegistry {
28524
28806
  }
28525
28807
 
28526
28808
  // src/native-vault-runtime.ts
28527
- import { randomUUID as randomUUID16 } from "node:crypto";
28809
+ import { randomUUID as randomUUID17 } from "node:crypto";
28528
28810
  import { SubcClient as SubcClient2 } from "@cortexkit/subc-client";
28529
28811
 
28530
28812
  // src/insula-quota.ts
28531
- function record8(value) {
28813
+ function record9(value) {
28532
28814
  return typeof value === "object" && value !== null && !Array.isArray(value);
28533
28815
  }
28534
28816
  function text5(value) {
@@ -28538,7 +28820,7 @@ function clampPercent3(value) {
28538
28820
  return Math.min(100, Math.max(0, value));
28539
28821
  }
28540
28822
  function windowReading(window2, checkedAt, expected) {
28541
- if (!record8(window2))
28823
+ if (!record9(window2))
28542
28824
  return;
28543
28825
  const usedPercent = window2.usedPercent;
28544
28826
  if (typeof usedPercent !== "number" || !Number.isFinite(usedPercent))
@@ -28562,7 +28844,7 @@ function scopedReadings(windows, checkedAt) {
28562
28844
  const seen = new Set;
28563
28845
  const scoped = [];
28564
28846
  for (const candidate of windows) {
28565
- if (!record8(candidate))
28847
+ if (!record9(candidate))
28566
28848
  continue;
28567
28849
  const identity3 = text5(candidate.id);
28568
28850
  if (!identity3)
@@ -28588,7 +28870,7 @@ function scopedReadings(windows, checkedAt) {
28588
28870
  return scoped;
28589
28871
  }
28590
28872
  function money2(value) {
28591
- if (!record8(value) || typeof value.minor !== "number" || !Number.isSafeInteger(value.minor) || value.minor < 0)
28873
+ if (!record9(value) || typeof value.minor !== "number" || !Number.isSafeInteger(value.minor) || value.minor < 0)
28592
28874
  return null;
28593
28875
  const exponent = value.exponent ?? 2;
28594
28876
  if (typeof exponent !== "number" || !Number.isInteger(exponent) || exponent < 0 || exponent > 20)
@@ -28598,8 +28880,8 @@ function money2(value) {
28598
28880
  function extraUsageReading(pools) {
28599
28881
  if (!Array.isArray(pools))
28600
28882
  return;
28601
- const pool = pools.find((candidate) => record8(candidate) && candidate.title === "Extra usage");
28602
- if (!record8(pool))
28883
+ const pool = pools.find((candidate) => record9(candidate) && candidate.title === "Extra usage");
28884
+ if (!record9(pool))
28603
28885
  return;
28604
28886
  const limit = money2(pool.total ?? pool.limit);
28605
28887
  const remaining = money2(pool.remaining);
@@ -28614,7 +28896,7 @@ function extraUsageReading(pools) {
28614
28896
  used = Math.max(0, limit.minor - remaining.minor);
28615
28897
  if (used === undefined)
28616
28898
  return;
28617
- const unit = text5(pool.unit) ?? text5(record8(pool.total) && pool.total.unit);
28899
+ const unit = text5(pool.unit) ?? text5(record9(pool.total) && pool.total.unit);
28618
28900
  const currency = unit && /^[A-Za-z]{3}$/.test(unit) ? unit : "USD";
28619
28901
  return {
28620
28902
  used: { amountMinor: used, currency, exponent },
@@ -28770,12 +29052,12 @@ function expectedSeed(input, boundary, refuse3) {
28770
29052
  const inventory = capture(top("inventory", "roster-incomplete"), ["view", "credentials", "skipped"], "roster-incomplete", refuse3);
28771
29053
  const view = inventory.view;
28772
29054
  const skipped = items(inventory.skipped, "roster-incomplete", refuse3);
28773
- const credentialRecords = items(inventory.credentials, "roster-incomplete", refuse3).map((record9) => capture(record9, ["credentialId", "credentialType", "accountIdentity", "state"], "roster-incomplete", refuse3));
29055
+ const credentialRecords = items(inventory.credentials, "roster-incomplete", refuse3).map((record10) => capture(record10, ["credentialId", "credentialType", "accountIdentity", "state"], "roster-incomplete", refuse3));
28774
29056
  if (!filled(view) || skipped.length > 0)
28775
29057
  refuse3("roster-incomplete");
28776
29058
  const listed = new Map;
28777
- for (const record9 of credentialRecords) {
28778
- const { credentialId, credentialType, accountIdentity, state } = record9;
29059
+ for (const record10 of credentialRecords) {
29060
+ const { credentialId, credentialType, accountIdentity, state } = record10;
28779
29061
  if (!filled(credentialId) || !filled(accountIdentity) || !filled(state) || listed.has(credentialId)) {
28780
29062
  refuse3("roster-incomplete");
28781
29063
  }
@@ -28786,7 +29068,7 @@ function expectedSeed(input, boundary, refuse3) {
28786
29068
  const primaryIdentity = primary.accountIdentity;
28787
29069
  boundary.fallback = "seed-conflict";
28788
29070
  const primaryRouteId = top("primaryRouteId", "seed-conflict");
28789
- const legacyRecords = items(top("legacyRows", "seed-conflict"), "seed-conflict", refuse3).map((record9) => capture(record9, [
29071
+ const legacyRecords = items(top("legacyRows", "seed-conflict"), "seed-conflict", refuse3).map((record10) => capture(record10, [
28790
29072
  "routeId",
28791
29073
  "scopedCredentialId",
28792
29074
  "anthropicAccountUuid",
@@ -30253,7 +30535,7 @@ function createNativeVaultRuntime(options) {
30253
30535
  async getOrCreateAuthLineage(receipt) {
30254
30536
  let lineage;
30255
30537
  const kept = await mutateReceipt(receipt, (old) => {
30256
- lineage = old.authLineageId ?? randomUUID16();
30538
+ lineage = old.authLineageId ?? randomUUID17();
30257
30539
  return { ...old, authLineageId: lineage };
30258
30540
  });
30259
30541
  return kept ? lineage : undefined;
@@ -30649,7 +30931,7 @@ function leaseNativeVaultRuntime(use, close) {
30649
30931
 
30650
30932
  // src/relay.ts
30651
30933
  import { Buffer as Buffer3 } from "node:buffer";
30652
- import { createHash as createHash23, randomBytes as randomBytes5 } from "node:crypto";
30934
+ import { createHash as createHash24, randomBytes as randomBytes5 } from "node:crypto";
30653
30935
  var WEBSOCKET_RELAY_URL = /^wss?:\/\//i;
30654
30936
  function effectiveRelayTransport(stored, url) {
30655
30937
  if (stored === "http" || stored === "websocket")
@@ -30800,7 +31082,7 @@ function generateRelayToken() {
30800
31082
  return randomBytes5(32).toString("base64url");
30801
31083
  }
30802
31084
  function hashBody(body) {
30803
- return `sha256:${createHash23("sha256").update(body).digest("hex")}`;
31085
+ return `sha256:${createHash24("sha256").update(body).digest("hex")}`;
30804
31086
  }
30805
31087
  function createStringPatch(previous, next) {
30806
31088
  let start = 0;
@@ -32600,7 +32882,7 @@ function createNativeAccountRuntime(options) {
32600
32882
  const sameAccount = old?.kind === "local" && old.rowId === binding2.rowId && binding2.identity !== undefined && old.identity === binding2.identity;
32601
32883
  const next = {
32602
32884
  binding: binding2,
32603
- ...row.credential?.type === "oauth" ? { authLineageId: randomUUID17() } : {}
32885
+ ...row.credential?.type === "oauth" ? { authLineageId: randomUUID18() } : {}
32604
32886
  };
32605
32887
  if (sameAccount && previous) {
32606
32888
  for (const key of [
@@ -32763,7 +33045,7 @@ function createNativeAccountRuntime(options) {
32763
33045
  throw new NativeRuntimeError("publication-refused");
32764
33046
  const previous = relayFlags(read.settings.relay);
32765
33047
  const previousGeneration = relayGeneration(read.settings.relay);
32766
- const generation = randomUUID17();
33048
+ const generation = randomUUID18();
32767
33049
  const metadata2 = await readNativeRuntime(paths2.runtime, paths2.storageId);
32768
33050
  const token2 = patch.token === undefined ? metadata2.status === "ready" ? metadata2.state.relay?.token : undefined : patch.token?.trim();
32769
33051
  const next = relayFlags({
@@ -32989,7 +33271,7 @@ function createNativeAccountRuntime(options) {
32989
33271
  const snapshot = await runtime2.read();
32990
33272
  if (snapshot.mode !== "local")
32991
33273
  throw new NativeCustodyError("route-unavailable");
32992
- const id2 = input.routeId === "main" ? await physicalId("main").catch(() => randomUUID17()) : input.routeId;
33274
+ const id2 = input.routeId === "main" ? await physicalId("main").catch(() => randomUUID18()) : input.routeId;
32993
33275
  if (input.credential.type === "api" && (input.routeId === "main" || id2 === snapshot.settings.mainAccountId))
32994
33276
  throw new NativeCustodyError("route-unavailable");
32995
33277
  const old = await poolRow(id2);
@@ -33028,7 +33310,7 @@ function createNativeAccountRuntime(options) {
33028
33310
  return row;
33029
33311
  },
33030
33312
  addApi: (input) => runtime2.putAccount({
33031
- routeId: input.routeId ?? randomUUID17(),
33313
+ routeId: input.routeId ?? randomUUID18(),
33032
33314
  label: input.label,
33033
33315
  replace: input.replace,
33034
33316
  credential: {
@@ -33245,7 +33527,7 @@ function createNativeAccountRuntime(options) {
33245
33527
  return;
33246
33528
  let lineage;
33247
33529
  const kept = await metadataPublications.run(() => localMetadataWrite(fence, (old) => {
33248
- lineage = old.authLineageId ?? randomUUID17();
33530
+ lineage = old.authLineageId ?? randomUUID18();
33249
33531
  return {
33250
33532
  ...old,
33251
33533
  authLineageId: lineage
@@ -33452,9 +33734,9 @@ function relayGeneration(input) {
33452
33734
  return generation;
33453
33735
  }
33454
33736
  // src/native-host-auth-write.ts
33455
- import { randomUUID as randomUUID18 } from "node:crypto";
33456
- import { lstat as lstat15, open as open11, rename as rename13, unlink as unlink7 } from "node:fs/promises";
33457
- import { dirname as dirname19, isAbsolute as isAbsolute6, join as join22 } from "node:path";
33737
+ import { randomUUID as randomUUID19 } from "node:crypto";
33738
+ import { lstat as lstat16, open as open12, rename as rename13, unlink as unlink7 } from "node:fs/promises";
33739
+ import { dirname as dirname19, isAbsolute as isAbsolute6, join as join23 } from "node:path";
33458
33740
  class NativeHostAuthWriteError extends Error {
33459
33741
  code;
33460
33742
  effect;
@@ -33515,11 +33797,11 @@ async function writeNativeHostAuth(input, hooks = {}) {
33515
33797
  const removingFile = host === "pi" && Object.keys(next).length === 0;
33516
33798
  const outcome = Object.freeze(host === "pi" ? { status: "removed", file: removingFile ? "unlinked" : "replaced" } : { status: snapshot.data === undefined ? "created" : "replaced" });
33517
33799
  if (!removingFile) {
33518
- stage = join22(dirname19(authPath), `.native-host-auth-write.${randomUUID18()}.tmp`);
33800
+ stage = join23(dirname19(authPath), `.native-host-auth-write.${randomUUID19()}.tmp`);
33519
33801
  const bytes = `${JSON.stringify(next, null, 2)}
33520
33802
  `;
33521
33803
  const nativeCreated = await createWindowsOwnerOnly(stage, bytes);
33522
- const handle = await open11(stage, nativeCreated ? "r+" : "wx", 384);
33804
+ const handle = await open12(stage, nativeCreated ? "r+" : "wx", 384);
33523
33805
  try {
33524
33806
  const identity3 = await handle.stat();
33525
33807
  ownedStage = { dev: identity3.dev, ino: identity3.ino };
@@ -33565,7 +33847,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
33565
33847
  } finally {
33566
33848
  if (stage && ownedStage) {
33567
33849
  try {
33568
- const current = await lstat15(stage);
33850
+ const current = await lstat16(stage);
33569
33851
  if (current.dev === ownedStage.dev && current.ino === ownedStage.ino)
33570
33852
  await unlink7(stage);
33571
33853
  } catch {}
@@ -33574,8 +33856,8 @@ async function writeNativeHostAuth(input, hooks = {}) {
33574
33856
  }
33575
33857
 
33576
33858
  // src/native-migration.ts
33577
- import { createHash as createHash24 } from "node:crypto";
33578
- import { lstat as lstat16, mkdir as mkdir12, unlink as unlink8 } from "node:fs/promises";
33859
+ import { createHash as createHash25 } from "node:crypto";
33860
+ import { lstat as lstat17, mkdir as mkdir13, unlink as unlink8 } from "node:fs/promises";
33579
33861
  import { dirname as dirname20, isAbsolute as isAbsolute7 } from "node:path";
33580
33862
  class NativeMigrationError extends Error {
33581
33863
  code;
@@ -33625,7 +33907,7 @@ function owned(snapshot) {
33625
33907
  }
33626
33908
  async function absent(path2) {
33627
33909
  try {
33628
- await lstat16(path2);
33910
+ await lstat17(path2);
33629
33911
  return false;
33630
33912
  } catch (error) {
33631
33913
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
@@ -33954,7 +34236,7 @@ function routingBytes(captured) {
33954
34236
  `;
33955
34237
  }
33956
34238
  function bytesDigest(bytes) {
33957
- return bytes === undefined ? null : createHash24("sha256").update(bytes).digest("hex");
34239
+ return bytes === undefined ? null : createHash25("sha256").update(bytes).digest("hex");
33958
34240
  }
33959
34241
  function expectedAuth(input, snapshot) {
33960
34242
  const entry2 = inspectNativeHostAuthEntry(input.host, snapshot.data);
@@ -34329,7 +34611,7 @@ async function runNativeMigration(input, hooks = {}) {
34329
34611
  refuse3();
34330
34612
  await step("before:host");
34331
34613
  await recheck();
34332
- await mkdir12(dirname20(operation.hostAuthPath), {
34614
+ await mkdir13(dirname20(operation.hostAuthPath), {
34333
34615
  recursive: true,
34334
34616
  mode: 448
34335
34617
  });
@@ -36809,7 +37091,7 @@ function waitForRequest(pending, signal) {
36809
37091
  });
36810
37092
  }
36811
37093
  // src/native-vault-connection.ts
36812
- import { dirname as dirname22, join as join23, resolve as resolve16 } from "node:path";
37094
+ import { dirname as dirname22, join as join24, resolve as resolve16 } from "node:path";
36813
37095
  // ../../node_modules/@cortexkit/common-auth/dist/opencode2/integration.js
36814
37096
  var PLACEHOLDER_PREFIX = "common-auth-placeholder";
36815
37097
  var PLACEHOLDER_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
@@ -36817,15 +37099,15 @@ function placeholderSecret(integrationID) {
36817
37099
  return `${PLACEHOLDER_PREFIX}.${integrationID}`;
36818
37100
  }
36819
37101
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
36820
- import { createHash as createHash25 } from "node:crypto";
36821
- import { constants as constants4 } from "node:fs";
36822
- import { lstat as lstat17, mkdir as mkdir14, open as open12, unlink as unlink9 } from "node:fs/promises";
37102
+ import { createHash as createHash26 } from "node:crypto";
37103
+ import { constants as constants5 } from "node:fs";
37104
+ import { lstat as lstat18, mkdir as mkdir15, open as open13, unlink as unlink9 } from "node:fs/promises";
36823
37105
  import { dirname as dirname21, resolve as resolve15 } from "node:path";
36824
37106
  import { setTimeout as sleep } from "node:timers/promises";
36825
37107
 
36826
37108
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
36827
37109
  import { rmdirSync, statSync as statSync5, utimesSync } from "node:fs";
36828
- import { mkdir as mkdir13, rmdir, stat as stat11, utimes } from "node:fs/promises";
37110
+ import { mkdir as mkdir14, rmdir, stat as stat11, utimes } from "node:fs/promises";
36829
37111
  var STALE = 30000;
36830
37112
  var RENEWAL_STALE = 1e4;
36831
37113
  var UPDATE = 3000;
@@ -36861,7 +37143,7 @@ async function remove(path2) {
36861
37143
  }
36862
37144
  async function acquire(path2, stale) {
36863
37145
  try {
36864
- await mkdir13(path2);
37146
+ await mkdir14(path2);
36865
37147
  } catch (error) {
36866
37148
  if (errorCode4(error) !== "EEXIST")
36867
37149
  throw error;
@@ -37096,7 +37378,7 @@ function canonical(value) {
37096
37378
  return JSON.stringify(value);
37097
37379
  }
37098
37380
  function digest2(value) {
37099
- return createHash25("sha256").update(canonical(value)).digest("hex");
37381
+ return createHash26("sha256").update(canonical(value)).digest("hex");
37100
37382
  }
37101
37383
  function code(error) {
37102
37384
  return object2(error) ? error.code : undefined;
@@ -37118,13 +37400,13 @@ async function safeRead(path2, privateFile = false, afterReadCheck) {
37118
37400
  }
37119
37401
  let file;
37120
37402
  try {
37121
- file = await open12(path2, constants4.O_RDONLY | constants4.O_NOFOLLOW);
37403
+ file = await open13(path2, constants5.O_RDONLY | constants5.O_NOFOLLOW);
37122
37404
  const stat12 = await file.stat();
37123
37405
  if (!stat12.isFile() || privateFile && (stat12.mode & 511) !== 384) {
37124
37406
  throw new PiSlotError("unsafe-path");
37125
37407
  }
37126
37408
  await afterReadCheck?.(path2);
37127
- const current = await lstat17(path2);
37409
+ const current = await lstat18(path2);
37128
37410
  if (!current.isFile() || current.dev !== stat12.dev || current.ino !== stat12.ino) {
37129
37411
  throw new PiSlotError("unsafe-path");
37130
37412
  }
@@ -37196,7 +37478,7 @@ function replaceEntry(auth, provider, next) {
37196
37478
  async function syncDir(path2) {
37197
37479
  if (windowsPrivateFiles)
37198
37480
  return;
37199
- const dir = await open12(path2, "r");
37481
+ const dir = await open13(path2, "r");
37200
37482
  try {
37201
37483
  await dir.sync();
37202
37484
  } finally {
@@ -37259,7 +37541,7 @@ function createPiSlot(options, onStep, hooks) {
37259
37541
  if (windowsPrivateFiles)
37260
37542
  await ensurePrivateDirectory(dirname21(authPath));
37261
37543
  else
37262
- await mkdir14(dirname21(authPath), { recursive: true, mode: 448 });
37544
+ await mkdir15(dirname21(authPath), { recursive: true, mode: 448 });
37263
37545
  const deadline = Date.now() + timeout;
37264
37546
  let retry = 0;
37265
37547
  while (!release2) {
@@ -37321,8 +37603,8 @@ function createPiSlot(options, onStep, hooks) {
37321
37603
  if (windowsPrivateFiles)
37322
37604
  await ensurePrivateDirectory(dirname21(stashPath));
37323
37605
  else {
37324
- await mkdir14(dirname21(stashPath), { recursive: true, mode: 448 });
37325
- const dir = await lstat17(dirname21(stashPath));
37606
+ await mkdir15(dirname21(stashPath), { recursive: true, mode: 448 });
37607
+ const dir = await lstat18(dirname21(stashPath));
37326
37608
  if (!dir.isDirectory() || (dir.mode & 511) !== 448)
37327
37609
  throw new PiSlotError("unsafe-path");
37328
37610
  }
@@ -37363,7 +37645,7 @@ function createPiSlot(options, onStep, hooks) {
37363
37645
  function nativePiAuthSlotPaths(options) {
37364
37646
  return {
37365
37647
  authPath: resolve16(options.authPath),
37366
- stashPath: join23(dirname22(getHostClaustrumEnrollmentPaths("pi", options.env).tokenPath), "pi-auth-slot", "anthropic.json"),
37648
+ stashPath: join24(dirname22(getHostClaustrumEnrollmentPaths("pi", options.env).tokenPath), "pi-auth-slot", "anthropic.json"),
37367
37649
  provider: "anthropic",
37368
37650
  placeholderKey: placeholderSecret("anthropic")
37369
37651
  };
@@ -37493,11 +37775,11 @@ function createAnthropicOAuthFetch(options = {}) {
37493
37775
  });
37494
37776
  }
37495
37777
  // src/prime.ts
37496
- import { createHash as createHash26 } from "node:crypto";
37778
+ import { createHash as createHash27 } from "node:crypto";
37497
37779
  import { realpathSync as realpathSync3 } from "node:fs";
37498
- import { mkdir as mkdir15, readdir as readdir4, rm as rm8, stat as stat12, writeFile as writeFile5 } from "node:fs/promises";
37499
- import { tmpdir as tmpdir7 } from "node:os";
37500
- import { join as join24, resolve as resolve17 } from "node:path";
37780
+ import { mkdir as mkdir16, readdir as readdir5, rm as rm9, stat as stat12, writeFile as writeFile6 } from "node:fs/promises";
37781
+ import { tmpdir as tmpdir8 } from "node:os";
37782
+ import { join as join25, resolve as resolve17 } from "node:path";
37501
37783
  var CLAUDE_PRIME_COMMAND_NAME = "claude-prime";
37502
37784
  var PRIME_TICK_MS = 60000;
37503
37785
  var PRIME_DUE_OFFSET_MS = 60000;
@@ -37685,7 +37967,7 @@ function buildPrimeRequestBody() {
37685
37967
  return JSON.parse(JSON.stringify(PRIME_REQUEST_BODY));
37686
37968
  }
37687
37969
  function defaultMarkerDir() {
37688
- return join24(tmpdir7(), "opencode-anthropic-auth", "prime");
37970
+ return join25(tmpdir8(), "opencode-anthropic-auth", "prime");
37689
37971
  }
37690
37972
  function primeStorageFingerprint(storagePath) {
37691
37973
  const absolutePath = resolve17(storagePath);
@@ -37697,22 +37979,22 @@ function primeStorageFingerprint(storagePath) {
37697
37979
  throw error;
37698
37980
  canonicalPath2 = absolutePath;
37699
37981
  }
37700
- return createHash26("sha256").update(canonicalPath2).digest("hex").slice(0, 12);
37982
+ return createHash27("sha256").update(canonicalPath2).digest("hex").slice(0, 12);
37701
37983
  }
37702
37984
  function primeMarkerNamespaceDir(markerDir, storagePath) {
37703
- return join24(markerDir, primeStorageFingerprint(storagePath));
37985
+ return join25(markerDir, primeStorageFingerprint(storagePath));
37704
37986
  }
37705
37987
  function primeAccountMarkerDir(markerDir, storagePath, accountFingerprint) {
37706
37988
  if (!/^[a-f0-9]{12,}$/i.test(accountFingerprint)) {
37707
37989
  throw new Error("Prime account fingerprint must be a hexadecimal digest");
37708
37990
  }
37709
- return join24(primeMarkerNamespaceDir(markerDir, storagePath), accountFingerprint.toLowerCase().slice(0, 12));
37991
+ return join25(primeMarkerNamespaceDir(markerDir, storagePath), accountFingerprint.toLowerCase().slice(0, 12));
37710
37992
  }
37711
37993
  function primeMarkerPath(markerDir, accountId2, resetsAtEpochMs) {
37712
- return join24(markerDir, `${encodeURIComponent(accountId2)}-${resetsAtEpochMs}`);
37994
+ return join25(markerDir, `${encodeURIComponent(accountId2)}-${resetsAtEpochMs}`);
37713
37995
  }
37714
37996
  function primeBootstrapMarkerPath(markerDir, accountId2) {
37715
- return join24(markerDir, `${encodeURIComponent(accountId2)}-bootstrap`);
37997
+ return join25(markerDir, `${encodeURIComponent(accountId2)}-bootstrap`);
37716
37998
  }
37717
37999
  function primeAccountLabel(id2, fallback) {
37718
38000
  if (id2 === "main")
@@ -37988,13 +38270,13 @@ class PrimeManager {
37988
38270
  }
37989
38271
  const postClaimStorage = await this.options.loadStorage();
37990
38272
  if (this.stopped || postClaimStorage?.prime?.enabled !== true) {
37991
- await rm8(markerPath, { force: true });
38273
+ await rm9(markerPath, { force: true });
37992
38274
  return;
37993
38275
  }
37994
38276
  if (markerEpoch !== undefined) {
37995
- await rm8(bootstrapMarkerPath, { force: true });
38277
+ await rm9(bootstrapMarkerPath, { force: true });
37996
38278
  if (this.stopped) {
37997
- await rm8(markerPath, { force: true });
38279
+ await rm9(markerPath, { force: true });
37998
38280
  return;
37999
38281
  }
38000
38282
  }
@@ -38019,10 +38301,10 @@ class PrimeManager {
38019
38301
  }
38020
38302
  async tryClaimPath(dir, markerPath) {
38021
38303
  try {
38022
- await mkdir15(dir, { recursive: true });
38304
+ await mkdir16(dir, { recursive: true });
38023
38305
  } catch {}
38024
38306
  try {
38025
- await writeFile5(markerPath, "", { encoding: "utf8", flag: "wx" });
38307
+ await writeFile6(markerPath, "", { encoding: "utf8", flag: "wx" });
38026
38308
  return markerPath;
38027
38309
  } catch (error) {
38028
38310
  const code2 = error.code;
@@ -38035,7 +38317,7 @@ class PrimeManager {
38035
38317
  const dir = this.markerDir(accountFingerprint);
38036
38318
  const prefix = `${encodeURIComponent(accountId2)}-`;
38037
38319
  try {
38038
- return (await readdir4(dir)).some((entry2) => entry2.startsWith(prefix));
38320
+ return (await readdir5(dir)).some((entry2) => entry2.startsWith(prefix));
38039
38321
  } catch (error) {
38040
38322
  if (error.code === "ENOENT")
38041
38323
  return false;
@@ -38147,21 +38429,21 @@ class PrimeManager {
38147
38429
  async sweepMarkerDirectory(dir, now) {
38148
38430
  let entries;
38149
38431
  try {
38150
- entries = await readdir4(dir);
38432
+ entries = await readdir5(dir);
38151
38433
  } catch {
38152
38434
  return 0;
38153
38435
  }
38154
38436
  let swept = 0;
38155
38437
  for (const entry2 of entries) {
38156
38438
  try {
38157
- const path2 = join24(dir, entry2);
38439
+ const path2 = join25(dir, entry2);
38158
38440
  const s = await stat12(path2);
38159
38441
  if (s.isDirectory()) {
38160
38442
  swept += await this.sweepMarkerDirectory(path2, now);
38161
38443
  continue;
38162
38444
  }
38163
38445
  if (now - s.mtimeMs > PRIME_MARKER_MAX_AGE_MS) {
38164
- await rm8(path2, { force: true });
38446
+ await rm9(path2, { force: true });
38165
38447
  swept += 1;
38166
38448
  }
38167
38449
  } catch {}
@@ -38176,24 +38458,24 @@ class PrimeManager {
38176
38458
  }
38177
38459
  }
38178
38460
  // src/quota-header-feed.ts
38179
- import { randomUUID as randomUUID19 } from "node:crypto";
38461
+ import { randomUUID as randomUUID20 } from "node:crypto";
38180
38462
  import {
38181
38463
  chmod as chmod3,
38182
- lstat as lstat18,
38183
- mkdir as mkdir16,
38184
- readdir as readdir5,
38464
+ lstat as lstat19,
38465
+ mkdir as mkdir17,
38466
+ readdir as readdir6,
38185
38467
  readFile as readFile13,
38186
38468
  rename as rename14,
38187
- rm as rm9,
38469
+ rm as rm10,
38188
38470
  stat as stat13,
38189
- writeFile as writeFile6
38471
+ writeFile as writeFile7
38190
38472
  } from "node:fs/promises";
38191
- import { tmpdir as tmpdir8 } from "node:os";
38192
- import { join as join25 } from "node:path";
38473
+ import { tmpdir as tmpdir9 } from "node:os";
38474
+ import { join as join26 } from "node:path";
38193
38475
  var QUOTA_HEADER_FEED_SCHEMA_VERSION = 3;
38194
38476
  var QUOTA_HEADER_FEED_LEASE_MS = 180000;
38195
38477
  function getDefaultQuotaHeaderFeedDirectory() {
38196
- return process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR ?? join25(tmpdir8(), "opencode-anthropic-auth", "quota-header-feed");
38478
+ return process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR ?? join26(tmpdir9(), "opencode-anthropic-auth", "quota-header-feed");
38197
38479
  }
38198
38480
  function configuredAnthropicOAuthAccountCount(input) {
38199
38481
  const fallbackCount = input.storage?.accounts.filter(isOAuthAccount).length ?? 0;
@@ -38351,8 +38633,8 @@ class QuotaHeaderFeedRegistry {
38351
38633
  writeChain = Promise.resolve();
38352
38634
  constructor(options = {}) {
38353
38635
  this.options = options;
38354
- const instanceId = options.instanceId ?? `${process.pid}-${randomUUID19()}`;
38355
- this.filePath = join25(options.directory ?? getDefaultQuotaHeaderFeedDirectory(), `${instanceId}.json`);
38636
+ const instanceId = options.instanceId ?? `${process.pid}-${randomUUID20()}`;
38637
+ this.filePath = join26(options.directory ?? getDefaultQuotaHeaderFeedDirectory(), `${instanceId}.json`);
38356
38638
  }
38357
38639
  publish(entry2) {
38358
38640
  const { accountKey, quota: quota2 } = entry2;
@@ -38381,24 +38663,24 @@ class QuotaHeaderFeedRegistry {
38381
38663
  return Promise.reject(new Error("Invalid quota header feed account key"));
38382
38664
  this.writeChain = this.writeChain.catch(() => {}).then(async () => {
38383
38665
  const directory = this.options.directory ?? getDefaultQuotaHeaderFeedDirectory();
38384
- await mkdir16(directory, { recursive: true, mode: 448 });
38666
+ await mkdir17(directory, { recursive: true, mode: 448 });
38385
38667
  await chmod3(directory, 448);
38386
38668
  await this.reapStaleSiblingLeases(directory);
38387
38669
  let entries = {};
38388
38670
  try {
38389
- const record9 = JSON.parse(await readFile13(this.filePath, "utf8"));
38390
- if (record9.version === QUOTA_HEADER_FEED_SCHEMA_VERSION && record9.entries && typeof record9.entries === "object")
38391
- entries = record9.entries;
38671
+ const record10 = JSON.parse(await readFile13(this.filePath, "utf8"));
38672
+ if (record10.version === QUOTA_HEADER_FEED_SCHEMA_VERSION && record10.entries && typeof record10.entries === "object")
38673
+ entries = record10.entries;
38392
38674
  } catch {}
38393
38675
  entries[accountKey] = cleanEntry;
38394
- const tempPath = `${this.filePath}.${randomUUID19()}.tmp`;
38676
+ const tempPath = `${this.filePath}.${randomUUID20()}.tmp`;
38395
38677
  try {
38396
- await writeFile6(tempPath, `${JSON.stringify({ version: QUOTA_HEADER_FEED_SCHEMA_VERSION, lease_horizon_ms: this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS, entries })}
38678
+ await writeFile7(tempPath, `${JSON.stringify({ version: QUOTA_HEADER_FEED_SCHEMA_VERSION, lease_horizon_ms: this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS, entries })}
38397
38679
  `, { mode: 384 });
38398
38680
  await chmod3(tempPath, 384);
38399
38681
  await rename14(tempPath, this.filePath);
38400
38682
  } finally {
38401
- await rm9(tempPath, { force: true });
38683
+ await rm10(tempPath, { force: true });
38402
38684
  }
38403
38685
  });
38404
38686
  return this.writeChain;
@@ -38408,12 +38690,12 @@ class QuotaHeaderFeedRegistry {
38408
38690
  const leaseMs = this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS;
38409
38691
  let names2;
38410
38692
  try {
38411
- names2 = await readdir5(directory);
38693
+ names2 = await readdir6(directory);
38412
38694
  } catch {
38413
38695
  return;
38414
38696
  }
38415
38697
  await Promise.all(names2.filter((name) => /^\d+-[0-9a-f-]+\.json$/i.test(name)).map(async (name) => {
38416
- const path2 = join25(directory, name);
38698
+ const path2 = join26(directory, name);
38417
38699
  if (path2 === this.filePath)
38418
38700
  return;
38419
38701
  try {
@@ -38421,10 +38703,10 @@ class QuotaHeaderFeedRegistry {
38421
38703
  if (file.mtimeMs > now || now - file.mtimeMs < leaseMs)
38422
38704
  return;
38423
38705
  await this.options.beforeRemoveFile?.(path2);
38424
- const current = await lstat18(path2);
38706
+ const current = await lstat19(path2);
38425
38707
  if (current.ino !== file.ino || current.mtimeMs !== file.mtimeMs)
38426
38708
  return;
38427
- await (this.options.removeFile ?? ((target2) => rm9(target2)))(path2);
38709
+ await (this.options.removeFile ?? ((target2) => rm10(target2)))(path2);
38428
38710
  } catch {}
38429
38711
  }));
38430
38712
  }
@@ -38435,17 +38717,17 @@ class QuotaHeaderFeedRegistry {
38435
38717
  const leaseMs = this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS;
38436
38718
  let names2;
38437
38719
  try {
38438
- names2 = (await readdir5(directory)).filter((name) => name.endsWith(".json"));
38720
+ names2 = (await readdir6(directory)).filter((name) => name.endsWith(".json"));
38439
38721
  } catch {
38440
38722
  return [];
38441
38723
  }
38442
38724
  const newest = new Map;
38443
38725
  await Promise.all(names2.map(async (name) => {
38444
38726
  try {
38445
- const record9 = JSON.parse(await readFile13(join25(directory, name), "utf8"));
38446
- if (record9.version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || !record9.entries || typeof record9.entries !== "object")
38727
+ const record10 = JSON.parse(await readFile13(join26(directory, name), "utf8"));
38728
+ if (record10.version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || !record10.entries || typeof record10.entries !== "object")
38447
38729
  return;
38448
- for (const [accountKey, candidate] of Object.entries(record9.entries)) {
38730
+ for (const [accountKey, candidate] of Object.entries(record10.entries)) {
38449
38731
  if (!candidate || typeof candidate !== "object" || candidate.schema_version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || candidate.provider !== "anthropic" || !validIdentity(candidate))
38450
38732
  continue;
38451
38733
  const observed = candidate.observed_at_ms;
@@ -38461,7 +38743,7 @@ class QuotaHeaderFeedRegistry {
38461
38743
  }
38462
38744
  async dispose() {
38463
38745
  await this.writeChain.catch(() => {});
38464
- await rm9(this.filePath, { force: true });
38746
+ await rm10(this.filePath, { force: true });
38465
38747
  }
38466
38748
  }
38467
38749
  // src/quotas.ts
@@ -38622,11 +38904,11 @@ function buildClaudeQuotaSummary(input) {
38622
38904
  `).trimEnd();
38623
38905
  }
38624
38906
  // src/request-gzip.ts
38625
- import { mkdir as mkdir17, readFile as readFile14, rename as rename15, rm as rm10, writeFile as writeFile7 } from "node:fs/promises";
38626
- import { basename as basename10, dirname as dirname23, join as join26 } from "node:path";
38627
- import { promisify } from "node:util";
38628
- import { gzip } from "node:zlib";
38629
- var gzipAsync = promisify(gzip);
38907
+ import { mkdir as mkdir18, readFile as readFile14, rename as rename15, rm as rm11, writeFile as writeFile8 } from "node:fs/promises";
38908
+ import { basename as basename10, dirname as dirname23, join as join27 } from "node:path";
38909
+ import { promisify as promisify2 } from "node:util";
38910
+ import { gzip as gzip2 } from "node:zlib";
38911
+ var gzipAsync = promisify2(gzip2);
38630
38912
  var GZIP_REQUEST_BODIES_ENV = "CLAUDE_CODE_GZIP_REQUEST_BODIES";
38631
38913
  var GZIP_HOST = "api.anthropic.com";
38632
38914
  var GZIP_LEVEL = 6;
@@ -38737,7 +39019,7 @@ class RequestGzipLatch {
38737
39019
  const age = typeof latchedAt === "number" && Number.isFinite(latchedAt) ? this.now() - latchedAt : -1;
38738
39020
  if (age >= 0 && age < GZIP_LATCH_TTL_MS)
38739
39021
  return true;
38740
- await rm10(this.path, { force: true }).catch(() => {});
39022
+ await rm11(this.path, { force: true }).catch(() => {});
38741
39023
  return false;
38742
39024
  }
38743
39025
  async persist(status) {
@@ -38747,12 +39029,12 @@ class RequestGzipLatch {
38747
39029
  return;
38748
39030
  const temporary = `${this.path}.${process.pid}.tmp`;
38749
39031
  try {
38750
- await mkdir17(dirname23(this.path), { recursive: true });
38751
- await writeFile7(temporary, `${JSON.stringify({ latchedAt: this.now(), status })}
39032
+ await mkdir18(dirname23(this.path), { recursive: true });
39033
+ await writeFile8(temporary, `${JSON.stringify({ latchedAt: this.now(), status })}
38752
39034
  `, { mode: 384 });
38753
39035
  await rename15(temporary, this.path);
38754
39036
  } catch {
38755
- await rm10(temporary, { force: true }).catch(() => {});
39037
+ await rm11(temporary, { force: true }).catch(() => {});
38756
39038
  }
38757
39039
  }
38758
39040
  }
@@ -38769,7 +39051,7 @@ function getRequestGzipLatch(path2) {
38769
39051
  function getRequestGzipLatchPath(accountStoragePath) {
38770
39052
  const name = basename10(accountStoragePath);
38771
39053
  const stem = name.endsWith(".json") ? name.slice(0, -5) : name;
38772
- return join26(dirname23(accountStoragePath), `${stem}-request-gzip.json`);
39054
+ return join27(dirname23(accountStoragePath), `${stem}-request-gzip.json`);
38773
39055
  }
38774
39056
  async function decideRequestGzip(options) {
38775
39057
  if (!CLAUDE_CODE_GZIPS_REQUEST_BODIES)
@@ -38838,13 +39120,13 @@ function isInvalidJsonBody(text6) {
38838
39120
  }
38839
39121
  if (!parsed || typeof parsed !== "object")
38840
39122
  return false;
38841
- const record9 = parsed;
38842
- const error = record9.error;
38843
- if (record9.type === "error" && error && typeof error === "object" && typeof error.type === "string" && typeof error.message === "string") {
39123
+ const record10 = parsed;
39124
+ const error = record10.error;
39125
+ if (record10.type === "error" && error && typeof error === "object" && typeof error.type === "string" && typeof error.message === "string") {
38844
39126
  const message = error.message;
38845
39127
  return INVALID_JSON_MESSAGES.some((prefix) => message.startsWith(prefix));
38846
39128
  }
38847
- return typeof record9.error === "string" && record9.reason === "bad_json" && BAD_JSON_TEXT.test(record9.error);
39129
+ return typeof record10.error === "string" && record10.reason === "bad_json" && BAD_JSON_TEXT.test(record10.error);
38848
39130
  }
38849
39131
  async function classifyGzipRejection(response) {
38850
39132
  const { status } = response;
@@ -38997,14 +39279,14 @@ function executeLaneStartCommand(input) {
38997
39279
  };
38998
39280
  }
38999
39281
  // src/state-layout-decision.ts
39000
- import { mkdir as mkdir18, readdir as readdir8 } from "node:fs/promises";
39282
+ import { mkdir as mkdir19, readdir as readdir9 } from "node:fs/promises";
39001
39283
  import { homedir as homedir8 } from "node:os";
39002
- import { basename as basename13, dirname as dirname25, join as join30 } from "node:path";
39284
+ import { basename as basename13, dirname as dirname25, join as join31 } from "node:path";
39003
39285
 
39004
39286
  // src/layout-fence.ts
39005
- import { open as open13, readdir as readdir6 } from "node:fs/promises";
39287
+ import { open as open14, readdir as readdir7 } from "node:fs/promises";
39006
39288
  import { homedir as homedir6 } from "node:os";
39007
- import { basename as basename11, join as join27, resolve as resolve18 } from "node:path";
39289
+ import { basename as basename11, join as join28, resolve as resolve18 } from "node:path";
39008
39290
  var STATE_PATH_OVERRIDE_VARIABLES = [
39009
39291
  "OPENCODE_ANTHROPIC_AUTH_FILE",
39010
39292
  "OPENCODE_ANTHROPIC_AUTH_STATE_FILE",
@@ -39040,7 +39322,7 @@ async function holderFenceBlockers(input) {
39040
39322
  const files = new Set(input.files);
39041
39323
  const blockers = [];
39042
39324
  for (const dir of [...new Set(input.directories)].sort()) {
39043
- const holderFile = join27(dir, HOLDER_FILE_NAME);
39325
+ const holderFile = join28(dir, HOLDER_FILE_NAME);
39044
39326
  let contents;
39045
39327
  try {
39046
39328
  contents = await readHolderFile(holderFile);
@@ -39054,8 +39336,8 @@ async function holderFenceBlockers(input) {
39054
39336
  }
39055
39337
  for (const value of contents?.entries ?? []) {
39056
39338
  const life = holderEntryLiveness(value);
39057
- const record9 = value;
39058
- const listed = Array.isArray(record9?.files) ? record9.files.filter((file) => typeof file === "string") : undefined;
39339
+ const record10 = value;
39340
+ const listed = Array.isArray(record10?.files) ? record10.files.filter((file) => typeof file === "string") : undefined;
39059
39341
  if (!life || !listed) {
39060
39342
  blockers.push({
39061
39343
  kind: "holder",
@@ -39075,7 +39357,7 @@ async function holderFenceBlockers(input) {
39075
39357
  kind: "holder",
39076
39358
  holderFile,
39077
39359
  pid: life.pid,
39078
- role: typeof record9.role === "string" ? record9.role : null,
39360
+ role: typeof record10.role === "string" ? record10.role : null,
39079
39361
  file: overlap
39080
39362
  });
39081
39363
  }
@@ -39090,7 +39372,7 @@ function defaultPreNArtifactLocations(env = process.env, home = homedir6()) {
39090
39372
  });
39091
39373
  const rpcOverride = env.OPENCODE_ANTHROPIC_AUTH_RPC_DIR?.trim();
39092
39374
  return {
39093
- rpcRoots: [join27(root, "rpc")],
39375
+ rpcRoots: [join28(root, "rpc")],
39094
39376
  rpcDirs: rpcOverride ? [resolve18(rpcOverride)] : [],
39095
39377
  cacheKeepDirs: [
39096
39378
  ...new Set([
@@ -39106,7 +39388,7 @@ function defaultPreNArtifactLocations(env = process.env, home = homedir6()) {
39106
39388
  }
39107
39389
  async function listDir(dir, blockers) {
39108
39390
  try {
39109
- return await readdir6(dir);
39391
+ return await readdir7(dir);
39110
39392
  } catch (error) {
39111
39393
  if (errorCode5(error) === "ENOENT")
39112
39394
  return [];
@@ -39124,7 +39406,7 @@ async function readArtifact(path2, blockers) {
39124
39406
  let text6;
39125
39407
  let mtimeMs;
39126
39408
  try {
39127
- const file = await open13(path2, "r");
39409
+ const file = await open14(path2, "r");
39128
39410
  try {
39129
39411
  text6 = await file.readFile("utf8");
39130
39412
  mtimeMs = (await file.stat()).mtimeMs;
@@ -39151,16 +39433,16 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
39151
39433
  const portDirs = [...locations.rpcDirs];
39152
39434
  for (const root of locations.rpcRoots)
39153
39435
  for (const name of await listDir(root, blockers))
39154
- portDirs.push(join27(root, name));
39436
+ portDirs.push(join28(root, name));
39155
39437
  for (const dir of [...new Set(portDirs)]) {
39156
39438
  for (const name of await listDir(dir, blockers)) {
39157
39439
  if (!/^port-\d+\.json$/.test(name))
39158
39440
  continue;
39159
- const path2 = join27(dir, name);
39160
- const record9 = await readArtifact(path2, blockers);
39161
- if (record9 === undefined || stamped(record9.value))
39441
+ const path2 = join28(dir, name);
39442
+ const record10 = await readArtifact(path2, blockers);
39443
+ if (record10 === undefined || stamped(record10.value))
39162
39444
  continue;
39163
- const { value, startedAt } = record9;
39445
+ const { value, startedAt } = record10;
39164
39446
  const pid = value.pid;
39165
39447
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0) {
39166
39448
  blockers.push({ kind: "artifact-scan", path: path2, reason: "invalid" });
@@ -39175,12 +39457,12 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
39175
39457
  const match = /^(\d+)-.+\.json$/.exec(name);
39176
39458
  if (!match)
39177
39459
  continue;
39178
- const path2 = join27(dir, name);
39179
- const record9 = await readArtifact(path2, blockers);
39180
- if (record9 === undefined || stamped(record9.value))
39460
+ const path2 = join28(dir, name);
39461
+ const record10 = await readArtifact(path2, blockers);
39462
+ if (record10 === undefined || stamped(record10.value))
39181
39463
  continue;
39182
39464
  const pid = Number(match[1]);
39183
- if (!recordPredatesBoot(record9.startedAt, clock) && pidAlive2(pid))
39465
+ if (!recordPredatesBoot(record10.startedAt, clock) && pidAlive2(pid))
39184
39466
  blockers.push({ kind: "pre-n-artifact", artifact: path2, pid });
39185
39467
  }
39186
39468
  }
@@ -39202,15 +39484,15 @@ function describeFenceBlocker(blocker) {
39202
39484
  }
39203
39485
 
39204
39486
  // src/state-layout-move.ts
39205
- import { randomUUID as randomUUID20 } from "node:crypto";
39206
- import { lstat as lstat19, readdir as readdir7, readFile as readFile15, stat as stat14, unlink as unlink10 } from "node:fs/promises";
39207
- import { basename as basename12, dirname as dirname24, join as join28, sep as sep2 } from "node:path";
39487
+ import { randomUUID as randomUUID21 } from "node:crypto";
39488
+ import { lstat as lstat20, readdir as readdir8, readFile as readFile15, stat as stat14, unlink as unlink10 } from "node:fs/promises";
39489
+ import { basename as basename12, dirname as dirname24, join as join29, sep as sep2 } from "node:path";
39208
39490
  var ACCOUNT_FILE = "anthropic-auth.json";
39209
39491
  var ACCOUNT_STATE_FILE = "anthropic-auth-state.json";
39210
39492
  var LAYOUT_LOCK_NAME = "runtime-layout";
39211
39493
  var LAYOUT_LOCK_TIMEOUT_MS = 120000;
39212
39494
  async function resolveLegacyDatasetFiles(configDir) {
39213
- const oldPaths = await resolveNativePoolPaths(join28(configDir, ACCOUNT_FILE), join28(configDir, ACCOUNT_STATE_FILE), { kind: "legacy" });
39495
+ const oldPaths = await resolveNativePoolPaths(join29(configDir, ACCOUNT_FILE), join29(configDir, ACCOUNT_STATE_FILE), { kind: "legacy" });
39214
39496
  return {
39215
39497
  oldDir: await canonicalPath(configDir),
39216
39498
  oldPaths,
@@ -39218,8 +39500,8 @@ async function resolveLegacyDatasetFiles(configDir) {
39218
39500
  };
39219
39501
  }
39220
39502
  async function resolveRelocationDataset(input) {
39221
- const legacyConfig = join28(input.configDir, ACCOUNT_FILE);
39222
- const legacyState = join28(input.configDir, ACCOUNT_STATE_FILE);
39503
+ const legacyConfig = join29(input.configDir, ACCOUNT_FILE);
39504
+ const legacyState = join29(input.configDir, ACCOUNT_STATE_FILE);
39223
39505
  const { oldDir, oldPaths, oldVault } = await resolveLegacyDatasetFiles(input.configDir);
39224
39506
  const stateHome = { kind: "state-home", dir: input.sub };
39225
39507
  const newPaths = await resolveNativePoolPaths(legacyConfig, legacyState, stateHome);
@@ -39248,7 +39530,7 @@ async function resolveRelocationDataset(input) {
39248
39530
  role,
39249
39531
  from: pairs[role][0],
39250
39532
  to: pairs[role][1],
39251
- configured: join28(input.configDir, STATE_HOME_FILE_NAMES[role])
39533
+ configured: join29(input.configDir, STATE_HOME_FILE_NAMES[role])
39252
39534
  })),
39253
39535
  storageIds: { local: oldPaths.storageId, vault: oldVault.storageId }
39254
39536
  };
@@ -39270,8 +39552,8 @@ function errorCode6(error) {
39270
39552
  }
39271
39553
  function transitionHolderFiles(dataset) {
39272
39554
  return [
39273
- join28(dataset.oldDir, HOLDER_FILE_NAME),
39274
- join28(dataset.sub, HOLDER_FILE_NAME)
39555
+ join29(dataset.oldDir, HOLDER_FILE_NAME),
39556
+ join29(dataset.sub, HOLDER_FILE_NAME)
39275
39557
  ].sort();
39276
39558
  }
39277
39559
  async function acquireHolderLock(ctx, holderFile, timeoutMs) {
@@ -39288,7 +39570,7 @@ async function acquireHolderLock(ctx, holderFile, timeoutMs) {
39288
39570
  }
39289
39571
  }
39290
39572
  async function acquireHolderLocks(dataset, ctx) {
39291
- const oldHolders = join28(dataset.oldDir, HOLDER_FILE_NAME);
39573
+ const oldHolders = join29(dataset.oldDir, HOLDER_FILE_NAME);
39292
39574
  for (const file of transitionHolderFiles(dataset)) {
39293
39575
  if (file === oldHolders)
39294
39576
  await stateLayoutStep(ctx, "old-holders-locking");
@@ -39468,14 +39750,14 @@ async function drainCoalescedWrites(dataset) {
39468
39750
  await drainVaultQuota(dataset.oldVault.roster);
39469
39751
  forgetRelocationObservations();
39470
39752
  }
39471
- function relocationTombstone(record9) {
39753
+ function relocationTombstone(record10) {
39472
39754
  return `${JSON.stringify({
39473
39755
  version: 0,
39474
- relocatedTo: record9.sub,
39475
- stateRoot: record9.stateRoot,
39476
- identity: record9.identity,
39477
- attempt: record9.attempt,
39478
- by: record9.by
39756
+ relocatedTo: record10.sub,
39757
+ stateRoot: record10.stateRoot,
39758
+ identity: record10.identity,
39759
+ attempt: record10.attempt,
39760
+ by: record10.by
39479
39761
  })}
39480
39762
  `;
39481
39763
  }
@@ -39494,7 +39776,7 @@ function restoringPath(path2, attempt) {
39494
39776
  }
39495
39777
  async function exists3(path2) {
39496
39778
  try {
39497
- await lstat19(path2);
39779
+ await lstat20(path2);
39498
39780
  return true;
39499
39781
  } catch (error) {
39500
39782
  if (errorCode6(error) === "ENOENT")
@@ -39504,7 +39786,7 @@ async function exists3(path2) {
39504
39786
  }
39505
39787
  async function removeOwnStaging(path2) {
39506
39788
  try {
39507
- const info = await lstat19(path2);
39789
+ const info = await lstat20(path2);
39508
39790
  if (info.isFile())
39509
39791
  await unlink10(path2);
39510
39792
  } catch (error) {
@@ -39512,17 +39794,17 @@ async function removeOwnStaging(path2) {
39512
39794
  throw error;
39513
39795
  }
39514
39796
  }
39515
- function recordFilesProblem(record9, dataset) {
39516
- if (record9.files.length !== dataset.slots.length)
39517
- return `it lists ${record9.files.length} files, not ${dataset.slots.length}`;
39797
+ function recordFilesProblem(record10, dataset) {
39798
+ if (record10.files.length !== dataset.slots.length)
39799
+ return `it lists ${record10.files.length} files, not ${dataset.slots.length}`;
39518
39800
  for (const slot of dataset.slots) {
39519
- const file = record9.files.find((candidate) => candidate.role === slot.role);
39801
+ const file = record10.files.find((candidate) => candidate.role === slot.role);
39520
39802
  if (!file)
39521
39803
  return `it has no ${slot.role} entry`;
39522
39804
  if (file.from !== slot.from || file.to !== slot.to)
39523
39805
  return `its ${slot.role} entry names ${file.from} and ${file.to}, not ${slot.from} and ${slot.to}`;
39524
39806
  }
39525
- for (const file of record9.restore?.files ?? []) {
39807
+ for (const file of record10.restore?.files ?? []) {
39526
39808
  const slot = dataset.slots.find((candidate) => candidate.role === file.role);
39527
39809
  if (!slot || file.from !== slot.from || file.to !== slot.to)
39528
39810
  return `its restore lists ${file.from} and ${file.to} for ${file.role}`;
@@ -39547,7 +39829,7 @@ async function movePreconditionFailure(dataset, platform) {
39547
39829
  for (const path2 of new Set([slot.configured, slot.from])) {
39548
39830
  let info;
39549
39831
  try {
39550
- info = await lstat19(path2);
39832
+ info = await lstat20(path2);
39551
39833
  } catch (error) {
39552
39834
  if (errorCode6(error) === "ENOENT")
39553
39835
  continue;
@@ -39564,7 +39846,7 @@ async function movePreconditionFailure(dataset, platform) {
39564
39846
  anyOld ||= fromExists;
39565
39847
  if (await exists3(slot.to)) {
39566
39848
  if (fromExists) {
39567
- const [a, b] = await Promise.all([lstat19(slot.from), lstat19(slot.to)]);
39849
+ const [a, b] = await Promise.all([lstat20(slot.from), lstat20(slot.to)]);
39568
39850
  if (a.dev === b.dev && a.ino === b.ino)
39569
39851
  return `${slot.from} and ${slot.to} are the same file`;
39570
39852
  }
@@ -39639,15 +39921,15 @@ async function owned2(ctx, step, expect) {
39639
39921
  if (outcome2 === "skipped")
39640
39922
  throw new Error(`anthropic-auth stopped: ${step.kind === "rename" ? step.to : step.path} changed while it was being replaced`);
39641
39923
  }
39642
- async function rollbackPreparing(record9, dataset, ctx) {
39643
- const { attempt } = record9;
39924
+ async function rollbackPreparing(record10, dataset, ctx) {
39925
+ const { attempt } = record10;
39644
39926
  const slot = (role) => {
39645
- const found = record9.files.find((file) => file.role === role);
39927
+ const found = record10.files.find((file) => file.role === role);
39646
39928
  if (!found)
39647
39929
  throw new StateLayoutRollbackRefused(dataset.sub, `no ${role} entry`);
39648
39930
  return found;
39649
39931
  };
39650
- if (record9.barriers.journal === "present") {
39932
+ if (record10.barriers.journal === "present") {
39651
39933
  const journal = slot("journal");
39652
39934
  const moving = movingJournalPath(journal.from, attempt);
39653
39935
  const movingThere = await exists3(moving);
@@ -39662,7 +39944,7 @@ async function rollbackPreparing(record9, dataset, ctx) {
39662
39944
  await stateLayoutStep(ctx, "rollback:journal");
39663
39945
  for (const role of ["localRuntime", "vaultRuntime"]) {
39664
39946
  const file = slot(role);
39665
- const original = record9.barriers[role].original;
39947
+ const original = record10.barriers[role].original;
39666
39948
  await removeOwnStaging(relocatingPath(file.from, attempt));
39667
39949
  const found = await tombstoneAttempt(file.from);
39668
39950
  if (found !== undefined && found !== attempt)
@@ -39691,7 +39973,7 @@ async function rollbackPreparing(record9, dataset, ctx) {
39691
39973
  }
39692
39974
  await ctx.fs.syncDirectory(dataset.oldDir);
39693
39975
  await stateLayoutStep(ctx, "rollback:old-dir-flushed");
39694
- for (const file of record9.files) {
39976
+ for (const file of record10.files) {
39695
39977
  await removeOwnStaging(relocatingPath(file.to, attempt));
39696
39978
  if (file.sha256 === null)
39697
39979
  continue;
@@ -39702,14 +39984,14 @@ async function rollbackPreparing(record9, dataset, ctx) {
39702
39984
  continue;
39703
39985
  await owned2(ctx, { kind: "unlink", path: file.to }, expectDigest(file.to, file.sha256));
39704
39986
  }
39705
- for (const name of await readdir7(dataset.sub))
39987
+ for (const name of await readdir8(dataset.sub))
39706
39988
  if (isLayoutRecordStage(name, attempt))
39707
- await removeOwnStaging(join28(dataset.sub, name));
39989
+ await removeOwnStaging(join29(dataset.sub, name));
39708
39990
  await stateLayoutStep(ctx, "rollback:destination-removed");
39709
39991
  await ctx.fs.syncDirectory(dataset.sub);
39710
39992
  await stateLayoutStep(ctx, "rollback:sub-flushed");
39711
39993
  const rolledBack = {
39712
- ...record9,
39994
+ ...record10,
39713
39995
  phase: "rolled-back",
39714
39996
  rolledBackAt: ctx.now()
39715
39997
  };
@@ -39721,19 +40003,19 @@ async function rollbackPreparing(record9, dataset, ctx) {
39721
40003
  forgetRelocationObservations();
39722
40004
  return rolledBack;
39723
40005
  }
39724
- async function cleanupOldCopies(record9, dataset, ctx) {
40006
+ async function cleanupOldCopies(record10, dataset, ctx) {
39725
40007
  const kept = [];
39726
40008
  const conflict = [];
39727
40009
  const publish = (next2) => publishStateLayoutRecord(next2, {
39728
40010
  assertLeases: () => ctx.stack.assertAll(),
39729
40011
  expect: expectRecord(dataset.sub, {
39730
40012
  phase: "committed",
39731
- attempt: record9.attempt
40013
+ attempt: record10.attempt
39732
40014
  })
39733
40015
  }, ctx.fs);
39734
40016
  const outcome2 = () => {
39735
40017
  const next2 = {
39736
- ...record9,
40018
+ ...record10,
39737
40019
  cleanup: conflict.length ? "conflict" : kept.length ? "kept" : "done",
39738
40020
  ...kept.length ? { kept: [...kept] } : {},
39739
40021
  ...conflict.length ? { conflict: [...conflict] } : {}
@@ -39749,16 +40031,16 @@ async function cleanupOldCopies(record9, dataset, ctx) {
39749
40031
  return stateLayoutConflict(first?.old ?? dataset.oldPaths.state, first?.new ?? dataset.newPaths.state, cause);
39750
40032
  };
39751
40033
  try {
39752
- const journalSlot = record9.files.find((file) => file.role === "journal");
40034
+ const journalSlot = record10.files.find((file) => file.role === "journal");
39753
40035
  if (journalSlot && await exists3(journalSlot.from))
39754
40036
  conflict.push({ old: journalSlot.from, new: journalSlot.to });
39755
40037
  for (const role of RELOCATION_ROLES) {
39756
40038
  if (role === "localRuntime" || role === "vaultRuntime")
39757
40039
  continue;
39758
- const file = record9.files.find((candidate) => candidate.role === role);
40040
+ const file = record10.files.find((candidate) => candidate.role === role);
39759
40041
  if (!file)
39760
40042
  continue;
39761
- const path2 = role === "journal" ? movingJournalPath(file.from, record9.attempt) : file.from;
40043
+ const path2 = role === "journal" ? movingJournalPath(file.from, record10.attempt) : file.from;
39762
40044
  await ctx.stack.assertAll();
39763
40045
  const credential2 = CREDENTIAL_AUTHORITY_ROLES.includes(role);
39764
40046
  let digest3;
@@ -39807,7 +40089,7 @@ class MoveRefused extends Error {
39807
40089
  }
39808
40090
  }
39809
40091
  async function moveDataset(dataset, ctx, checkArtifacts) {
39810
- const attempt = randomUUID20();
40092
+ const attempt = randomUUID21();
39811
40093
  const files = [];
39812
40094
  for (const slot of dataset.slots)
39813
40095
  files.push({
@@ -39818,7 +40100,7 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
39818
40100
  });
39819
40101
  const sha = (role) => files.find((file) => file.role === role)?.sha256 ?? null;
39820
40102
  await ctx.stack.assertAll();
39821
- const configDirPath = join28(dataset.sub, STATE_HOME_FILE_NAMES.configDirMarker);
40103
+ const configDirPath = join29(dataset.sub, STATE_HOME_FILE_NAMES.configDirMarker);
39822
40104
  if (!await exists3(configDirPath)) {
39823
40105
  const stage = `${configDirPath}.${attempt}.tmp`;
39824
40106
  await createOwnerOnlyFile(ctx.fs, stage, Buffer.from(`${JSON.stringify({ version: 1, identity: dataset.identity })}
@@ -39829,7 +40111,7 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
39829
40111
  await removeOwnStaging(stage);
39830
40112
  }
39831
40113
  }
39832
- const holderFile = join28(dataset.sub, HOLDER_FILE_NAME);
40114
+ const holderFile = join29(dataset.sub, HOLDER_FILE_NAME);
39833
40115
  if (!await exists3(holderFile))
39834
40116
  await writeJsonAtomic(holderFile, { version: 1, entries: [] }, {
39835
40117
  beforeRename: () => ctx.stack.assertAll(),
@@ -39920,8 +40202,8 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
39920
40202
  logger2.error("state-layout", "anthropic-auth could not move its state; keeping the old folder", {
39921
40203
  reason
39922
40204
  });
39923
- const record9 = await rollbackAfterFailure(preparing, dataset, ctx);
39924
- return { status: "rolled-back", reason, record: record9 };
40205
+ const record10 = await rollbackAfterFailure(preparing, dataset, ctx);
40206
+ return { status: "rolled-back", reason, record: record10 };
39925
40207
  }
39926
40208
  const committed = {
39927
40209
  ...preparing,
@@ -39942,8 +40224,8 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
39942
40224
  await syncCommitted(dataset, ctx);
39943
40225
  } else if (onDisk?.phase === "preparing" && onDisk.attempt === attempt) {
39944
40226
  const reason = error instanceof Error ? error.message : String(error);
39945
- const record9 = await rollbackAfterFailure(preparing, dataset, ctx);
39946
- return { status: "rolled-back", reason, record: record9 };
40227
+ const record10 = await rollbackAfterFailure(preparing, dataset, ctx);
40228
+ return { status: "rolled-back", reason, record: record10 };
39947
40229
  } else
39948
40230
  throw error;
39949
40231
  }
@@ -39980,10 +40262,10 @@ async function rollbackAfterFailure(preparing, dataset, ctx) {
39980
40262
  }
39981
40263
 
39982
40264
  // src/state-layout-restore.ts
39983
- import { randomUUID as randomUUID21 } from "node:crypto";
40265
+ import { randomUUID as randomUUID22 } from "node:crypto";
39984
40266
  import { readFile as readFile16 } from "node:fs/promises";
39985
40267
  import { homedir as homedir7 } from "node:os";
39986
- import { join as join29 } from "node:path";
40268
+ import { join as join30 } from "node:path";
39987
40269
  var DATA_ROLES = [
39988
40270
  "localPoolState",
39989
40271
  "localRoster",
@@ -39996,10 +40278,10 @@ function refused2(message, paths = [], cause) {
39996
40278
  logger2.error("state-layout", message, { code: "restore-refused", paths });
39997
40279
  return new StateLayoutRefusalError("restore-refused", message, paths, cause);
39998
40280
  }
39999
- function requireRestoreDetail(record9) {
40000
- const restore = record9.restore;
40281
+ function requireRestoreDetail(record10) {
40282
+ const restore = record10.restore;
40001
40283
  if (!restore?.attempt || !restore.files || !restore.runtimes)
40002
- throw refused2(`${layoutRecordPath(record9.sub)} records an unfinished restore without the files it moved, so anthropic-auth can't finish it.`, [layoutRecordPath(record9.sub)]);
40284
+ throw refused2(`${layoutRecordPath(record10.sub)} records an unfinished restore without the files it moved, so anthropic-auth can't finish it.`, [layoutRecordPath(record10.sub)]);
40003
40285
  return {
40004
40286
  ...restore,
40005
40287
  attempt: restore.attempt,
@@ -40060,9 +40342,9 @@ async function syncObservedRestoreRecord(dataset, ctx) {
40060
40342
  throw new StateLayoutRefusalError("unsafe", `anthropic-auth could not make ${path2} durable, so it won't finish restoring its state; run ${RESTORE_LEGACY_COMMAND} again.`, [path2], error);
40061
40343
  }
40062
40344
  }
40063
- async function finishRestoreRetirement(record9, dataset, ctx) {
40064
- const restore = requireRestoreDetail(record9);
40065
- const kept = [...record9.restore?.kept ?? []];
40345
+ async function finishRestoreRetirement(record10, dataset, ctx) {
40346
+ const restore = requireRestoreDetail(record10);
40347
+ const kept = [...record10.restore?.kept ?? []];
40066
40348
  for (const file of restore.files) {
40067
40349
  try {
40068
40350
  const digest3 = await digestFile(file.to);
@@ -40087,7 +40369,7 @@ async function finishRestoreRetirement(record9, dataset, ctx) {
40087
40369
  await ctx.fs.syncDirectory(dataset.sub);
40088
40370
  await stateLayoutStep(ctx, "restore:sub-flushed");
40089
40371
  const done2 = {
40090
- ...record9,
40372
+ ...record10,
40091
40373
  restore: { ...restore, cleanup: "done", ...kept.length ? { kept } : {} }
40092
40374
  };
40093
40375
  await publishStateLayoutRecord(done2, {
@@ -40098,13 +40380,13 @@ async function finishRestoreRetirement(record9, dataset, ctx) {
40098
40380
  forgetRelocationObservations();
40099
40381
  return done2;
40100
40382
  }
40101
- async function discardAbandonedRestore(record9, dataset, ctx) {
40102
- const restore = requireRestoreDetail(record9);
40383
+ async function discardAbandonedRestore(record10, dataset, ctx) {
40384
+ const restore = requireRestoreDetail(record10);
40103
40385
  for (const file of restore.files)
40104
40386
  if (await exists3(file.staging))
40105
40387
  await owned2(ctx, { kind: "unlink", path: file.staging }, expectPresent(file.staging));
40106
40388
  await ctx.fs.syncDirectory(dataset.oldDir);
40107
- const { restore: _abandoned, ...move } = record9;
40389
+ const { restore: _abandoned, ...move } = record10;
40108
40390
  const committed = { ...move, phase: "committed" };
40109
40391
  await publishStateLayoutRecord(committed, {
40110
40392
  assertLeases: () => ctx.stack.assertAll(),
@@ -40114,8 +40396,8 @@ async function discardAbandonedRestore(record9, dataset, ctx) {
40114
40396
  forgetRelocationObservations();
40115
40397
  return committed;
40116
40398
  }
40117
- async function classifyStagedRestore(record9, dataset) {
40118
- const restore = requireRestoreDetail(record9);
40399
+ async function classifyStagedRestore(record10, dataset) {
40400
+ const restore = requireRestoreDetail(record10);
40119
40401
  const problems = [];
40120
40402
  const listed = (role) => restore.files.find((file) => file.role === role);
40121
40403
  const isStaged = async (file) => {
@@ -40175,7 +40457,7 @@ async function classifyStagedRestore(record9, dataset) {
40175
40457
  if (!file)
40176
40458
  continue;
40177
40459
  const staged = await isStaged(file);
40178
- if (staged && tombstone === record9.attempt)
40460
+ if (staged && tombstone === record10.attempt)
40179
40461
  barriers.push({
40180
40462
  role,
40181
40463
  action: { kind: "rename", file, over: "tombstone" }
@@ -40187,7 +40469,7 @@ async function classifyStagedRestore(record9, dataset) {
40187
40469
  problems.push(`${file.staging} is missing, so ${legacy} can't be restored`);
40188
40470
  else
40189
40471
  problems.push(`${legacy} is no longer this move's tombstone while ${file.staging} still waits to replace it`);
40190
- } else if (tombstone === record9.attempt)
40472
+ } else if (tombstone === record10.attempt)
40191
40473
  barriers.push({
40192
40474
  role,
40193
40475
  action: { kind: "unlink-tombstone", path: legacy }
@@ -40206,36 +40488,36 @@ async function classifyStagedRestore(record9, dataset) {
40206
40488
  }
40207
40489
  return { data, barriers, problems };
40208
40490
  }
40209
- async function act(action, record9, ctx) {
40491
+ async function act(action, record10, ctx) {
40210
40492
  if (action.kind === "none")
40211
40493
  return;
40212
40494
  if (action.kind === "unlink-tombstone") {
40213
- await owned2(ctx, { kind: "unlink", path: action.path }, expectTombstone(action.path, record9.attempt));
40495
+ await owned2(ctx, { kind: "unlink", path: action.path }, expectTombstone(action.path, record10.attempt));
40214
40496
  return;
40215
40497
  }
40216
40498
  const { file, over } = action;
40217
- const target2 = over === "absent" ? expectAbsent(file.from) : over === "present" ? expectPresent(file.from) : expectTombstone(file.from, record9.attempt);
40499
+ const target2 = over === "absent" ? expectAbsent(file.from) : over === "present" ? expectPresent(file.from) : expectTombstone(file.from, record10.attempt);
40218
40500
  await owned2(ctx, { kind: "rename", from: file.staging, to: file.from }, both(expectDigest(file.staging, file.sha256), target2));
40219
40501
  }
40220
- async function finishStagedRestore(record9, dataset, ctx) {
40221
- const restore = requireRestoreDetail(record9);
40222
- const plan2 = await classifyStagedRestore(record9, dataset);
40502
+ async function finishStagedRestore(record10, dataset, ctx) {
40503
+ const restore = requireRestoreDetail(record10);
40504
+ const plan2 = await classifyStagedRestore(record10, dataset);
40223
40505
  if (plan2.problems.length)
40224
40506
  throw refused2(`anthropic-auth can't finish restoring its state to ${dataset.oldDir}: ${plan2.problems.join("; ")}. Then run ${RESTORE_LEGACY_COMMAND} again.`, [dataset.oldDir]);
40225
40507
  for (const { role, action } of plan2.data) {
40226
- await act(action, record9, ctx);
40508
+ await act(action, record10, ctx);
40227
40509
  await stateLayoutStep(ctx, `restore:placed:${role}`);
40228
40510
  }
40229
40511
  await ctx.fs.syncDirectory(dataset.oldDir);
40230
40512
  await stateLayoutStep(ctx, "restore:data-flushed");
40231
40513
  for (const { role, action } of plan2.barriers) {
40232
- await act(action, record9, ctx);
40514
+ await act(action, record10, ctx);
40233
40515
  await stateLayoutStep(ctx, `restore:placed:${role}`);
40234
40516
  }
40235
40517
  await ctx.fs.syncDirectory(dataset.oldDir);
40236
40518
  await stateLayoutStep(ctx, "restore:barriers-flushed");
40237
40519
  const restored = {
40238
- ...record9,
40520
+ ...record10,
40239
40521
  phase: "restored",
40240
40522
  restore: { ...restore, cleanup: "pending" }
40241
40523
  };
@@ -40247,41 +40529,41 @@ async function finishStagedRestore(record9, dataset, ctx) {
40247
40529
  forgetRelocationObservations();
40248
40530
  return finishRestoreRetirement(restored, dataset, ctx);
40249
40531
  }
40250
- async function newRestoreProblems(record9, dataset, options) {
40532
+ async function newRestoreProblems(record10, dataset, options) {
40251
40533
  const problems = [];
40252
- if (record9.cleanup === "pending")
40534
+ if (record10.cleanup === "pending")
40253
40535
  problems.push("the move has not finished removing the old copies; start OpenCode with anthropic-auth once and close it again");
40254
- if (record9.cleanup === "conflict")
40255
- for (const pair of record9.conflict ?? [])
40536
+ if (record10.cleanup === "conflict")
40537
+ for (const pair of record10.conflict ?? [])
40256
40538
  problems.push(`two copies of the account state exist (${pair.old} and ${pair.new}); keep the one you trust and move the other out of both folders`);
40257
- if (record9.cleanup === "kept") {
40258
- for (const path2 of record9.kept ?? [])
40539
+ if (record10.cleanup === "kept") {
40540
+ for (const path2 of record10.kept ?? [])
40259
40541
  if (await exists3(path2))
40260
40542
  problems.push(`${path2} changed after the move and was kept; move it aside or delete it`);
40261
40543
  }
40262
- problems.push(...await holderProblems(join29(dataset.sub, HOLDER_FILE_NAME), options.liveness, true), ...await holderProblems(join29(dataset.oldDir, HOLDER_FILE_NAME), options.liveness, false));
40544
+ problems.push(...await holderProblems(join30(dataset.sub, HOLDER_FILE_NAME), options.liveness, true), ...await holderProblems(join30(dataset.oldDir, HOLDER_FILE_NAME), options.liveness, false));
40263
40545
  const artifacts = options.artifacts ?? defaultPreNArtifactLocations(options.env ?? process.env, options.home ?? homedir7());
40264
40546
  for (const blocker of await preNArtifactBlockers(artifacts, options.liveness?.pidAlive, options.liveness))
40265
40547
  problems.push(`${describeFenceBlocker(blocker)} is still running`);
40266
40548
  for (const slot of dataset.slots) {
40267
40549
  if (slot.role === "localRuntime" || slot.role === "vaultRuntime") {
40268
- if (await tombstoneAttempt(slot.from) !== record9.attempt)
40550
+ if (await tombstoneAttempt(slot.from) !== record10.attempt)
40269
40551
  problems.push(`${slot.from} is no longer the marker the move left there; move it aside`);
40270
40552
  continue;
40271
40553
  }
40272
40554
  if (await exists3(slot.from))
40273
40555
  problems.push(`${slot.from} came back after the move; move it aside or delete it`);
40274
40556
  }
40275
- const moving = movingJournalPath(dataset.oldPaths.journal, record9.attempt);
40557
+ const moving = movingJournalPath(dataset.oldPaths.journal, record10.attempt);
40276
40558
  if (await exists3(moving))
40277
40559
  problems.push(`${moving} is still there; move it aside or delete it`);
40278
40560
  return problems;
40279
40561
  }
40280
- async function startRestore(record9, dataset, ctx, options) {
40281
- const problems = await newRestoreProblems(record9, dataset, options);
40562
+ async function startRestore(record10, dataset, ctx, options) {
40563
+ const problems = await newRestoreProblems(record10, dataset, options);
40282
40564
  if (problems.length)
40283
40565
  throw refused2(`anthropic-auth can't restore its state to ${dataset.oldDir} yet: ${problems.join("; ")}. Then run ${RESTORE_LEGACY_COMMAND} again.`, [dataset.oldDir, dataset.sub]);
40284
- const attempt = randomUUID21();
40566
+ const attempt = randomUUID22();
40285
40567
  const files = [];
40286
40568
  for (const slot of dataset.slots) {
40287
40569
  let digest3;
@@ -40302,7 +40584,7 @@ async function startRestore(record9, dataset, ctx, options) {
40302
40584
  }
40303
40585
  const listed = (role) => files.some((file) => file.role === role);
40304
40586
  const restoring = {
40305
- ...record9,
40587
+ ...record10,
40306
40588
  phase: "restoring",
40307
40589
  restore: {
40308
40590
  attempt,
@@ -40320,7 +40602,7 @@ async function startRestore(record9, dataset, ctx, options) {
40320
40602
  const current = await readStateLayoutRecord(dataset.sub).catch(() => {
40321
40603
  return;
40322
40604
  });
40323
- return current?.phase === "committed" && current.attempt === record9.attempt ? undefined : "layout.json is no longer the committed move";
40605
+ return current?.phase === "committed" && current.attempt === record10.attempt ? undefined : "layout.json is no longer the committed move";
40324
40606
  }
40325
40607
  }, ctx.fs);
40326
40608
  await stateLayoutStep(ctx, "restore:restoring-written");
@@ -40345,11 +40627,11 @@ async function startRestore(record9, dataset, ctx, options) {
40345
40627
  await stateLayoutStep(ctx, "restore:staged-written");
40346
40628
  return finishStagedRestore(staged, dataset, ctx);
40347
40629
  }
40348
- function requireRecordMatches(record9, dataset) {
40630
+ function requireRecordMatches(record10, dataset) {
40349
40631
  const path2 = layoutRecordPath(dataset.sub);
40350
- if (record9.identity !== dataset.identity || record9.oldDir !== dataset.oldDir || record9.sub !== dataset.sub || record9.storageIds.local !== dataset.storageIds.local || record9.storageIds.vault !== dataset.storageIds.vault)
40351
- throw new StateLayoutRefusalError("other-dataset", `${path2} belongs to another config folder (${record9.oldDir}), not ${dataset.oldDir}. Check OPENCODE_CONFIG_DIR and any symlink to the config folder.`, [path2, record9.oldDir, dataset.oldDir]);
40352
- const problem = recordFilesProblem(record9, dataset);
40632
+ if (record10.identity !== dataset.identity || record10.oldDir !== dataset.oldDir || record10.sub !== dataset.sub || record10.storageIds.local !== dataset.storageIds.local || record10.storageIds.vault !== dataset.storageIds.vault)
40633
+ throw new StateLayoutRefusalError("other-dataset", `${path2} belongs to another config folder (${record10.oldDir}), not ${dataset.oldDir}. Check OPENCODE_CONFIG_DIR and any symlink to the config folder.`, [path2, record10.oldDir, dataset.oldDir]);
40634
+ const problem = recordFilesProblem(record10, dataset);
40353
40635
  if (problem)
40354
40636
  throw new StateLayoutRefusalError("marker-unreadable", `anthropic-auth can't use ${path2}: ${problem}.`, [path2]);
40355
40637
  }
@@ -40361,12 +40643,12 @@ async function readRecord(sub) {
40361
40643
  throw new StateLayoutRefusalError("marker-unreadable", `anthropic-auth can't read ${path2}, which records where its state is, so it won't restore anything. Restore the file from a backup or ask for help; do not delete the state folder.`, [path2], error);
40362
40644
  }
40363
40645
  }
40364
- function finished(record9) {
40365
- if (record9 === undefined)
40646
+ function finished(record10) {
40647
+ if (record10 === undefined)
40366
40648
  return "anthropic-auth has not moved this state out of the config folder";
40367
- if (record9.phase === "rolled-back")
40649
+ if (record10.phase === "rolled-back")
40368
40650
  return "the move of this state was undone before it finished";
40369
- if (record9.phase === "restored" && record9.restore?.cleanup === "done")
40651
+ if (record10.phase === "restored" && record10.restore?.cleanup === "done")
40370
40652
  return "this state was already restored to the config folder";
40371
40653
  return;
40372
40654
  }
@@ -40431,32 +40713,32 @@ async function restoreLegacyLayout(options = {}) {
40431
40713
  }
40432
40714
  await stateLayoutStep(ctx, "restore:locks-held");
40433
40715
  for (let round = 0;round < 3; round++) {
40434
- const record9 = await readRecord(sub);
40435
- const done2 = finished(record9);
40436
- if (done2 || !record9)
40716
+ const record10 = await readRecord(sub);
40717
+ const done2 = finished(record10);
40718
+ if (done2 || !record10)
40437
40719
  return { status: "not-moved", reason: done2 ?? "" };
40438
- requireRecordMatches(record9, dataset);
40720
+ requireRecordMatches(record10, dataset);
40439
40721
  let result;
40440
- switch (record9.phase) {
40722
+ switch (record10.phase) {
40441
40723
  case "preparing":
40442
40724
  throw refused2(`A move of anthropic-auth's state for ${dataset.oldDir} did not finish. Start OpenCode with anthropic-auth once to undo it; there is then nothing to restore.`, [layoutRecordPath(sub)]);
40443
40725
  case "restoring":
40444
- await discardAbandonedRestore(record9, dataset, ctx);
40726
+ await discardAbandonedRestore(record10, dataset, ctx);
40445
40727
  continue;
40446
40728
  case "committed":
40447
- result = await startRestore(record9, dataset, ctx, options);
40729
+ result = await startRestore(record10, dataset, ctx, options);
40448
40730
  break;
40449
40731
  case "restore-staged": {
40450
40732
  await syncObservedRestoreRecord(dataset, ctx);
40451
- const problems = await holderProblems(join29(dataset.sub, HOLDER_FILE_NAME), options.liveness, true);
40733
+ const problems = await holderProblems(join30(dataset.sub, HOLDER_FILE_NAME), options.liveness, true);
40452
40734
  if (problems.length)
40453
40735
  throw refused2(`anthropic-auth can't finish restoring its state to ${dataset.oldDir}: ${problems.join("; ")}. Close them, then run ${RESTORE_LEGACY_COMMAND} again.`, [dataset.sub]);
40454
- result = await finishStagedRestore(record9, dataset, ctx);
40736
+ result = await finishStagedRestore(record10, dataset, ctx);
40455
40737
  break;
40456
40738
  }
40457
40739
  default:
40458
40740
  await syncObservedRestoreRecord(dataset, ctx);
40459
- result = await finishRestoreRetirement(record9, dataset, ctx);
40741
+ result = await finishRestoreRetirement(record10, dataset, ctx);
40460
40742
  }
40461
40743
  return {
40462
40744
  status: "restored",
@@ -40514,13 +40796,13 @@ function configIdentity(configDir) {
40514
40796
  refuse5("io-failed", `anthropic-auth can't resolve its config folder ${configDir}: ${errorMessage(error)}`, [configDir], error);
40515
40797
  }
40516
40798
  }
40517
- function noMoveRecord(record9) {
40518
- return record9 === undefined || record9.phase === "rolled-back" || record9.phase === "restored" && record9.restore?.cleanup === "done";
40799
+ function noMoveRecord(record10) {
40800
+ return record10 === undefined || record10.phase === "rolled-back" || record10.phase === "restored" && record10.restore?.cleanup === "done";
40519
40801
  }
40520
- function requireRecordMatches2(record9, dataset) {
40521
- if (record9.identity !== dataset.identity || record9.oldDir !== dataset.oldDir || record9.sub !== dataset.sub || record9.storageIds.local !== dataset.storageIds.local || record9.storageIds.vault !== dataset.storageIds.vault)
40522
- refuse5("other-dataset", `${layoutRecordPath(dataset.sub)} belongs to another config folder (${record9.oldDir}), not ${dataset.oldDir}. Check OPENCODE_CONFIG_DIR and any symlink to the config folder.`, [layoutRecordPath(dataset.sub), record9.oldDir, dataset.oldDir]);
40523
- const problem = recordFilesProblem(record9, dataset);
40802
+ function requireRecordMatches2(record10, dataset) {
40803
+ if (record10.identity !== dataset.identity || record10.oldDir !== dataset.oldDir || record10.sub !== dataset.sub || record10.storageIds.local !== dataset.storageIds.local || record10.storageIds.vault !== dataset.storageIds.vault)
40804
+ refuse5("other-dataset", `${layoutRecordPath(dataset.sub)} belongs to another config folder (${record10.oldDir}), not ${dataset.oldDir}. Check OPENCODE_CONFIG_DIR and any symlink to the config folder.`, [layoutRecordPath(dataset.sub), record10.oldDir, dataset.oldDir]);
40805
+ const problem = recordFilesProblem(record10, dataset);
40524
40806
  if (problem)
40525
40807
  markerUnreadable(dataset.sub, new Error(problem));
40526
40808
  }
@@ -40563,7 +40845,7 @@ function deferLegacyRegistration(paths, dir, options, error) {
40563
40845
  }
40564
40846
  async function registerLegacyHeld(oldDir, paths, identity3, options, ctx) {
40565
40847
  try {
40566
- await registerHeld(join30(oldDir, HOLDER_FILE_NAME), paths, "legacy", identity3, options, ctx);
40848
+ await registerHeld(join31(oldDir, HOLDER_FILE_NAME), paths, "legacy", identity3, options, ctx);
40567
40849
  return;
40568
40850
  } catch (error) {
40569
40851
  if (unmovedRegistrationPolicy(options) === "mandatory")
@@ -40583,10 +40865,10 @@ function chooseLegacy(paths, reasons2, log2, registration) {
40583
40865
  };
40584
40866
  }
40585
40867
  async function admitHeld(dataset, options, ctx, moved, allowPendingCleanup) {
40586
- const record9 = await readRecord2(dataset.sub);
40587
- if (record9?.phase !== "committed" || !allowPendingCleanup && record9.cleanup === "pending")
40868
+ const record10 = await readRecord2(dataset.sub);
40869
+ if (record10?.phase !== "committed" || !allowPendingCleanup && record10.cleanup === "pending")
40588
40870
  return "changed";
40589
- requireRecordMatches2(record9, dataset);
40871
+ requireRecordMatches2(record10, dataset);
40590
40872
  const conflict = await checkStateHomeServing(stateHomeServingFiles(dataset.newPaths));
40591
40873
  if (conflict) {
40592
40874
  logger2.error("state-layout", conflict.message, {
@@ -40595,15 +40877,15 @@ async function admitHeld(dataset, options, ctx, moved, allowPendingCleanup) {
40595
40877
  });
40596
40878
  throw conflict;
40597
40879
  }
40598
- await warnReappearedMetadata(record9);
40599
- await registerHeld(join30(dataset.sub, HOLDER_FILE_NAME), dataset.newPaths, "state-home", dataset.identity, options, ctx);
40880
+ await warnReappearedMetadata(record10);
40881
+ await registerHeld(join31(dataset.sub, HOLDER_FILE_NAME), dataset.newPaths, "state-home", dataset.identity, options, ctx);
40600
40882
  const layout = { kind: "state-home", dir: dataset.sub };
40601
40883
  recordProcessStateLayout(dataset.oldPaths.legacyConfig, layout);
40602
- return { kind: "state-home", layout, dataset, record: record9, moved };
40884
+ return { kind: "state-home", layout, dataset, record: record10, moved };
40603
40885
  }
40604
40886
  async function admitFast(dataset, options, ctx) {
40605
40887
  try {
40606
- await acquireHolderLock(ctx, join30(dataset.sub, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40888
+ await acquireHolderLock(ctx, join31(dataset.sub, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40607
40889
  } catch (error) {
40608
40890
  if (error instanceof LockContentionError)
40609
40891
  busy(dataset.configDir, error);
@@ -40645,12 +40927,12 @@ async function readPointers(dataset) {
40645
40927
  }
40646
40928
  async function legacyHeld(dataset, options, ctx, reasons2, log2 = true) {
40647
40929
  const pointed = await readPointers(dataset);
40648
- const record9 = await readRecord2(dataset.sub);
40649
- if (record9)
40650
- requireRecordMatches2(record9, dataset);
40651
- if (pointed && noMoveRecord(record9))
40930
+ const record10 = await readRecord2(dataset.sub);
40931
+ if (record10)
40932
+ requireRecordMatches2(record10, dataset);
40933
+ if (pointed && noMoveRecord(record10))
40652
40934
  markerUnreadable(dataset.sub);
40653
- if (pointed || !noMoveRecord(record9))
40935
+ if (pointed || !noMoveRecord(record10))
40654
40936
  return "changed";
40655
40937
  const registration = await registerLegacyHeld(dataset.oldDir, dataset.oldPaths, dataset.identity, options, ctx);
40656
40938
  return chooseLegacy(dataset.oldPaths, reasons2, log2, registration);
@@ -40668,7 +40950,7 @@ async function oldFolderTransition(old, recordedMovingJournal) {
40668
40950
  }
40669
40951
  let names2;
40670
40952
  try {
40671
- names2 = await readdir8(dirname25(journal));
40953
+ names2 = await readdir9(dirname25(journal));
40672
40954
  } catch (error) {
40673
40955
  if (error?.code === "ENOENT")
40674
40956
  return false;
@@ -40689,10 +40971,10 @@ async function recordedMovingJournal(journal, identity3, options) {
40689
40971
  env: options.env ?? process.env,
40690
40972
  home: options.home ?? homedir8()
40691
40973
  });
40692
- const record9 = await readStateLayoutRecord(await canonicalPath(target2.dir));
40693
- if (record9?.barriers.journal !== "present")
40974
+ const record10 = await readStateLayoutRecord(await canonicalPath(target2.dir));
40975
+ if (record10?.barriers.journal !== "present")
40694
40976
  return;
40695
- return movingJournalPath(journal, record9.attempt);
40977
+ return movingJournalPath(journal, record10.attempt);
40696
40978
  } catch {
40697
40979
  return;
40698
40980
  }
@@ -40711,7 +40993,7 @@ async function legacyWhileMoveOff(configDir, identity3, options, ctx, stayReason
40711
40993
  await stateLayoutStep(ctx, "old-holders-locking");
40712
40994
  let lockFailure;
40713
40995
  try {
40714
- await acquireHolderLock(ctx, join30(old.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40996
+ await acquireHolderLock(ctx, join31(old.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40715
40997
  } catch (error) {
40716
40998
  lockFailure = { error };
40717
40999
  }
@@ -40741,8 +41023,8 @@ async function decideOpenCodeStateLayout(options) {
40741
41023
  holderLockTimeoutMs: options.timeouts?.holderMs
40742
41024
  });
40743
41025
  if (isExplicit(env)) {
40744
- const legacyConfig = env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join30(configDir, ACCOUNT_FILE2);
40745
- const legacyState = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (legacyConfig.endsWith(ACCOUNT_FILE2) ? join30(dirname25(legacyConfig), ACCOUNT_STATE_FILE2) : `${legacyConfig}.state.json`);
41026
+ const legacyConfig = env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join31(configDir, ACCOUNT_FILE2);
41027
+ const legacyState = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (legacyConfig.endsWith(ACCOUNT_FILE2) ? join31(dirname25(legacyConfig), ACCOUNT_STATE_FILE2) : `${legacyConfig}.state.json`);
40746
41028
  const paths = await resolveNativePoolPaths(legacyConfig, legacyState, LEGACY_STATE_LAYOUT);
40747
41029
  const registration = await registerNativePoolHolder({
40748
41030
  paths,
@@ -40765,7 +41047,7 @@ async function decideOpenCodeStateLayout(options) {
40765
41047
  } catch (error) {
40766
41048
  if (unmovedRegistrationPolicy(options) === "mandatory")
40767
41049
  throw new HolderRegistrationError("unavailable", configDir, error);
40768
- const paths = await resolveNativePoolPaths(join30(configDir, ACCOUNT_FILE2), join30(configDir, ACCOUNT_STATE_FILE2), LEGACY_STATE_LAYOUT);
41050
+ const paths = await resolveNativePoolPaths(join31(configDir, ACCOUNT_FILE2), join31(configDir, ACCOUNT_STATE_FILE2), LEGACY_STATE_LAYOUT);
40769
41051
  return chooseLegacy(paths, [reason], true, deferLegacyRegistration(paths, configDir, options, error));
40770
41052
  }
40771
41053
  identity3 = configIdentity(configDir);
@@ -40816,26 +41098,26 @@ async function decideOpenCodeStateLayout(options) {
40816
41098
  refuse5("other-dataset", `${sub} holds anthropic-auth state for ${marker.identity}, not for ${target2.identity}. Check OPENCODE_CONFIG_DIR and any symlink to the config folder.`, [sub, marker.identity, target2.identity]);
40817
41099
  const pointed = await readPointers(dataset);
40818
41100
  for (let round = 0;round < 3; round++) {
40819
- const record9 = await readRecord2(sub);
40820
- if (record9)
40821
- requireRecordMatches2(record9, dataset);
40822
- if (pointed && noMoveRecord(record9))
41101
+ const record10 = await readRecord2(sub);
41102
+ if (record10)
41103
+ requireRecordMatches2(record10, dataset);
41104
+ if (pointed && noMoveRecord(record10))
40823
41105
  markerUnreadable(sub);
40824
- if (record9?.phase === "restore-staged")
41106
+ if (record10?.phase === "restore-staged")
40825
41107
  restoreUnfinished(dataset.oldDir);
40826
- if (record9?.phase === "committed" && (record9.cleanup === "done" || record9.cleanup === "kept")) {
41108
+ if (record10?.phase === "committed" && (record10.cleanup === "done" || record10.cleanup === "kept")) {
40827
41109
  const admitted = await admitFast(dataset, options, newContext());
40828
41110
  if (admitted !== "changed")
40829
41111
  return admitted;
40830
41112
  continue;
40831
41113
  }
40832
- if ((overrides.length || neverMove.length || !moveEnabled) && noMoveRecord(record9)) {
41114
+ if ((overrides.length || neverMove.length || !moveEnabled) && noMoveRecord(record10)) {
40833
41115
  const ctx = newContext();
40834
41116
  const reasons2 = stayReasons.length ? stayReasons : [RELOCATION_MOVE_DISABLED_REASON];
40835
41117
  try {
40836
41118
  await stateLayoutStep(ctx, "old-holders-locking");
40837
41119
  try {
40838
- await acquireHolderLock(ctx, join30(dataset.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
41120
+ await acquireHolderLock(ctx, join31(dataset.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40839
41121
  } catch (error) {
40840
41122
  if (unmovedRegistrationPolicy(options) === "mandatory")
40841
41123
  throw error;
@@ -40870,8 +41152,8 @@ async function decideOpenCodeStateLayout(options) {
40870
41152
  } catch (error) {
40871
41153
  if (!(error instanceof LockContentionError))
40872
41154
  refuse5("io-failed", `anthropic-auth can't take the layout lock beside ${layoutRecordPath(sub)}: ${errorMessage(error)}`, [layoutRecordPath(sub)], error);
40873
- const record9 = await readRecord2(sub);
40874
- if (record9?.phase === "committed" && (record9.cleanup === "done" || record9.cleanup === "kept")) {
41155
+ const record10 = await readRecord2(sub);
41156
+ if (record10?.phase === "committed" && (record10.cleanup === "done" || record10.cleanup === "kept")) {
40875
41157
  const admitted = await admitFast(dataset, options, newContext());
40876
41158
  if (admitted !== "changed")
40877
41159
  return admitted;
@@ -40899,7 +41181,7 @@ async function ensureSubfolder(sub, fs3) {
40899
41181
  await ensureWindowsOwnerOnlyDirectory(sub);
40900
41182
  return;
40901
41183
  }
40902
- const created = await mkdir18(sub, { recursive: true, mode: 448 });
41184
+ const created = await mkdir19(sub, { recursive: true, mode: 448 });
40903
41185
  if (created === undefined)
40904
41186
  return;
40905
41187
  for (let dir = dirname25(sub);; dir = dirname25(dir)) {
@@ -40914,36 +41196,36 @@ async function ensureSubfolder(sub, fs3) {
40914
41196
  }
40915
41197
  }
40916
41198
  async function underLayoutLock(dataset, options, ctx, overrides, neverMove) {
40917
- const record9 = await readRecord2(dataset.sub);
40918
- if (record9)
40919
- requireRecordMatches2(record9, dataset);
40920
- if (record9?.phase === "restore-staged")
41199
+ const record10 = await readRecord2(dataset.sub);
41200
+ if (record10)
41201
+ requireRecordMatches2(record10, dataset);
41202
+ if (record10?.phase === "restore-staged")
40921
41203
  restoreUnfinished(dataset.oldDir);
40922
- if (record9?.phase === "restoring" || record9?.phase === "restored" && record9.restore?.cleanup !== "done") {
41204
+ if (record10?.phase === "restoring" || record10?.phase === "restored" && record10.restore?.cleanup !== "done") {
40923
41205
  if (overrides.length)
40924
41206
  refuse5("restore-unfinished", `A restore of anthropic-auth's state for ${dataset.oldDir} did not finish; start anthropic-auth without path overrides (${overrides.join(", ")}), or run ${RESTORE_LEGACY_COMMAND} again.`, [layoutRecordPath(dataset.sub)]);
40925
41207
  await acquireHolderLocks(dataset, ctx);
40926
- if (record9.phase === "restoring")
40927
- await discardAbandonedRestore(record9, dataset, ctx);
41208
+ if (record10.phase === "restoring")
41209
+ await discardAbandonedRestore(record10, dataset, ctx);
40928
41210
  else {
40929
41211
  await syncObservedRestoreRecord(dataset, ctx);
40930
- await finishRestoreRetirement(record9, dataset, ctx);
41212
+ await finishRestoreRetirement(record10, dataset, ctx);
40931
41213
  }
40932
41214
  return "again";
40933
41215
  }
40934
- if (record9?.phase === "committed") {
41216
+ if (record10?.phase === "committed") {
40935
41217
  try {
40936
41218
  await syncCommitted(dataset, ctx);
40937
41219
  } catch (error) {
40938
41220
  refuse5("unsafe", `anthropic-auth could not make the move of its state to ${dataset.sub} durable, so it won't use either copy.`, [layoutRecordPath(dataset.sub)], error);
40939
41221
  }
40940
41222
  await acquireHolderLocks(dataset, ctx);
40941
- if ((record9.cleanup === "pending" || record9.cleanup === "conflict") && !overrides.length) {
41223
+ if ((record10.cleanup === "pending" || record10.cleanup === "conflict") && !overrides.length) {
40942
41224
  const mark = ctx.stack.size;
40943
41225
  try {
40944
41226
  await drainCoalescedWrites(dataset);
40945
41227
  await acquireDataLocks(dataset, ctx);
40946
- await cleanupOldCopies(record9, dataset, ctx);
41228
+ await cleanupOldCopies(record10, dataset, ctx);
40947
41229
  } catch (error) {
40948
41230
  if (error instanceof StateLayoutCrash)
40949
41231
  throw error;
@@ -40957,13 +41239,13 @@ async function underLayoutLock(dataset, options, ctx, overrides, neverMove) {
40957
41239
  const admitted2 = await admitHeld(dataset, options, ctx, false, true);
40958
41240
  return admitted2 === "changed" ? "again" : admitted2;
40959
41241
  }
40960
- if (record9?.phase === "preparing") {
41242
+ if (record10?.phase === "preparing") {
40961
41243
  if (overrides.length)
40962
41244
  refuse5("unsafe", `A move of anthropic-auth's state for ${dataset.oldDir} did not finish; start anthropic-auth without path overrides (${overrides.join(", ")}) to finish it.`, [layoutRecordPath(dataset.sub)]);
40963
41245
  await acquireHolderLocks(dataset, ctx);
40964
41246
  await drainCoalescedWrites(dataset);
40965
41247
  await acquireDataLocks(dataset, ctx);
40966
- await rollbackPreparing(record9, dataset, ctx);
41248
+ await rollbackPreparing(record10, dataset, ctx);
40967
41249
  return "again";
40968
41250
  }
40969
41251
  const stay = async (reasons2, log2 = true) => {
@@ -41326,6 +41608,7 @@ export {
41326
41608
  writerStamp,
41327
41609
  writeNativeHostAuth,
41328
41610
  writeDumpFile,
41611
+ withNativeLock,
41329
41612
  withAbortableFetch,
41330
41613
  usesPerTurnControl,
41331
41614
  usagePublicationRefusalIsFatal,
@@ -41512,6 +41795,7 @@ export {
41512
41795
  logger2 as logger,
41513
41796
  log,
41514
41797
  localDayKey,
41798
+ legacyCacheKeepStoreDirectory,
41515
41799
  killswitchRetryAfterSeconds,
41516
41800
  killswitchPassesPolicy,
41517
41801
  isWithinCacheKeepWindow,
@@ -41708,6 +41992,7 @@ export {
41708
41992
  captureNativeLocalPoolBinding,
41709
41993
  canonicalPath,
41710
41994
  cacheWarmCacheablePrefixFingerprint,
41995
+ cacheKeepStoreDirectory,
41711
41996
  cacheKeepSourceWarmIdleCap,
41712
41997
  buildRoutingStatusSummary,
41713
41998
  buildRefreshOperationError,
@@ -41846,6 +42131,7 @@ export {
41846
42131
  ClaudeUnsupportedAccessError,
41847
42132
  ClaudeOAuthRefreshError,
41848
42133
  ClaudeCodeFirstUserTextTracker,
42134
+ CacheKeepStore,
41849
42135
  CacheKeepSessionRegistry,
41850
42136
  CacheKeepPrewarmError,
41851
42137
  CacheKeepManager,