@cortexkit/anthropic-auth-core 2.5.5 → 2.5.7

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
@@ -14,6 +14,39 @@ function routingHandle(sessionId) {
14
14
  function isObject(value) {
15
15
  return typeof value === "object" && value !== null;
16
16
  }
17
+ function turnNotes(sessionId) {
18
+ try {
19
+ const handle = routingHandle(sessionId);
20
+ if (!handle)
21
+ return [];
22
+ const read = handle.turn_notes;
23
+ if (typeof read !== "function")
24
+ return [];
25
+ const answer = read.call(handle);
26
+ if (isObject(answer) && typeof answer.then === "function") {
27
+ Promise.resolve(answer).catch(() => {});
28
+ return [];
29
+ }
30
+ if (!Array.isArray(answer))
31
+ return [];
32
+ const notes = [];
33
+ const encoder = new TextEncoder;
34
+ for (const entry of answer) {
35
+ try {
36
+ if (!isObject(entry) || Array.isArray(entry))
37
+ continue;
38
+ const afterToolUseId = entry.after_tool_use_id;
39
+ const text = entry.text;
40
+ if (typeof afterToolUseId !== "string" || afterToolUseId.length === 0 || typeof text !== "string" || text.trim().length === 0 || encoder.encode(text).byteLength > 16384)
41
+ continue;
42
+ notes.push({ afterToolUseId, text });
43
+ } catch {}
44
+ }
45
+ return notes;
46
+ } catch {
47
+ return [];
48
+ }
49
+ }
17
50
  function selectionFor(answer, candidates) {
18
51
  if (!isObject(answer))
19
52
  return;
@@ -76,32 +109,61 @@ function reportRouting(input) {
76
109
  const report = handle.report;
77
110
  if (typeof report !== "function")
78
111
  return;
79
- const identity = {
80
- account_id: input.accountId,
81
- ...input.credentialId !== undefined ? { credential_id: input.credentialId } : {}
82
- };
83
112
  let payload;
84
- switch (input.outcome) {
85
- case "served":
86
- payload = { ...identity, outcome: "served", headers: input.headers };
87
- break;
88
- case "exhausted": {
89
- const { window, pool } = input;
90
- if (window !== "5h" && window !== "7d")
113
+ if ("kind" in input) {
114
+ switch (input.kind) {
115
+ case "turn_notes_supported": {
116
+ const { model, supported } = input;
117
+ if (typeof model !== "string" || model.length === 0 || typeof supported !== "boolean")
118
+ return;
119
+ payload = {
120
+ kind: "turn_notes_supported",
121
+ model,
122
+ supported
123
+ };
124
+ break;
125
+ }
126
+ case "turn_note_skipped": {
127
+ const { after_tool_use_id, reason } = input;
128
+ if (typeof after_tool_use_id !== "string" || after_tool_use_id.length === 0 || reason !== "anchor_missing" && reason !== "before_user_message" && reason !== "unsupported_model" && reason !== "not_oauth")
129
+ return;
130
+ payload = {
131
+ kind: "turn_note_skipped",
132
+ after_tool_use_id,
133
+ reason
134
+ };
135
+ break;
136
+ }
137
+ default:
91
138
  return;
92
- if (pool !== undefined && (typeof pool !== "string" || !/^[a-z0-9._-]{1,64}$/.test(pool)))
139
+ }
140
+ } else {
141
+ const identity = {
142
+ account_id: input.accountId,
143
+ ...input.credentialId !== undefined ? { credential_id: input.credentialId } : {}
144
+ };
145
+ switch (input.outcome) {
146
+ case "served":
147
+ payload = { ...identity, outcome: "served", headers: input.headers };
148
+ break;
149
+ case "exhausted": {
150
+ const { window, pool } = input;
151
+ if (window !== "5h" && window !== "7d")
152
+ return;
153
+ if (pool !== undefined && (typeof pool !== "string" || !/^[a-z0-9._-]{1,64}$/.test(pool)))
154
+ return;
155
+ payload = {
156
+ ...identity,
157
+ outcome: "exhausted",
158
+ window,
159
+ ...pool ? { pool } : {},
160
+ ...input.resetsAt !== undefined ? { resets_at: input.resetsAt } : {}
161
+ };
162
+ break;
163
+ }
164
+ default:
93
165
  return;
94
- payload = {
95
- ...identity,
96
- outcome: "exhausted",
97
- window,
98
- ...pool ? { pool } : {},
99
- ...input.resetsAt !== undefined ? { resets_at: input.resetsAt } : {}
100
- };
101
- break;
102
166
  }
103
- default:
104
- return;
105
167
  }
106
168
  const pending = report.call(handle, payload);
107
169
  if (isObject(pending) && typeof pending.then === "function") {
@@ -802,7 +864,7 @@ var WRITER_LOCK_CONSTANTS = Object.freeze({
802
864
  });
803
865
  // ../../node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
804
866
  import { randomUUID as randomUUID3 } from "node:crypto";
805
- import { lstat as lstat3, mkdir as mkdir2, open as open2, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2 } from "node:fs/promises";
867
+ import { link, lstat as lstat3, mkdir as mkdir2, open as open2, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2 } from "node:fs/promises";
806
868
  import { dirname as dirname3, join as join3 } from "node:path";
807
869
 
808
870
  // ../../node_modules/@cortexkit/common-auth/dist/fs/with-lock.js
@@ -878,7 +940,35 @@ async function withLock(target, options, fn) {
878
940
  }
879
941
 
880
942
  // ../../node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
943
+ var leaseCreationTestHooks;
881
944
  async function createExclusiveText(path, text) {
945
+ const tempPath = `${path}.${randomUUID3()}.tmp`;
946
+ let handle;
947
+ try {
948
+ handle = await open2(tempPath, "wx", 384);
949
+ try {
950
+ if (leaseCreationTestHooks?.beforeWrite)
951
+ await leaseCreationTestHooks.beforeWrite(tempPath);
952
+ await handle.writeFile(text, "utf8");
953
+ } finally {
954
+ await handle.close();
955
+ }
956
+ try {
957
+ if (leaseCreationTestHooks?.beforeLink)
958
+ await leaseCreationTestHooks.beforeLink(tempPath, path);
959
+ await link(tempPath, path);
960
+ } catch (error) {
961
+ const code = error.code;
962
+ if (code !== "EPERM" && code !== "ENOTSUP" && code !== "EOPNOTSUPP" && code !== "EXDEV")
963
+ throw error;
964
+ await writeExclusiveText(path, text);
965
+ }
966
+ } finally {
967
+ if (handle)
968
+ await rm2(tempPath, { force: true }).catch(() => {});
969
+ }
970
+ }
971
+ async function writeExclusiveText(path, text) {
882
972
  const handle = await open2(path, "wx", 384);
883
973
  let createdStat;
884
974
  try {
@@ -887,6 +977,8 @@ async function createExclusiveText(path, text) {
887
977
  createdStat = undefined;
888
978
  }
889
979
  try {
980
+ if (leaseCreationTestHooks?.beforeWrite)
981
+ await leaseCreationTestHooks.beforeWrite(path);
890
982
  await handle.writeFile(text, "utf8");
891
983
  } catch (error) {
892
984
  try {
@@ -1257,7 +1349,7 @@ async function acquireRefreshFileLockWithClock(options) {
1257
1349
  if (windowsPrivateFiles)
1258
1350
  await createPrivateBytes(evictOwnerPath, bytes);
1259
1351
  else
1260
- await createExclusiveText(evictOwnerPath, bytes);
1352
+ await writeExclusiveText(evictOwnerPath, bytes);
1261
1353
  } catch (error) {
1262
1354
  const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
1263
1355
  if (isLostMarkerRaceError(error) && !stillOurs)
@@ -15770,7 +15862,7 @@ class CacheKeepManager {
15770
15862
  // src/cachekeep-registry.ts
15771
15863
  import { randomUUID as randomUUID15 } from "node:crypto";
15772
15864
  import {
15773
- link,
15865
+ link as link2,
15774
15866
  lstat as lstat13,
15775
15867
  mkdir as mkdir11,
15776
15868
  readdir as readdir3,
@@ -24019,7 +24111,7 @@ class CacheKeepSessionRegistry {
24019
24111
  }
24020
24112
  async restoreSweptRecord(recordPath, sweptPath, raw) {
24021
24113
  try {
24022
- await link(sweptPath, recordPath);
24114
+ await link2(sweptPath, recordPath);
24023
24115
  } catch (error) {
24024
24116
  const code = error && typeof error === "object" && "code" in error ? error.code : undefined;
24025
24117
  if (code === "EEXIST") {
@@ -24048,6 +24140,288 @@ class CacheKeepSessionRegistry {
24048
24140
  } catch {}
24049
24141
  }
24050
24142
  }
24143
+ // src/cachekeep-store.ts
24144
+ import { createHash as createHash20, randomUUID as randomUUID16 } from "node:crypto";
24145
+ import { constants as constants3 } from "node:fs";
24146
+ import { lstat as lstat14, mkdir as mkdir12, open as open10, readdir as readdir4, rm as rm8, writeFile as writeFile5 } from "node:fs/promises";
24147
+ import { tmpdir as tmpdir7 } from "node:os";
24148
+ import { join as join22 } from "node:path";
24149
+ import { promisify } from "node:util";
24150
+ import { gunzip, gzip } from "node:zlib";
24151
+ var compress = promisify(gzip);
24152
+ var decompress = promisify(gunzip);
24153
+ var hash3 = (value) => createHash20("sha256").update(value).digest("hex");
24154
+ var FILE = /^[a-f0-9]{64}\.json\.gz$/;
24155
+ var TEMP = /^[a-f0-9]{64}\.json\.gz\.[a-f0-9-]+\.tmp$/;
24156
+ var MAX_RECORD_BYTES = 2 * CACHE_KEEP_MAX_BODY_BYTES + 64 * 1024;
24157
+ var RECORD_FORMAT_VERSION = 1;
24158
+ function cacheKeepStoreDirectory(storageId, root = getHostDataHome(), host) {
24159
+ return join22(root, "cortexkit", "anthropic-auth", "cachekeep-restore", ...host ? [host] : [], hash3(storageId).slice(0, 16));
24160
+ }
24161
+ function legacyCacheKeepStoreDirectory(storageId, root = tmpdir7()) {
24162
+ return join22(root, `cortexkit-anthropic-auth-cachekeep-${hash3(storageId).slice(0, 16)}`);
24163
+ }
24164
+ function record8(target, pluginVersion) {
24165
+ return {
24166
+ v: RECORD_FORMAT_VERSION,
24167
+ pluginVersion,
24168
+ id: target.id,
24169
+ bodyText: target.bodyText,
24170
+ url: target.url,
24171
+ cacheExpiresAt: target.cacheExpiresAt,
24172
+ nextPrewarmAt: target.nextPrewarmAt,
24173
+ oauthAccountIdentity: target.oauthAccountIdentity,
24174
+ isSubagent: target.isSubagent,
24175
+ ttlMs: target.ttlMs,
24176
+ lastTouchAt: target.lastTouchAt,
24177
+ lastTouchKind: target.lastTouchKind
24178
+ };
24179
+ }
24180
+ function sanitizedBody(text5) {
24181
+ const body = JSON.parse(text5);
24182
+ if (!body || typeof body !== "object" || Array.isArray(body))
24183
+ throw new Error("Invalid restart body");
24184
+ let stripped = false;
24185
+ for (const key of Object.keys(body)) {
24186
+ if (/^(authorization|x-api-key|cookie|set-cookie|headers|credentials|token|access[_-]?token|refresh[_-]?token)$/i.test(key)) {
24187
+ delete body[key];
24188
+ stripped = true;
24189
+ }
24190
+ }
24191
+ return stripped ? JSON.stringify(body) : text5;
24192
+ }
24193
+ function invalidReason(value, name, now) {
24194
+ if (!value || typeof value !== "object" || Array.isArray(value))
24195
+ return "invalid";
24196
+ if (value.v !== RECORD_FORMAT_VERSION)
24197
+ return "format";
24198
+ 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))
24199
+ return "invalid";
24200
+ if (value.cacheExpiresAt <= now)
24201
+ return "expired";
24202
+ if (sanitizedBody(value.bodyText) !== value.bodyText)
24203
+ return "invalid";
24204
+ }
24205
+
24206
+ class CacheKeepStore {
24207
+ options;
24208
+ directory;
24209
+ disabled = false;
24210
+ legacyLoadAttempted = false;
24211
+ chain = Promise.resolve();
24212
+ pending = new Map;
24213
+ timers = new Map;
24214
+ lastWrite = new Map;
24215
+ latest = new Map;
24216
+ constructor(options, previous) {
24217
+ this.options = options;
24218
+ this.directory = cacheKeepStoreDirectory(options.storageId, options.root, options.host);
24219
+ this.chain = previous?.drain() ?? Promise.resolve();
24220
+ }
24221
+ refuse() {
24222
+ if (this.disabled)
24223
+ return;
24224
+ this.disabled = true;
24225
+ for (const timer of this.timers.values())
24226
+ (this.options.clearTimeoutImpl ?? clearTimeout)(timer);
24227
+ this.timers.clear();
24228
+ this.pending.clear();
24229
+ this.latest.clear();
24230
+ this.lastWrite.clear();
24231
+ logger2.warn("cachekeep", "restart storage unavailable; retaining sessions in memory only");
24232
+ }
24233
+ async directoryReady(directory = this.directory) {
24234
+ if (this.disabled)
24235
+ return false;
24236
+ try {
24237
+ if (!await ensureWindowsOwnerOnlyDirectory(directory, this.options.ownerOnly)) {
24238
+ try {
24239
+ await mkdir12(directory, { recursive: true, mode: 448 });
24240
+ } catch (error) {
24241
+ if (error.code !== "EEXIST")
24242
+ throw error;
24243
+ }
24244
+ }
24245
+ const stat11 = await lstat14(directory);
24246
+ if (!stat11.isDirectory() || stat11.isSymbolicLink() || !await isOwnerOnly(directory, () => stat11.uid === process.getuid?.() && (stat11.mode & 511) === 448, this.options.ownerOnly))
24247
+ throw new Error("Unsafe restart directory");
24248
+ return true;
24249
+ } catch {
24250
+ this.refuse();
24251
+ return false;
24252
+ }
24253
+ }
24254
+ enqueue(action) {
24255
+ this.chain = this.chain.then(async () => {
24256
+ if (await this.directoryReady())
24257
+ await action();
24258
+ }).catch(() => this.refuse());
24259
+ }
24260
+ async load(now, accept, claim) {
24261
+ await this.chain;
24262
+ if (!await this.directoryReady())
24263
+ return;
24264
+ let directory = this.directory;
24265
+ const firstLoad = !this.legacyLoadAttempted;
24266
+ this.legacyLoadAttempted = true;
24267
+ if (!this.options.host && firstLoad && (await readdir4(directory)).length === 0) {
24268
+ const legacy = legacyCacheKeepStoreDirectory(this.options.storageId, this.options.legacyRoot ?? this.options.root);
24269
+ try {
24270
+ await lstat14(legacy);
24271
+ if (!await this.directoryReady(legacy))
24272
+ return;
24273
+ directory = legacy;
24274
+ } catch {
24275
+ return;
24276
+ }
24277
+ }
24278
+ let restored = 0;
24279
+ let dropped = 0;
24280
+ try {
24281
+ for (const name of (await readdir4(directory)).sort()) {
24282
+ if (!FILE.test(name) && !TEMP.test(name))
24283
+ continue;
24284
+ const release2 = claim ? await claim(name.slice(0, 64)) : undefined;
24285
+ if (claim && !release2)
24286
+ continue;
24287
+ const path2 = join22(directory, name);
24288
+ let reason = "unreadable";
24289
+ try {
24290
+ if (TEMP.test(name)) {
24291
+ reason = "unfinished-write";
24292
+ throw new Error("Unfinished write");
24293
+ }
24294
+ const stat11 = await lstat14(path2);
24295
+ if (!stat11.isFile() || stat11.isSymbolicLink() || stat11.size > MAX_RECORD_BYTES || !await isOwnerOnly(path2, () => stat11.uid === process.getuid?.() && (stat11.mode & 511) === 384, this.options.ownerOnly)) {
24296
+ reason = "unsafe-file";
24297
+ throw new Error("Unsafe restart file");
24298
+ }
24299
+ let bytes = await readWindowsOwnerOnly(path2, this.options.ownerOnly);
24300
+ if (!bytes) {
24301
+ const file = await open10(path2, constants3.O_RDONLY | constants3.O_NOFOLLOW);
24302
+ try {
24303
+ bytes = await file.readFile();
24304
+ } finally {
24305
+ await file.close();
24306
+ }
24307
+ }
24308
+ const raw = await decompress(bytes, {
24309
+ maxOutputLength: MAX_RECORD_BYTES
24310
+ });
24311
+ reason = "invalid";
24312
+ const entry2 = JSON.parse(raw.toString("utf8"));
24313
+ const invalid = invalidReason(entry2, name, now);
24314
+ const accepted = invalid ?? accept(entry2);
24315
+ if (accepted !== true && accepted !== undefined) {
24316
+ reason = accepted || "invalid";
24317
+ throw new Error("Stale restart file");
24318
+ }
24319
+ if (accepted === true) {
24320
+ if (directory !== this.directory) {
24321
+ try {
24322
+ await this.writeEntry(entry2);
24323
+ } catch {
24324
+ this.refuse();
24325
+ return;
24326
+ }
24327
+ await rm8(path2, { force: true });
24328
+ }
24329
+ restored++;
24330
+ }
24331
+ } catch {
24332
+ logger2.debug("cachekeep", "restart record dropped", {
24333
+ file: name,
24334
+ reason
24335
+ });
24336
+ dropped++;
24337
+ await rm8(path2, { force: true });
24338
+ } finally {
24339
+ await release2?.();
24340
+ }
24341
+ }
24342
+ } catch {
24343
+ this.refuse();
24344
+ } finally {
24345
+ if (restored || dropped)
24346
+ logger2.info("cachekeep", "restart records loaded", {
24347
+ restored,
24348
+ dropped
24349
+ });
24350
+ }
24351
+ }
24352
+ changed(target) {
24353
+ if (this.disabled)
24354
+ return;
24355
+ const entry2 = record8(target, this.options.pluginVersion);
24356
+ const previous = this.latest.get(entry2.id);
24357
+ 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)
24358
+ return;
24359
+ this.latest.set(entry2.id, entry2);
24360
+ this.pending.set(entry2.id, entry2);
24361
+ if (this.timers.has(entry2.id))
24362
+ return;
24363
+ const delay3 = Math.max(250, (this.lastWrite.get(entry2.id) ?? 0) + 5000 - (this.options.now?.() ?? Date.now()));
24364
+ const timer = (this.options.setTimeoutImpl ?? setTimeout)(() => this.flush(entry2.id), delay3);
24365
+ timer.unref?.();
24366
+ this.timers.set(entry2.id, timer);
24367
+ }
24368
+ flush(id2) {
24369
+ const timer = this.timers.get(id2);
24370
+ if (timer)
24371
+ (this.options.clearTimeoutImpl ?? clearTimeout)(timer);
24372
+ this.timers.delete(id2);
24373
+ const entry2 = this.pending.get(id2);
24374
+ this.pending.delete(id2);
24375
+ if (!entry2)
24376
+ return this.chain;
24377
+ this.lastWrite.set(id2, this.options.now?.() ?? Date.now());
24378
+ this.enqueue(() => this.writeEntry(entry2));
24379
+ return this.chain;
24380
+ }
24381
+ async writeEntry(entry2) {
24382
+ const path2 = join22(this.directory, `${hash3(entry2.id)}.json.gz`);
24383
+ const temp = `${path2}.${randomUUID16()}.tmp`;
24384
+ try {
24385
+ const safe = { ...entry2, bodyText: sanitizedBody(entry2.bodyText) };
24386
+ const bytes = await compress(JSON.stringify(safe));
24387
+ if (!await createWindowsOwnerOnly(temp, bytes, this.options.ownerOnly))
24388
+ await writeFile5(temp, bytes, { flag: "wx", mode: 384 });
24389
+ await renameWithWindowsSharingRetry(temp, path2, {
24390
+ platform: this.options.ownerOnly?.platform
24391
+ });
24392
+ } finally {
24393
+ await rm8(temp, { force: true });
24394
+ }
24395
+ }
24396
+ removed(id2) {
24397
+ const timer = this.timers.get(id2);
24398
+ if (timer)
24399
+ (this.options.clearTimeoutImpl ?? clearTimeout)(timer);
24400
+ this.timers.delete(id2);
24401
+ this.pending.delete(id2);
24402
+ this.latest.delete(id2);
24403
+ this.lastWrite.delete(id2);
24404
+ this.enqueue(() => rm8(join22(this.directory, `${hash3(id2)}.json.gz`), { force: true }));
24405
+ }
24406
+ clear() {
24407
+ for (const timer of this.timers.values())
24408
+ (this.options.clearTimeoutImpl ?? clearTimeout)(timer);
24409
+ this.timers.clear();
24410
+ this.pending.clear();
24411
+ this.latest.clear();
24412
+ this.lastWrite.clear();
24413
+ this.enqueue(async () => {
24414
+ for (const name of await readdir4(this.directory))
24415
+ if (FILE.test(name) || TEMP.test(name))
24416
+ await rm8(join22(this.directory, name), { force: true });
24417
+ });
24418
+ }
24419
+ async drain() {
24420
+ for (const id2 of this.pending.keys())
24421
+ this.flush(id2);
24422
+ await this.chain;
24423
+ }
24424
+ }
24051
24425
  // src/oauth-profile.ts
24052
24426
  var PROFILE_URL = "https://api.anthropic.com/api/oauth/profile";
24053
24427
  var PROFILE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
@@ -24802,13 +25176,13 @@ function executeLoggingCommand(input) {
24802
25176
  `);
24803
25177
  }
24804
25178
  // src/message-threads.ts
24805
- import { createHash as createHash20 } from "node:crypto";
25179
+ import { createHash as createHash21 } from "node:crypto";
24806
25180
  var MESSAGE_THREADS_BETA = "message-threads-2026-08-12";
24807
25181
  var MAX_AGE_MS = 5 * 60000;
24808
25182
  var MAX_SESSIONS = 2048;
24809
25183
  var MAX_MESSAGE_HASHES = 131072;
24810
- function hash3(value) {
24811
- return createHash20("sha256").update(JSON.stringify(value)).digest("hex");
25184
+ function hash4(value) {
25185
+ return createHash21("sha256").update(JSON.stringify(value)).digest("hex");
24812
25186
  }
24813
25187
  function normalizedReplyName(name) {
24814
25188
  const bare = name.startsWith("mcp_") ? name.slice(4) : name;
@@ -24854,7 +25228,7 @@ class ReplyFingerprint {
24854
25228
  layout = new Map;
24855
25229
  textBlocks = new Map;
24856
25230
  signatures = new Map;
24857
- text = createHash20("sha256");
25231
+ text = createHash21("sha256");
24858
25232
  committedText = this.text.copy();
24859
25233
  hasText = false;
24860
25234
  activeText;
@@ -24876,7 +25250,7 @@ class ReplyFingerprint {
24876
25250
  this.text.update(part.slice(visible.length));
24877
25251
  }
24878
25252
  appendBlockText(state, value) {
24879
- state.text ??= createHash20("sha256");
25253
+ state.text ??= createHash21("sha256");
24880
25254
  state.committedText ??= state.text.copy();
24881
25255
  const part = state.textHasContent ? value : value.trimStart();
24882
25256
  const visible = part.trimEnd();
@@ -24923,7 +25297,7 @@ class ReplyFingerprint {
24923
25297
  state.input = block.input;
24924
25298
  }
24925
25299
  if (block.type === "thinking" || block.type === "redacted_thinking") {
24926
- state.signature = createHash20("sha256");
25300
+ state.signature = createHash21("sha256");
24927
25301
  const signature = block.type === "redacted_thinking" ? block.data : block.signature;
24928
25302
  if (typeof signature === "string") {
24929
25303
  state.signature.update(signature);
@@ -25001,7 +25375,7 @@ class ReplyFingerprint {
25001
25375
  this.tools.set(index, [
25002
25376
  state.id,
25003
25377
  state.name,
25004
- hash3(canonicalValue(input))
25378
+ hash4(canonicalValue(input))
25005
25379
  ]);
25006
25380
  } catch {
25007
25381
  this.invalid = true;
@@ -25013,7 +25387,7 @@ class ReplyFingerprint {
25013
25387
  return;
25014
25388
  const ordered = [...this.layout].sort(([a], [b]) => a - b);
25015
25389
  const kept = withoutTrailingToolWhitespace(ordered.map(([, block]) => block));
25016
- return hash3({
25390
+ return hash4({
25017
25391
  blocks: kept.map((block) => block.type),
25018
25392
  texts: ordered.slice(0, kept.length).filter(([, block]) => block.type === "text").map(([index]) => this.textBlocks.get(index)),
25019
25393
  tools: [...this.tools].sort(([a], [b]) => a - b).map(([, tool]) => tool),
@@ -25120,7 +25494,7 @@ function fixedThreadFingerprint(input) {
25120
25494
  "tool_choice",
25121
25495
  "context_management"
25122
25496
  ].map((key) => [key, body[key]]));
25123
- return hash3(canonicalValue({
25497
+ return hash4(canonicalValue({
25124
25498
  ...fixed,
25125
25499
  tools: JSON.stringify(body.tools),
25126
25500
  system: JSON.stringify(system),
@@ -25129,9 +25503,9 @@ function fixedThreadFingerprint(input) {
25129
25503
  betas: input.betas
25130
25504
  }));
25131
25505
  }
25132
- function messageThreadSnapshot(input, identity3 = hash3([input.account, input.credential]), fingerprint = fixedThreadFingerprint(input)) {
25133
- const messages = (Array.isArray(input.body.messages) ? input.body.messages : []).map((message) => hash3(canonicalValue(withoutMessageCache(message))));
25134
- return { identity: identity3, fingerprint, messages, prefix: hash3(messages) };
25506
+ function messageThreadSnapshot(input, identity3 = hash4([input.account, input.credential]), fingerprint = fixedThreadFingerprint(input)) {
25507
+ const messages = (Array.isArray(input.body.messages) ? input.body.messages : []).map((message) => hash4(canonicalValue(withoutMessageCache(message))));
25508
+ return { identity: identity3, fingerprint, messages, prefix: hash4(messages) };
25135
25509
  }
25136
25510
  function canContinueFrom(anchor, input, identity3, now) {
25137
25511
  if (!anchor || !identity3 || anchor.identity !== identity3 || now < anchor.completedAt || now - anchor.completedAt >= MAX_AGE_MS)
@@ -25140,7 +25514,7 @@ function canContinueFrom(anchor, input, identity3, now) {
25140
25514
  return messages.length >= anchor.messages.length + 2 && messages[anchor.messages.length]?.role === "assistant" && !messages.slice(anchor.messages.length + 1).some((message) => message?.role === "assistant") && assistantReplyFingerprint(messages[anchor.messages.length], replyToolNameResolver(input)) === anchor.replyFingerprint;
25141
25515
  }
25142
25516
  function decideMessageThread(anchor, input, snapshot, now) {
25143
- if (!canContinueFrom(anchor, input, snapshot.identity, now) || anchor.fingerprint !== snapshot.fingerprint || hash3(snapshot.messages.slice(0, anchor.messages.length)) !== anchor.prefix)
25517
+ if (!canContinueFrom(anchor, input, snapshot.identity, now) || anchor.fingerprint !== snapshot.fingerprint || hash4(snapshot.messages.slice(0, anchor.messages.length)) !== anchor.prefix)
25144
25518
  return { type: "create" };
25145
25519
  const messages = Array.isArray(input.body.messages) ? input.body.messages : [];
25146
25520
  return {
@@ -25184,7 +25558,7 @@ class MessageThreadTracker {
25184
25558
  const previous = this.sessions.get(input.session);
25185
25559
  const anchor = previous?.anchor;
25186
25560
  const now = this.now();
25187
- const identity3 = anchor && now >= anchor.completedAt && now - anchor.completedAt < MAX_AGE_MS ? hash3([input.account, input.credential]) : undefined;
25561
+ const identity3 = anchor && now >= anchor.completedAt && now - anchor.completedAt < MAX_AGE_MS ? hash4([input.account, input.credential]) : undefined;
25188
25562
  let snapshot;
25189
25563
  if (canContinueFrom(anchor, input, identity3, now)) {
25190
25564
  const fingerprint = fixedThreadFingerprint(input);
@@ -25443,7 +25817,7 @@ function disableThreadsForAccount(key) {
25443
25817
  if (disabledThreadAccounts.has(key))
25444
25818
  return;
25445
25819
  disabledThreadAccounts.add(key);
25446
- logger2.warn("message-threads", "Anthropic rejected message threads; using full stateless requests for this account until restart", { account: hash3(key).slice(0, 12) });
25820
+ logger2.warn("message-threads", "Anthropic rejected message threads; using full stateless requests for this account until restart", { account: hash4(key).slice(0, 12) });
25447
25821
  }
25448
25822
  function ignoreThreadFailure() {}
25449
25823
  function threadFailureState(initial) {
@@ -25733,7 +26107,7 @@ function remapRequestBodyModel(parsed) {
25733
26107
  return true;
25734
26108
  }
25735
26109
  // src/native-account-runtime.ts
25736
- import { randomUUID as randomUUID17 } from "node:crypto";
26110
+ import { randomUUID as randomUUID18 } from "node:crypto";
25737
26111
 
25738
26112
  // src/native-account-view.ts
25739
26113
  import { types as types2 } from "node:util";
@@ -26498,7 +26872,7 @@ function createNativeLocalRuntimeReaders(options) {
26498
26872
  }
26499
26873
 
26500
26874
  // src/native-refresh-coordinator.ts
26501
- import { createHash as createHash21 } from "node:crypto";
26875
+ import { createHash as createHash22 } from "node:crypto";
26502
26876
 
26503
26877
  // src/native-transient-account.ts
26504
26878
  var TRANSIENT_ACCOUNT_MESSAGE = "Anthropic account update in progress; retry the request";
@@ -26600,7 +26974,7 @@ function pause(ms, signals) {
26600
26974
  var NATIVE_REFRESH_MAX_ATTEMPTS = 3;
26601
26975
  var NATIVE_REFRESH_JOIN_BUDGET_MS = 2000;
26602
26976
  function nativeAccountProviderLock(paths, identity3) {
26603
- const key = createHash21("sha256").update(JSON.stringify([paths.storageId, identity3])).digest("hex");
26977
+ const key = createHash22("sha256").update(JSON.stringify([paths.storageId, identity3])).digest("hex");
26604
26978
  return {
26605
26979
  path: paths.state,
26606
26980
  name: `native-account-provider-${key}`,
@@ -27400,9 +27774,9 @@ function createNativeRefreshCoordinator(options) {
27400
27774
  import { isAbsolute as isAbsolute5, normalize, parse as parse3, sep } from "node:path";
27401
27775
 
27402
27776
  // src/migration-source.ts
27403
- import { createHash as createHash22 } from "node:crypto";
27404
- import { constants as constants3 } from "node:fs";
27405
- import { lstat as lstat14, open as open10 } from "node:fs/promises";
27777
+ import { createHash as createHash23 } from "node:crypto";
27778
+ import { constants as constants4 } from "node:fs";
27779
+ import { lstat as lstat15, open as open11 } from "node:fs/promises";
27406
27780
  class NativeMigrationSourceError extends Error {
27407
27781
  role;
27408
27782
  code;
@@ -27445,7 +27819,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27445
27819
  });
27446
27820
  let initial;
27447
27821
  try {
27448
- initial = await lstat14(path2, { bigint: true });
27822
+ initial = await lstat15(path2, { bigint: true });
27449
27823
  } catch (error) {
27450
27824
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
27451
27825
  return missing2;
@@ -27455,7 +27829,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27455
27829
  throw new NativeMigrationSourceError(role, "unsafe-source");
27456
27830
  let handle;
27457
27831
  try {
27458
- handle = await open10(path2, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0) | (constants3.O_NONBLOCK ?? 0));
27832
+ handle = await open11(path2, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0) | (constants4.O_NONBLOCK ?? 0));
27459
27833
  const before = await handle.stat({ bigint: true });
27460
27834
  if (!before.isFile() || before.dev !== initial.dev || before.ino !== initial.ino) {
27461
27835
  throw new NativeMigrationSourceError(role, "source-changed");
@@ -27483,7 +27857,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27483
27857
  chunks.push(chunk.subarray(0, read.bytesRead));
27484
27858
  }
27485
27859
  const after = await handle.stat({ bigint: true });
27486
- const current = await lstat14(path2, { bigint: true });
27860
+ const current = await lstat15(path2, { bigint: true });
27487
27861
  if (before.uid !== after.uid || before.gid !== after.gid || before.mode !== after.mode || current.uid !== before.uid || current.gid !== before.gid || current.mode !== before.mode || before.dev !== after.dev || before.ino !== after.ino || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs || before.size !== after.size || current.dev !== before.dev || current.ino !== before.ino || current.isSymbolicLink() || current.mtimeNs !== before.mtimeNs || current.ctimeNs !== before.ctimeNs || current.size !== before.size || BigInt(bytes) !== before.size) {
27488
27862
  throw new NativeMigrationSourceError(role, "source-changed");
27489
27863
  }
@@ -27499,7 +27873,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27499
27873
  return sourceSnapshot({
27500
27874
  role,
27501
27875
  path: path2,
27502
- digest: createHash22("sha256").update(content).digest("hex"),
27876
+ digest: createHash23("sha256").update(content).digest("hex"),
27503
27877
  data: freezeJson(data),
27504
27878
  metadata: Object.freeze({
27505
27879
  uid: Number(before.uid),
@@ -28524,11 +28898,11 @@ class NativeRuntimeRegistry {
28524
28898
  }
28525
28899
 
28526
28900
  // src/native-vault-runtime.ts
28527
- import { randomUUID as randomUUID16 } from "node:crypto";
28901
+ import { randomUUID as randomUUID17 } from "node:crypto";
28528
28902
  import { SubcClient as SubcClient2 } from "@cortexkit/subc-client";
28529
28903
 
28530
28904
  // src/insula-quota.ts
28531
- function record8(value) {
28905
+ function record9(value) {
28532
28906
  return typeof value === "object" && value !== null && !Array.isArray(value);
28533
28907
  }
28534
28908
  function text5(value) {
@@ -28538,7 +28912,7 @@ function clampPercent3(value) {
28538
28912
  return Math.min(100, Math.max(0, value));
28539
28913
  }
28540
28914
  function windowReading(window2, checkedAt, expected) {
28541
- if (!record8(window2))
28915
+ if (!record9(window2))
28542
28916
  return;
28543
28917
  const usedPercent = window2.usedPercent;
28544
28918
  if (typeof usedPercent !== "number" || !Number.isFinite(usedPercent))
@@ -28562,7 +28936,7 @@ function scopedReadings(windows, checkedAt) {
28562
28936
  const seen = new Set;
28563
28937
  const scoped = [];
28564
28938
  for (const candidate of windows) {
28565
- if (!record8(candidate))
28939
+ if (!record9(candidate))
28566
28940
  continue;
28567
28941
  const identity3 = text5(candidate.id);
28568
28942
  if (!identity3)
@@ -28588,7 +28962,7 @@ function scopedReadings(windows, checkedAt) {
28588
28962
  return scoped;
28589
28963
  }
28590
28964
  function money2(value) {
28591
- if (!record8(value) || typeof value.minor !== "number" || !Number.isSafeInteger(value.minor) || value.minor < 0)
28965
+ if (!record9(value) || typeof value.minor !== "number" || !Number.isSafeInteger(value.minor) || value.minor < 0)
28592
28966
  return null;
28593
28967
  const exponent = value.exponent ?? 2;
28594
28968
  if (typeof exponent !== "number" || !Number.isInteger(exponent) || exponent < 0 || exponent > 20)
@@ -28598,8 +28972,8 @@ function money2(value) {
28598
28972
  function extraUsageReading(pools) {
28599
28973
  if (!Array.isArray(pools))
28600
28974
  return;
28601
- const pool = pools.find((candidate) => record8(candidate) && candidate.title === "Extra usage");
28602
- if (!record8(pool))
28975
+ const pool = pools.find((candidate) => record9(candidate) && candidate.title === "Extra usage");
28976
+ if (!record9(pool))
28603
28977
  return;
28604
28978
  const limit = money2(pool.total ?? pool.limit);
28605
28979
  const remaining = money2(pool.remaining);
@@ -28614,7 +28988,7 @@ function extraUsageReading(pools) {
28614
28988
  used = Math.max(0, limit.minor - remaining.minor);
28615
28989
  if (used === undefined)
28616
28990
  return;
28617
- const unit = text5(pool.unit) ?? text5(record8(pool.total) && pool.total.unit);
28991
+ const unit = text5(pool.unit) ?? text5(record9(pool.total) && pool.total.unit);
28618
28992
  const currency = unit && /^[A-Za-z]{3}$/.test(unit) ? unit : "USD";
28619
28993
  return {
28620
28994
  used: { amountMinor: used, currency, exponent },
@@ -28770,12 +29144,12 @@ function expectedSeed(input, boundary, refuse3) {
28770
29144
  const inventory = capture(top("inventory", "roster-incomplete"), ["view", "credentials", "skipped"], "roster-incomplete", refuse3);
28771
29145
  const view = inventory.view;
28772
29146
  const skipped = items(inventory.skipped, "roster-incomplete", refuse3);
28773
- const credentialRecords = items(inventory.credentials, "roster-incomplete", refuse3).map((record9) => capture(record9, ["credentialId", "credentialType", "accountIdentity", "state"], "roster-incomplete", refuse3));
29147
+ const credentialRecords = items(inventory.credentials, "roster-incomplete", refuse3).map((record10) => capture(record10, ["credentialId", "credentialType", "accountIdentity", "state"], "roster-incomplete", refuse3));
28774
29148
  if (!filled(view) || skipped.length > 0)
28775
29149
  refuse3("roster-incomplete");
28776
29150
  const listed = new Map;
28777
- for (const record9 of credentialRecords) {
28778
- const { credentialId, credentialType, accountIdentity, state } = record9;
29151
+ for (const record10 of credentialRecords) {
29152
+ const { credentialId, credentialType, accountIdentity, state } = record10;
28779
29153
  if (!filled(credentialId) || !filled(accountIdentity) || !filled(state) || listed.has(credentialId)) {
28780
29154
  refuse3("roster-incomplete");
28781
29155
  }
@@ -28786,7 +29160,7 @@ function expectedSeed(input, boundary, refuse3) {
28786
29160
  const primaryIdentity = primary.accountIdentity;
28787
29161
  boundary.fallback = "seed-conflict";
28788
29162
  const primaryRouteId = top("primaryRouteId", "seed-conflict");
28789
- const legacyRecords = items(top("legacyRows", "seed-conflict"), "seed-conflict", refuse3).map((record9) => capture(record9, [
29163
+ const legacyRecords = items(top("legacyRows", "seed-conflict"), "seed-conflict", refuse3).map((record10) => capture(record10, [
28790
29164
  "routeId",
28791
29165
  "scopedCredentialId",
28792
29166
  "anthropicAccountUuid",
@@ -30253,7 +30627,7 @@ function createNativeVaultRuntime(options) {
30253
30627
  async getOrCreateAuthLineage(receipt) {
30254
30628
  let lineage;
30255
30629
  const kept = await mutateReceipt(receipt, (old) => {
30256
- lineage = old.authLineageId ?? randomUUID16();
30630
+ lineage = old.authLineageId ?? randomUUID17();
30257
30631
  return { ...old, authLineageId: lineage };
30258
30632
  });
30259
30633
  return kept ? lineage : undefined;
@@ -30649,7 +31023,7 @@ function leaseNativeVaultRuntime(use, close) {
30649
31023
 
30650
31024
  // src/relay.ts
30651
31025
  import { Buffer as Buffer3 } from "node:buffer";
30652
- import { createHash as createHash23, randomBytes as randomBytes5 } from "node:crypto";
31026
+ import { createHash as createHash24, randomBytes as randomBytes5 } from "node:crypto";
30653
31027
  var WEBSOCKET_RELAY_URL = /^wss?:\/\//i;
30654
31028
  function effectiveRelayTransport(stored, url) {
30655
31029
  if (stored === "http" || stored === "websocket")
@@ -30800,7 +31174,7 @@ function generateRelayToken() {
30800
31174
  return randomBytes5(32).toString("base64url");
30801
31175
  }
30802
31176
  function hashBody(body) {
30803
- return `sha256:${createHash23("sha256").update(body).digest("hex")}`;
31177
+ return `sha256:${createHash24("sha256").update(body).digest("hex")}`;
30804
31178
  }
30805
31179
  function createStringPatch(previous, next) {
30806
31180
  let start = 0;
@@ -32600,7 +32974,7 @@ function createNativeAccountRuntime(options) {
32600
32974
  const sameAccount = old?.kind === "local" && old.rowId === binding2.rowId && binding2.identity !== undefined && old.identity === binding2.identity;
32601
32975
  const next = {
32602
32976
  binding: binding2,
32603
- ...row.credential?.type === "oauth" ? { authLineageId: randomUUID17() } : {}
32977
+ ...row.credential?.type === "oauth" ? { authLineageId: randomUUID18() } : {}
32604
32978
  };
32605
32979
  if (sameAccount && previous) {
32606
32980
  for (const key of [
@@ -32763,7 +33137,7 @@ function createNativeAccountRuntime(options) {
32763
33137
  throw new NativeRuntimeError("publication-refused");
32764
33138
  const previous = relayFlags(read.settings.relay);
32765
33139
  const previousGeneration = relayGeneration(read.settings.relay);
32766
- const generation = randomUUID17();
33140
+ const generation = randomUUID18();
32767
33141
  const metadata2 = await readNativeRuntime(paths2.runtime, paths2.storageId);
32768
33142
  const token2 = patch.token === undefined ? metadata2.status === "ready" ? metadata2.state.relay?.token : undefined : patch.token?.trim();
32769
33143
  const next = relayFlags({
@@ -32989,7 +33363,7 @@ function createNativeAccountRuntime(options) {
32989
33363
  const snapshot = await runtime2.read();
32990
33364
  if (snapshot.mode !== "local")
32991
33365
  throw new NativeCustodyError("route-unavailable");
32992
- const id2 = input.routeId === "main" ? await physicalId("main").catch(() => randomUUID17()) : input.routeId;
33366
+ const id2 = input.routeId === "main" ? await physicalId("main").catch(() => randomUUID18()) : input.routeId;
32993
33367
  if (input.credential.type === "api" && (input.routeId === "main" || id2 === snapshot.settings.mainAccountId))
32994
33368
  throw new NativeCustodyError("route-unavailable");
32995
33369
  const old = await poolRow(id2);
@@ -33028,7 +33402,7 @@ function createNativeAccountRuntime(options) {
33028
33402
  return row;
33029
33403
  },
33030
33404
  addApi: (input) => runtime2.putAccount({
33031
- routeId: input.routeId ?? randomUUID17(),
33405
+ routeId: input.routeId ?? randomUUID18(),
33032
33406
  label: input.label,
33033
33407
  replace: input.replace,
33034
33408
  credential: {
@@ -33245,7 +33619,7 @@ function createNativeAccountRuntime(options) {
33245
33619
  return;
33246
33620
  let lineage;
33247
33621
  const kept = await metadataPublications.run(() => localMetadataWrite(fence, (old) => {
33248
- lineage = old.authLineageId ?? randomUUID17();
33622
+ lineage = old.authLineageId ?? randomUUID18();
33249
33623
  return {
33250
33624
  ...old,
33251
33625
  authLineageId: lineage
@@ -33452,9 +33826,9 @@ function relayGeneration(input) {
33452
33826
  return generation;
33453
33827
  }
33454
33828
  // src/native-host-auth-write.ts
33455
- import { randomUUID as randomUUID18 } from "node:crypto";
33456
- import { lstat as lstat15, open as open11, rename as rename13, unlink as unlink7 } from "node:fs/promises";
33457
- import { dirname as dirname19, isAbsolute as isAbsolute6, join as join22 } from "node:path";
33829
+ import { randomUUID as randomUUID19 } from "node:crypto";
33830
+ import { lstat as lstat16, open as open12, rename as rename13, unlink as unlink7 } from "node:fs/promises";
33831
+ import { dirname as dirname19, isAbsolute as isAbsolute6, join as join23 } from "node:path";
33458
33832
  class NativeHostAuthWriteError extends Error {
33459
33833
  code;
33460
33834
  effect;
@@ -33515,11 +33889,11 @@ async function writeNativeHostAuth(input, hooks = {}) {
33515
33889
  const removingFile = host === "pi" && Object.keys(next).length === 0;
33516
33890
  const outcome = Object.freeze(host === "pi" ? { status: "removed", file: removingFile ? "unlinked" : "replaced" } : { status: snapshot.data === undefined ? "created" : "replaced" });
33517
33891
  if (!removingFile) {
33518
- stage = join22(dirname19(authPath), `.native-host-auth-write.${randomUUID18()}.tmp`);
33892
+ stage = join23(dirname19(authPath), `.native-host-auth-write.${randomUUID19()}.tmp`);
33519
33893
  const bytes = `${JSON.stringify(next, null, 2)}
33520
33894
  `;
33521
33895
  const nativeCreated = await createWindowsOwnerOnly(stage, bytes);
33522
- const handle = await open11(stage, nativeCreated ? "r+" : "wx", 384);
33896
+ const handle = await open12(stage, nativeCreated ? "r+" : "wx", 384);
33523
33897
  try {
33524
33898
  const identity3 = await handle.stat();
33525
33899
  ownedStage = { dev: identity3.dev, ino: identity3.ino };
@@ -33565,7 +33939,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
33565
33939
  } finally {
33566
33940
  if (stage && ownedStage) {
33567
33941
  try {
33568
- const current = await lstat15(stage);
33942
+ const current = await lstat16(stage);
33569
33943
  if (current.dev === ownedStage.dev && current.ino === ownedStage.ino)
33570
33944
  await unlink7(stage);
33571
33945
  } catch {}
@@ -33574,8 +33948,8 @@ async function writeNativeHostAuth(input, hooks = {}) {
33574
33948
  }
33575
33949
 
33576
33950
  // src/native-migration.ts
33577
- import { createHash as createHash24 } from "node:crypto";
33578
- import { lstat as lstat16, mkdir as mkdir12, unlink as unlink8 } from "node:fs/promises";
33951
+ import { createHash as createHash25 } from "node:crypto";
33952
+ import { lstat as lstat17, mkdir as mkdir13, unlink as unlink8 } from "node:fs/promises";
33579
33953
  import { dirname as dirname20, isAbsolute as isAbsolute7 } from "node:path";
33580
33954
  class NativeMigrationError extends Error {
33581
33955
  code;
@@ -33625,7 +33999,7 @@ function owned(snapshot) {
33625
33999
  }
33626
34000
  async function absent(path2) {
33627
34001
  try {
33628
- await lstat16(path2);
34002
+ await lstat17(path2);
33629
34003
  return false;
33630
34004
  } catch (error) {
33631
34005
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
@@ -33954,7 +34328,7 @@ function routingBytes(captured) {
33954
34328
  `;
33955
34329
  }
33956
34330
  function bytesDigest(bytes) {
33957
- return bytes === undefined ? null : createHash24("sha256").update(bytes).digest("hex");
34331
+ return bytes === undefined ? null : createHash25("sha256").update(bytes).digest("hex");
33958
34332
  }
33959
34333
  function expectedAuth(input, snapshot) {
33960
34334
  const entry2 = inspectNativeHostAuthEntry(input.host, snapshot.data);
@@ -34329,7 +34703,7 @@ async function runNativeMigration(input, hooks = {}) {
34329
34703
  refuse3();
34330
34704
  await step("before:host");
34331
34705
  await recheck();
34332
- await mkdir12(dirname20(operation.hostAuthPath), {
34706
+ await mkdir13(dirname20(operation.hostAuthPath), {
34333
34707
  recursive: true,
34334
34708
  mode: 448
34335
34709
  });
@@ -36475,10 +36849,10 @@ function isSignInLink(candidate) {
36475
36849
  }
36476
36850
  function showSignInLink(text6, scrub) {
36477
36851
  const links = new Set((text6.match(/https:\/\/\S+/g) ?? []).filter(isSignInLink));
36478
- const [link2] = links;
36479
- if (links.size !== 1 || link2 === undefined)
36852
+ const [link3] = links;
36853
+ if (links.size !== 1 || link3 === undefined)
36480
36854
  return { text: scrub(text6) };
36481
- return { text: text6.split(link2).map(scrub).join(link2), link: link2 };
36855
+ return { text: text6.split(link3).map(scrub).join(link3), link: link3 };
36482
36856
  }
36483
36857
  var DISCONNECT_OUTCOMES = {
36484
36858
  disconnected: {
@@ -36809,7 +37183,7 @@ function waitForRequest(pending, signal) {
36809
37183
  });
36810
37184
  }
36811
37185
  // src/native-vault-connection.ts
36812
- import { dirname as dirname22, join as join23, resolve as resolve16 } from "node:path";
37186
+ import { dirname as dirname22, join as join24, resolve as resolve16 } from "node:path";
36813
37187
  // ../../node_modules/@cortexkit/common-auth/dist/opencode2/integration.js
36814
37188
  var PLACEHOLDER_PREFIX = "common-auth-placeholder";
36815
37189
  var PLACEHOLDER_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
@@ -36817,15 +37191,15 @@ function placeholderSecret(integrationID) {
36817
37191
  return `${PLACEHOLDER_PREFIX}.${integrationID}`;
36818
37192
  }
36819
37193
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
36820
- import { createHash as createHash25 } from "node:crypto";
36821
- import { constants as constants4 } from "node:fs";
36822
- import { lstat as lstat17, mkdir as mkdir14, open as open12, unlink as unlink9 } from "node:fs/promises";
37194
+ import { createHash as createHash26 } from "node:crypto";
37195
+ import { constants as constants5 } from "node:fs";
37196
+ import { lstat as lstat18, mkdir as mkdir15, open as open13, unlink as unlink9 } from "node:fs/promises";
36823
37197
  import { dirname as dirname21, resolve as resolve15 } from "node:path";
36824
37198
  import { setTimeout as sleep } from "node:timers/promises";
36825
37199
 
36826
37200
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
36827
37201
  import { rmdirSync, statSync as statSync5, utimesSync } from "node:fs";
36828
- import { mkdir as mkdir13, rmdir, stat as stat11, utimes } from "node:fs/promises";
37202
+ import { mkdir as mkdir14, rmdir, stat as stat11, utimes } from "node:fs/promises";
36829
37203
  var STALE = 30000;
36830
37204
  var RENEWAL_STALE = 1e4;
36831
37205
  var UPDATE = 3000;
@@ -36861,7 +37235,7 @@ async function remove(path2) {
36861
37235
  }
36862
37236
  async function acquire(path2, stale) {
36863
37237
  try {
36864
- await mkdir13(path2);
37238
+ await mkdir14(path2);
36865
37239
  } catch (error) {
36866
37240
  if (errorCode4(error) !== "EEXIST")
36867
37241
  throw error;
@@ -37096,7 +37470,7 @@ function canonical(value) {
37096
37470
  return JSON.stringify(value);
37097
37471
  }
37098
37472
  function digest2(value) {
37099
- return createHash25("sha256").update(canonical(value)).digest("hex");
37473
+ return createHash26("sha256").update(canonical(value)).digest("hex");
37100
37474
  }
37101
37475
  function code(error) {
37102
37476
  return object2(error) ? error.code : undefined;
@@ -37118,13 +37492,13 @@ async function safeRead(path2, privateFile = false, afterReadCheck) {
37118
37492
  }
37119
37493
  let file;
37120
37494
  try {
37121
- file = await open12(path2, constants4.O_RDONLY | constants4.O_NOFOLLOW);
37495
+ file = await open13(path2, constants5.O_RDONLY | constants5.O_NOFOLLOW);
37122
37496
  const stat12 = await file.stat();
37123
37497
  if (!stat12.isFile() || privateFile && (stat12.mode & 511) !== 384) {
37124
37498
  throw new PiSlotError("unsafe-path");
37125
37499
  }
37126
37500
  await afterReadCheck?.(path2);
37127
- const current = await lstat17(path2);
37501
+ const current = await lstat18(path2);
37128
37502
  if (!current.isFile() || current.dev !== stat12.dev || current.ino !== stat12.ino) {
37129
37503
  throw new PiSlotError("unsafe-path");
37130
37504
  }
@@ -37196,7 +37570,7 @@ function replaceEntry(auth, provider, next) {
37196
37570
  async function syncDir(path2) {
37197
37571
  if (windowsPrivateFiles)
37198
37572
  return;
37199
- const dir = await open12(path2, "r");
37573
+ const dir = await open13(path2, "r");
37200
37574
  try {
37201
37575
  await dir.sync();
37202
37576
  } finally {
@@ -37259,7 +37633,7 @@ function createPiSlot(options, onStep, hooks) {
37259
37633
  if (windowsPrivateFiles)
37260
37634
  await ensurePrivateDirectory(dirname21(authPath));
37261
37635
  else
37262
- await mkdir14(dirname21(authPath), { recursive: true, mode: 448 });
37636
+ await mkdir15(dirname21(authPath), { recursive: true, mode: 448 });
37263
37637
  const deadline = Date.now() + timeout;
37264
37638
  let retry = 0;
37265
37639
  while (!release2) {
@@ -37321,8 +37695,8 @@ function createPiSlot(options, onStep, hooks) {
37321
37695
  if (windowsPrivateFiles)
37322
37696
  await ensurePrivateDirectory(dirname21(stashPath));
37323
37697
  else {
37324
- await mkdir14(dirname21(stashPath), { recursive: true, mode: 448 });
37325
- const dir = await lstat17(dirname21(stashPath));
37698
+ await mkdir15(dirname21(stashPath), { recursive: true, mode: 448 });
37699
+ const dir = await lstat18(dirname21(stashPath));
37326
37700
  if (!dir.isDirectory() || (dir.mode & 511) !== 448)
37327
37701
  throw new PiSlotError("unsafe-path");
37328
37702
  }
@@ -37363,7 +37737,7 @@ function createPiSlot(options, onStep, hooks) {
37363
37737
  function nativePiAuthSlotPaths(options) {
37364
37738
  return {
37365
37739
  authPath: resolve16(options.authPath),
37366
- stashPath: join23(dirname22(getHostClaustrumEnrollmentPaths("pi", options.env).tokenPath), "pi-auth-slot", "anthropic.json"),
37740
+ stashPath: join24(dirname22(getHostClaustrumEnrollmentPaths("pi", options.env).tokenPath), "pi-auth-slot", "anthropic.json"),
37367
37741
  provider: "anthropic",
37368
37742
  placeholderKey: placeholderSecret("anthropic")
37369
37743
  };
@@ -37493,11 +37867,11 @@ function createAnthropicOAuthFetch(options = {}) {
37493
37867
  });
37494
37868
  }
37495
37869
  // src/prime.ts
37496
- import { createHash as createHash26 } from "node:crypto";
37870
+ import { createHash as createHash27 } from "node:crypto";
37497
37871
  import { realpathSync as realpathSync3 } from "node:fs";
37498
- import { mkdir as mkdir15, readdir as readdir4, rm as rm8, stat as stat12, writeFile as writeFile5 } from "node:fs/promises";
37499
- import { tmpdir as tmpdir7 } from "node:os";
37500
- import { join as join24, resolve as resolve17 } from "node:path";
37872
+ import { mkdir as mkdir16, readdir as readdir5, rm as rm9, stat as stat12, writeFile as writeFile6 } from "node:fs/promises";
37873
+ import { tmpdir as tmpdir8 } from "node:os";
37874
+ import { join as join25, resolve as resolve17 } from "node:path";
37501
37875
  var CLAUDE_PRIME_COMMAND_NAME = "claude-prime";
37502
37876
  var PRIME_TICK_MS = 60000;
37503
37877
  var PRIME_DUE_OFFSET_MS = 60000;
@@ -37685,7 +38059,7 @@ function buildPrimeRequestBody() {
37685
38059
  return JSON.parse(JSON.stringify(PRIME_REQUEST_BODY));
37686
38060
  }
37687
38061
  function defaultMarkerDir() {
37688
- return join24(tmpdir7(), "opencode-anthropic-auth", "prime");
38062
+ return join25(tmpdir8(), "opencode-anthropic-auth", "prime");
37689
38063
  }
37690
38064
  function primeStorageFingerprint(storagePath) {
37691
38065
  const absolutePath = resolve17(storagePath);
@@ -37697,22 +38071,22 @@ function primeStorageFingerprint(storagePath) {
37697
38071
  throw error;
37698
38072
  canonicalPath2 = absolutePath;
37699
38073
  }
37700
- return createHash26("sha256").update(canonicalPath2).digest("hex").slice(0, 12);
38074
+ return createHash27("sha256").update(canonicalPath2).digest("hex").slice(0, 12);
37701
38075
  }
37702
38076
  function primeMarkerNamespaceDir(markerDir, storagePath) {
37703
- return join24(markerDir, primeStorageFingerprint(storagePath));
38077
+ return join25(markerDir, primeStorageFingerprint(storagePath));
37704
38078
  }
37705
38079
  function primeAccountMarkerDir(markerDir, storagePath, accountFingerprint) {
37706
38080
  if (!/^[a-f0-9]{12,}$/i.test(accountFingerprint)) {
37707
38081
  throw new Error("Prime account fingerprint must be a hexadecimal digest");
37708
38082
  }
37709
- return join24(primeMarkerNamespaceDir(markerDir, storagePath), accountFingerprint.toLowerCase().slice(0, 12));
38083
+ return join25(primeMarkerNamespaceDir(markerDir, storagePath), accountFingerprint.toLowerCase().slice(0, 12));
37710
38084
  }
37711
38085
  function primeMarkerPath(markerDir, accountId2, resetsAtEpochMs) {
37712
- return join24(markerDir, `${encodeURIComponent(accountId2)}-${resetsAtEpochMs}`);
38086
+ return join25(markerDir, `${encodeURIComponent(accountId2)}-${resetsAtEpochMs}`);
37713
38087
  }
37714
38088
  function primeBootstrapMarkerPath(markerDir, accountId2) {
37715
- return join24(markerDir, `${encodeURIComponent(accountId2)}-bootstrap`);
38089
+ return join25(markerDir, `${encodeURIComponent(accountId2)}-bootstrap`);
37716
38090
  }
37717
38091
  function primeAccountLabel(id2, fallback) {
37718
38092
  if (id2 === "main")
@@ -37988,13 +38362,13 @@ class PrimeManager {
37988
38362
  }
37989
38363
  const postClaimStorage = await this.options.loadStorage();
37990
38364
  if (this.stopped || postClaimStorage?.prime?.enabled !== true) {
37991
- await rm8(markerPath, { force: true });
38365
+ await rm9(markerPath, { force: true });
37992
38366
  return;
37993
38367
  }
37994
38368
  if (markerEpoch !== undefined) {
37995
- await rm8(bootstrapMarkerPath, { force: true });
38369
+ await rm9(bootstrapMarkerPath, { force: true });
37996
38370
  if (this.stopped) {
37997
- await rm8(markerPath, { force: true });
38371
+ await rm9(markerPath, { force: true });
37998
38372
  return;
37999
38373
  }
38000
38374
  }
@@ -38019,10 +38393,10 @@ class PrimeManager {
38019
38393
  }
38020
38394
  async tryClaimPath(dir, markerPath) {
38021
38395
  try {
38022
- await mkdir15(dir, { recursive: true });
38396
+ await mkdir16(dir, { recursive: true });
38023
38397
  } catch {}
38024
38398
  try {
38025
- await writeFile5(markerPath, "", { encoding: "utf8", flag: "wx" });
38399
+ await writeFile6(markerPath, "", { encoding: "utf8", flag: "wx" });
38026
38400
  return markerPath;
38027
38401
  } catch (error) {
38028
38402
  const code2 = error.code;
@@ -38035,7 +38409,7 @@ class PrimeManager {
38035
38409
  const dir = this.markerDir(accountFingerprint);
38036
38410
  const prefix = `${encodeURIComponent(accountId2)}-`;
38037
38411
  try {
38038
- return (await readdir4(dir)).some((entry2) => entry2.startsWith(prefix));
38412
+ return (await readdir5(dir)).some((entry2) => entry2.startsWith(prefix));
38039
38413
  } catch (error) {
38040
38414
  if (error.code === "ENOENT")
38041
38415
  return false;
@@ -38147,21 +38521,21 @@ class PrimeManager {
38147
38521
  async sweepMarkerDirectory(dir, now) {
38148
38522
  let entries;
38149
38523
  try {
38150
- entries = await readdir4(dir);
38524
+ entries = await readdir5(dir);
38151
38525
  } catch {
38152
38526
  return 0;
38153
38527
  }
38154
38528
  let swept = 0;
38155
38529
  for (const entry2 of entries) {
38156
38530
  try {
38157
- const path2 = join24(dir, entry2);
38531
+ const path2 = join25(dir, entry2);
38158
38532
  const s = await stat12(path2);
38159
38533
  if (s.isDirectory()) {
38160
38534
  swept += await this.sweepMarkerDirectory(path2, now);
38161
38535
  continue;
38162
38536
  }
38163
38537
  if (now - s.mtimeMs > PRIME_MARKER_MAX_AGE_MS) {
38164
- await rm8(path2, { force: true });
38538
+ await rm9(path2, { force: true });
38165
38539
  swept += 1;
38166
38540
  }
38167
38541
  } catch {}
@@ -38176,24 +38550,24 @@ class PrimeManager {
38176
38550
  }
38177
38551
  }
38178
38552
  // src/quota-header-feed.ts
38179
- import { randomUUID as randomUUID19 } from "node:crypto";
38553
+ import { randomUUID as randomUUID20 } from "node:crypto";
38180
38554
  import {
38181
38555
  chmod as chmod3,
38182
- lstat as lstat18,
38183
- mkdir as mkdir16,
38184
- readdir as readdir5,
38556
+ lstat as lstat19,
38557
+ mkdir as mkdir17,
38558
+ readdir as readdir6,
38185
38559
  readFile as readFile13,
38186
38560
  rename as rename14,
38187
- rm as rm9,
38561
+ rm as rm10,
38188
38562
  stat as stat13,
38189
- writeFile as writeFile6
38563
+ writeFile as writeFile7
38190
38564
  } from "node:fs/promises";
38191
- import { tmpdir as tmpdir8 } from "node:os";
38192
- import { join as join25 } from "node:path";
38565
+ import { tmpdir as tmpdir9 } from "node:os";
38566
+ import { join as join26 } from "node:path";
38193
38567
  var QUOTA_HEADER_FEED_SCHEMA_VERSION = 3;
38194
38568
  var QUOTA_HEADER_FEED_LEASE_MS = 180000;
38195
38569
  function getDefaultQuotaHeaderFeedDirectory() {
38196
- return process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR ?? join25(tmpdir8(), "opencode-anthropic-auth", "quota-header-feed");
38570
+ return process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR ?? join26(tmpdir9(), "opencode-anthropic-auth", "quota-header-feed");
38197
38571
  }
38198
38572
  function configuredAnthropicOAuthAccountCount(input) {
38199
38573
  const fallbackCount = input.storage?.accounts.filter(isOAuthAccount).length ?? 0;
@@ -38351,8 +38725,8 @@ class QuotaHeaderFeedRegistry {
38351
38725
  writeChain = Promise.resolve();
38352
38726
  constructor(options = {}) {
38353
38727
  this.options = options;
38354
- const instanceId = options.instanceId ?? `${process.pid}-${randomUUID19()}`;
38355
- this.filePath = join25(options.directory ?? getDefaultQuotaHeaderFeedDirectory(), `${instanceId}.json`);
38728
+ const instanceId = options.instanceId ?? `${process.pid}-${randomUUID20()}`;
38729
+ this.filePath = join26(options.directory ?? getDefaultQuotaHeaderFeedDirectory(), `${instanceId}.json`);
38356
38730
  }
38357
38731
  publish(entry2) {
38358
38732
  const { accountKey, quota: quota2 } = entry2;
@@ -38381,24 +38755,24 @@ class QuotaHeaderFeedRegistry {
38381
38755
  return Promise.reject(new Error("Invalid quota header feed account key"));
38382
38756
  this.writeChain = this.writeChain.catch(() => {}).then(async () => {
38383
38757
  const directory = this.options.directory ?? getDefaultQuotaHeaderFeedDirectory();
38384
- await mkdir16(directory, { recursive: true, mode: 448 });
38758
+ await mkdir17(directory, { recursive: true, mode: 448 });
38385
38759
  await chmod3(directory, 448);
38386
38760
  await this.reapStaleSiblingLeases(directory);
38387
38761
  let entries = {};
38388
38762
  try {
38389
- const record9 = JSON.parse(await readFile13(this.filePath, "utf8"));
38390
- if (record9.version === QUOTA_HEADER_FEED_SCHEMA_VERSION && record9.entries && typeof record9.entries === "object")
38391
- entries = record9.entries;
38763
+ const record10 = JSON.parse(await readFile13(this.filePath, "utf8"));
38764
+ if (record10.version === QUOTA_HEADER_FEED_SCHEMA_VERSION && record10.entries && typeof record10.entries === "object")
38765
+ entries = record10.entries;
38392
38766
  } catch {}
38393
38767
  entries[accountKey] = cleanEntry;
38394
- const tempPath = `${this.filePath}.${randomUUID19()}.tmp`;
38768
+ const tempPath = `${this.filePath}.${randomUUID20()}.tmp`;
38395
38769
  try {
38396
- await writeFile6(tempPath, `${JSON.stringify({ version: QUOTA_HEADER_FEED_SCHEMA_VERSION, lease_horizon_ms: this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS, entries })}
38770
+ await writeFile7(tempPath, `${JSON.stringify({ version: QUOTA_HEADER_FEED_SCHEMA_VERSION, lease_horizon_ms: this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS, entries })}
38397
38771
  `, { mode: 384 });
38398
38772
  await chmod3(tempPath, 384);
38399
38773
  await rename14(tempPath, this.filePath);
38400
38774
  } finally {
38401
- await rm9(tempPath, { force: true });
38775
+ await rm10(tempPath, { force: true });
38402
38776
  }
38403
38777
  });
38404
38778
  return this.writeChain;
@@ -38408,12 +38782,12 @@ class QuotaHeaderFeedRegistry {
38408
38782
  const leaseMs = this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS;
38409
38783
  let names2;
38410
38784
  try {
38411
- names2 = await readdir5(directory);
38785
+ names2 = await readdir6(directory);
38412
38786
  } catch {
38413
38787
  return;
38414
38788
  }
38415
38789
  await Promise.all(names2.filter((name) => /^\d+-[0-9a-f-]+\.json$/i.test(name)).map(async (name) => {
38416
- const path2 = join25(directory, name);
38790
+ const path2 = join26(directory, name);
38417
38791
  if (path2 === this.filePath)
38418
38792
  return;
38419
38793
  try {
@@ -38421,10 +38795,10 @@ class QuotaHeaderFeedRegistry {
38421
38795
  if (file.mtimeMs > now || now - file.mtimeMs < leaseMs)
38422
38796
  return;
38423
38797
  await this.options.beforeRemoveFile?.(path2);
38424
- const current = await lstat18(path2);
38798
+ const current = await lstat19(path2);
38425
38799
  if (current.ino !== file.ino || current.mtimeMs !== file.mtimeMs)
38426
38800
  return;
38427
- await (this.options.removeFile ?? ((target2) => rm9(target2)))(path2);
38801
+ await (this.options.removeFile ?? ((target2) => rm10(target2)))(path2);
38428
38802
  } catch {}
38429
38803
  }));
38430
38804
  }
@@ -38435,17 +38809,17 @@ class QuotaHeaderFeedRegistry {
38435
38809
  const leaseMs = this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS;
38436
38810
  let names2;
38437
38811
  try {
38438
- names2 = (await readdir5(directory)).filter((name) => name.endsWith(".json"));
38812
+ names2 = (await readdir6(directory)).filter((name) => name.endsWith(".json"));
38439
38813
  } catch {
38440
38814
  return [];
38441
38815
  }
38442
38816
  const newest = new Map;
38443
38817
  await Promise.all(names2.map(async (name) => {
38444
38818
  try {
38445
- const record9 = JSON.parse(await readFile13(join25(directory, name), "utf8"));
38446
- if (record9.version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || !record9.entries || typeof record9.entries !== "object")
38819
+ const record10 = JSON.parse(await readFile13(join26(directory, name), "utf8"));
38820
+ if (record10.version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || !record10.entries || typeof record10.entries !== "object")
38447
38821
  return;
38448
- for (const [accountKey, candidate] of Object.entries(record9.entries)) {
38822
+ for (const [accountKey, candidate] of Object.entries(record10.entries)) {
38449
38823
  if (!candidate || typeof candidate !== "object" || candidate.schema_version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || candidate.provider !== "anthropic" || !validIdentity(candidate))
38450
38824
  continue;
38451
38825
  const observed = candidate.observed_at_ms;
@@ -38461,7 +38835,7 @@ class QuotaHeaderFeedRegistry {
38461
38835
  }
38462
38836
  async dispose() {
38463
38837
  await this.writeChain.catch(() => {});
38464
- await rm9(this.filePath, { force: true });
38838
+ await rm10(this.filePath, { force: true });
38465
38839
  }
38466
38840
  }
38467
38841
  // src/quotas.ts
@@ -38622,11 +38996,11 @@ function buildClaudeQuotaSummary(input) {
38622
38996
  `).trimEnd();
38623
38997
  }
38624
38998
  // src/request-gzip.ts
38625
- import { mkdir as mkdir17, readFile as readFile14, rename as rename15, rm as rm10, writeFile as writeFile7 } from "node:fs/promises";
38626
- import { basename as basename10, dirname as dirname23, join as join26 } from "node:path";
38627
- import { promisify } from "node:util";
38628
- import { gzip } from "node:zlib";
38629
- var gzipAsync = promisify(gzip);
38999
+ import { mkdir as mkdir18, readFile as readFile14, rename as rename15, rm as rm11, writeFile as writeFile8 } from "node:fs/promises";
39000
+ import { basename as basename10, dirname as dirname23, join as join27 } from "node:path";
39001
+ import { promisify as promisify2 } from "node:util";
39002
+ import { gzip as gzip2 } from "node:zlib";
39003
+ var gzipAsync = promisify2(gzip2);
38630
39004
  var GZIP_REQUEST_BODIES_ENV = "CLAUDE_CODE_GZIP_REQUEST_BODIES";
38631
39005
  var GZIP_HOST = "api.anthropic.com";
38632
39006
  var GZIP_LEVEL = 6;
@@ -38737,7 +39111,7 @@ class RequestGzipLatch {
38737
39111
  const age = typeof latchedAt === "number" && Number.isFinite(latchedAt) ? this.now() - latchedAt : -1;
38738
39112
  if (age >= 0 && age < GZIP_LATCH_TTL_MS)
38739
39113
  return true;
38740
- await rm10(this.path, { force: true }).catch(() => {});
39114
+ await rm11(this.path, { force: true }).catch(() => {});
38741
39115
  return false;
38742
39116
  }
38743
39117
  async persist(status) {
@@ -38747,12 +39121,12 @@ class RequestGzipLatch {
38747
39121
  return;
38748
39122
  const temporary = `${this.path}.${process.pid}.tmp`;
38749
39123
  try {
38750
- await mkdir17(dirname23(this.path), { recursive: true });
38751
- await writeFile7(temporary, `${JSON.stringify({ latchedAt: this.now(), status })}
39124
+ await mkdir18(dirname23(this.path), { recursive: true });
39125
+ await writeFile8(temporary, `${JSON.stringify({ latchedAt: this.now(), status })}
38752
39126
  `, { mode: 384 });
38753
39127
  await rename15(temporary, this.path);
38754
39128
  } catch {
38755
- await rm10(temporary, { force: true }).catch(() => {});
39129
+ await rm11(temporary, { force: true }).catch(() => {});
38756
39130
  }
38757
39131
  }
38758
39132
  }
@@ -38769,7 +39143,7 @@ function getRequestGzipLatch(path2) {
38769
39143
  function getRequestGzipLatchPath(accountStoragePath) {
38770
39144
  const name = basename10(accountStoragePath);
38771
39145
  const stem = name.endsWith(".json") ? name.slice(0, -5) : name;
38772
- return join26(dirname23(accountStoragePath), `${stem}-request-gzip.json`);
39146
+ return join27(dirname23(accountStoragePath), `${stem}-request-gzip.json`);
38773
39147
  }
38774
39148
  async function decideRequestGzip(options) {
38775
39149
  if (!CLAUDE_CODE_GZIPS_REQUEST_BODIES)
@@ -38838,13 +39212,13 @@ function isInvalidJsonBody(text6) {
38838
39212
  }
38839
39213
  if (!parsed || typeof parsed !== "object")
38840
39214
  return false;
38841
- const record9 = parsed;
38842
- const error = record9.error;
38843
- if (record9.type === "error" && error && typeof error === "object" && typeof error.type === "string" && typeof error.message === "string") {
39215
+ const record10 = parsed;
39216
+ const error = record10.error;
39217
+ if (record10.type === "error" && error && typeof error === "object" && typeof error.type === "string" && typeof error.message === "string") {
38844
39218
  const message = error.message;
38845
39219
  return INVALID_JSON_MESSAGES.some((prefix) => message.startsWith(prefix));
38846
39220
  }
38847
- return typeof record9.error === "string" && record9.reason === "bad_json" && BAD_JSON_TEXT.test(record9.error);
39221
+ return typeof record10.error === "string" && record10.reason === "bad_json" && BAD_JSON_TEXT.test(record10.error);
38848
39222
  }
38849
39223
  async function classifyGzipRejection(response) {
38850
39224
  const { status } = response;
@@ -38997,14 +39371,14 @@ function executeLaneStartCommand(input) {
38997
39371
  };
38998
39372
  }
38999
39373
  // src/state-layout-decision.ts
39000
- import { mkdir as mkdir18, readdir as readdir8 } from "node:fs/promises";
39374
+ import { mkdir as mkdir19, readdir as readdir9 } from "node:fs/promises";
39001
39375
  import { homedir as homedir8 } from "node:os";
39002
- import { basename as basename13, dirname as dirname25, join as join30 } from "node:path";
39376
+ import { basename as basename13, dirname as dirname25, join as join31 } from "node:path";
39003
39377
 
39004
39378
  // src/layout-fence.ts
39005
- import { open as open13, readdir as readdir6 } from "node:fs/promises";
39379
+ import { open as open14, readdir as readdir7 } from "node:fs/promises";
39006
39380
  import { homedir as homedir6 } from "node:os";
39007
- import { basename as basename11, join as join27, resolve as resolve18 } from "node:path";
39381
+ import { basename as basename11, join as join28, resolve as resolve18 } from "node:path";
39008
39382
  var STATE_PATH_OVERRIDE_VARIABLES = [
39009
39383
  "OPENCODE_ANTHROPIC_AUTH_FILE",
39010
39384
  "OPENCODE_ANTHROPIC_AUTH_STATE_FILE",
@@ -39040,7 +39414,7 @@ async function holderFenceBlockers(input) {
39040
39414
  const files = new Set(input.files);
39041
39415
  const blockers = [];
39042
39416
  for (const dir of [...new Set(input.directories)].sort()) {
39043
- const holderFile = join27(dir, HOLDER_FILE_NAME);
39417
+ const holderFile = join28(dir, HOLDER_FILE_NAME);
39044
39418
  let contents;
39045
39419
  try {
39046
39420
  contents = await readHolderFile(holderFile);
@@ -39054,8 +39428,8 @@ async function holderFenceBlockers(input) {
39054
39428
  }
39055
39429
  for (const value of contents?.entries ?? []) {
39056
39430
  const life = holderEntryLiveness(value);
39057
- const record9 = value;
39058
- const listed = Array.isArray(record9?.files) ? record9.files.filter((file) => typeof file === "string") : undefined;
39431
+ const record10 = value;
39432
+ const listed = Array.isArray(record10?.files) ? record10.files.filter((file) => typeof file === "string") : undefined;
39059
39433
  if (!life || !listed) {
39060
39434
  blockers.push({
39061
39435
  kind: "holder",
@@ -39075,7 +39449,7 @@ async function holderFenceBlockers(input) {
39075
39449
  kind: "holder",
39076
39450
  holderFile,
39077
39451
  pid: life.pid,
39078
- role: typeof record9.role === "string" ? record9.role : null,
39452
+ role: typeof record10.role === "string" ? record10.role : null,
39079
39453
  file: overlap
39080
39454
  });
39081
39455
  }
@@ -39090,7 +39464,7 @@ function defaultPreNArtifactLocations(env = process.env, home = homedir6()) {
39090
39464
  });
39091
39465
  const rpcOverride = env.OPENCODE_ANTHROPIC_AUTH_RPC_DIR?.trim();
39092
39466
  return {
39093
- rpcRoots: [join27(root, "rpc")],
39467
+ rpcRoots: [join28(root, "rpc")],
39094
39468
  rpcDirs: rpcOverride ? [resolve18(rpcOverride)] : [],
39095
39469
  cacheKeepDirs: [
39096
39470
  ...new Set([
@@ -39106,7 +39480,7 @@ function defaultPreNArtifactLocations(env = process.env, home = homedir6()) {
39106
39480
  }
39107
39481
  async function listDir(dir, blockers) {
39108
39482
  try {
39109
- return await readdir6(dir);
39483
+ return await readdir7(dir);
39110
39484
  } catch (error) {
39111
39485
  if (errorCode5(error) === "ENOENT")
39112
39486
  return [];
@@ -39124,7 +39498,7 @@ async function readArtifact(path2, blockers) {
39124
39498
  let text6;
39125
39499
  let mtimeMs;
39126
39500
  try {
39127
- const file = await open13(path2, "r");
39501
+ const file = await open14(path2, "r");
39128
39502
  try {
39129
39503
  text6 = await file.readFile("utf8");
39130
39504
  mtimeMs = (await file.stat()).mtimeMs;
@@ -39151,16 +39525,16 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
39151
39525
  const portDirs = [...locations.rpcDirs];
39152
39526
  for (const root of locations.rpcRoots)
39153
39527
  for (const name of await listDir(root, blockers))
39154
- portDirs.push(join27(root, name));
39528
+ portDirs.push(join28(root, name));
39155
39529
  for (const dir of [...new Set(portDirs)]) {
39156
39530
  for (const name of await listDir(dir, blockers)) {
39157
39531
  if (!/^port-\d+\.json$/.test(name))
39158
39532
  continue;
39159
- const path2 = join27(dir, name);
39160
- const record9 = await readArtifact(path2, blockers);
39161
- if (record9 === undefined || stamped(record9.value))
39533
+ const path2 = join28(dir, name);
39534
+ const record10 = await readArtifact(path2, blockers);
39535
+ if (record10 === undefined || stamped(record10.value))
39162
39536
  continue;
39163
- const { value, startedAt } = record9;
39537
+ const { value, startedAt } = record10;
39164
39538
  const pid = value.pid;
39165
39539
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0) {
39166
39540
  blockers.push({ kind: "artifact-scan", path: path2, reason: "invalid" });
@@ -39175,12 +39549,12 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
39175
39549
  const match = /^(\d+)-.+\.json$/.exec(name);
39176
39550
  if (!match)
39177
39551
  continue;
39178
- const path2 = join27(dir, name);
39179
- const record9 = await readArtifact(path2, blockers);
39180
- if (record9 === undefined || stamped(record9.value))
39552
+ const path2 = join28(dir, name);
39553
+ const record10 = await readArtifact(path2, blockers);
39554
+ if (record10 === undefined || stamped(record10.value))
39181
39555
  continue;
39182
39556
  const pid = Number(match[1]);
39183
- if (!recordPredatesBoot(record9.startedAt, clock) && pidAlive2(pid))
39557
+ if (!recordPredatesBoot(record10.startedAt, clock) && pidAlive2(pid))
39184
39558
  blockers.push({ kind: "pre-n-artifact", artifact: path2, pid });
39185
39559
  }
39186
39560
  }
@@ -39202,15 +39576,15 @@ function describeFenceBlocker(blocker) {
39202
39576
  }
39203
39577
 
39204
39578
  // src/state-layout-move.ts
39205
- import { randomUUID as randomUUID20 } from "node:crypto";
39206
- import { lstat as lstat19, readdir as readdir7, readFile as readFile15, stat as stat14, unlink as unlink10 } from "node:fs/promises";
39207
- import { basename as basename12, dirname as dirname24, join as join28, sep as sep2 } from "node:path";
39579
+ import { randomUUID as randomUUID21 } from "node:crypto";
39580
+ import { lstat as lstat20, readdir as readdir8, readFile as readFile15, stat as stat14, unlink as unlink10 } from "node:fs/promises";
39581
+ import { basename as basename12, dirname as dirname24, join as join29, sep as sep2 } from "node:path";
39208
39582
  var ACCOUNT_FILE = "anthropic-auth.json";
39209
39583
  var ACCOUNT_STATE_FILE = "anthropic-auth-state.json";
39210
39584
  var LAYOUT_LOCK_NAME = "runtime-layout";
39211
39585
  var LAYOUT_LOCK_TIMEOUT_MS = 120000;
39212
39586
  async function resolveLegacyDatasetFiles(configDir) {
39213
- const oldPaths = await resolveNativePoolPaths(join28(configDir, ACCOUNT_FILE), join28(configDir, ACCOUNT_STATE_FILE), { kind: "legacy" });
39587
+ const oldPaths = await resolveNativePoolPaths(join29(configDir, ACCOUNT_FILE), join29(configDir, ACCOUNT_STATE_FILE), { kind: "legacy" });
39214
39588
  return {
39215
39589
  oldDir: await canonicalPath(configDir),
39216
39590
  oldPaths,
@@ -39218,8 +39592,8 @@ async function resolveLegacyDatasetFiles(configDir) {
39218
39592
  };
39219
39593
  }
39220
39594
  async function resolveRelocationDataset(input) {
39221
- const legacyConfig = join28(input.configDir, ACCOUNT_FILE);
39222
- const legacyState = join28(input.configDir, ACCOUNT_STATE_FILE);
39595
+ const legacyConfig = join29(input.configDir, ACCOUNT_FILE);
39596
+ const legacyState = join29(input.configDir, ACCOUNT_STATE_FILE);
39223
39597
  const { oldDir, oldPaths, oldVault } = await resolveLegacyDatasetFiles(input.configDir);
39224
39598
  const stateHome = { kind: "state-home", dir: input.sub };
39225
39599
  const newPaths = await resolveNativePoolPaths(legacyConfig, legacyState, stateHome);
@@ -39248,7 +39622,7 @@ async function resolveRelocationDataset(input) {
39248
39622
  role,
39249
39623
  from: pairs[role][0],
39250
39624
  to: pairs[role][1],
39251
- configured: join28(input.configDir, STATE_HOME_FILE_NAMES[role])
39625
+ configured: join29(input.configDir, STATE_HOME_FILE_NAMES[role])
39252
39626
  })),
39253
39627
  storageIds: { local: oldPaths.storageId, vault: oldVault.storageId }
39254
39628
  };
@@ -39270,8 +39644,8 @@ function errorCode6(error) {
39270
39644
  }
39271
39645
  function transitionHolderFiles(dataset) {
39272
39646
  return [
39273
- join28(dataset.oldDir, HOLDER_FILE_NAME),
39274
- join28(dataset.sub, HOLDER_FILE_NAME)
39647
+ join29(dataset.oldDir, HOLDER_FILE_NAME),
39648
+ join29(dataset.sub, HOLDER_FILE_NAME)
39275
39649
  ].sort();
39276
39650
  }
39277
39651
  async function acquireHolderLock(ctx, holderFile, timeoutMs) {
@@ -39288,7 +39662,7 @@ async function acquireHolderLock(ctx, holderFile, timeoutMs) {
39288
39662
  }
39289
39663
  }
39290
39664
  async function acquireHolderLocks(dataset, ctx) {
39291
- const oldHolders = join28(dataset.oldDir, HOLDER_FILE_NAME);
39665
+ const oldHolders = join29(dataset.oldDir, HOLDER_FILE_NAME);
39292
39666
  for (const file of transitionHolderFiles(dataset)) {
39293
39667
  if (file === oldHolders)
39294
39668
  await stateLayoutStep(ctx, "old-holders-locking");
@@ -39468,14 +39842,14 @@ async function drainCoalescedWrites(dataset) {
39468
39842
  await drainVaultQuota(dataset.oldVault.roster);
39469
39843
  forgetRelocationObservations();
39470
39844
  }
39471
- function relocationTombstone(record9) {
39845
+ function relocationTombstone(record10) {
39472
39846
  return `${JSON.stringify({
39473
39847
  version: 0,
39474
- relocatedTo: record9.sub,
39475
- stateRoot: record9.stateRoot,
39476
- identity: record9.identity,
39477
- attempt: record9.attempt,
39478
- by: record9.by
39848
+ relocatedTo: record10.sub,
39849
+ stateRoot: record10.stateRoot,
39850
+ identity: record10.identity,
39851
+ attempt: record10.attempt,
39852
+ by: record10.by
39479
39853
  })}
39480
39854
  `;
39481
39855
  }
@@ -39494,7 +39868,7 @@ function restoringPath(path2, attempt) {
39494
39868
  }
39495
39869
  async function exists3(path2) {
39496
39870
  try {
39497
- await lstat19(path2);
39871
+ await lstat20(path2);
39498
39872
  return true;
39499
39873
  } catch (error) {
39500
39874
  if (errorCode6(error) === "ENOENT")
@@ -39504,7 +39878,7 @@ async function exists3(path2) {
39504
39878
  }
39505
39879
  async function removeOwnStaging(path2) {
39506
39880
  try {
39507
- const info = await lstat19(path2);
39881
+ const info = await lstat20(path2);
39508
39882
  if (info.isFile())
39509
39883
  await unlink10(path2);
39510
39884
  } catch (error) {
@@ -39512,17 +39886,17 @@ async function removeOwnStaging(path2) {
39512
39886
  throw error;
39513
39887
  }
39514
39888
  }
39515
- function recordFilesProblem(record9, dataset) {
39516
- if (record9.files.length !== dataset.slots.length)
39517
- return `it lists ${record9.files.length} files, not ${dataset.slots.length}`;
39889
+ function recordFilesProblem(record10, dataset) {
39890
+ if (record10.files.length !== dataset.slots.length)
39891
+ return `it lists ${record10.files.length} files, not ${dataset.slots.length}`;
39518
39892
  for (const slot of dataset.slots) {
39519
- const file = record9.files.find((candidate) => candidate.role === slot.role);
39893
+ const file = record10.files.find((candidate) => candidate.role === slot.role);
39520
39894
  if (!file)
39521
39895
  return `it has no ${slot.role} entry`;
39522
39896
  if (file.from !== slot.from || file.to !== slot.to)
39523
39897
  return `its ${slot.role} entry names ${file.from} and ${file.to}, not ${slot.from} and ${slot.to}`;
39524
39898
  }
39525
- for (const file of record9.restore?.files ?? []) {
39899
+ for (const file of record10.restore?.files ?? []) {
39526
39900
  const slot = dataset.slots.find((candidate) => candidate.role === file.role);
39527
39901
  if (!slot || file.from !== slot.from || file.to !== slot.to)
39528
39902
  return `its restore lists ${file.from} and ${file.to} for ${file.role}`;
@@ -39547,7 +39921,7 @@ async function movePreconditionFailure(dataset, platform) {
39547
39921
  for (const path2 of new Set([slot.configured, slot.from])) {
39548
39922
  let info;
39549
39923
  try {
39550
- info = await lstat19(path2);
39924
+ info = await lstat20(path2);
39551
39925
  } catch (error) {
39552
39926
  if (errorCode6(error) === "ENOENT")
39553
39927
  continue;
@@ -39564,7 +39938,7 @@ async function movePreconditionFailure(dataset, platform) {
39564
39938
  anyOld ||= fromExists;
39565
39939
  if (await exists3(slot.to)) {
39566
39940
  if (fromExists) {
39567
- const [a, b] = await Promise.all([lstat19(slot.from), lstat19(slot.to)]);
39941
+ const [a, b] = await Promise.all([lstat20(slot.from), lstat20(slot.to)]);
39568
39942
  if (a.dev === b.dev && a.ino === b.ino)
39569
39943
  return `${slot.from} and ${slot.to} are the same file`;
39570
39944
  }
@@ -39639,15 +40013,15 @@ async function owned2(ctx, step, expect) {
39639
40013
  if (outcome2 === "skipped")
39640
40014
  throw new Error(`anthropic-auth stopped: ${step.kind === "rename" ? step.to : step.path} changed while it was being replaced`);
39641
40015
  }
39642
- async function rollbackPreparing(record9, dataset, ctx) {
39643
- const { attempt } = record9;
40016
+ async function rollbackPreparing(record10, dataset, ctx) {
40017
+ const { attempt } = record10;
39644
40018
  const slot = (role) => {
39645
- const found = record9.files.find((file) => file.role === role);
40019
+ const found = record10.files.find((file) => file.role === role);
39646
40020
  if (!found)
39647
40021
  throw new StateLayoutRollbackRefused(dataset.sub, `no ${role} entry`);
39648
40022
  return found;
39649
40023
  };
39650
- if (record9.barriers.journal === "present") {
40024
+ if (record10.barriers.journal === "present") {
39651
40025
  const journal = slot("journal");
39652
40026
  const moving = movingJournalPath(journal.from, attempt);
39653
40027
  const movingThere = await exists3(moving);
@@ -39662,7 +40036,7 @@ async function rollbackPreparing(record9, dataset, ctx) {
39662
40036
  await stateLayoutStep(ctx, "rollback:journal");
39663
40037
  for (const role of ["localRuntime", "vaultRuntime"]) {
39664
40038
  const file = slot(role);
39665
- const original = record9.barriers[role].original;
40039
+ const original = record10.barriers[role].original;
39666
40040
  await removeOwnStaging(relocatingPath(file.from, attempt));
39667
40041
  const found = await tombstoneAttempt(file.from);
39668
40042
  if (found !== undefined && found !== attempt)
@@ -39691,7 +40065,7 @@ async function rollbackPreparing(record9, dataset, ctx) {
39691
40065
  }
39692
40066
  await ctx.fs.syncDirectory(dataset.oldDir);
39693
40067
  await stateLayoutStep(ctx, "rollback:old-dir-flushed");
39694
- for (const file of record9.files) {
40068
+ for (const file of record10.files) {
39695
40069
  await removeOwnStaging(relocatingPath(file.to, attempt));
39696
40070
  if (file.sha256 === null)
39697
40071
  continue;
@@ -39702,14 +40076,14 @@ async function rollbackPreparing(record9, dataset, ctx) {
39702
40076
  continue;
39703
40077
  await owned2(ctx, { kind: "unlink", path: file.to }, expectDigest(file.to, file.sha256));
39704
40078
  }
39705
- for (const name of await readdir7(dataset.sub))
40079
+ for (const name of await readdir8(dataset.sub))
39706
40080
  if (isLayoutRecordStage(name, attempt))
39707
- await removeOwnStaging(join28(dataset.sub, name));
40081
+ await removeOwnStaging(join29(dataset.sub, name));
39708
40082
  await stateLayoutStep(ctx, "rollback:destination-removed");
39709
40083
  await ctx.fs.syncDirectory(dataset.sub);
39710
40084
  await stateLayoutStep(ctx, "rollback:sub-flushed");
39711
40085
  const rolledBack = {
39712
- ...record9,
40086
+ ...record10,
39713
40087
  phase: "rolled-back",
39714
40088
  rolledBackAt: ctx.now()
39715
40089
  };
@@ -39721,19 +40095,19 @@ async function rollbackPreparing(record9, dataset, ctx) {
39721
40095
  forgetRelocationObservations();
39722
40096
  return rolledBack;
39723
40097
  }
39724
- async function cleanupOldCopies(record9, dataset, ctx) {
40098
+ async function cleanupOldCopies(record10, dataset, ctx) {
39725
40099
  const kept = [];
39726
40100
  const conflict = [];
39727
40101
  const publish = (next2) => publishStateLayoutRecord(next2, {
39728
40102
  assertLeases: () => ctx.stack.assertAll(),
39729
40103
  expect: expectRecord(dataset.sub, {
39730
40104
  phase: "committed",
39731
- attempt: record9.attempt
40105
+ attempt: record10.attempt
39732
40106
  })
39733
40107
  }, ctx.fs);
39734
40108
  const outcome2 = () => {
39735
40109
  const next2 = {
39736
- ...record9,
40110
+ ...record10,
39737
40111
  cleanup: conflict.length ? "conflict" : kept.length ? "kept" : "done",
39738
40112
  ...kept.length ? { kept: [...kept] } : {},
39739
40113
  ...conflict.length ? { conflict: [...conflict] } : {}
@@ -39749,16 +40123,16 @@ async function cleanupOldCopies(record9, dataset, ctx) {
39749
40123
  return stateLayoutConflict(first?.old ?? dataset.oldPaths.state, first?.new ?? dataset.newPaths.state, cause);
39750
40124
  };
39751
40125
  try {
39752
- const journalSlot = record9.files.find((file) => file.role === "journal");
40126
+ const journalSlot = record10.files.find((file) => file.role === "journal");
39753
40127
  if (journalSlot && await exists3(journalSlot.from))
39754
40128
  conflict.push({ old: journalSlot.from, new: journalSlot.to });
39755
40129
  for (const role of RELOCATION_ROLES) {
39756
40130
  if (role === "localRuntime" || role === "vaultRuntime")
39757
40131
  continue;
39758
- const file = record9.files.find((candidate) => candidate.role === role);
40132
+ const file = record10.files.find((candidate) => candidate.role === role);
39759
40133
  if (!file)
39760
40134
  continue;
39761
- const path2 = role === "journal" ? movingJournalPath(file.from, record9.attempt) : file.from;
40135
+ const path2 = role === "journal" ? movingJournalPath(file.from, record10.attempt) : file.from;
39762
40136
  await ctx.stack.assertAll();
39763
40137
  const credential2 = CREDENTIAL_AUTHORITY_ROLES.includes(role);
39764
40138
  let digest3;
@@ -39807,7 +40181,7 @@ class MoveRefused extends Error {
39807
40181
  }
39808
40182
  }
39809
40183
  async function moveDataset(dataset, ctx, checkArtifacts) {
39810
- const attempt = randomUUID20();
40184
+ const attempt = randomUUID21();
39811
40185
  const files = [];
39812
40186
  for (const slot of dataset.slots)
39813
40187
  files.push({
@@ -39818,7 +40192,7 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
39818
40192
  });
39819
40193
  const sha = (role) => files.find((file) => file.role === role)?.sha256 ?? null;
39820
40194
  await ctx.stack.assertAll();
39821
- const configDirPath = join28(dataset.sub, STATE_HOME_FILE_NAMES.configDirMarker);
40195
+ const configDirPath = join29(dataset.sub, STATE_HOME_FILE_NAMES.configDirMarker);
39822
40196
  if (!await exists3(configDirPath)) {
39823
40197
  const stage = `${configDirPath}.${attempt}.tmp`;
39824
40198
  await createOwnerOnlyFile(ctx.fs, stage, Buffer.from(`${JSON.stringify({ version: 1, identity: dataset.identity })}
@@ -39829,7 +40203,7 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
39829
40203
  await removeOwnStaging(stage);
39830
40204
  }
39831
40205
  }
39832
- const holderFile = join28(dataset.sub, HOLDER_FILE_NAME);
40206
+ const holderFile = join29(dataset.sub, HOLDER_FILE_NAME);
39833
40207
  if (!await exists3(holderFile))
39834
40208
  await writeJsonAtomic(holderFile, { version: 1, entries: [] }, {
39835
40209
  beforeRename: () => ctx.stack.assertAll(),
@@ -39920,8 +40294,8 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
39920
40294
  logger2.error("state-layout", "anthropic-auth could not move its state; keeping the old folder", {
39921
40295
  reason
39922
40296
  });
39923
- const record9 = await rollbackAfterFailure(preparing, dataset, ctx);
39924
- return { status: "rolled-back", reason, record: record9 };
40297
+ const record10 = await rollbackAfterFailure(preparing, dataset, ctx);
40298
+ return { status: "rolled-back", reason, record: record10 };
39925
40299
  }
39926
40300
  const committed = {
39927
40301
  ...preparing,
@@ -39942,8 +40316,8 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
39942
40316
  await syncCommitted(dataset, ctx);
39943
40317
  } else if (onDisk?.phase === "preparing" && onDisk.attempt === attempt) {
39944
40318
  const reason = error instanceof Error ? error.message : String(error);
39945
- const record9 = await rollbackAfterFailure(preparing, dataset, ctx);
39946
- return { status: "rolled-back", reason, record: record9 };
40319
+ const record10 = await rollbackAfterFailure(preparing, dataset, ctx);
40320
+ return { status: "rolled-back", reason, record: record10 };
39947
40321
  } else
39948
40322
  throw error;
39949
40323
  }
@@ -39980,10 +40354,10 @@ async function rollbackAfterFailure(preparing, dataset, ctx) {
39980
40354
  }
39981
40355
 
39982
40356
  // src/state-layout-restore.ts
39983
- import { randomUUID as randomUUID21 } from "node:crypto";
40357
+ import { randomUUID as randomUUID22 } from "node:crypto";
39984
40358
  import { readFile as readFile16 } from "node:fs/promises";
39985
40359
  import { homedir as homedir7 } from "node:os";
39986
- import { join as join29 } from "node:path";
40360
+ import { join as join30 } from "node:path";
39987
40361
  var DATA_ROLES = [
39988
40362
  "localPoolState",
39989
40363
  "localRoster",
@@ -39996,10 +40370,10 @@ function refused2(message, paths = [], cause) {
39996
40370
  logger2.error("state-layout", message, { code: "restore-refused", paths });
39997
40371
  return new StateLayoutRefusalError("restore-refused", message, paths, cause);
39998
40372
  }
39999
- function requireRestoreDetail(record9) {
40000
- const restore = record9.restore;
40373
+ function requireRestoreDetail(record10) {
40374
+ const restore = record10.restore;
40001
40375
  if (!restore?.attempt || !restore.files || !restore.runtimes)
40002
- throw refused2(`${layoutRecordPath(record9.sub)} records an unfinished restore without the files it moved, so anthropic-auth can't finish it.`, [layoutRecordPath(record9.sub)]);
40376
+ throw refused2(`${layoutRecordPath(record10.sub)} records an unfinished restore without the files it moved, so anthropic-auth can't finish it.`, [layoutRecordPath(record10.sub)]);
40003
40377
  return {
40004
40378
  ...restore,
40005
40379
  attempt: restore.attempt,
@@ -40060,9 +40434,9 @@ async function syncObservedRestoreRecord(dataset, ctx) {
40060
40434
  throw new StateLayoutRefusalError("unsafe", `anthropic-auth could not make ${path2} durable, so it won't finish restoring its state; run ${RESTORE_LEGACY_COMMAND} again.`, [path2], error);
40061
40435
  }
40062
40436
  }
40063
- async function finishRestoreRetirement(record9, dataset, ctx) {
40064
- const restore = requireRestoreDetail(record9);
40065
- const kept = [...record9.restore?.kept ?? []];
40437
+ async function finishRestoreRetirement(record10, dataset, ctx) {
40438
+ const restore = requireRestoreDetail(record10);
40439
+ const kept = [...record10.restore?.kept ?? []];
40066
40440
  for (const file of restore.files) {
40067
40441
  try {
40068
40442
  const digest3 = await digestFile(file.to);
@@ -40087,7 +40461,7 @@ async function finishRestoreRetirement(record9, dataset, ctx) {
40087
40461
  await ctx.fs.syncDirectory(dataset.sub);
40088
40462
  await stateLayoutStep(ctx, "restore:sub-flushed");
40089
40463
  const done2 = {
40090
- ...record9,
40464
+ ...record10,
40091
40465
  restore: { ...restore, cleanup: "done", ...kept.length ? { kept } : {} }
40092
40466
  };
40093
40467
  await publishStateLayoutRecord(done2, {
@@ -40098,13 +40472,13 @@ async function finishRestoreRetirement(record9, dataset, ctx) {
40098
40472
  forgetRelocationObservations();
40099
40473
  return done2;
40100
40474
  }
40101
- async function discardAbandonedRestore(record9, dataset, ctx) {
40102
- const restore = requireRestoreDetail(record9);
40475
+ async function discardAbandonedRestore(record10, dataset, ctx) {
40476
+ const restore = requireRestoreDetail(record10);
40103
40477
  for (const file of restore.files)
40104
40478
  if (await exists3(file.staging))
40105
40479
  await owned2(ctx, { kind: "unlink", path: file.staging }, expectPresent(file.staging));
40106
40480
  await ctx.fs.syncDirectory(dataset.oldDir);
40107
- const { restore: _abandoned, ...move } = record9;
40481
+ const { restore: _abandoned, ...move } = record10;
40108
40482
  const committed = { ...move, phase: "committed" };
40109
40483
  await publishStateLayoutRecord(committed, {
40110
40484
  assertLeases: () => ctx.stack.assertAll(),
@@ -40114,8 +40488,8 @@ async function discardAbandonedRestore(record9, dataset, ctx) {
40114
40488
  forgetRelocationObservations();
40115
40489
  return committed;
40116
40490
  }
40117
- async function classifyStagedRestore(record9, dataset) {
40118
- const restore = requireRestoreDetail(record9);
40491
+ async function classifyStagedRestore(record10, dataset) {
40492
+ const restore = requireRestoreDetail(record10);
40119
40493
  const problems = [];
40120
40494
  const listed = (role) => restore.files.find((file) => file.role === role);
40121
40495
  const isStaged = async (file) => {
@@ -40175,7 +40549,7 @@ async function classifyStagedRestore(record9, dataset) {
40175
40549
  if (!file)
40176
40550
  continue;
40177
40551
  const staged = await isStaged(file);
40178
- if (staged && tombstone === record9.attempt)
40552
+ if (staged && tombstone === record10.attempt)
40179
40553
  barriers.push({
40180
40554
  role,
40181
40555
  action: { kind: "rename", file, over: "tombstone" }
@@ -40187,7 +40561,7 @@ async function classifyStagedRestore(record9, dataset) {
40187
40561
  problems.push(`${file.staging} is missing, so ${legacy} can't be restored`);
40188
40562
  else
40189
40563
  problems.push(`${legacy} is no longer this move's tombstone while ${file.staging} still waits to replace it`);
40190
- } else if (tombstone === record9.attempt)
40564
+ } else if (tombstone === record10.attempt)
40191
40565
  barriers.push({
40192
40566
  role,
40193
40567
  action: { kind: "unlink-tombstone", path: legacy }
@@ -40206,36 +40580,36 @@ async function classifyStagedRestore(record9, dataset) {
40206
40580
  }
40207
40581
  return { data, barriers, problems };
40208
40582
  }
40209
- async function act(action, record9, ctx) {
40583
+ async function act(action, record10, ctx) {
40210
40584
  if (action.kind === "none")
40211
40585
  return;
40212
40586
  if (action.kind === "unlink-tombstone") {
40213
- await owned2(ctx, { kind: "unlink", path: action.path }, expectTombstone(action.path, record9.attempt));
40587
+ await owned2(ctx, { kind: "unlink", path: action.path }, expectTombstone(action.path, record10.attempt));
40214
40588
  return;
40215
40589
  }
40216
40590
  const { file, over } = action;
40217
- const target2 = over === "absent" ? expectAbsent(file.from) : over === "present" ? expectPresent(file.from) : expectTombstone(file.from, record9.attempt);
40591
+ const target2 = over === "absent" ? expectAbsent(file.from) : over === "present" ? expectPresent(file.from) : expectTombstone(file.from, record10.attempt);
40218
40592
  await owned2(ctx, { kind: "rename", from: file.staging, to: file.from }, both(expectDigest(file.staging, file.sha256), target2));
40219
40593
  }
40220
- async function finishStagedRestore(record9, dataset, ctx) {
40221
- const restore = requireRestoreDetail(record9);
40222
- const plan2 = await classifyStagedRestore(record9, dataset);
40594
+ async function finishStagedRestore(record10, dataset, ctx) {
40595
+ const restore = requireRestoreDetail(record10);
40596
+ const plan2 = await classifyStagedRestore(record10, dataset);
40223
40597
  if (plan2.problems.length)
40224
40598
  throw refused2(`anthropic-auth can't finish restoring its state to ${dataset.oldDir}: ${plan2.problems.join("; ")}. Then run ${RESTORE_LEGACY_COMMAND} again.`, [dataset.oldDir]);
40225
40599
  for (const { role, action } of plan2.data) {
40226
- await act(action, record9, ctx);
40600
+ await act(action, record10, ctx);
40227
40601
  await stateLayoutStep(ctx, `restore:placed:${role}`);
40228
40602
  }
40229
40603
  await ctx.fs.syncDirectory(dataset.oldDir);
40230
40604
  await stateLayoutStep(ctx, "restore:data-flushed");
40231
40605
  for (const { role, action } of plan2.barriers) {
40232
- await act(action, record9, ctx);
40606
+ await act(action, record10, ctx);
40233
40607
  await stateLayoutStep(ctx, `restore:placed:${role}`);
40234
40608
  }
40235
40609
  await ctx.fs.syncDirectory(dataset.oldDir);
40236
40610
  await stateLayoutStep(ctx, "restore:barriers-flushed");
40237
40611
  const restored = {
40238
- ...record9,
40612
+ ...record10,
40239
40613
  phase: "restored",
40240
40614
  restore: { ...restore, cleanup: "pending" }
40241
40615
  };
@@ -40247,41 +40621,41 @@ async function finishStagedRestore(record9, dataset, ctx) {
40247
40621
  forgetRelocationObservations();
40248
40622
  return finishRestoreRetirement(restored, dataset, ctx);
40249
40623
  }
40250
- async function newRestoreProblems(record9, dataset, options) {
40624
+ async function newRestoreProblems(record10, dataset, options) {
40251
40625
  const problems = [];
40252
- if (record9.cleanup === "pending")
40626
+ if (record10.cleanup === "pending")
40253
40627
  problems.push("the move has not finished removing the old copies; start OpenCode with anthropic-auth once and close it again");
40254
- if (record9.cleanup === "conflict")
40255
- for (const pair of record9.conflict ?? [])
40628
+ if (record10.cleanup === "conflict")
40629
+ for (const pair of record10.conflict ?? [])
40256
40630
  problems.push(`two copies of the account state exist (${pair.old} and ${pair.new}); keep the one you trust and move the other out of both folders`);
40257
- if (record9.cleanup === "kept") {
40258
- for (const path2 of record9.kept ?? [])
40631
+ if (record10.cleanup === "kept") {
40632
+ for (const path2 of record10.kept ?? [])
40259
40633
  if (await exists3(path2))
40260
40634
  problems.push(`${path2} changed after the move and was kept; move it aside or delete it`);
40261
40635
  }
40262
- problems.push(...await holderProblems(join29(dataset.sub, HOLDER_FILE_NAME), options.liveness, true), ...await holderProblems(join29(dataset.oldDir, HOLDER_FILE_NAME), options.liveness, false));
40636
+ problems.push(...await holderProblems(join30(dataset.sub, HOLDER_FILE_NAME), options.liveness, true), ...await holderProblems(join30(dataset.oldDir, HOLDER_FILE_NAME), options.liveness, false));
40263
40637
  const artifacts = options.artifacts ?? defaultPreNArtifactLocations(options.env ?? process.env, options.home ?? homedir7());
40264
40638
  for (const blocker of await preNArtifactBlockers(artifacts, options.liveness?.pidAlive, options.liveness))
40265
40639
  problems.push(`${describeFenceBlocker(blocker)} is still running`);
40266
40640
  for (const slot of dataset.slots) {
40267
40641
  if (slot.role === "localRuntime" || slot.role === "vaultRuntime") {
40268
- if (await tombstoneAttempt(slot.from) !== record9.attempt)
40642
+ if (await tombstoneAttempt(slot.from) !== record10.attempt)
40269
40643
  problems.push(`${slot.from} is no longer the marker the move left there; move it aside`);
40270
40644
  continue;
40271
40645
  }
40272
40646
  if (await exists3(slot.from))
40273
40647
  problems.push(`${slot.from} came back after the move; move it aside or delete it`);
40274
40648
  }
40275
- const moving = movingJournalPath(dataset.oldPaths.journal, record9.attempt);
40649
+ const moving = movingJournalPath(dataset.oldPaths.journal, record10.attempt);
40276
40650
  if (await exists3(moving))
40277
40651
  problems.push(`${moving} is still there; move it aside or delete it`);
40278
40652
  return problems;
40279
40653
  }
40280
- async function startRestore(record9, dataset, ctx, options) {
40281
- const problems = await newRestoreProblems(record9, dataset, options);
40654
+ async function startRestore(record10, dataset, ctx, options) {
40655
+ const problems = await newRestoreProblems(record10, dataset, options);
40282
40656
  if (problems.length)
40283
40657
  throw refused2(`anthropic-auth can't restore its state to ${dataset.oldDir} yet: ${problems.join("; ")}. Then run ${RESTORE_LEGACY_COMMAND} again.`, [dataset.oldDir, dataset.sub]);
40284
- const attempt = randomUUID21();
40658
+ const attempt = randomUUID22();
40285
40659
  const files = [];
40286
40660
  for (const slot of dataset.slots) {
40287
40661
  let digest3;
@@ -40302,7 +40676,7 @@ async function startRestore(record9, dataset, ctx, options) {
40302
40676
  }
40303
40677
  const listed = (role) => files.some((file) => file.role === role);
40304
40678
  const restoring = {
40305
- ...record9,
40679
+ ...record10,
40306
40680
  phase: "restoring",
40307
40681
  restore: {
40308
40682
  attempt,
@@ -40320,7 +40694,7 @@ async function startRestore(record9, dataset, ctx, options) {
40320
40694
  const current = await readStateLayoutRecord(dataset.sub).catch(() => {
40321
40695
  return;
40322
40696
  });
40323
- return current?.phase === "committed" && current.attempt === record9.attempt ? undefined : "layout.json is no longer the committed move";
40697
+ return current?.phase === "committed" && current.attempt === record10.attempt ? undefined : "layout.json is no longer the committed move";
40324
40698
  }
40325
40699
  }, ctx.fs);
40326
40700
  await stateLayoutStep(ctx, "restore:restoring-written");
@@ -40345,11 +40719,11 @@ async function startRestore(record9, dataset, ctx, options) {
40345
40719
  await stateLayoutStep(ctx, "restore:staged-written");
40346
40720
  return finishStagedRestore(staged, dataset, ctx);
40347
40721
  }
40348
- function requireRecordMatches(record9, dataset) {
40722
+ function requireRecordMatches(record10, dataset) {
40349
40723
  const path2 = layoutRecordPath(dataset.sub);
40350
- if (record9.identity !== dataset.identity || record9.oldDir !== dataset.oldDir || record9.sub !== dataset.sub || record9.storageIds.local !== dataset.storageIds.local || record9.storageIds.vault !== dataset.storageIds.vault)
40351
- throw new StateLayoutRefusalError("other-dataset", `${path2} belongs to another config folder (${record9.oldDir}), not ${dataset.oldDir}. Check OPENCODE_CONFIG_DIR and any symlink to the config folder.`, [path2, record9.oldDir, dataset.oldDir]);
40352
- const problem = recordFilesProblem(record9, dataset);
40724
+ 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)
40725
+ 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]);
40726
+ const problem = recordFilesProblem(record10, dataset);
40353
40727
  if (problem)
40354
40728
  throw new StateLayoutRefusalError("marker-unreadable", `anthropic-auth can't use ${path2}: ${problem}.`, [path2]);
40355
40729
  }
@@ -40361,12 +40735,12 @@ async function readRecord(sub) {
40361
40735
  throw new StateLayoutRefusalError("marker-unreadable", `anthropic-auth can't read ${path2}, which records where its state is, so it won't restore anything. Restore the file from a backup or ask for help; do not delete the state folder.`, [path2], error);
40362
40736
  }
40363
40737
  }
40364
- function finished(record9) {
40365
- if (record9 === undefined)
40738
+ function finished(record10) {
40739
+ if (record10 === undefined)
40366
40740
  return "anthropic-auth has not moved this state out of the config folder";
40367
- if (record9.phase === "rolled-back")
40741
+ if (record10.phase === "rolled-back")
40368
40742
  return "the move of this state was undone before it finished";
40369
- if (record9.phase === "restored" && record9.restore?.cleanup === "done")
40743
+ if (record10.phase === "restored" && record10.restore?.cleanup === "done")
40370
40744
  return "this state was already restored to the config folder";
40371
40745
  return;
40372
40746
  }
@@ -40431,32 +40805,32 @@ async function restoreLegacyLayout(options = {}) {
40431
40805
  }
40432
40806
  await stateLayoutStep(ctx, "restore:locks-held");
40433
40807
  for (let round = 0;round < 3; round++) {
40434
- const record9 = await readRecord(sub);
40435
- const done2 = finished(record9);
40436
- if (done2 || !record9)
40808
+ const record10 = await readRecord(sub);
40809
+ const done2 = finished(record10);
40810
+ if (done2 || !record10)
40437
40811
  return { status: "not-moved", reason: done2 ?? "" };
40438
- requireRecordMatches(record9, dataset);
40812
+ requireRecordMatches(record10, dataset);
40439
40813
  let result;
40440
- switch (record9.phase) {
40814
+ switch (record10.phase) {
40441
40815
  case "preparing":
40442
40816
  throw refused2(`A move of anthropic-auth's state for ${dataset.oldDir} did not finish. Start OpenCode with anthropic-auth once to undo it; there is then nothing to restore.`, [layoutRecordPath(sub)]);
40443
40817
  case "restoring":
40444
- await discardAbandonedRestore(record9, dataset, ctx);
40818
+ await discardAbandonedRestore(record10, dataset, ctx);
40445
40819
  continue;
40446
40820
  case "committed":
40447
- result = await startRestore(record9, dataset, ctx, options);
40821
+ result = await startRestore(record10, dataset, ctx, options);
40448
40822
  break;
40449
40823
  case "restore-staged": {
40450
40824
  await syncObservedRestoreRecord(dataset, ctx);
40451
- const problems = await holderProblems(join29(dataset.sub, HOLDER_FILE_NAME), options.liveness, true);
40825
+ const problems = await holderProblems(join30(dataset.sub, HOLDER_FILE_NAME), options.liveness, true);
40452
40826
  if (problems.length)
40453
40827
  throw refused2(`anthropic-auth can't finish restoring its state to ${dataset.oldDir}: ${problems.join("; ")}. Close them, then run ${RESTORE_LEGACY_COMMAND} again.`, [dataset.sub]);
40454
- result = await finishStagedRestore(record9, dataset, ctx);
40828
+ result = await finishStagedRestore(record10, dataset, ctx);
40455
40829
  break;
40456
40830
  }
40457
40831
  default:
40458
40832
  await syncObservedRestoreRecord(dataset, ctx);
40459
- result = await finishRestoreRetirement(record9, dataset, ctx);
40833
+ result = await finishRestoreRetirement(record10, dataset, ctx);
40460
40834
  }
40461
40835
  return {
40462
40836
  status: "restored",
@@ -40514,13 +40888,13 @@ function configIdentity(configDir) {
40514
40888
  refuse5("io-failed", `anthropic-auth can't resolve its config folder ${configDir}: ${errorMessage(error)}`, [configDir], error);
40515
40889
  }
40516
40890
  }
40517
- function noMoveRecord(record9) {
40518
- return record9 === undefined || record9.phase === "rolled-back" || record9.phase === "restored" && record9.restore?.cleanup === "done";
40891
+ function noMoveRecord(record10) {
40892
+ return record10 === undefined || record10.phase === "rolled-back" || record10.phase === "restored" && record10.restore?.cleanup === "done";
40519
40893
  }
40520
- function requireRecordMatches2(record9, dataset) {
40521
- if (record9.identity !== dataset.identity || record9.oldDir !== dataset.oldDir || record9.sub !== dataset.sub || record9.storageIds.local !== dataset.storageIds.local || record9.storageIds.vault !== dataset.storageIds.vault)
40522
- refuse5("other-dataset", `${layoutRecordPath(dataset.sub)} belongs to another config folder (${record9.oldDir}), not ${dataset.oldDir}. Check OPENCODE_CONFIG_DIR and any symlink to the config folder.`, [layoutRecordPath(dataset.sub), record9.oldDir, dataset.oldDir]);
40523
- const problem = recordFilesProblem(record9, dataset);
40894
+ function requireRecordMatches2(record10, dataset) {
40895
+ 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)
40896
+ 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]);
40897
+ const problem = recordFilesProblem(record10, dataset);
40524
40898
  if (problem)
40525
40899
  markerUnreadable(dataset.sub, new Error(problem));
40526
40900
  }
@@ -40563,7 +40937,7 @@ function deferLegacyRegistration(paths, dir, options, error) {
40563
40937
  }
40564
40938
  async function registerLegacyHeld(oldDir, paths, identity3, options, ctx) {
40565
40939
  try {
40566
- await registerHeld(join30(oldDir, HOLDER_FILE_NAME), paths, "legacy", identity3, options, ctx);
40940
+ await registerHeld(join31(oldDir, HOLDER_FILE_NAME), paths, "legacy", identity3, options, ctx);
40567
40941
  return;
40568
40942
  } catch (error) {
40569
40943
  if (unmovedRegistrationPolicy(options) === "mandatory")
@@ -40583,10 +40957,10 @@ function chooseLegacy(paths, reasons2, log2, registration) {
40583
40957
  };
40584
40958
  }
40585
40959
  async function admitHeld(dataset, options, ctx, moved, allowPendingCleanup) {
40586
- const record9 = await readRecord2(dataset.sub);
40587
- if (record9?.phase !== "committed" || !allowPendingCleanup && record9.cleanup === "pending")
40960
+ const record10 = await readRecord2(dataset.sub);
40961
+ if (record10?.phase !== "committed" || !allowPendingCleanup && record10.cleanup === "pending")
40588
40962
  return "changed";
40589
- requireRecordMatches2(record9, dataset);
40963
+ requireRecordMatches2(record10, dataset);
40590
40964
  const conflict = await checkStateHomeServing(stateHomeServingFiles(dataset.newPaths));
40591
40965
  if (conflict) {
40592
40966
  logger2.error("state-layout", conflict.message, {
@@ -40595,15 +40969,15 @@ async function admitHeld(dataset, options, ctx, moved, allowPendingCleanup) {
40595
40969
  });
40596
40970
  throw conflict;
40597
40971
  }
40598
- await warnReappearedMetadata(record9);
40599
- await registerHeld(join30(dataset.sub, HOLDER_FILE_NAME), dataset.newPaths, "state-home", dataset.identity, options, ctx);
40972
+ await warnReappearedMetadata(record10);
40973
+ await registerHeld(join31(dataset.sub, HOLDER_FILE_NAME), dataset.newPaths, "state-home", dataset.identity, options, ctx);
40600
40974
  const layout = { kind: "state-home", dir: dataset.sub };
40601
40975
  recordProcessStateLayout(dataset.oldPaths.legacyConfig, layout);
40602
- return { kind: "state-home", layout, dataset, record: record9, moved };
40976
+ return { kind: "state-home", layout, dataset, record: record10, moved };
40603
40977
  }
40604
40978
  async function admitFast(dataset, options, ctx) {
40605
40979
  try {
40606
- await acquireHolderLock(ctx, join30(dataset.sub, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40980
+ await acquireHolderLock(ctx, join31(dataset.sub, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40607
40981
  } catch (error) {
40608
40982
  if (error instanceof LockContentionError)
40609
40983
  busy(dataset.configDir, error);
@@ -40645,12 +41019,12 @@ async function readPointers(dataset) {
40645
41019
  }
40646
41020
  async function legacyHeld(dataset, options, ctx, reasons2, log2 = true) {
40647
41021
  const pointed = await readPointers(dataset);
40648
- const record9 = await readRecord2(dataset.sub);
40649
- if (record9)
40650
- requireRecordMatches2(record9, dataset);
40651
- if (pointed && noMoveRecord(record9))
41022
+ const record10 = await readRecord2(dataset.sub);
41023
+ if (record10)
41024
+ requireRecordMatches2(record10, dataset);
41025
+ if (pointed && noMoveRecord(record10))
40652
41026
  markerUnreadable(dataset.sub);
40653
- if (pointed || !noMoveRecord(record9))
41027
+ if (pointed || !noMoveRecord(record10))
40654
41028
  return "changed";
40655
41029
  const registration = await registerLegacyHeld(dataset.oldDir, dataset.oldPaths, dataset.identity, options, ctx);
40656
41030
  return chooseLegacy(dataset.oldPaths, reasons2, log2, registration);
@@ -40668,7 +41042,7 @@ async function oldFolderTransition(old, recordedMovingJournal) {
40668
41042
  }
40669
41043
  let names2;
40670
41044
  try {
40671
- names2 = await readdir8(dirname25(journal));
41045
+ names2 = await readdir9(dirname25(journal));
40672
41046
  } catch (error) {
40673
41047
  if (error?.code === "ENOENT")
40674
41048
  return false;
@@ -40689,10 +41063,10 @@ async function recordedMovingJournal(journal, identity3, options) {
40689
41063
  env: options.env ?? process.env,
40690
41064
  home: options.home ?? homedir8()
40691
41065
  });
40692
- const record9 = await readStateLayoutRecord(await canonicalPath(target2.dir));
40693
- if (record9?.barriers.journal !== "present")
41066
+ const record10 = await readStateLayoutRecord(await canonicalPath(target2.dir));
41067
+ if (record10?.barriers.journal !== "present")
40694
41068
  return;
40695
- return movingJournalPath(journal, record9.attempt);
41069
+ return movingJournalPath(journal, record10.attempt);
40696
41070
  } catch {
40697
41071
  return;
40698
41072
  }
@@ -40711,7 +41085,7 @@ async function legacyWhileMoveOff(configDir, identity3, options, ctx, stayReason
40711
41085
  await stateLayoutStep(ctx, "old-holders-locking");
40712
41086
  let lockFailure;
40713
41087
  try {
40714
- await acquireHolderLock(ctx, join30(old.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
41088
+ await acquireHolderLock(ctx, join31(old.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40715
41089
  } catch (error) {
40716
41090
  lockFailure = { error };
40717
41091
  }
@@ -40741,8 +41115,8 @@ async function decideOpenCodeStateLayout(options) {
40741
41115
  holderLockTimeoutMs: options.timeouts?.holderMs
40742
41116
  });
40743
41117
  if (isExplicit(env)) {
40744
- const legacyConfig = env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join30(configDir, ACCOUNT_FILE2);
40745
- const legacyState = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (legacyConfig.endsWith(ACCOUNT_FILE2) ? join30(dirname25(legacyConfig), ACCOUNT_STATE_FILE2) : `${legacyConfig}.state.json`);
41118
+ const legacyConfig = env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join31(configDir, ACCOUNT_FILE2);
41119
+ const legacyState = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (legacyConfig.endsWith(ACCOUNT_FILE2) ? join31(dirname25(legacyConfig), ACCOUNT_STATE_FILE2) : `${legacyConfig}.state.json`);
40746
41120
  const paths = await resolveNativePoolPaths(legacyConfig, legacyState, LEGACY_STATE_LAYOUT);
40747
41121
  const registration = await registerNativePoolHolder({
40748
41122
  paths,
@@ -40765,7 +41139,7 @@ async function decideOpenCodeStateLayout(options) {
40765
41139
  } catch (error) {
40766
41140
  if (unmovedRegistrationPolicy(options) === "mandatory")
40767
41141
  throw new HolderRegistrationError("unavailable", configDir, error);
40768
- const paths = await resolveNativePoolPaths(join30(configDir, ACCOUNT_FILE2), join30(configDir, ACCOUNT_STATE_FILE2), LEGACY_STATE_LAYOUT);
41142
+ const paths = await resolveNativePoolPaths(join31(configDir, ACCOUNT_FILE2), join31(configDir, ACCOUNT_STATE_FILE2), LEGACY_STATE_LAYOUT);
40769
41143
  return chooseLegacy(paths, [reason], true, deferLegacyRegistration(paths, configDir, options, error));
40770
41144
  }
40771
41145
  identity3 = configIdentity(configDir);
@@ -40816,26 +41190,26 @@ async function decideOpenCodeStateLayout(options) {
40816
41190
  refuse5("other-dataset", `${sub} holds anthropic-auth state for ${marker.identity}, not for ${target2.identity}. Check OPENCODE_CONFIG_DIR and any symlink to the config folder.`, [sub, marker.identity, target2.identity]);
40817
41191
  const pointed = await readPointers(dataset);
40818
41192
  for (let round = 0;round < 3; round++) {
40819
- const record9 = await readRecord2(sub);
40820
- if (record9)
40821
- requireRecordMatches2(record9, dataset);
40822
- if (pointed && noMoveRecord(record9))
41193
+ const record10 = await readRecord2(sub);
41194
+ if (record10)
41195
+ requireRecordMatches2(record10, dataset);
41196
+ if (pointed && noMoveRecord(record10))
40823
41197
  markerUnreadable(sub);
40824
- if (record9?.phase === "restore-staged")
41198
+ if (record10?.phase === "restore-staged")
40825
41199
  restoreUnfinished(dataset.oldDir);
40826
- if (record9?.phase === "committed" && (record9.cleanup === "done" || record9.cleanup === "kept")) {
41200
+ if (record10?.phase === "committed" && (record10.cleanup === "done" || record10.cleanup === "kept")) {
40827
41201
  const admitted = await admitFast(dataset, options, newContext());
40828
41202
  if (admitted !== "changed")
40829
41203
  return admitted;
40830
41204
  continue;
40831
41205
  }
40832
- if ((overrides.length || neverMove.length || !moveEnabled) && noMoveRecord(record9)) {
41206
+ if ((overrides.length || neverMove.length || !moveEnabled) && noMoveRecord(record10)) {
40833
41207
  const ctx = newContext();
40834
41208
  const reasons2 = stayReasons.length ? stayReasons : [RELOCATION_MOVE_DISABLED_REASON];
40835
41209
  try {
40836
41210
  await stateLayoutStep(ctx, "old-holders-locking");
40837
41211
  try {
40838
- await acquireHolderLock(ctx, join30(dataset.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
41212
+ await acquireHolderLock(ctx, join31(dataset.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
40839
41213
  } catch (error) {
40840
41214
  if (unmovedRegistrationPolicy(options) === "mandatory")
40841
41215
  throw error;
@@ -40870,8 +41244,8 @@ async function decideOpenCodeStateLayout(options) {
40870
41244
  } catch (error) {
40871
41245
  if (!(error instanceof LockContentionError))
40872
41246
  refuse5("io-failed", `anthropic-auth can't take the layout lock beside ${layoutRecordPath(sub)}: ${errorMessage(error)}`, [layoutRecordPath(sub)], error);
40873
- const record9 = await readRecord2(sub);
40874
- if (record9?.phase === "committed" && (record9.cleanup === "done" || record9.cleanup === "kept")) {
41247
+ const record10 = await readRecord2(sub);
41248
+ if (record10?.phase === "committed" && (record10.cleanup === "done" || record10.cleanup === "kept")) {
40875
41249
  const admitted = await admitFast(dataset, options, newContext());
40876
41250
  if (admitted !== "changed")
40877
41251
  return admitted;
@@ -40899,7 +41273,7 @@ async function ensureSubfolder(sub, fs3) {
40899
41273
  await ensureWindowsOwnerOnlyDirectory(sub);
40900
41274
  return;
40901
41275
  }
40902
- const created = await mkdir18(sub, { recursive: true, mode: 448 });
41276
+ const created = await mkdir19(sub, { recursive: true, mode: 448 });
40903
41277
  if (created === undefined)
40904
41278
  return;
40905
41279
  for (let dir = dirname25(sub);; dir = dirname25(dir)) {
@@ -40914,36 +41288,36 @@ async function ensureSubfolder(sub, fs3) {
40914
41288
  }
40915
41289
  }
40916
41290
  async function underLayoutLock(dataset, options, ctx, overrides, neverMove) {
40917
- const record9 = await readRecord2(dataset.sub);
40918
- if (record9)
40919
- requireRecordMatches2(record9, dataset);
40920
- if (record9?.phase === "restore-staged")
41291
+ const record10 = await readRecord2(dataset.sub);
41292
+ if (record10)
41293
+ requireRecordMatches2(record10, dataset);
41294
+ if (record10?.phase === "restore-staged")
40921
41295
  restoreUnfinished(dataset.oldDir);
40922
- if (record9?.phase === "restoring" || record9?.phase === "restored" && record9.restore?.cleanup !== "done") {
41296
+ if (record10?.phase === "restoring" || record10?.phase === "restored" && record10.restore?.cleanup !== "done") {
40923
41297
  if (overrides.length)
40924
41298
  refuse5("restore-unfinished", `A restore of anthropic-auth's state for ${dataset.oldDir} did not finish; start anthropic-auth without path overrides (${overrides.join(", ")}), or run ${RESTORE_LEGACY_COMMAND} again.`, [layoutRecordPath(dataset.sub)]);
40925
41299
  await acquireHolderLocks(dataset, ctx);
40926
- if (record9.phase === "restoring")
40927
- await discardAbandonedRestore(record9, dataset, ctx);
41300
+ if (record10.phase === "restoring")
41301
+ await discardAbandonedRestore(record10, dataset, ctx);
40928
41302
  else {
40929
41303
  await syncObservedRestoreRecord(dataset, ctx);
40930
- await finishRestoreRetirement(record9, dataset, ctx);
41304
+ await finishRestoreRetirement(record10, dataset, ctx);
40931
41305
  }
40932
41306
  return "again";
40933
41307
  }
40934
- if (record9?.phase === "committed") {
41308
+ if (record10?.phase === "committed") {
40935
41309
  try {
40936
41310
  await syncCommitted(dataset, ctx);
40937
41311
  } catch (error) {
40938
41312
  refuse5("unsafe", `anthropic-auth could not make the move of its state to ${dataset.sub} durable, so it won't use either copy.`, [layoutRecordPath(dataset.sub)], error);
40939
41313
  }
40940
41314
  await acquireHolderLocks(dataset, ctx);
40941
- if ((record9.cleanup === "pending" || record9.cleanup === "conflict") && !overrides.length) {
41315
+ if ((record10.cleanup === "pending" || record10.cleanup === "conflict") && !overrides.length) {
40942
41316
  const mark = ctx.stack.size;
40943
41317
  try {
40944
41318
  await drainCoalescedWrites(dataset);
40945
41319
  await acquireDataLocks(dataset, ctx);
40946
- await cleanupOldCopies(record9, dataset, ctx);
41320
+ await cleanupOldCopies(record10, dataset, ctx);
40947
41321
  } catch (error) {
40948
41322
  if (error instanceof StateLayoutCrash)
40949
41323
  throw error;
@@ -40957,13 +41331,13 @@ async function underLayoutLock(dataset, options, ctx, overrides, neverMove) {
40957
41331
  const admitted2 = await admitHeld(dataset, options, ctx, false, true);
40958
41332
  return admitted2 === "changed" ? "again" : admitted2;
40959
41333
  }
40960
- if (record9?.phase === "preparing") {
41334
+ if (record10?.phase === "preparing") {
40961
41335
  if (overrides.length)
40962
41336
  refuse5("unsafe", `A move of anthropic-auth's state for ${dataset.oldDir} did not finish; start anthropic-auth without path overrides (${overrides.join(", ")}) to finish it.`, [layoutRecordPath(dataset.sub)]);
40963
41337
  await acquireHolderLocks(dataset, ctx);
40964
41338
  await drainCoalescedWrites(dataset);
40965
41339
  await acquireDataLocks(dataset, ctx);
40966
- await rollbackPreparing(record9, dataset, ctx);
41340
+ await rollbackPreparing(record10, dataset, ctx);
40967
41341
  return "again";
40968
41342
  }
40969
41343
  const stay = async (reasons2, log2 = true) => {
@@ -41150,60 +41524,26 @@ function supportsTurnEndNote(model) {
41150
41524
  var runnerReports = new Map;
41151
41525
  var SKIP_REPORT_LIMIT = 512;
41152
41526
  var RUNNER_REPORT_SESSION_LIMIT = 1024;
41153
- function readRunnerNotes(handle) {
41154
- try {
41155
- const read = handle.turn_notes;
41156
- if (typeof read !== "function")
41157
- return [];
41158
- const answer = read.call(handle);
41159
- if (answer !== null && (typeof answer === "object" || typeof answer === "function") && typeof Reflect.get(answer, "then") === "function") {
41160
- Promise.resolve(answer).catch(() => {});
41161
- return [];
41162
- }
41163
- if (!Array.isArray(answer))
41164
- return [];
41165
- const notes = [];
41166
- for (let index = 0;index < answer.length; index++) {
41167
- try {
41168
- const entry2 = answer[index];
41169
- if (!isRecord20(entry2) || Array.isArray(entry2))
41170
- continue;
41171
- const { after_tool_use_id, text: text6 } = entry2;
41172
- if (typeof after_tool_use_id !== "string" || typeof text6 !== "string" || !text6.trim() || new TextEncoder().encode(text6).byteLength > 16384)
41173
- continue;
41174
- notes.push({ after_tool_use_id, text: text6 });
41175
- } catch {}
41176
- }
41177
- return notes;
41178
- } catch {
41179
- return [];
41180
- }
41181
- }
41182
- function runnerNotes(sessionId) {
41527
+ function hasRunnerTurnNotes(sessionId) {
41183
41528
  try {
41184
41529
  const routing = Reflect.get(globalThis, Symbol.for("cortexkit.routing"));
41185
41530
  if (typeof routing !== "function")
41186
- return;
41531
+ return false;
41187
41532
  const handle = routing(sessionId);
41188
- if (isRecord20(handle) && typeof handle.turn_notes === "function")
41189
- return { handle, notes: readRunnerNotes(handle) };
41533
+ return isRecord20(handle) && typeof handle.turn_notes === "function";
41190
41534
  } catch {
41191
- return;
41535
+ return false;
41192
41536
  }
41193
41537
  }
41194
- function reportRunnerNote(handle, payload) {
41195
- Promise.resolve().then(() => {
41196
- const report = handle.report;
41197
- if (typeof report === "function")
41198
- return report.call(handle, payload);
41199
- }).catch(() => {});
41538
+ function reportRunnerNote(payload) {
41539
+ Promise.resolve().then(() => reportRouting(payload)).catch(() => {});
41200
41540
  }
41201
41541
  function applyRunnerTurnNotes(body, options) {
41202
41542
  if (!options.sessionId)
41203
41543
  return 0;
41204
- const runner = runnerNotes(options.sessionId);
41205
- if (!runner)
41544
+ if (!hasRunnerTurnNotes(options.sessionId))
41206
41545
  return 0;
41546
+ const notes = turnNotes(options.sessionId);
41207
41547
  let reported3 = runnerReports.get(options.sessionId);
41208
41548
  if (reported3) {
41209
41549
  runnerReports.delete(options.sessionId);
@@ -41220,7 +41560,8 @@ function applyRunnerTurnNotes(body, options) {
41220
41560
  const model = options.modelId;
41221
41561
  if (reported3.models.get(model) !== supported) {
41222
41562
  reported3.models.set(model, supported);
41223
- reportRunnerNote(runner.handle, {
41563
+ reportRunnerNote({
41564
+ sessionId: options.sessionId,
41224
41565
  kind: "turn_notes_supported",
41225
41566
  model,
41226
41567
  supported
@@ -41238,21 +41579,22 @@ function applyRunnerTurnNotes(body, options) {
41238
41579
  }
41239
41580
  const insertions = new Map;
41240
41581
  let inserted = 0;
41241
- for (const note of runner.notes) {
41242
- const index = anchors.get(note.after_tool_use_id);
41582
+ for (const note of notes) {
41583
+ const index = anchors.get(note.afterToolUseId);
41243
41584
  const next = index === undefined ? undefined : messages[index + 1];
41244
41585
  const reason = !options.isOAuth ? "not_oauth" : !supported ? "unsupported_model" : index === undefined ? "anchor_missing" : isRecord20(next) && next.role === "user" ? "before_user_message" : undefined;
41245
41586
  if (reason) {
41246
- if (!reported3.skipped.has(note.after_tool_use_id)) {
41587
+ if (!reported3.skipped.has(note.afterToolUseId)) {
41247
41588
  if (reported3.skipped.size >= SKIP_REPORT_LIMIT) {
41248
41589
  const oldest = reported3.skipped.values().next();
41249
41590
  if (!oldest.done)
41250
41591
  reported3.skipped.delete(oldest.value);
41251
41592
  }
41252
- reported3.skipped.add(note.after_tool_use_id);
41253
- reportRunnerNote(runner.handle, {
41593
+ reported3.skipped.add(note.afterToolUseId);
41594
+ reportRunnerNote({
41595
+ sessionId: options.sessionId,
41254
41596
  kind: "turn_note_skipped",
41255
- after_tool_use_id: note.after_tool_use_id,
41597
+ after_tool_use_id: note.afterToolUseId,
41256
41598
  reason
41257
41599
  });
41258
41600
  }
@@ -41326,6 +41668,7 @@ export {
41326
41668
  writerStamp,
41327
41669
  writeNativeHostAuth,
41328
41670
  writeDumpFile,
41671
+ withNativeLock,
41329
41672
  withAbortableFetch,
41330
41673
  usesPerTurnControl,
41331
41674
  usagePublicationRefusalIsFatal,
@@ -41512,6 +41855,7 @@ export {
41512
41855
  logger2 as logger,
41513
41856
  log,
41514
41857
  localDayKey,
41858
+ legacyCacheKeepStoreDirectory,
41515
41859
  killswitchRetryAfterSeconds,
41516
41860
  killswitchPassesPolicy,
41517
41861
  isWithinCacheKeepWindow,
@@ -41708,6 +42052,7 @@ export {
41708
42052
  captureNativeLocalPoolBinding,
41709
42053
  canonicalPath,
41710
42054
  cacheWarmCacheablePrefixFingerprint,
42055
+ cacheKeepStoreDirectory,
41711
42056
  cacheKeepSourceWarmIdleCap,
41712
42057
  buildRoutingStatusSummary,
41713
42058
  buildRefreshOperationError,
@@ -41846,6 +42191,7 @@ export {
41846
42191
  ClaudeUnsupportedAccessError,
41847
42192
  ClaudeOAuthRefreshError,
41848
42193
  ClaudeCodeFirstUserTextTracker,
42194
+ CacheKeepStore,
41849
42195
  CacheKeepSessionRegistry,
41850
42196
  CacheKeepPrewarmError,
41851
42197
  CacheKeepManager,