@cortexkit/anthropic-auth-core 2.5.4 → 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
@@ -8509,13 +8509,20 @@ async function mutateVaultRoster(path, change, options = {}) {
8509
8509
  });
8510
8510
  if (next) {
8511
8511
  await lock.assertOwned();
8512
- await writeJsonAtomic(path, next, {
8513
- beforeRename: async () => {
8514
- await options.beforePublish?.();
8515
- options.signal?.throwIfAborted();
8516
- await lock.assertOwned();
8517
- }
8518
- });
8512
+ try {
8513
+ await writeJsonAtomic(path, next, {
8514
+ beforeRename: async () => {
8515
+ await options.beforePublish?.();
8516
+ options.signal?.throwIfAborted();
8517
+ await lock.assertOwned();
8518
+ }
8519
+ });
8520
+ } catch (error) {
8521
+ if (error && typeof error === "object" && "published" in error && error.published === true)
8522
+ options.onPublished?.();
8523
+ throw error;
8524
+ }
8525
+ options.onPublished?.();
8519
8526
  }
8520
8527
  return result;
8521
8528
  });
@@ -17243,7 +17250,7 @@ async function recordQuota(rt, id, attribution, observation) {
17243
17250
  }
17244
17251
 
17245
17252
  // ../../node_modules/@cortexkit/common-auth/dist/store/limits-namespace.js
17246
- async function updatePoolLimitsNamespace(rt, mutator) {
17253
+ async function updatePoolLimitsNamespace(rt, mutator, options = {}) {
17247
17254
  assertLimitsWriteAllowed();
17248
17255
  const { ctx } = rt;
17249
17256
  await runOperation(ctx, "updateLimitsNamespace", undefined, undefined, async (locks, progress) => {
@@ -17263,13 +17270,21 @@ async function updatePoolLimitsNamespace(rt, mutator) {
17263
17270
  operation: "updateLimitsNamespace",
17264
17271
  rowId: undefined
17265
17272
  };
17266
- await writeJsonAtomic(ctx.configPath, config, {
17267
- beforeRename: async () => {
17268
- await ctx.onStep?.("before-config-write", info);
17269
- await locks.assertAll();
17270
- }
17271
- });
17273
+ try {
17274
+ await writeJsonAtomic(ctx.configPath, config, {
17275
+ beforeRename: async () => {
17276
+ await ctx.onStep?.("before-config-write", info);
17277
+ await locks.assertAll();
17278
+ options.beforePublish?.();
17279
+ }
17280
+ });
17281
+ } catch (error) {
17282
+ if (error && typeof error === "object" && "published" in error && error.published === true)
17283
+ options.onPublished?.();
17284
+ throw error;
17285
+ }
17272
17286
  progress.writes++;
17287
+ options.onPublished?.();
17273
17288
  await ctx.onStep?.("after-config-write", info);
17274
17289
  });
17275
17290
  }
@@ -19257,7 +19272,7 @@ function openPoolStore(options) {
19257
19272
  reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
19258
19273
  readSettings: () => readPoolSettings(rt),
19259
19274
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
19260
- updateLimitsNamespace: (mutator) => updatePoolLimitsNamespace(rt, mutator),
19275
+ updateLimitsNamespace: (mutator, options2) => updatePoolLimitsNamespace(rt, mutator, options2),
19261
19276
  recordIdentity: (id, identity2, attribution, callOptions) => recordRowIdentity(rt, id, identity2, attribution, callOptions),
19262
19277
  refresh: (id, provider, callOptions) => refreshRow(rt, id, provider, callOptions),
19263
19278
  recordQuota: record2,
@@ -24033,6 +24048,288 @@ class CacheKeepSessionRegistry {
24033
24048
  } catch {}
24034
24049
  }
24035
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
+ }
24036
24333
  // src/oauth-profile.ts
24037
24334
  var PROFILE_URL = "https://api.anthropic.com/api/oauth/profile";
24038
24335
  var PROFILE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
@@ -24787,13 +25084,13 @@ function executeLoggingCommand(input) {
24787
25084
  `);
24788
25085
  }
24789
25086
  // src/message-threads.ts
24790
- import { createHash as createHash20 } from "node:crypto";
25087
+ import { createHash as createHash21 } from "node:crypto";
24791
25088
  var MESSAGE_THREADS_BETA = "message-threads-2026-08-12";
24792
25089
  var MAX_AGE_MS = 5 * 60000;
24793
25090
  var MAX_SESSIONS = 2048;
24794
25091
  var MAX_MESSAGE_HASHES = 131072;
24795
- function hash3(value) {
24796
- return createHash20("sha256").update(JSON.stringify(value)).digest("hex");
25092
+ function hash4(value) {
25093
+ return createHash21("sha256").update(JSON.stringify(value)).digest("hex");
24797
25094
  }
24798
25095
  function normalizedReplyName(name) {
24799
25096
  const bare = name.startsWith("mcp_") ? name.slice(4) : name;
@@ -24839,7 +25136,7 @@ class ReplyFingerprint {
24839
25136
  layout = new Map;
24840
25137
  textBlocks = new Map;
24841
25138
  signatures = new Map;
24842
- text = createHash20("sha256");
25139
+ text = createHash21("sha256");
24843
25140
  committedText = this.text.copy();
24844
25141
  hasText = false;
24845
25142
  activeText;
@@ -24861,7 +25158,7 @@ class ReplyFingerprint {
24861
25158
  this.text.update(part.slice(visible.length));
24862
25159
  }
24863
25160
  appendBlockText(state, value) {
24864
- state.text ??= createHash20("sha256");
25161
+ state.text ??= createHash21("sha256");
24865
25162
  state.committedText ??= state.text.copy();
24866
25163
  const part = state.textHasContent ? value : value.trimStart();
24867
25164
  const visible = part.trimEnd();
@@ -24908,7 +25205,7 @@ class ReplyFingerprint {
24908
25205
  state.input = block.input;
24909
25206
  }
24910
25207
  if (block.type === "thinking" || block.type === "redacted_thinking") {
24911
- state.signature = createHash20("sha256");
25208
+ state.signature = createHash21("sha256");
24912
25209
  const signature = block.type === "redacted_thinking" ? block.data : block.signature;
24913
25210
  if (typeof signature === "string") {
24914
25211
  state.signature.update(signature);
@@ -24986,7 +25283,7 @@ class ReplyFingerprint {
24986
25283
  this.tools.set(index, [
24987
25284
  state.id,
24988
25285
  state.name,
24989
- hash3(canonicalValue(input))
25286
+ hash4(canonicalValue(input))
24990
25287
  ]);
24991
25288
  } catch {
24992
25289
  this.invalid = true;
@@ -24998,7 +25295,7 @@ class ReplyFingerprint {
24998
25295
  return;
24999
25296
  const ordered = [...this.layout].sort(([a], [b]) => a - b);
25000
25297
  const kept = withoutTrailingToolWhitespace(ordered.map(([, block]) => block));
25001
- return hash3({
25298
+ return hash4({
25002
25299
  blocks: kept.map((block) => block.type),
25003
25300
  texts: ordered.slice(0, kept.length).filter(([, block]) => block.type === "text").map(([index]) => this.textBlocks.get(index)),
25004
25301
  tools: [...this.tools].sort(([a], [b]) => a - b).map(([, tool]) => tool),
@@ -25105,7 +25402,7 @@ function fixedThreadFingerprint(input) {
25105
25402
  "tool_choice",
25106
25403
  "context_management"
25107
25404
  ].map((key) => [key, body[key]]));
25108
- return hash3(canonicalValue({
25405
+ return hash4(canonicalValue({
25109
25406
  ...fixed,
25110
25407
  tools: JSON.stringify(body.tools),
25111
25408
  system: JSON.stringify(system),
@@ -25114,9 +25411,9 @@ function fixedThreadFingerprint(input) {
25114
25411
  betas: input.betas
25115
25412
  }));
25116
25413
  }
25117
- function messageThreadSnapshot(input, identity3 = hash3([input.account, input.credential]), fingerprint = fixedThreadFingerprint(input)) {
25118
- const messages = (Array.isArray(input.body.messages) ? input.body.messages : []).map((message) => hash3(canonicalValue(withoutMessageCache(message))));
25119
- 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) };
25120
25417
  }
25121
25418
  function canContinueFrom(anchor, input, identity3, now) {
25122
25419
  if (!anchor || !identity3 || anchor.identity !== identity3 || now < anchor.completedAt || now - anchor.completedAt >= MAX_AGE_MS)
@@ -25125,7 +25422,7 @@ function canContinueFrom(anchor, input, identity3, now) {
25125
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;
25126
25423
  }
25127
25424
  function decideMessageThread(anchor, input, snapshot, now) {
25128
- 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)
25129
25426
  return { type: "create" };
25130
25427
  const messages = Array.isArray(input.body.messages) ? input.body.messages : [];
25131
25428
  return {
@@ -25169,7 +25466,7 @@ class MessageThreadTracker {
25169
25466
  const previous = this.sessions.get(input.session);
25170
25467
  const anchor = previous?.anchor;
25171
25468
  const now = this.now();
25172
- 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;
25173
25470
  let snapshot;
25174
25471
  if (canContinueFrom(anchor, input, identity3, now)) {
25175
25472
  const fingerprint = fixedThreadFingerprint(input);
@@ -25428,7 +25725,7 @@ function disableThreadsForAccount(key) {
25428
25725
  if (disabledThreadAccounts.has(key))
25429
25726
  return;
25430
25727
  disabledThreadAccounts.add(key);
25431
- 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) });
25432
25729
  }
25433
25730
  function ignoreThreadFailure() {}
25434
25731
  function threadFailureState(initial) {
@@ -25718,7 +26015,7 @@ function remapRequestBodyModel(parsed) {
25718
26015
  return true;
25719
26016
  }
25720
26017
  // src/native-account-runtime.ts
25721
- import { randomUUID as randomUUID17 } from "node:crypto";
26018
+ import { randomUUID as randomUUID18 } from "node:crypto";
25722
26019
 
25723
26020
  // src/native-account-view.ts
25724
26021
  import { types as types2 } from "node:util";
@@ -26483,7 +26780,7 @@ function createNativeLocalRuntimeReaders(options) {
26483
26780
  }
26484
26781
 
26485
26782
  // src/native-refresh-coordinator.ts
26486
- import { createHash as createHash21 } from "node:crypto";
26783
+ import { createHash as createHash22 } from "node:crypto";
26487
26784
 
26488
26785
  // src/native-transient-account.ts
26489
26786
  var TRANSIENT_ACCOUNT_MESSAGE = "Anthropic account update in progress; retry the request";
@@ -26585,7 +26882,7 @@ function pause(ms, signals) {
26585
26882
  var NATIVE_REFRESH_MAX_ATTEMPTS = 3;
26586
26883
  var NATIVE_REFRESH_JOIN_BUDGET_MS = 2000;
26587
26884
  function nativeAccountProviderLock(paths, identity3) {
26588
- 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");
26589
26886
  return {
26590
26887
  path: paths.state,
26591
26888
  name: `native-account-provider-${key}`,
@@ -27385,9 +27682,9 @@ function createNativeRefreshCoordinator(options) {
27385
27682
  import { isAbsolute as isAbsolute5, normalize, parse as parse3, sep } from "node:path";
27386
27683
 
27387
27684
  // src/migration-source.ts
27388
- import { createHash as createHash22 } from "node:crypto";
27389
- import { constants as constants3 } from "node:fs";
27390
- 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";
27391
27688
  class NativeMigrationSourceError extends Error {
27392
27689
  role;
27393
27690
  code;
@@ -27430,7 +27727,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27430
27727
  });
27431
27728
  let initial;
27432
27729
  try {
27433
- initial = await lstat14(path2, { bigint: true });
27730
+ initial = await lstat15(path2, { bigint: true });
27434
27731
  } catch (error) {
27435
27732
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
27436
27733
  return missing2;
@@ -27440,7 +27737,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27440
27737
  throw new NativeMigrationSourceError(role, "unsafe-source");
27441
27738
  let handle;
27442
27739
  try {
27443
- 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));
27444
27741
  const before = await handle.stat({ bigint: true });
27445
27742
  if (!before.isFile() || before.dev !== initial.dev || before.ino !== initial.ino) {
27446
27743
  throw new NativeMigrationSourceError(role, "source-changed");
@@ -27468,7 +27765,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27468
27765
  chunks.push(chunk.subarray(0, read.bytesRead));
27469
27766
  }
27470
27767
  const after = await handle.stat({ bigint: true });
27471
- const current = await lstat14(path2, { bigint: true });
27768
+ const current = await lstat15(path2, { bigint: true });
27472
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) {
27473
27770
  throw new NativeMigrationSourceError(role, "source-changed");
27474
27771
  }
@@ -27484,7 +27781,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27484
27781
  return sourceSnapshot({
27485
27782
  role,
27486
27783
  path: path2,
27487
- digest: createHash22("sha256").update(content).digest("hex"),
27784
+ digest: createHash23("sha256").update(content).digest("hex"),
27488
27785
  data: freezeJson(data),
27489
27786
  metadata: Object.freeze({
27490
27787
  uid: Number(before.uid),
@@ -28509,11 +28806,11 @@ class NativeRuntimeRegistry {
28509
28806
  }
28510
28807
 
28511
28808
  // src/native-vault-runtime.ts
28512
- import { randomUUID as randomUUID16 } from "node:crypto";
28809
+ import { randomUUID as randomUUID17 } from "node:crypto";
28513
28810
  import { SubcClient as SubcClient2 } from "@cortexkit/subc-client";
28514
28811
 
28515
28812
  // src/insula-quota.ts
28516
- function record8(value) {
28813
+ function record9(value) {
28517
28814
  return typeof value === "object" && value !== null && !Array.isArray(value);
28518
28815
  }
28519
28816
  function text5(value) {
@@ -28523,7 +28820,7 @@ function clampPercent3(value) {
28523
28820
  return Math.min(100, Math.max(0, value));
28524
28821
  }
28525
28822
  function windowReading(window2, checkedAt, expected) {
28526
- if (!record8(window2))
28823
+ if (!record9(window2))
28527
28824
  return;
28528
28825
  const usedPercent = window2.usedPercent;
28529
28826
  if (typeof usedPercent !== "number" || !Number.isFinite(usedPercent))
@@ -28547,7 +28844,7 @@ function scopedReadings(windows, checkedAt) {
28547
28844
  const seen = new Set;
28548
28845
  const scoped = [];
28549
28846
  for (const candidate of windows) {
28550
- if (!record8(candidate))
28847
+ if (!record9(candidate))
28551
28848
  continue;
28552
28849
  const identity3 = text5(candidate.id);
28553
28850
  if (!identity3)
@@ -28573,7 +28870,7 @@ function scopedReadings(windows, checkedAt) {
28573
28870
  return scoped;
28574
28871
  }
28575
28872
  function money2(value) {
28576
- 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)
28577
28874
  return null;
28578
28875
  const exponent = value.exponent ?? 2;
28579
28876
  if (typeof exponent !== "number" || !Number.isInteger(exponent) || exponent < 0 || exponent > 20)
@@ -28583,8 +28880,8 @@ function money2(value) {
28583
28880
  function extraUsageReading(pools) {
28584
28881
  if (!Array.isArray(pools))
28585
28882
  return;
28586
- const pool = pools.find((candidate) => record8(candidate) && candidate.title === "Extra usage");
28587
- if (!record8(pool))
28883
+ const pool = pools.find((candidate) => record9(candidate) && candidate.title === "Extra usage");
28884
+ if (!record9(pool))
28588
28885
  return;
28589
28886
  const limit = money2(pool.total ?? pool.limit);
28590
28887
  const remaining = money2(pool.remaining);
@@ -28599,7 +28896,7 @@ function extraUsageReading(pools) {
28599
28896
  used = Math.max(0, limit.minor - remaining.minor);
28600
28897
  if (used === undefined)
28601
28898
  return;
28602
- 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);
28603
28900
  const currency = unit && /^[A-Za-z]{3}$/.test(unit) ? unit : "USD";
28604
28901
  return {
28605
28902
  used: { amountMinor: used, currency, exponent },
@@ -28755,12 +29052,12 @@ function expectedSeed(input, boundary, refuse3) {
28755
29052
  const inventory = capture(top("inventory", "roster-incomplete"), ["view", "credentials", "skipped"], "roster-incomplete", refuse3);
28756
29053
  const view = inventory.view;
28757
29054
  const skipped = items(inventory.skipped, "roster-incomplete", refuse3);
28758
- 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));
28759
29056
  if (!filled(view) || skipped.length > 0)
28760
29057
  refuse3("roster-incomplete");
28761
29058
  const listed = new Map;
28762
- for (const record9 of credentialRecords) {
28763
- const { credentialId, credentialType, accountIdentity, state } = record9;
29059
+ for (const record10 of credentialRecords) {
29060
+ const { credentialId, credentialType, accountIdentity, state } = record10;
28764
29061
  if (!filled(credentialId) || !filled(accountIdentity) || !filled(state) || listed.has(credentialId)) {
28765
29062
  refuse3("roster-incomplete");
28766
29063
  }
@@ -28771,7 +29068,7 @@ function expectedSeed(input, boundary, refuse3) {
28771
29068
  const primaryIdentity = primary.accountIdentity;
28772
29069
  boundary.fallback = "seed-conflict";
28773
29070
  const primaryRouteId = top("primaryRouteId", "seed-conflict");
28774
- 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, [
28775
29072
  "routeId",
28776
29073
  "scopedCredentialId",
28777
29074
  "anthropicAccountUuid",
@@ -30238,7 +30535,7 @@ function createNativeVaultRuntime(options) {
30238
30535
  async getOrCreateAuthLineage(receipt) {
30239
30536
  let lineage;
30240
30537
  const kept = await mutateReceipt(receipt, (old) => {
30241
- lineage = old.authLineageId ?? randomUUID16();
30538
+ lineage = old.authLineageId ?? randomUUID17();
30242
30539
  return { ...old, authLineageId: lineage };
30243
30540
  });
30244
30541
  return kept ? lineage : undefined;
@@ -30634,7 +30931,7 @@ function leaseNativeVaultRuntime(use, close) {
30634
30931
 
30635
30932
  // src/relay.ts
30636
30933
  import { Buffer as Buffer3 } from "node:buffer";
30637
- import { createHash as createHash23, randomBytes as randomBytes5 } from "node:crypto";
30934
+ import { createHash as createHash24, randomBytes as randomBytes5 } from "node:crypto";
30638
30935
  var WEBSOCKET_RELAY_URL = /^wss?:\/\//i;
30639
30936
  function effectiveRelayTransport(stored, url) {
30640
30937
  if (stored === "http" || stored === "websocket")
@@ -30785,7 +31082,7 @@ function generateRelayToken() {
30785
31082
  return randomBytes5(32).toString("base64url");
30786
31083
  }
30787
31084
  function hashBody(body) {
30788
- return `sha256:${createHash23("sha256").update(body).digest("hex")}`;
31085
+ return `sha256:${createHash24("sha256").update(body).digest("hex")}`;
30789
31086
  }
30790
31087
  function createStringPatch(previous, next) {
30791
31088
  let start = 0;
@@ -32585,7 +32882,7 @@ function createNativeAccountRuntime(options) {
32585
32882
  const sameAccount = old?.kind === "local" && old.rowId === binding2.rowId && binding2.identity !== undefined && old.identity === binding2.identity;
32586
32883
  const next = {
32587
32884
  binding: binding2,
32588
- ...row.credential?.type === "oauth" ? { authLineageId: randomUUID17() } : {}
32885
+ ...row.credential?.type === "oauth" ? { authLineageId: randomUUID18() } : {}
32589
32886
  };
32590
32887
  if (sameAccount && previous) {
32591
32888
  for (const key of [
@@ -32748,7 +33045,7 @@ function createNativeAccountRuntime(options) {
32748
33045
  throw new NativeRuntimeError("publication-refused");
32749
33046
  const previous = relayFlags(read.settings.relay);
32750
33047
  const previousGeneration = relayGeneration(read.settings.relay);
32751
- const generation = randomUUID17();
33048
+ const generation = randomUUID18();
32752
33049
  const metadata2 = await readNativeRuntime(paths2.runtime, paths2.storageId);
32753
33050
  const token2 = patch.token === undefined ? metadata2.status === "ready" ? metadata2.state.relay?.token : undefined : patch.token?.trim();
32754
33051
  const next = relayFlags({
@@ -32974,7 +33271,7 @@ function createNativeAccountRuntime(options) {
32974
33271
  const snapshot = await runtime2.read();
32975
33272
  if (snapshot.mode !== "local")
32976
33273
  throw new NativeCustodyError("route-unavailable");
32977
- 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;
32978
33275
  if (input.credential.type === "api" && (input.routeId === "main" || id2 === snapshot.settings.mainAccountId))
32979
33276
  throw new NativeCustodyError("route-unavailable");
32980
33277
  const old = await poolRow(id2);
@@ -33013,7 +33310,7 @@ function createNativeAccountRuntime(options) {
33013
33310
  return row;
33014
33311
  },
33015
33312
  addApi: (input) => runtime2.putAccount({
33016
- routeId: input.routeId ?? randomUUID17(),
33313
+ routeId: input.routeId ?? randomUUID18(),
33017
33314
  label: input.label,
33018
33315
  replace: input.replace,
33019
33316
  credential: {
@@ -33230,7 +33527,7 @@ function createNativeAccountRuntime(options) {
33230
33527
  return;
33231
33528
  let lineage;
33232
33529
  const kept = await metadataPublications.run(() => localMetadataWrite(fence, (old) => {
33233
- lineage = old.authLineageId ?? randomUUID17();
33530
+ lineage = old.authLineageId ?? randomUUID18();
33234
33531
  return {
33235
33532
  ...old,
33236
33533
  authLineageId: lineage
@@ -33437,9 +33734,9 @@ function relayGeneration(input) {
33437
33734
  return generation;
33438
33735
  }
33439
33736
  // src/native-host-auth-write.ts
33440
- import { randomUUID as randomUUID18 } from "node:crypto";
33441
- import { lstat as lstat15, open as open11, rename as rename13, unlink as unlink7 } from "node:fs/promises";
33442
- 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";
33443
33740
  class NativeHostAuthWriteError extends Error {
33444
33741
  code;
33445
33742
  effect;
@@ -33500,11 +33797,11 @@ async function writeNativeHostAuth(input, hooks = {}) {
33500
33797
  const removingFile = host === "pi" && Object.keys(next).length === 0;
33501
33798
  const outcome = Object.freeze(host === "pi" ? { status: "removed", file: removingFile ? "unlinked" : "replaced" } : { status: snapshot.data === undefined ? "created" : "replaced" });
33502
33799
  if (!removingFile) {
33503
- stage = join22(dirname19(authPath), `.native-host-auth-write.${randomUUID18()}.tmp`);
33800
+ stage = join23(dirname19(authPath), `.native-host-auth-write.${randomUUID19()}.tmp`);
33504
33801
  const bytes = `${JSON.stringify(next, null, 2)}
33505
33802
  `;
33506
33803
  const nativeCreated = await createWindowsOwnerOnly(stage, bytes);
33507
- const handle = await open11(stage, nativeCreated ? "r+" : "wx", 384);
33804
+ const handle = await open12(stage, nativeCreated ? "r+" : "wx", 384);
33508
33805
  try {
33509
33806
  const identity3 = await handle.stat();
33510
33807
  ownedStage = { dev: identity3.dev, ino: identity3.ino };
@@ -33550,7 +33847,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
33550
33847
  } finally {
33551
33848
  if (stage && ownedStage) {
33552
33849
  try {
33553
- const current = await lstat15(stage);
33850
+ const current = await lstat16(stage);
33554
33851
  if (current.dev === ownedStage.dev && current.ino === ownedStage.ino)
33555
33852
  await unlink7(stage);
33556
33853
  } catch {}
@@ -33559,8 +33856,8 @@ async function writeNativeHostAuth(input, hooks = {}) {
33559
33856
  }
33560
33857
 
33561
33858
  // src/native-migration.ts
33562
- import { createHash as createHash24 } from "node:crypto";
33563
- 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";
33564
33861
  import { dirname as dirname20, isAbsolute as isAbsolute7 } from "node:path";
33565
33862
  class NativeMigrationError extends Error {
33566
33863
  code;
@@ -33610,7 +33907,7 @@ function owned(snapshot) {
33610
33907
  }
33611
33908
  async function absent(path2) {
33612
33909
  try {
33613
- await lstat16(path2);
33910
+ await lstat17(path2);
33614
33911
  return false;
33615
33912
  } catch (error) {
33616
33913
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
@@ -33939,7 +34236,7 @@ function routingBytes(captured) {
33939
34236
  `;
33940
34237
  }
33941
34238
  function bytesDigest(bytes) {
33942
- return bytes === undefined ? null : createHash24("sha256").update(bytes).digest("hex");
34239
+ return bytes === undefined ? null : createHash25("sha256").update(bytes).digest("hex");
33943
34240
  }
33944
34241
  function expectedAuth(input, snapshot) {
33945
34242
  const entry2 = inspectNativeHostAuthEntry(input.host, snapshot.data);
@@ -34314,7 +34611,7 @@ async function runNativeMigration(input, hooks = {}) {
34314
34611
  refuse3();
34315
34612
  await step("before:host");
34316
34613
  await recheck();
34317
- await mkdir12(dirname20(operation.hostAuthPath), {
34614
+ await mkdir13(dirname20(operation.hostAuthPath), {
34318
34615
  recursive: true,
34319
34616
  mode: 448
34320
34617
  });
@@ -36794,7 +37091,7 @@ function waitForRequest(pending, signal) {
36794
37091
  });
36795
37092
  }
36796
37093
  // src/native-vault-connection.ts
36797
- 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";
36798
37095
  // ../../node_modules/@cortexkit/common-auth/dist/opencode2/integration.js
36799
37096
  var PLACEHOLDER_PREFIX = "common-auth-placeholder";
36800
37097
  var PLACEHOLDER_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
@@ -36802,15 +37099,15 @@ function placeholderSecret(integrationID) {
36802
37099
  return `${PLACEHOLDER_PREFIX}.${integrationID}`;
36803
37100
  }
36804
37101
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
36805
- import { createHash as createHash25 } from "node:crypto";
36806
- import { constants as constants4 } from "node:fs";
36807
- 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";
36808
37105
  import { dirname as dirname21, resolve as resolve15 } from "node:path";
36809
37106
  import { setTimeout as sleep } from "node:timers/promises";
36810
37107
 
36811
37108
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
36812
37109
  import { rmdirSync, statSync as statSync5, utimesSync } from "node:fs";
36813
- 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";
36814
37111
  var STALE = 30000;
36815
37112
  var RENEWAL_STALE = 1e4;
36816
37113
  var UPDATE = 3000;
@@ -36846,7 +37143,7 @@ async function remove(path2) {
36846
37143
  }
36847
37144
  async function acquire(path2, stale) {
36848
37145
  try {
36849
- await mkdir13(path2);
37146
+ await mkdir14(path2);
36850
37147
  } catch (error) {
36851
37148
  if (errorCode4(error) !== "EEXIST")
36852
37149
  throw error;
@@ -37081,7 +37378,7 @@ function canonical(value) {
37081
37378
  return JSON.stringify(value);
37082
37379
  }
37083
37380
  function digest2(value) {
37084
- return createHash25("sha256").update(canonical(value)).digest("hex");
37381
+ return createHash26("sha256").update(canonical(value)).digest("hex");
37085
37382
  }
37086
37383
  function code(error) {
37087
37384
  return object2(error) ? error.code : undefined;
@@ -37103,13 +37400,13 @@ async function safeRead(path2, privateFile = false, afterReadCheck) {
37103
37400
  }
37104
37401
  let file;
37105
37402
  try {
37106
- file = await open12(path2, constants4.O_RDONLY | constants4.O_NOFOLLOW);
37403
+ file = await open13(path2, constants5.O_RDONLY | constants5.O_NOFOLLOW);
37107
37404
  const stat12 = await file.stat();
37108
37405
  if (!stat12.isFile() || privateFile && (stat12.mode & 511) !== 384) {
37109
37406
  throw new PiSlotError("unsafe-path");
37110
37407
  }
37111
37408
  await afterReadCheck?.(path2);
37112
- const current = await lstat17(path2);
37409
+ const current = await lstat18(path2);
37113
37410
  if (!current.isFile() || current.dev !== stat12.dev || current.ino !== stat12.ino) {
37114
37411
  throw new PiSlotError("unsafe-path");
37115
37412
  }
@@ -37181,7 +37478,7 @@ function replaceEntry(auth, provider, next) {
37181
37478
  async function syncDir(path2) {
37182
37479
  if (windowsPrivateFiles)
37183
37480
  return;
37184
- const dir = await open12(path2, "r");
37481
+ const dir = await open13(path2, "r");
37185
37482
  try {
37186
37483
  await dir.sync();
37187
37484
  } finally {
@@ -37244,7 +37541,7 @@ function createPiSlot(options, onStep, hooks) {
37244
37541
  if (windowsPrivateFiles)
37245
37542
  await ensurePrivateDirectory(dirname21(authPath));
37246
37543
  else
37247
- await mkdir14(dirname21(authPath), { recursive: true, mode: 448 });
37544
+ await mkdir15(dirname21(authPath), { recursive: true, mode: 448 });
37248
37545
  const deadline = Date.now() + timeout;
37249
37546
  let retry = 0;
37250
37547
  while (!release2) {
@@ -37306,8 +37603,8 @@ function createPiSlot(options, onStep, hooks) {
37306
37603
  if (windowsPrivateFiles)
37307
37604
  await ensurePrivateDirectory(dirname21(stashPath));
37308
37605
  else {
37309
- await mkdir14(dirname21(stashPath), { recursive: true, mode: 448 });
37310
- const dir = await lstat17(dirname21(stashPath));
37606
+ await mkdir15(dirname21(stashPath), { recursive: true, mode: 448 });
37607
+ const dir = await lstat18(dirname21(stashPath));
37311
37608
  if (!dir.isDirectory() || (dir.mode & 511) !== 448)
37312
37609
  throw new PiSlotError("unsafe-path");
37313
37610
  }
@@ -37348,7 +37645,7 @@ function createPiSlot(options, onStep, hooks) {
37348
37645
  function nativePiAuthSlotPaths(options) {
37349
37646
  return {
37350
37647
  authPath: resolve16(options.authPath),
37351
- 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"),
37352
37649
  provider: "anthropic",
37353
37650
  placeholderKey: placeholderSecret("anthropic")
37354
37651
  };
@@ -37478,11 +37775,11 @@ function createAnthropicOAuthFetch(options = {}) {
37478
37775
  });
37479
37776
  }
37480
37777
  // src/prime.ts
37481
- import { createHash as createHash26 } from "node:crypto";
37778
+ import { createHash as createHash27 } from "node:crypto";
37482
37779
  import { realpathSync as realpathSync3 } from "node:fs";
37483
- import { mkdir as mkdir15, readdir as readdir4, rm as rm8, stat as stat12, writeFile as writeFile5 } from "node:fs/promises";
37484
- import { tmpdir as tmpdir7 } from "node:os";
37485
- 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";
37486
37783
  var CLAUDE_PRIME_COMMAND_NAME = "claude-prime";
37487
37784
  var PRIME_TICK_MS = 60000;
37488
37785
  var PRIME_DUE_OFFSET_MS = 60000;
@@ -37670,7 +37967,7 @@ function buildPrimeRequestBody() {
37670
37967
  return JSON.parse(JSON.stringify(PRIME_REQUEST_BODY));
37671
37968
  }
37672
37969
  function defaultMarkerDir() {
37673
- return join24(tmpdir7(), "opencode-anthropic-auth", "prime");
37970
+ return join25(tmpdir8(), "opencode-anthropic-auth", "prime");
37674
37971
  }
37675
37972
  function primeStorageFingerprint(storagePath) {
37676
37973
  const absolutePath = resolve17(storagePath);
@@ -37682,22 +37979,22 @@ function primeStorageFingerprint(storagePath) {
37682
37979
  throw error;
37683
37980
  canonicalPath2 = absolutePath;
37684
37981
  }
37685
- return createHash26("sha256").update(canonicalPath2).digest("hex").slice(0, 12);
37982
+ return createHash27("sha256").update(canonicalPath2).digest("hex").slice(0, 12);
37686
37983
  }
37687
37984
  function primeMarkerNamespaceDir(markerDir, storagePath) {
37688
- return join24(markerDir, primeStorageFingerprint(storagePath));
37985
+ return join25(markerDir, primeStorageFingerprint(storagePath));
37689
37986
  }
37690
37987
  function primeAccountMarkerDir(markerDir, storagePath, accountFingerprint) {
37691
37988
  if (!/^[a-f0-9]{12,}$/i.test(accountFingerprint)) {
37692
37989
  throw new Error("Prime account fingerprint must be a hexadecimal digest");
37693
37990
  }
37694
- return join24(primeMarkerNamespaceDir(markerDir, storagePath), accountFingerprint.toLowerCase().slice(0, 12));
37991
+ return join25(primeMarkerNamespaceDir(markerDir, storagePath), accountFingerprint.toLowerCase().slice(0, 12));
37695
37992
  }
37696
37993
  function primeMarkerPath(markerDir, accountId2, resetsAtEpochMs) {
37697
- return join24(markerDir, `${encodeURIComponent(accountId2)}-${resetsAtEpochMs}`);
37994
+ return join25(markerDir, `${encodeURIComponent(accountId2)}-${resetsAtEpochMs}`);
37698
37995
  }
37699
37996
  function primeBootstrapMarkerPath(markerDir, accountId2) {
37700
- return join24(markerDir, `${encodeURIComponent(accountId2)}-bootstrap`);
37997
+ return join25(markerDir, `${encodeURIComponent(accountId2)}-bootstrap`);
37701
37998
  }
37702
37999
  function primeAccountLabel(id2, fallback) {
37703
38000
  if (id2 === "main")
@@ -37973,13 +38270,13 @@ class PrimeManager {
37973
38270
  }
37974
38271
  const postClaimStorage = await this.options.loadStorage();
37975
38272
  if (this.stopped || postClaimStorage?.prime?.enabled !== true) {
37976
- await rm8(markerPath, { force: true });
38273
+ await rm9(markerPath, { force: true });
37977
38274
  return;
37978
38275
  }
37979
38276
  if (markerEpoch !== undefined) {
37980
- await rm8(bootstrapMarkerPath, { force: true });
38277
+ await rm9(bootstrapMarkerPath, { force: true });
37981
38278
  if (this.stopped) {
37982
- await rm8(markerPath, { force: true });
38279
+ await rm9(markerPath, { force: true });
37983
38280
  return;
37984
38281
  }
37985
38282
  }
@@ -38004,10 +38301,10 @@ class PrimeManager {
38004
38301
  }
38005
38302
  async tryClaimPath(dir, markerPath) {
38006
38303
  try {
38007
- await mkdir15(dir, { recursive: true });
38304
+ await mkdir16(dir, { recursive: true });
38008
38305
  } catch {}
38009
38306
  try {
38010
- await writeFile5(markerPath, "", { encoding: "utf8", flag: "wx" });
38307
+ await writeFile6(markerPath, "", { encoding: "utf8", flag: "wx" });
38011
38308
  return markerPath;
38012
38309
  } catch (error) {
38013
38310
  const code2 = error.code;
@@ -38020,7 +38317,7 @@ class PrimeManager {
38020
38317
  const dir = this.markerDir(accountFingerprint);
38021
38318
  const prefix = `${encodeURIComponent(accountId2)}-`;
38022
38319
  try {
38023
- return (await readdir4(dir)).some((entry2) => entry2.startsWith(prefix));
38320
+ return (await readdir5(dir)).some((entry2) => entry2.startsWith(prefix));
38024
38321
  } catch (error) {
38025
38322
  if (error.code === "ENOENT")
38026
38323
  return false;
@@ -38132,21 +38429,21 @@ class PrimeManager {
38132
38429
  async sweepMarkerDirectory(dir, now) {
38133
38430
  let entries;
38134
38431
  try {
38135
- entries = await readdir4(dir);
38432
+ entries = await readdir5(dir);
38136
38433
  } catch {
38137
38434
  return 0;
38138
38435
  }
38139
38436
  let swept = 0;
38140
38437
  for (const entry2 of entries) {
38141
38438
  try {
38142
- const path2 = join24(dir, entry2);
38439
+ const path2 = join25(dir, entry2);
38143
38440
  const s = await stat12(path2);
38144
38441
  if (s.isDirectory()) {
38145
38442
  swept += await this.sweepMarkerDirectory(path2, now);
38146
38443
  continue;
38147
38444
  }
38148
38445
  if (now - s.mtimeMs > PRIME_MARKER_MAX_AGE_MS) {
38149
- await rm8(path2, { force: true });
38446
+ await rm9(path2, { force: true });
38150
38447
  swept += 1;
38151
38448
  }
38152
38449
  } catch {}
@@ -38161,24 +38458,24 @@ class PrimeManager {
38161
38458
  }
38162
38459
  }
38163
38460
  // src/quota-header-feed.ts
38164
- import { randomUUID as randomUUID19 } from "node:crypto";
38461
+ import { randomUUID as randomUUID20 } from "node:crypto";
38165
38462
  import {
38166
38463
  chmod as chmod3,
38167
- lstat as lstat18,
38168
- mkdir as mkdir16,
38169
- readdir as readdir5,
38464
+ lstat as lstat19,
38465
+ mkdir as mkdir17,
38466
+ readdir as readdir6,
38170
38467
  readFile as readFile13,
38171
38468
  rename as rename14,
38172
- rm as rm9,
38469
+ rm as rm10,
38173
38470
  stat as stat13,
38174
- writeFile as writeFile6
38471
+ writeFile as writeFile7
38175
38472
  } from "node:fs/promises";
38176
- import { tmpdir as tmpdir8 } from "node:os";
38177
- import { join as join25 } from "node:path";
38473
+ import { tmpdir as tmpdir9 } from "node:os";
38474
+ import { join as join26 } from "node:path";
38178
38475
  var QUOTA_HEADER_FEED_SCHEMA_VERSION = 3;
38179
38476
  var QUOTA_HEADER_FEED_LEASE_MS = 180000;
38180
38477
  function getDefaultQuotaHeaderFeedDirectory() {
38181
- 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");
38182
38479
  }
38183
38480
  function configuredAnthropicOAuthAccountCount(input) {
38184
38481
  const fallbackCount = input.storage?.accounts.filter(isOAuthAccount).length ?? 0;
@@ -38336,8 +38633,8 @@ class QuotaHeaderFeedRegistry {
38336
38633
  writeChain = Promise.resolve();
38337
38634
  constructor(options = {}) {
38338
38635
  this.options = options;
38339
- const instanceId = options.instanceId ?? `${process.pid}-${randomUUID19()}`;
38340
- 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`);
38341
38638
  }
38342
38639
  publish(entry2) {
38343
38640
  const { accountKey, quota: quota2 } = entry2;
@@ -38366,24 +38663,24 @@ class QuotaHeaderFeedRegistry {
38366
38663
  return Promise.reject(new Error("Invalid quota header feed account key"));
38367
38664
  this.writeChain = this.writeChain.catch(() => {}).then(async () => {
38368
38665
  const directory = this.options.directory ?? getDefaultQuotaHeaderFeedDirectory();
38369
- await mkdir16(directory, { recursive: true, mode: 448 });
38666
+ await mkdir17(directory, { recursive: true, mode: 448 });
38370
38667
  await chmod3(directory, 448);
38371
38668
  await this.reapStaleSiblingLeases(directory);
38372
38669
  let entries = {};
38373
38670
  try {
38374
- const record9 = JSON.parse(await readFile13(this.filePath, "utf8"));
38375
- if (record9.version === QUOTA_HEADER_FEED_SCHEMA_VERSION && record9.entries && typeof record9.entries === "object")
38376
- 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;
38377
38674
  } catch {}
38378
38675
  entries[accountKey] = cleanEntry;
38379
- const tempPath = `${this.filePath}.${randomUUID19()}.tmp`;
38676
+ const tempPath = `${this.filePath}.${randomUUID20()}.tmp`;
38380
38677
  try {
38381
- 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 })}
38382
38679
  `, { mode: 384 });
38383
38680
  await chmod3(tempPath, 384);
38384
38681
  await rename14(tempPath, this.filePath);
38385
38682
  } finally {
38386
- await rm9(tempPath, { force: true });
38683
+ await rm10(tempPath, { force: true });
38387
38684
  }
38388
38685
  });
38389
38686
  return this.writeChain;
@@ -38393,12 +38690,12 @@ class QuotaHeaderFeedRegistry {
38393
38690
  const leaseMs = this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS;
38394
38691
  let names2;
38395
38692
  try {
38396
- names2 = await readdir5(directory);
38693
+ names2 = await readdir6(directory);
38397
38694
  } catch {
38398
38695
  return;
38399
38696
  }
38400
38697
  await Promise.all(names2.filter((name) => /^\d+-[0-9a-f-]+\.json$/i.test(name)).map(async (name) => {
38401
- const path2 = join25(directory, name);
38698
+ const path2 = join26(directory, name);
38402
38699
  if (path2 === this.filePath)
38403
38700
  return;
38404
38701
  try {
@@ -38406,10 +38703,10 @@ class QuotaHeaderFeedRegistry {
38406
38703
  if (file.mtimeMs > now || now - file.mtimeMs < leaseMs)
38407
38704
  return;
38408
38705
  await this.options.beforeRemoveFile?.(path2);
38409
- const current = await lstat18(path2);
38706
+ const current = await lstat19(path2);
38410
38707
  if (current.ino !== file.ino || current.mtimeMs !== file.mtimeMs)
38411
38708
  return;
38412
- await (this.options.removeFile ?? ((target2) => rm9(target2)))(path2);
38709
+ await (this.options.removeFile ?? ((target2) => rm10(target2)))(path2);
38413
38710
  } catch {}
38414
38711
  }));
38415
38712
  }
@@ -38420,17 +38717,17 @@ class QuotaHeaderFeedRegistry {
38420
38717
  const leaseMs = this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS;
38421
38718
  let names2;
38422
38719
  try {
38423
- names2 = (await readdir5(directory)).filter((name) => name.endsWith(".json"));
38720
+ names2 = (await readdir6(directory)).filter((name) => name.endsWith(".json"));
38424
38721
  } catch {
38425
38722
  return [];
38426
38723
  }
38427
38724
  const newest = new Map;
38428
38725
  await Promise.all(names2.map(async (name) => {
38429
38726
  try {
38430
- const record9 = JSON.parse(await readFile13(join25(directory, name), "utf8"));
38431
- 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")
38432
38729
  return;
38433
- for (const [accountKey, candidate] of Object.entries(record9.entries)) {
38730
+ for (const [accountKey, candidate] of Object.entries(record10.entries)) {
38434
38731
  if (!candidate || typeof candidate !== "object" || candidate.schema_version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || candidate.provider !== "anthropic" || !validIdentity(candidate))
38435
38732
  continue;
38436
38733
  const observed = candidate.observed_at_ms;
@@ -38446,7 +38743,7 @@ class QuotaHeaderFeedRegistry {
38446
38743
  }
38447
38744
  async dispose() {
38448
38745
  await this.writeChain.catch(() => {});
38449
- await rm9(this.filePath, { force: true });
38746
+ await rm10(this.filePath, { force: true });
38450
38747
  }
38451
38748
  }
38452
38749
  // src/quotas.ts
@@ -38607,11 +38904,11 @@ function buildClaudeQuotaSummary(input) {
38607
38904
  `).trimEnd();
38608
38905
  }
38609
38906
  // src/request-gzip.ts
38610
- import { mkdir as mkdir17, readFile as readFile14, rename as rename15, rm as rm10, writeFile as writeFile7 } from "node:fs/promises";
38611
- import { basename as basename10, dirname as dirname23, join as join26 } from "node:path";
38612
- import { promisify } from "node:util";
38613
- import { gzip } from "node:zlib";
38614
- 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);
38615
38912
  var GZIP_REQUEST_BODIES_ENV = "CLAUDE_CODE_GZIP_REQUEST_BODIES";
38616
38913
  var GZIP_HOST = "api.anthropic.com";
38617
38914
  var GZIP_LEVEL = 6;
@@ -38722,7 +39019,7 @@ class RequestGzipLatch {
38722
39019
  const age = typeof latchedAt === "number" && Number.isFinite(latchedAt) ? this.now() - latchedAt : -1;
38723
39020
  if (age >= 0 && age < GZIP_LATCH_TTL_MS)
38724
39021
  return true;
38725
- await rm10(this.path, { force: true }).catch(() => {});
39022
+ await rm11(this.path, { force: true }).catch(() => {});
38726
39023
  return false;
38727
39024
  }
38728
39025
  async persist(status) {
@@ -38732,12 +39029,12 @@ class RequestGzipLatch {
38732
39029
  return;
38733
39030
  const temporary = `${this.path}.${process.pid}.tmp`;
38734
39031
  try {
38735
- await mkdir17(dirname23(this.path), { recursive: true });
38736
- 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 })}
38737
39034
  `, { mode: 384 });
38738
39035
  await rename15(temporary, this.path);
38739
39036
  } catch {
38740
- await rm10(temporary, { force: true }).catch(() => {});
39037
+ await rm11(temporary, { force: true }).catch(() => {});
38741
39038
  }
38742
39039
  }
38743
39040
  }
@@ -38754,7 +39051,7 @@ function getRequestGzipLatch(path2) {
38754
39051
  function getRequestGzipLatchPath(accountStoragePath) {
38755
39052
  const name = basename10(accountStoragePath);
38756
39053
  const stem = name.endsWith(".json") ? name.slice(0, -5) : name;
38757
- return join26(dirname23(accountStoragePath), `${stem}-request-gzip.json`);
39054
+ return join27(dirname23(accountStoragePath), `${stem}-request-gzip.json`);
38758
39055
  }
38759
39056
  async function decideRequestGzip(options) {
38760
39057
  if (!CLAUDE_CODE_GZIPS_REQUEST_BODIES)
@@ -38823,13 +39120,13 @@ function isInvalidJsonBody(text6) {
38823
39120
  }
38824
39121
  if (!parsed || typeof parsed !== "object")
38825
39122
  return false;
38826
- const record9 = parsed;
38827
- const error = record9.error;
38828
- 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") {
38829
39126
  const message = error.message;
38830
39127
  return INVALID_JSON_MESSAGES.some((prefix) => message.startsWith(prefix));
38831
39128
  }
38832
- 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);
38833
39130
  }
38834
39131
  async function classifyGzipRejection(response) {
38835
39132
  const { status } = response;
@@ -38982,14 +39279,14 @@ function executeLaneStartCommand(input) {
38982
39279
  };
38983
39280
  }
38984
39281
  // src/state-layout-decision.ts
38985
- import { mkdir as mkdir18, readdir as readdir8 } from "node:fs/promises";
39282
+ import { mkdir as mkdir19, readdir as readdir9 } from "node:fs/promises";
38986
39283
  import { homedir as homedir8 } from "node:os";
38987
- 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";
38988
39285
 
38989
39286
  // src/layout-fence.ts
38990
- import { open as open13, readdir as readdir6 } from "node:fs/promises";
39287
+ import { open as open14, readdir as readdir7 } from "node:fs/promises";
38991
39288
  import { homedir as homedir6 } from "node:os";
38992
- 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";
38993
39290
  var STATE_PATH_OVERRIDE_VARIABLES = [
38994
39291
  "OPENCODE_ANTHROPIC_AUTH_FILE",
38995
39292
  "OPENCODE_ANTHROPIC_AUTH_STATE_FILE",
@@ -39025,7 +39322,7 @@ async function holderFenceBlockers(input) {
39025
39322
  const files = new Set(input.files);
39026
39323
  const blockers = [];
39027
39324
  for (const dir of [...new Set(input.directories)].sort()) {
39028
- const holderFile = join27(dir, HOLDER_FILE_NAME);
39325
+ const holderFile = join28(dir, HOLDER_FILE_NAME);
39029
39326
  let contents;
39030
39327
  try {
39031
39328
  contents = await readHolderFile(holderFile);
@@ -39039,8 +39336,8 @@ async function holderFenceBlockers(input) {
39039
39336
  }
39040
39337
  for (const value of contents?.entries ?? []) {
39041
39338
  const life = holderEntryLiveness(value);
39042
- const record9 = value;
39043
- 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;
39044
39341
  if (!life || !listed) {
39045
39342
  blockers.push({
39046
39343
  kind: "holder",
@@ -39060,7 +39357,7 @@ async function holderFenceBlockers(input) {
39060
39357
  kind: "holder",
39061
39358
  holderFile,
39062
39359
  pid: life.pid,
39063
- role: typeof record9.role === "string" ? record9.role : null,
39360
+ role: typeof record10.role === "string" ? record10.role : null,
39064
39361
  file: overlap
39065
39362
  });
39066
39363
  }
@@ -39075,7 +39372,7 @@ function defaultPreNArtifactLocations(env = process.env, home = homedir6()) {
39075
39372
  });
39076
39373
  const rpcOverride = env.OPENCODE_ANTHROPIC_AUTH_RPC_DIR?.trim();
39077
39374
  return {
39078
- rpcRoots: [join27(root, "rpc")],
39375
+ rpcRoots: [join28(root, "rpc")],
39079
39376
  rpcDirs: rpcOverride ? [resolve18(rpcOverride)] : [],
39080
39377
  cacheKeepDirs: [
39081
39378
  ...new Set([
@@ -39091,7 +39388,7 @@ function defaultPreNArtifactLocations(env = process.env, home = homedir6()) {
39091
39388
  }
39092
39389
  async function listDir(dir, blockers) {
39093
39390
  try {
39094
- return await readdir6(dir);
39391
+ return await readdir7(dir);
39095
39392
  } catch (error) {
39096
39393
  if (errorCode5(error) === "ENOENT")
39097
39394
  return [];
@@ -39109,7 +39406,7 @@ async function readArtifact(path2, blockers) {
39109
39406
  let text6;
39110
39407
  let mtimeMs;
39111
39408
  try {
39112
- const file = await open13(path2, "r");
39409
+ const file = await open14(path2, "r");
39113
39410
  try {
39114
39411
  text6 = await file.readFile("utf8");
39115
39412
  mtimeMs = (await file.stat()).mtimeMs;
@@ -39136,16 +39433,16 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
39136
39433
  const portDirs = [...locations.rpcDirs];
39137
39434
  for (const root of locations.rpcRoots)
39138
39435
  for (const name of await listDir(root, blockers))
39139
- portDirs.push(join27(root, name));
39436
+ portDirs.push(join28(root, name));
39140
39437
  for (const dir of [...new Set(portDirs)]) {
39141
39438
  for (const name of await listDir(dir, blockers)) {
39142
39439
  if (!/^port-\d+\.json$/.test(name))
39143
39440
  continue;
39144
- const path2 = join27(dir, name);
39145
- const record9 = await readArtifact(path2, blockers);
39146
- 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))
39147
39444
  continue;
39148
- const { value, startedAt } = record9;
39445
+ const { value, startedAt } = record10;
39149
39446
  const pid = value.pid;
39150
39447
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0) {
39151
39448
  blockers.push({ kind: "artifact-scan", path: path2, reason: "invalid" });
@@ -39160,12 +39457,12 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
39160
39457
  const match = /^(\d+)-.+\.json$/.exec(name);
39161
39458
  if (!match)
39162
39459
  continue;
39163
- const path2 = join27(dir, name);
39164
- const record9 = await readArtifact(path2, blockers);
39165
- 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))
39166
39463
  continue;
39167
39464
  const pid = Number(match[1]);
39168
- if (!recordPredatesBoot(record9.startedAt, clock) && pidAlive2(pid))
39465
+ if (!recordPredatesBoot(record10.startedAt, clock) && pidAlive2(pid))
39169
39466
  blockers.push({ kind: "pre-n-artifact", artifact: path2, pid });
39170
39467
  }
39171
39468
  }
@@ -39187,15 +39484,15 @@ function describeFenceBlocker(blocker) {
39187
39484
  }
39188
39485
 
39189
39486
  // src/state-layout-move.ts
39190
- import { randomUUID as randomUUID20 } from "node:crypto";
39191
- import { lstat as lstat19, readdir as readdir7, readFile as readFile15, stat as stat14, unlink as unlink10 } from "node:fs/promises";
39192
- 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";
39193
39490
  var ACCOUNT_FILE = "anthropic-auth.json";
39194
39491
  var ACCOUNT_STATE_FILE = "anthropic-auth-state.json";
39195
39492
  var LAYOUT_LOCK_NAME = "runtime-layout";
39196
39493
  var LAYOUT_LOCK_TIMEOUT_MS = 120000;
39197
39494
  async function resolveLegacyDatasetFiles(configDir) {
39198
- 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" });
39199
39496
  return {
39200
39497
  oldDir: await canonicalPath(configDir),
39201
39498
  oldPaths,
@@ -39203,8 +39500,8 @@ async function resolveLegacyDatasetFiles(configDir) {
39203
39500
  };
39204
39501
  }
39205
39502
  async function resolveRelocationDataset(input) {
39206
- const legacyConfig = join28(input.configDir, ACCOUNT_FILE);
39207
- 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);
39208
39505
  const { oldDir, oldPaths, oldVault } = await resolveLegacyDatasetFiles(input.configDir);
39209
39506
  const stateHome = { kind: "state-home", dir: input.sub };
39210
39507
  const newPaths = await resolveNativePoolPaths(legacyConfig, legacyState, stateHome);
@@ -39233,7 +39530,7 @@ async function resolveRelocationDataset(input) {
39233
39530
  role,
39234
39531
  from: pairs[role][0],
39235
39532
  to: pairs[role][1],
39236
- configured: join28(input.configDir, STATE_HOME_FILE_NAMES[role])
39533
+ configured: join29(input.configDir, STATE_HOME_FILE_NAMES[role])
39237
39534
  })),
39238
39535
  storageIds: { local: oldPaths.storageId, vault: oldVault.storageId }
39239
39536
  };
@@ -39255,8 +39552,8 @@ function errorCode6(error) {
39255
39552
  }
39256
39553
  function transitionHolderFiles(dataset) {
39257
39554
  return [
39258
- join28(dataset.oldDir, HOLDER_FILE_NAME),
39259
- join28(dataset.sub, HOLDER_FILE_NAME)
39555
+ join29(dataset.oldDir, HOLDER_FILE_NAME),
39556
+ join29(dataset.sub, HOLDER_FILE_NAME)
39260
39557
  ].sort();
39261
39558
  }
39262
39559
  async function acquireHolderLock(ctx, holderFile, timeoutMs) {
@@ -39273,7 +39570,7 @@ async function acquireHolderLock(ctx, holderFile, timeoutMs) {
39273
39570
  }
39274
39571
  }
39275
39572
  async function acquireHolderLocks(dataset, ctx) {
39276
- const oldHolders = join28(dataset.oldDir, HOLDER_FILE_NAME);
39573
+ const oldHolders = join29(dataset.oldDir, HOLDER_FILE_NAME);
39277
39574
  for (const file of transitionHolderFiles(dataset)) {
39278
39575
  if (file === oldHolders)
39279
39576
  await stateLayoutStep(ctx, "old-holders-locking");
@@ -39453,14 +39750,14 @@ async function drainCoalescedWrites(dataset) {
39453
39750
  await drainVaultQuota(dataset.oldVault.roster);
39454
39751
  forgetRelocationObservations();
39455
39752
  }
39456
- function relocationTombstone(record9) {
39753
+ function relocationTombstone(record10) {
39457
39754
  return `${JSON.stringify({
39458
39755
  version: 0,
39459
- relocatedTo: record9.sub,
39460
- stateRoot: record9.stateRoot,
39461
- identity: record9.identity,
39462
- attempt: record9.attempt,
39463
- by: record9.by
39756
+ relocatedTo: record10.sub,
39757
+ stateRoot: record10.stateRoot,
39758
+ identity: record10.identity,
39759
+ attempt: record10.attempt,
39760
+ by: record10.by
39464
39761
  })}
39465
39762
  `;
39466
39763
  }
@@ -39479,7 +39776,7 @@ function restoringPath(path2, attempt) {
39479
39776
  }
39480
39777
  async function exists3(path2) {
39481
39778
  try {
39482
- await lstat19(path2);
39779
+ await lstat20(path2);
39483
39780
  return true;
39484
39781
  } catch (error) {
39485
39782
  if (errorCode6(error) === "ENOENT")
@@ -39489,7 +39786,7 @@ async function exists3(path2) {
39489
39786
  }
39490
39787
  async function removeOwnStaging(path2) {
39491
39788
  try {
39492
- const info = await lstat19(path2);
39789
+ const info = await lstat20(path2);
39493
39790
  if (info.isFile())
39494
39791
  await unlink10(path2);
39495
39792
  } catch (error) {
@@ -39497,17 +39794,17 @@ async function removeOwnStaging(path2) {
39497
39794
  throw error;
39498
39795
  }
39499
39796
  }
39500
- function recordFilesProblem(record9, dataset) {
39501
- if (record9.files.length !== dataset.slots.length)
39502
- 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}`;
39503
39800
  for (const slot of dataset.slots) {
39504
- const file = record9.files.find((candidate) => candidate.role === slot.role);
39801
+ const file = record10.files.find((candidate) => candidate.role === slot.role);
39505
39802
  if (!file)
39506
39803
  return `it has no ${slot.role} entry`;
39507
39804
  if (file.from !== slot.from || file.to !== slot.to)
39508
39805
  return `its ${slot.role} entry names ${file.from} and ${file.to}, not ${slot.from} and ${slot.to}`;
39509
39806
  }
39510
- for (const file of record9.restore?.files ?? []) {
39807
+ for (const file of record10.restore?.files ?? []) {
39511
39808
  const slot = dataset.slots.find((candidate) => candidate.role === file.role);
39512
39809
  if (!slot || file.from !== slot.from || file.to !== slot.to)
39513
39810
  return `its restore lists ${file.from} and ${file.to} for ${file.role}`;
@@ -39532,7 +39829,7 @@ async function movePreconditionFailure(dataset, platform) {
39532
39829
  for (const path2 of new Set([slot.configured, slot.from])) {
39533
39830
  let info;
39534
39831
  try {
39535
- info = await lstat19(path2);
39832
+ info = await lstat20(path2);
39536
39833
  } catch (error) {
39537
39834
  if (errorCode6(error) === "ENOENT")
39538
39835
  continue;
@@ -39549,7 +39846,7 @@ async function movePreconditionFailure(dataset, platform) {
39549
39846
  anyOld ||= fromExists;
39550
39847
  if (await exists3(slot.to)) {
39551
39848
  if (fromExists) {
39552
- 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)]);
39553
39850
  if (a.dev === b.dev && a.ino === b.ino)
39554
39851
  return `${slot.from} and ${slot.to} are the same file`;
39555
39852
  }
@@ -39624,15 +39921,15 @@ async function owned2(ctx, step, expect) {
39624
39921
  if (outcome2 === "skipped")
39625
39922
  throw new Error(`anthropic-auth stopped: ${step.kind === "rename" ? step.to : step.path} changed while it was being replaced`);
39626
39923
  }
39627
- async function rollbackPreparing(record9, dataset, ctx) {
39628
- const { attempt } = record9;
39924
+ async function rollbackPreparing(record10, dataset, ctx) {
39925
+ const { attempt } = record10;
39629
39926
  const slot = (role) => {
39630
- const found = record9.files.find((file) => file.role === role);
39927
+ const found = record10.files.find((file) => file.role === role);
39631
39928
  if (!found)
39632
39929
  throw new StateLayoutRollbackRefused(dataset.sub, `no ${role} entry`);
39633
39930
  return found;
39634
39931
  };
39635
- if (record9.barriers.journal === "present") {
39932
+ if (record10.barriers.journal === "present") {
39636
39933
  const journal = slot("journal");
39637
39934
  const moving = movingJournalPath(journal.from, attempt);
39638
39935
  const movingThere = await exists3(moving);
@@ -39647,7 +39944,7 @@ async function rollbackPreparing(record9, dataset, ctx) {
39647
39944
  await stateLayoutStep(ctx, "rollback:journal");
39648
39945
  for (const role of ["localRuntime", "vaultRuntime"]) {
39649
39946
  const file = slot(role);
39650
- const original = record9.barriers[role].original;
39947
+ const original = record10.barriers[role].original;
39651
39948
  await removeOwnStaging(relocatingPath(file.from, attempt));
39652
39949
  const found = await tombstoneAttempt(file.from);
39653
39950
  if (found !== undefined && found !== attempt)
@@ -39676,7 +39973,7 @@ async function rollbackPreparing(record9, dataset, ctx) {
39676
39973
  }
39677
39974
  await ctx.fs.syncDirectory(dataset.oldDir);
39678
39975
  await stateLayoutStep(ctx, "rollback:old-dir-flushed");
39679
- for (const file of record9.files) {
39976
+ for (const file of record10.files) {
39680
39977
  await removeOwnStaging(relocatingPath(file.to, attempt));
39681
39978
  if (file.sha256 === null)
39682
39979
  continue;
@@ -39687,14 +39984,14 @@ async function rollbackPreparing(record9, dataset, ctx) {
39687
39984
  continue;
39688
39985
  await owned2(ctx, { kind: "unlink", path: file.to }, expectDigest(file.to, file.sha256));
39689
39986
  }
39690
- for (const name of await readdir7(dataset.sub))
39987
+ for (const name of await readdir8(dataset.sub))
39691
39988
  if (isLayoutRecordStage(name, attempt))
39692
- await removeOwnStaging(join28(dataset.sub, name));
39989
+ await removeOwnStaging(join29(dataset.sub, name));
39693
39990
  await stateLayoutStep(ctx, "rollback:destination-removed");
39694
39991
  await ctx.fs.syncDirectory(dataset.sub);
39695
39992
  await stateLayoutStep(ctx, "rollback:sub-flushed");
39696
39993
  const rolledBack = {
39697
- ...record9,
39994
+ ...record10,
39698
39995
  phase: "rolled-back",
39699
39996
  rolledBackAt: ctx.now()
39700
39997
  };
@@ -39706,19 +40003,19 @@ async function rollbackPreparing(record9, dataset, ctx) {
39706
40003
  forgetRelocationObservations();
39707
40004
  return rolledBack;
39708
40005
  }
39709
- async function cleanupOldCopies(record9, dataset, ctx) {
40006
+ async function cleanupOldCopies(record10, dataset, ctx) {
39710
40007
  const kept = [];
39711
40008
  const conflict = [];
39712
40009
  const publish = (next2) => publishStateLayoutRecord(next2, {
39713
40010
  assertLeases: () => ctx.stack.assertAll(),
39714
40011
  expect: expectRecord(dataset.sub, {
39715
40012
  phase: "committed",
39716
- attempt: record9.attempt
40013
+ attempt: record10.attempt
39717
40014
  })
39718
40015
  }, ctx.fs);
39719
40016
  const outcome2 = () => {
39720
40017
  const next2 = {
39721
- ...record9,
40018
+ ...record10,
39722
40019
  cleanup: conflict.length ? "conflict" : kept.length ? "kept" : "done",
39723
40020
  ...kept.length ? { kept: [...kept] } : {},
39724
40021
  ...conflict.length ? { conflict: [...conflict] } : {}
@@ -39734,16 +40031,16 @@ async function cleanupOldCopies(record9, dataset, ctx) {
39734
40031
  return stateLayoutConflict(first?.old ?? dataset.oldPaths.state, first?.new ?? dataset.newPaths.state, cause);
39735
40032
  };
39736
40033
  try {
39737
- const journalSlot = record9.files.find((file) => file.role === "journal");
40034
+ const journalSlot = record10.files.find((file) => file.role === "journal");
39738
40035
  if (journalSlot && await exists3(journalSlot.from))
39739
40036
  conflict.push({ old: journalSlot.from, new: journalSlot.to });
39740
40037
  for (const role of RELOCATION_ROLES) {
39741
40038
  if (role === "localRuntime" || role === "vaultRuntime")
39742
40039
  continue;
39743
- const file = record9.files.find((candidate) => candidate.role === role);
40040
+ const file = record10.files.find((candidate) => candidate.role === role);
39744
40041
  if (!file)
39745
40042
  continue;
39746
- const path2 = role === "journal" ? movingJournalPath(file.from, record9.attempt) : file.from;
40043
+ const path2 = role === "journal" ? movingJournalPath(file.from, record10.attempt) : file.from;
39747
40044
  await ctx.stack.assertAll();
39748
40045
  const credential2 = CREDENTIAL_AUTHORITY_ROLES.includes(role);
39749
40046
  let digest3;
@@ -39792,7 +40089,7 @@ class MoveRefused extends Error {
39792
40089
  }
39793
40090
  }
39794
40091
  async function moveDataset(dataset, ctx, checkArtifacts) {
39795
- const attempt = randomUUID20();
40092
+ const attempt = randomUUID21();
39796
40093
  const files = [];
39797
40094
  for (const slot of dataset.slots)
39798
40095
  files.push({
@@ -39803,7 +40100,7 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
39803
40100
  });
39804
40101
  const sha = (role) => files.find((file) => file.role === role)?.sha256 ?? null;
39805
40102
  await ctx.stack.assertAll();
39806
- const configDirPath = join28(dataset.sub, STATE_HOME_FILE_NAMES.configDirMarker);
40103
+ const configDirPath = join29(dataset.sub, STATE_HOME_FILE_NAMES.configDirMarker);
39807
40104
  if (!await exists3(configDirPath)) {
39808
40105
  const stage = `${configDirPath}.${attempt}.tmp`;
39809
40106
  await createOwnerOnlyFile(ctx.fs, stage, Buffer.from(`${JSON.stringify({ version: 1, identity: dataset.identity })}
@@ -39814,7 +40111,7 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
39814
40111
  await removeOwnStaging(stage);
39815
40112
  }
39816
40113
  }
39817
- const holderFile = join28(dataset.sub, HOLDER_FILE_NAME);
40114
+ const holderFile = join29(dataset.sub, HOLDER_FILE_NAME);
39818
40115
  if (!await exists3(holderFile))
39819
40116
  await writeJsonAtomic(holderFile, { version: 1, entries: [] }, {
39820
40117
  beforeRename: () => ctx.stack.assertAll(),
@@ -39905,8 +40202,8 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
39905
40202
  logger2.error("state-layout", "anthropic-auth could not move its state; keeping the old folder", {
39906
40203
  reason
39907
40204
  });
39908
- const record9 = await rollbackAfterFailure(preparing, dataset, ctx);
39909
- return { status: "rolled-back", reason, record: record9 };
40205
+ const record10 = await rollbackAfterFailure(preparing, dataset, ctx);
40206
+ return { status: "rolled-back", reason, record: record10 };
39910
40207
  }
39911
40208
  const committed = {
39912
40209
  ...preparing,
@@ -39927,8 +40224,8 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
39927
40224
  await syncCommitted(dataset, ctx);
39928
40225
  } else if (onDisk?.phase === "preparing" && onDisk.attempt === attempt) {
39929
40226
  const reason = error instanceof Error ? error.message : String(error);
39930
- const record9 = await rollbackAfterFailure(preparing, dataset, ctx);
39931
- return { status: "rolled-back", reason, record: record9 };
40227
+ const record10 = await rollbackAfterFailure(preparing, dataset, ctx);
40228
+ return { status: "rolled-back", reason, record: record10 };
39932
40229
  } else
39933
40230
  throw error;
39934
40231
  }
@@ -39965,10 +40262,10 @@ async function rollbackAfterFailure(preparing, dataset, ctx) {
39965
40262
  }
39966
40263
 
39967
40264
  // src/state-layout-restore.ts
39968
- import { randomUUID as randomUUID21 } from "node:crypto";
40265
+ import { randomUUID as randomUUID22 } from "node:crypto";
39969
40266
  import { readFile as readFile16 } from "node:fs/promises";
39970
40267
  import { homedir as homedir7 } from "node:os";
39971
- import { join as join29 } from "node:path";
40268
+ import { join as join30 } from "node:path";
39972
40269
  var DATA_ROLES = [
39973
40270
  "localPoolState",
39974
40271
  "localRoster",
@@ -39981,10 +40278,10 @@ function refused2(message, paths = [], cause) {
39981
40278
  logger2.error("state-layout", message, { code: "restore-refused", paths });
39982
40279
  return new StateLayoutRefusalError("restore-refused", message, paths, cause);
39983
40280
  }
39984
- function requireRestoreDetail(record9) {
39985
- const restore = record9.restore;
40281
+ function requireRestoreDetail(record10) {
40282
+ const restore = record10.restore;
39986
40283
  if (!restore?.attempt || !restore.files || !restore.runtimes)
39987
- 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)]);
39988
40285
  return {
39989
40286
  ...restore,
39990
40287
  attempt: restore.attempt,
@@ -40045,9 +40342,9 @@ async function syncObservedRestoreRecord(dataset, ctx) {
40045
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);
40046
40343
  }
40047
40344
  }
40048
- async function finishRestoreRetirement(record9, dataset, ctx) {
40049
- const restore = requireRestoreDetail(record9);
40050
- const kept = [...record9.restore?.kept ?? []];
40345
+ async function finishRestoreRetirement(record10, dataset, ctx) {
40346
+ const restore = requireRestoreDetail(record10);
40347
+ const kept = [...record10.restore?.kept ?? []];
40051
40348
  for (const file of restore.files) {
40052
40349
  try {
40053
40350
  const digest3 = await digestFile(file.to);
@@ -40072,7 +40369,7 @@ async function finishRestoreRetirement(record9, dataset, ctx) {
40072
40369
  await ctx.fs.syncDirectory(dataset.sub);
40073
40370
  await stateLayoutStep(ctx, "restore:sub-flushed");
40074
40371
  const done2 = {
40075
- ...record9,
40372
+ ...record10,
40076
40373
  restore: { ...restore, cleanup: "done", ...kept.length ? { kept } : {} }
40077
40374
  };
40078
40375
  await publishStateLayoutRecord(done2, {
@@ -40083,13 +40380,13 @@ async function finishRestoreRetirement(record9, dataset, ctx) {
40083
40380
  forgetRelocationObservations();
40084
40381
  return done2;
40085
40382
  }
40086
- async function discardAbandonedRestore(record9, dataset, ctx) {
40087
- const restore = requireRestoreDetail(record9);
40383
+ async function discardAbandonedRestore(record10, dataset, ctx) {
40384
+ const restore = requireRestoreDetail(record10);
40088
40385
  for (const file of restore.files)
40089
40386
  if (await exists3(file.staging))
40090
40387
  await owned2(ctx, { kind: "unlink", path: file.staging }, expectPresent(file.staging));
40091
40388
  await ctx.fs.syncDirectory(dataset.oldDir);
40092
- const { restore: _abandoned, ...move } = record9;
40389
+ const { restore: _abandoned, ...move } = record10;
40093
40390
  const committed = { ...move, phase: "committed" };
40094
40391
  await publishStateLayoutRecord(committed, {
40095
40392
  assertLeases: () => ctx.stack.assertAll(),
@@ -40099,8 +40396,8 @@ async function discardAbandonedRestore(record9, dataset, ctx) {
40099
40396
  forgetRelocationObservations();
40100
40397
  return committed;
40101
40398
  }
40102
- async function classifyStagedRestore(record9, dataset) {
40103
- const restore = requireRestoreDetail(record9);
40399
+ async function classifyStagedRestore(record10, dataset) {
40400
+ const restore = requireRestoreDetail(record10);
40104
40401
  const problems = [];
40105
40402
  const listed = (role) => restore.files.find((file) => file.role === role);
40106
40403
  const isStaged = async (file) => {
@@ -40160,7 +40457,7 @@ async function classifyStagedRestore(record9, dataset) {
40160
40457
  if (!file)
40161
40458
  continue;
40162
40459
  const staged = await isStaged(file);
40163
- if (staged && tombstone === record9.attempt)
40460
+ if (staged && tombstone === record10.attempt)
40164
40461
  barriers.push({
40165
40462
  role,
40166
40463
  action: { kind: "rename", file, over: "tombstone" }
@@ -40172,7 +40469,7 @@ async function classifyStagedRestore(record9, dataset) {
40172
40469
  problems.push(`${file.staging} is missing, so ${legacy} can't be restored`);
40173
40470
  else
40174
40471
  problems.push(`${legacy} is no longer this move's tombstone while ${file.staging} still waits to replace it`);
40175
- } else if (tombstone === record9.attempt)
40472
+ } else if (tombstone === record10.attempt)
40176
40473
  barriers.push({
40177
40474
  role,
40178
40475
  action: { kind: "unlink-tombstone", path: legacy }
@@ -40191,36 +40488,36 @@ async function classifyStagedRestore(record9, dataset) {
40191
40488
  }
40192
40489
  return { data, barriers, problems };
40193
40490
  }
40194
- async function act(action, record9, ctx) {
40491
+ async function act(action, record10, ctx) {
40195
40492
  if (action.kind === "none")
40196
40493
  return;
40197
40494
  if (action.kind === "unlink-tombstone") {
40198
- 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));
40199
40496
  return;
40200
40497
  }
40201
40498
  const { file, over } = action;
40202
- 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);
40203
40500
  await owned2(ctx, { kind: "rename", from: file.staging, to: file.from }, both(expectDigest(file.staging, file.sha256), target2));
40204
40501
  }
40205
- async function finishStagedRestore(record9, dataset, ctx) {
40206
- const restore = requireRestoreDetail(record9);
40207
- 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);
40208
40505
  if (plan2.problems.length)
40209
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]);
40210
40507
  for (const { role, action } of plan2.data) {
40211
- await act(action, record9, ctx);
40508
+ await act(action, record10, ctx);
40212
40509
  await stateLayoutStep(ctx, `restore:placed:${role}`);
40213
40510
  }
40214
40511
  await ctx.fs.syncDirectory(dataset.oldDir);
40215
40512
  await stateLayoutStep(ctx, "restore:data-flushed");
40216
40513
  for (const { role, action } of plan2.barriers) {
40217
- await act(action, record9, ctx);
40514
+ await act(action, record10, ctx);
40218
40515
  await stateLayoutStep(ctx, `restore:placed:${role}`);
40219
40516
  }
40220
40517
  await ctx.fs.syncDirectory(dataset.oldDir);
40221
40518
  await stateLayoutStep(ctx, "restore:barriers-flushed");
40222
40519
  const restored = {
40223
- ...record9,
40520
+ ...record10,
40224
40521
  phase: "restored",
40225
40522
  restore: { ...restore, cleanup: "pending" }
40226
40523
  };
@@ -40232,41 +40529,41 @@ async function finishStagedRestore(record9, dataset, ctx) {
40232
40529
  forgetRelocationObservations();
40233
40530
  return finishRestoreRetirement(restored, dataset, ctx);
40234
40531
  }
40235
- async function newRestoreProblems(record9, dataset, options) {
40532
+ async function newRestoreProblems(record10, dataset, options) {
40236
40533
  const problems = [];
40237
- if (record9.cleanup === "pending")
40534
+ if (record10.cleanup === "pending")
40238
40535
  problems.push("the move has not finished removing the old copies; start OpenCode with anthropic-auth once and close it again");
40239
- if (record9.cleanup === "conflict")
40240
- for (const pair of record9.conflict ?? [])
40536
+ if (record10.cleanup === "conflict")
40537
+ for (const pair of record10.conflict ?? [])
40241
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`);
40242
- if (record9.cleanup === "kept") {
40243
- for (const path2 of record9.kept ?? [])
40539
+ if (record10.cleanup === "kept") {
40540
+ for (const path2 of record10.kept ?? [])
40244
40541
  if (await exists3(path2))
40245
40542
  problems.push(`${path2} changed after the move and was kept; move it aside or delete it`);
40246
40543
  }
40247
- 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));
40248
40545
  const artifacts = options.artifacts ?? defaultPreNArtifactLocations(options.env ?? process.env, options.home ?? homedir7());
40249
40546
  for (const blocker of await preNArtifactBlockers(artifacts, options.liveness?.pidAlive, options.liveness))
40250
40547
  problems.push(`${describeFenceBlocker(blocker)} is still running`);
40251
40548
  for (const slot of dataset.slots) {
40252
40549
  if (slot.role === "localRuntime" || slot.role === "vaultRuntime") {
40253
- if (await tombstoneAttempt(slot.from) !== record9.attempt)
40550
+ if (await tombstoneAttempt(slot.from) !== record10.attempt)
40254
40551
  problems.push(`${slot.from} is no longer the marker the move left there; move it aside`);
40255
40552
  continue;
40256
40553
  }
40257
40554
  if (await exists3(slot.from))
40258
40555
  problems.push(`${slot.from} came back after the move; move it aside or delete it`);
40259
40556
  }
40260
- const moving = movingJournalPath(dataset.oldPaths.journal, record9.attempt);
40557
+ const moving = movingJournalPath(dataset.oldPaths.journal, record10.attempt);
40261
40558
  if (await exists3(moving))
40262
40559
  problems.push(`${moving} is still there; move it aside or delete it`);
40263
40560
  return problems;
40264
40561
  }
40265
- async function startRestore(record9, dataset, ctx, options) {
40266
- const problems = await newRestoreProblems(record9, dataset, options);
40562
+ async function startRestore(record10, dataset, ctx, options) {
40563
+ const problems = await newRestoreProblems(record10, dataset, options);
40267
40564
  if (problems.length)
40268
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]);
40269
- const attempt = randomUUID21();
40566
+ const attempt = randomUUID22();
40270
40567
  const files = [];
40271
40568
  for (const slot of dataset.slots) {
40272
40569
  let digest3;
@@ -40287,7 +40584,7 @@ async function startRestore(record9, dataset, ctx, options) {
40287
40584
  }
40288
40585
  const listed = (role) => files.some((file) => file.role === role);
40289
40586
  const restoring = {
40290
- ...record9,
40587
+ ...record10,
40291
40588
  phase: "restoring",
40292
40589
  restore: {
40293
40590
  attempt,
@@ -40305,7 +40602,7 @@ async function startRestore(record9, dataset, ctx, options) {
40305
40602
  const current = await readStateLayoutRecord(dataset.sub).catch(() => {
40306
40603
  return;
40307
40604
  });
40308
- 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";
40309
40606
  }
40310
40607
  }, ctx.fs);
40311
40608
  await stateLayoutStep(ctx, "restore:restoring-written");
@@ -40330,11 +40627,11 @@ async function startRestore(record9, dataset, ctx, options) {
40330
40627
  await stateLayoutStep(ctx, "restore:staged-written");
40331
40628
  return finishStagedRestore(staged, dataset, ctx);
40332
40629
  }
40333
- function requireRecordMatches(record9, dataset) {
40630
+ function requireRecordMatches(record10, dataset) {
40334
40631
  const path2 = layoutRecordPath(dataset.sub);
40335
- 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)
40336
- 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]);
40337
- 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);
40338
40635
  if (problem)
40339
40636
  throw new StateLayoutRefusalError("marker-unreadable", `anthropic-auth can't use ${path2}: ${problem}.`, [path2]);
40340
40637
  }
@@ -40346,12 +40643,12 @@ async function readRecord(sub) {
40346
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);
40347
40644
  }
40348
40645
  }
40349
- function finished(record9) {
40350
- if (record9 === undefined)
40646
+ function finished(record10) {
40647
+ if (record10 === undefined)
40351
40648
  return "anthropic-auth has not moved this state out of the config folder";
40352
- if (record9.phase === "rolled-back")
40649
+ if (record10.phase === "rolled-back")
40353
40650
  return "the move of this state was undone before it finished";
40354
- if (record9.phase === "restored" && record9.restore?.cleanup === "done")
40651
+ if (record10.phase === "restored" && record10.restore?.cleanup === "done")
40355
40652
  return "this state was already restored to the config folder";
40356
40653
  return;
40357
40654
  }
@@ -40416,32 +40713,32 @@ async function restoreLegacyLayout(options = {}) {
40416
40713
  }
40417
40714
  await stateLayoutStep(ctx, "restore:locks-held");
40418
40715
  for (let round = 0;round < 3; round++) {
40419
- const record9 = await readRecord(sub);
40420
- const done2 = finished(record9);
40421
- if (done2 || !record9)
40716
+ const record10 = await readRecord(sub);
40717
+ const done2 = finished(record10);
40718
+ if (done2 || !record10)
40422
40719
  return { status: "not-moved", reason: done2 ?? "" };
40423
- requireRecordMatches(record9, dataset);
40720
+ requireRecordMatches(record10, dataset);
40424
40721
  let result;
40425
- switch (record9.phase) {
40722
+ switch (record10.phase) {
40426
40723
  case "preparing":
40427
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)]);
40428
40725
  case "restoring":
40429
- await discardAbandonedRestore(record9, dataset, ctx);
40726
+ await discardAbandonedRestore(record10, dataset, ctx);
40430
40727
  continue;
40431
40728
  case "committed":
40432
- result = await startRestore(record9, dataset, ctx, options);
40729
+ result = await startRestore(record10, dataset, ctx, options);
40433
40730
  break;
40434
40731
  case "restore-staged": {
40435
40732
  await syncObservedRestoreRecord(dataset, ctx);
40436
- 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);
40437
40734
  if (problems.length)
40438
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]);
40439
- result = await finishStagedRestore(record9, dataset, ctx);
40736
+ result = await finishStagedRestore(record10, dataset, ctx);
40440
40737
  break;
40441
40738
  }
40442
40739
  default:
40443
40740
  await syncObservedRestoreRecord(dataset, ctx);
40444
- result = await finishRestoreRetirement(record9, dataset, ctx);
40741
+ result = await finishRestoreRetirement(record10, dataset, ctx);
40445
40742
  }
40446
40743
  return {
40447
40744
  status: "restored",
@@ -40499,13 +40796,13 @@ function configIdentity(configDir) {
40499
40796
  refuse5("io-failed", `anthropic-auth can't resolve its config folder ${configDir}: ${errorMessage(error)}`, [configDir], error);
40500
40797
  }
40501
40798
  }
40502
- function noMoveRecord(record9) {
40503
- 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";
40504
40801
  }
40505
- function requireRecordMatches2(record9, dataset) {
40506
- 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)
40507
- 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]);
40508
- 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);
40509
40806
  if (problem)
40510
40807
  markerUnreadable(dataset.sub, new Error(problem));
40511
40808
  }
@@ -40548,7 +40845,7 @@ function deferLegacyRegistration(paths, dir, options, error) {
40548
40845
  }
40549
40846
  async function registerLegacyHeld(oldDir, paths, identity3, options, ctx) {
40550
40847
  try {
40551
- 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);
40552
40849
  return;
40553
40850
  } catch (error) {
40554
40851
  if (unmovedRegistrationPolicy(options) === "mandatory")
@@ -40568,10 +40865,10 @@ function chooseLegacy(paths, reasons2, log2, registration) {
40568
40865
  };
40569
40866
  }
40570
40867
  async function admitHeld(dataset, options, ctx, moved, allowPendingCleanup) {
40571
- const record9 = await readRecord2(dataset.sub);
40572
- if (record9?.phase !== "committed" || !allowPendingCleanup && record9.cleanup === "pending")
40868
+ const record10 = await readRecord2(dataset.sub);
40869
+ if (record10?.phase !== "committed" || !allowPendingCleanup && record10.cleanup === "pending")
40573
40870
  return "changed";
40574
- requireRecordMatches2(record9, dataset);
40871
+ requireRecordMatches2(record10, dataset);
40575
40872
  const conflict = await checkStateHomeServing(stateHomeServingFiles(dataset.newPaths));
40576
40873
  if (conflict) {
40577
40874
  logger2.error("state-layout", conflict.message, {
@@ -40580,15 +40877,15 @@ async function admitHeld(dataset, options, ctx, moved, allowPendingCleanup) {
40580
40877
  });
40581
40878
  throw conflict;
40582
40879
  }
40583
- await warnReappearedMetadata(record9);
40584
- 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);
40585
40882
  const layout = { kind: "state-home", dir: dataset.sub };
40586
40883
  recordProcessStateLayout(dataset.oldPaths.legacyConfig, layout);
40587
- return { kind: "state-home", layout, dataset, record: record9, moved };
40884
+ return { kind: "state-home", layout, dataset, record: record10, moved };
40588
40885
  }
40589
40886
  async function admitFast(dataset, options, ctx) {
40590
40887
  try {
40591
- await acquireHolderLock(ctx, join30(dataset.sub, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40888
+ await acquireHolderLock(ctx, join31(dataset.sub, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40592
40889
  } catch (error) {
40593
40890
  if (error instanceof LockContentionError)
40594
40891
  busy(dataset.configDir, error);
@@ -40630,12 +40927,12 @@ async function readPointers(dataset) {
40630
40927
  }
40631
40928
  async function legacyHeld(dataset, options, ctx, reasons2, log2 = true) {
40632
40929
  const pointed = await readPointers(dataset);
40633
- const record9 = await readRecord2(dataset.sub);
40634
- if (record9)
40635
- requireRecordMatches2(record9, dataset);
40636
- if (pointed && noMoveRecord(record9))
40930
+ const record10 = await readRecord2(dataset.sub);
40931
+ if (record10)
40932
+ requireRecordMatches2(record10, dataset);
40933
+ if (pointed && noMoveRecord(record10))
40637
40934
  markerUnreadable(dataset.sub);
40638
- if (pointed || !noMoveRecord(record9))
40935
+ if (pointed || !noMoveRecord(record10))
40639
40936
  return "changed";
40640
40937
  const registration = await registerLegacyHeld(dataset.oldDir, dataset.oldPaths, dataset.identity, options, ctx);
40641
40938
  return chooseLegacy(dataset.oldPaths, reasons2, log2, registration);
@@ -40653,7 +40950,7 @@ async function oldFolderTransition(old, recordedMovingJournal) {
40653
40950
  }
40654
40951
  let names2;
40655
40952
  try {
40656
- names2 = await readdir8(dirname25(journal));
40953
+ names2 = await readdir9(dirname25(journal));
40657
40954
  } catch (error) {
40658
40955
  if (error?.code === "ENOENT")
40659
40956
  return false;
@@ -40674,10 +40971,10 @@ async function recordedMovingJournal(journal, identity3, options) {
40674
40971
  env: options.env ?? process.env,
40675
40972
  home: options.home ?? homedir8()
40676
40973
  });
40677
- const record9 = await readStateLayoutRecord(await canonicalPath(target2.dir));
40678
- if (record9?.barriers.journal !== "present")
40974
+ const record10 = await readStateLayoutRecord(await canonicalPath(target2.dir));
40975
+ if (record10?.barriers.journal !== "present")
40679
40976
  return;
40680
- return movingJournalPath(journal, record9.attempt);
40977
+ return movingJournalPath(journal, record10.attempt);
40681
40978
  } catch {
40682
40979
  return;
40683
40980
  }
@@ -40696,7 +40993,7 @@ async function legacyWhileMoveOff(configDir, identity3, options, ctx, stayReason
40696
40993
  await stateLayoutStep(ctx, "old-holders-locking");
40697
40994
  let lockFailure;
40698
40995
  try {
40699
- await acquireHolderLock(ctx, join30(old.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40996
+ await acquireHolderLock(ctx, join31(old.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40700
40997
  } catch (error) {
40701
40998
  lockFailure = { error };
40702
40999
  }
@@ -40726,8 +41023,8 @@ async function decideOpenCodeStateLayout(options) {
40726
41023
  holderLockTimeoutMs: options.timeouts?.holderMs
40727
41024
  });
40728
41025
  if (isExplicit(env)) {
40729
- const legacyConfig = env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join30(configDir, ACCOUNT_FILE2);
40730
- 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`);
40731
41028
  const paths = await resolveNativePoolPaths(legacyConfig, legacyState, LEGACY_STATE_LAYOUT);
40732
41029
  const registration = await registerNativePoolHolder({
40733
41030
  paths,
@@ -40750,7 +41047,7 @@ async function decideOpenCodeStateLayout(options) {
40750
41047
  } catch (error) {
40751
41048
  if (unmovedRegistrationPolicy(options) === "mandatory")
40752
41049
  throw new HolderRegistrationError("unavailable", configDir, error);
40753
- 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);
40754
41051
  return chooseLegacy(paths, [reason], true, deferLegacyRegistration(paths, configDir, options, error));
40755
41052
  }
40756
41053
  identity3 = configIdentity(configDir);
@@ -40801,26 +41098,26 @@ async function decideOpenCodeStateLayout(options) {
40801
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]);
40802
41099
  const pointed = await readPointers(dataset);
40803
41100
  for (let round = 0;round < 3; round++) {
40804
- const record9 = await readRecord2(sub);
40805
- if (record9)
40806
- requireRecordMatches2(record9, dataset);
40807
- if (pointed && noMoveRecord(record9))
41101
+ const record10 = await readRecord2(sub);
41102
+ if (record10)
41103
+ requireRecordMatches2(record10, dataset);
41104
+ if (pointed && noMoveRecord(record10))
40808
41105
  markerUnreadable(sub);
40809
- if (record9?.phase === "restore-staged")
41106
+ if (record10?.phase === "restore-staged")
40810
41107
  restoreUnfinished(dataset.oldDir);
40811
- if (record9?.phase === "committed" && (record9.cleanup === "done" || record9.cleanup === "kept")) {
41108
+ if (record10?.phase === "committed" && (record10.cleanup === "done" || record10.cleanup === "kept")) {
40812
41109
  const admitted = await admitFast(dataset, options, newContext());
40813
41110
  if (admitted !== "changed")
40814
41111
  return admitted;
40815
41112
  continue;
40816
41113
  }
40817
- if ((overrides.length || neverMove.length || !moveEnabled) && noMoveRecord(record9)) {
41114
+ if ((overrides.length || neverMove.length || !moveEnabled) && noMoveRecord(record10)) {
40818
41115
  const ctx = newContext();
40819
41116
  const reasons2 = stayReasons.length ? stayReasons : [RELOCATION_MOVE_DISABLED_REASON];
40820
41117
  try {
40821
41118
  await stateLayoutStep(ctx, "old-holders-locking");
40822
41119
  try {
40823
- await acquireHolderLock(ctx, join30(dataset.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
41120
+ await acquireHolderLock(ctx, join31(dataset.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40824
41121
  } catch (error) {
40825
41122
  if (unmovedRegistrationPolicy(options) === "mandatory")
40826
41123
  throw error;
@@ -40855,8 +41152,8 @@ async function decideOpenCodeStateLayout(options) {
40855
41152
  } catch (error) {
40856
41153
  if (!(error instanceof LockContentionError))
40857
41154
  refuse5("io-failed", `anthropic-auth can't take the layout lock beside ${layoutRecordPath(sub)}: ${errorMessage(error)}`, [layoutRecordPath(sub)], error);
40858
- const record9 = await readRecord2(sub);
40859
- 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")) {
40860
41157
  const admitted = await admitFast(dataset, options, newContext());
40861
41158
  if (admitted !== "changed")
40862
41159
  return admitted;
@@ -40884,7 +41181,7 @@ async function ensureSubfolder(sub, fs3) {
40884
41181
  await ensureWindowsOwnerOnlyDirectory(sub);
40885
41182
  return;
40886
41183
  }
40887
- const created = await mkdir18(sub, { recursive: true, mode: 448 });
41184
+ const created = await mkdir19(sub, { recursive: true, mode: 448 });
40888
41185
  if (created === undefined)
40889
41186
  return;
40890
41187
  for (let dir = dirname25(sub);; dir = dirname25(dir)) {
@@ -40899,36 +41196,36 @@ async function ensureSubfolder(sub, fs3) {
40899
41196
  }
40900
41197
  }
40901
41198
  async function underLayoutLock(dataset, options, ctx, overrides, neverMove) {
40902
- const record9 = await readRecord2(dataset.sub);
40903
- if (record9)
40904
- requireRecordMatches2(record9, dataset);
40905
- 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")
40906
41203
  restoreUnfinished(dataset.oldDir);
40907
- if (record9?.phase === "restoring" || record9?.phase === "restored" && record9.restore?.cleanup !== "done") {
41204
+ if (record10?.phase === "restoring" || record10?.phase === "restored" && record10.restore?.cleanup !== "done") {
40908
41205
  if (overrides.length)
40909
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)]);
40910
41207
  await acquireHolderLocks(dataset, ctx);
40911
- if (record9.phase === "restoring")
40912
- await discardAbandonedRestore(record9, dataset, ctx);
41208
+ if (record10.phase === "restoring")
41209
+ await discardAbandonedRestore(record10, dataset, ctx);
40913
41210
  else {
40914
41211
  await syncObservedRestoreRecord(dataset, ctx);
40915
- await finishRestoreRetirement(record9, dataset, ctx);
41212
+ await finishRestoreRetirement(record10, dataset, ctx);
40916
41213
  }
40917
41214
  return "again";
40918
41215
  }
40919
- if (record9?.phase === "committed") {
41216
+ if (record10?.phase === "committed") {
40920
41217
  try {
40921
41218
  await syncCommitted(dataset, ctx);
40922
41219
  } catch (error) {
40923
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);
40924
41221
  }
40925
41222
  await acquireHolderLocks(dataset, ctx);
40926
- if ((record9.cleanup === "pending" || record9.cleanup === "conflict") && !overrides.length) {
41223
+ if ((record10.cleanup === "pending" || record10.cleanup === "conflict") && !overrides.length) {
40927
41224
  const mark = ctx.stack.size;
40928
41225
  try {
40929
41226
  await drainCoalescedWrites(dataset);
40930
41227
  await acquireDataLocks(dataset, ctx);
40931
- await cleanupOldCopies(record9, dataset, ctx);
41228
+ await cleanupOldCopies(record10, dataset, ctx);
40932
41229
  } catch (error) {
40933
41230
  if (error instanceof StateLayoutCrash)
40934
41231
  throw error;
@@ -40942,13 +41239,13 @@ async function underLayoutLock(dataset, options, ctx, overrides, neverMove) {
40942
41239
  const admitted2 = await admitHeld(dataset, options, ctx, false, true);
40943
41240
  return admitted2 === "changed" ? "again" : admitted2;
40944
41241
  }
40945
- if (record9?.phase === "preparing") {
41242
+ if (record10?.phase === "preparing") {
40946
41243
  if (overrides.length)
40947
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)]);
40948
41245
  await acquireHolderLocks(dataset, ctx);
40949
41246
  await drainCoalescedWrites(dataset);
40950
41247
  await acquireDataLocks(dataset, ctx);
40951
- await rollbackPreparing(record9, dataset, ctx);
41248
+ await rollbackPreparing(record10, dataset, ctx);
40952
41249
  return "again";
40953
41250
  }
40954
41251
  const stay = async (reasons2, log2 = true) => {
@@ -41132,6 +41429,136 @@ function isRecord20(value) {
41132
41429
  function supportsTurnEndNote(model) {
41133
41430
  return resolveClaudeModelCapabilities(model)?.turnEndNote === true;
41134
41431
  }
41432
+ var runnerReports = new Map;
41433
+ var SKIP_REPORT_LIMIT = 512;
41434
+ var RUNNER_REPORT_SESSION_LIMIT = 1024;
41435
+ function readRunnerNotes(handle) {
41436
+ try {
41437
+ const read = handle.turn_notes;
41438
+ if (typeof read !== "function")
41439
+ return [];
41440
+ const answer = read.call(handle);
41441
+ if (answer !== null && (typeof answer === "object" || typeof answer === "function") && typeof Reflect.get(answer, "then") === "function") {
41442
+ Promise.resolve(answer).catch(() => {});
41443
+ return [];
41444
+ }
41445
+ if (!Array.isArray(answer))
41446
+ return [];
41447
+ const notes = [];
41448
+ for (let index = 0;index < answer.length; index++) {
41449
+ try {
41450
+ const entry2 = answer[index];
41451
+ if (!isRecord20(entry2) || Array.isArray(entry2))
41452
+ continue;
41453
+ const { after_tool_use_id, text: text6 } = entry2;
41454
+ if (typeof after_tool_use_id !== "string" || typeof text6 !== "string" || !text6.trim() || new TextEncoder().encode(text6).byteLength > 16384)
41455
+ continue;
41456
+ notes.push({ after_tool_use_id, text: text6 });
41457
+ } catch {}
41458
+ }
41459
+ return notes;
41460
+ } catch {
41461
+ return [];
41462
+ }
41463
+ }
41464
+ function runnerNotes(sessionId) {
41465
+ try {
41466
+ const routing = Reflect.get(globalThis, Symbol.for("cortexkit.routing"));
41467
+ if (typeof routing !== "function")
41468
+ return;
41469
+ const handle = routing(sessionId);
41470
+ if (isRecord20(handle) && typeof handle.turn_notes === "function")
41471
+ return { handle, notes: readRunnerNotes(handle) };
41472
+ } catch {
41473
+ return;
41474
+ }
41475
+ }
41476
+ function reportRunnerNote(handle, payload) {
41477
+ Promise.resolve().then(() => {
41478
+ const report = handle.report;
41479
+ if (typeof report === "function")
41480
+ return report.call(handle, payload);
41481
+ }).catch(() => {});
41482
+ }
41483
+ function applyRunnerTurnNotes(body, options) {
41484
+ if (!options.sessionId)
41485
+ return 0;
41486
+ const runner = runnerNotes(options.sessionId);
41487
+ if (!runner)
41488
+ return 0;
41489
+ let reported3 = runnerReports.get(options.sessionId);
41490
+ if (reported3) {
41491
+ runnerReports.delete(options.sessionId);
41492
+ } else {
41493
+ reported3 = { models: new Map, skipped: new Set };
41494
+ if (runnerReports.size >= RUNNER_REPORT_SESSION_LIMIT) {
41495
+ const oldest = runnerReports.keys().next();
41496
+ if (!oldest.done)
41497
+ runnerReports.delete(oldest.value);
41498
+ }
41499
+ }
41500
+ runnerReports.set(options.sessionId, reported3);
41501
+ const supported = options.isOAuth && supportsTurnEndNote(body.model);
41502
+ const model = options.modelId;
41503
+ if (reported3.models.get(model) !== supported) {
41504
+ reported3.models.set(model, supported);
41505
+ reportRunnerNote(runner.handle, {
41506
+ kind: "turn_notes_supported",
41507
+ model,
41508
+ supported
41509
+ });
41510
+ }
41511
+ const messages = Array.isArray(body.messages) ? body.messages : [];
41512
+ const anchors = new Map;
41513
+ for (const [index, message] of messages.entries()) {
41514
+ if (!isRecord20(message) || message.role !== "user" || !Array.isArray(message.content))
41515
+ continue;
41516
+ for (const block of message.content) {
41517
+ if (isRecord20(block) && block.type === "tool_result" && typeof block.tool_use_id === "string" && !anchors.has(block.tool_use_id))
41518
+ anchors.set(block.tool_use_id, index);
41519
+ }
41520
+ }
41521
+ const insertions = new Map;
41522
+ let inserted = 0;
41523
+ for (const note of runner.notes) {
41524
+ const index = anchors.get(note.after_tool_use_id);
41525
+ const next = index === undefined ? undefined : messages[index + 1];
41526
+ const reason = !options.isOAuth ? "not_oauth" : !supported ? "unsupported_model" : index === undefined ? "anchor_missing" : isRecord20(next) && next.role === "user" ? "before_user_message" : undefined;
41527
+ if (reason) {
41528
+ if (!reported3.skipped.has(note.after_tool_use_id)) {
41529
+ if (reported3.skipped.size >= SKIP_REPORT_LIMIT) {
41530
+ const oldest = reported3.skipped.values().next();
41531
+ if (!oldest.done)
41532
+ reported3.skipped.delete(oldest.value);
41533
+ }
41534
+ reported3.skipped.add(note.after_tool_use_id);
41535
+ reportRunnerNote(runner.handle, {
41536
+ kind: "turn_note_skipped",
41537
+ after_tool_use_id: note.after_tool_use_id,
41538
+ reason
41539
+ });
41540
+ }
41541
+ continue;
41542
+ }
41543
+ if (index === undefined)
41544
+ continue;
41545
+ const bucket = insertions.get(index) ?? [];
41546
+ bucket.push(note);
41547
+ insertions.set(index, bucket);
41548
+ inserted++;
41549
+ }
41550
+ if (inserted) {
41551
+ body.messages = messages.flatMap((message, index) => [
41552
+ message,
41553
+ ...(insertions.get(index) ?? []).map((note) => ({
41554
+ role: "system",
41555
+ clear_at: "next_user_message",
41556
+ content: note.text
41557
+ }))
41558
+ ]);
41559
+ }
41560
+ return inserted;
41561
+ }
41135
41562
  function applyTurnEndNotes(body, options = {}) {
41136
41563
  if (!supportsTurnEndNote(body.model) || !Array.isArray(body.messages))
41137
41564
  return 0;
@@ -41181,6 +41608,7 @@ export {
41181
41608
  writerStamp,
41182
41609
  writeNativeHostAuth,
41183
41610
  writeDumpFile,
41611
+ withNativeLock,
41184
41612
  withAbortableFetch,
41185
41613
  usesPerTurnControl,
41186
41614
  usagePublicationRefusalIsFatal,
@@ -41367,6 +41795,7 @@ export {
41367
41795
  logger2 as logger,
41368
41796
  log,
41369
41797
  localDayKey,
41798
+ legacyCacheKeepStoreDirectory,
41370
41799
  killswitchRetryAfterSeconds,
41371
41800
  killswitchPassesPolicy,
41372
41801
  isWithinCacheKeepWindow,
@@ -41563,6 +41992,7 @@ export {
41563
41992
  captureNativeLocalPoolBinding,
41564
41993
  canonicalPath,
41565
41994
  cacheWarmCacheablePrefixFingerprint,
41995
+ cacheKeepStoreDirectory,
41566
41996
  cacheKeepSourceWarmIdleCap,
41567
41997
  buildRoutingStatusSummary,
41568
41998
  buildRefreshOperationError,
@@ -41591,6 +42021,7 @@ export {
41591
42021
  askRouting,
41592
42022
  applyTurnEndNotes,
41593
42023
  applyThinkingBindingControls,
42024
+ applyRunnerTurnNotes,
41594
42025
  applyMidConversationOutputConfig,
41595
42026
  applyCustomHeaders,
41596
42027
  applyClaudeCodeMetadata,
@@ -41700,6 +42131,7 @@ export {
41700
42131
  ClaudeUnsupportedAccessError,
41701
42132
  ClaudeOAuthRefreshError,
41702
42133
  ClaudeCodeFirstUserTextTracker,
42134
+ CacheKeepStore,
41703
42135
  CacheKeepSessionRegistry,
41704
42136
  CacheKeepPrewarmError,
41705
42137
  CacheKeepManager,