@cortexkit/anthropic-auth-core 2.11.3 → 2.11.4

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
@@ -25813,6 +25813,29 @@ var settingFields = {
25813
25813
  relay: ["enabled", "url", "fallbackToDirect", "transport"],
25814
25814
  killswitch: ["enabled", "main", "accounts"]
25815
25815
  };
25816
+ function splitNativeMigrationSettings(settings) {
25817
+ const retained = structuredClone(settings);
25818
+ const moved = {};
25819
+ for (const [section, fields2] of Object.entries(settingFields)) {
25820
+ if (section === "relay" || settings[section] === undefined)
25821
+ continue;
25822
+ const selected = pick(object2(settings[section]), fields2);
25823
+ if (Object.keys(selected).length)
25824
+ moved[section] = selected;
25825
+ const rest = { ...object2(retained[section]) };
25826
+ for (const field of fields2)
25827
+ delete rest[field];
25828
+ if (Object.keys(rest).length)
25829
+ retained[section] = rest;
25830
+ else
25831
+ delete retained[section];
25832
+ }
25833
+ if (settings.fallbackOn !== undefined) {
25834
+ moved.fallbackOn = structuredClone(settings.fallbackOn);
25835
+ delete retained.fallbackOn;
25836
+ }
25837
+ return { moved, retained };
25838
+ }
25816
25839
  function validateNativeMigrationSettings(settings) {
25817
25840
  const threshold = (value) => record10(value) && Object.entries(value).every(([key, amount]) => ["five_hour", "seven_day", "5h", "1w", "scoped"].includes(key) && typeof amount === "number" && Number.isFinite(amount) && amount >= 0 && amount <= 100);
25818
25841
  const enums = {
@@ -28434,6 +28457,9 @@ async function assertUnmanagedInjectedPaths(paths) {
28434
28457
  throw new HolderRegistrationError("managed-folder", dir);
28435
28458
  }
28436
28459
  var instance = randomUUID17();
28460
+ function holderInstance() {
28461
+ return instance;
28462
+ }
28437
28463
  var ownIncarnation;
28438
28464
  var published = new Set;
28439
28465
  var warned2 = new Set;
@@ -34204,6 +34230,9 @@ class NativeRuntimeRegistry {
34204
34230
  }
34205
34231
  }
34206
34232
 
34233
+ // src/settings-authority.ts
34234
+ import { isDeepStrictEqual as isDeepStrictEqual4 } from "node:util";
34235
+
34207
34236
  // src/settings-definition.ts
34208
34237
  import { resolve as resolve18 } from "node:path";
34209
34238
  var user = { hosts: "both", project: "user-only" };
@@ -34511,279 +34540,6 @@ var SETTINGS_WRITE_FAILURES = {
34511
34540
  }
34512
34541
  };
34513
34542
 
34514
- // src/settings-mode.ts
34515
- import { lstat as lstat17, mkdir as mkdir14 } from "node:fs/promises";
34516
- async function exists4(path2) {
34517
- try {
34518
- await lstat17(path2);
34519
- return true;
34520
- } catch (error) {
34521
- if (error.code === "ENOENT")
34522
- return false;
34523
- throw error;
34524
- }
34525
- }
34526
- function hasSettingsMoveMarker(target, options = {}) {
34527
- return (options.fs?.exists ?? exists4)(`${target}.moved`);
34528
- }
34529
- async function writeSettingsMoveMarker(target, options = {}) {
34530
- if (await hasSettingsMoveMarker(target, options))
34531
- return;
34532
- const context = resolvePathOptions(options);
34533
- const bytes = Buffer.from(`${JSON.stringify({
34534
- version: 1,
34535
- target: await canonicalPath2(target, context),
34536
- at: (options.now ?? Date.now)()
34537
- })}
34538
- `);
34539
- const parent = context.paths.dirname(target);
34540
- if (options.fs?.mkdir)
34541
- await options.fs.mkdir(parent);
34542
- else if (!await ensureWindowsOwnerOnlyDirectory(parent, {
34543
- ...options.ownership,
34544
- platform: context.platform
34545
- }))
34546
- await mkdir14(parent, { recursive: true, mode: 448 });
34547
- try {
34548
- if (options.fs?.writeMarker)
34549
- await options.fs.writeMarker(`${target}.moved`, bytes);
34550
- else
34551
- await writeOwnerOnlyExclusive(`${target}.moved`, bytes, context.platform, {
34552
- ownership: options.ownership
34553
- });
34554
- } catch (error) {
34555
- if (error.code !== "EEXIST")
34556
- throw error;
34557
- }
34558
- }
34559
- async function resolveSettingsMode(paths, options = {}) {
34560
- if (paths.separate)
34561
- return "separate";
34562
- if (options.moveCompleted)
34563
- return "user-file";
34564
- if (await (options.fs?.exists ?? exists4)(paths.target))
34565
- return "user-file";
34566
- return await hasSettingsMoveMarker(paths.target, options) ? "user-file" : "legacy";
34567
- }
34568
-
34569
- // src/settings-record.ts
34570
- function settingsFileSets(generation, key, host2, model2) {
34571
- const levels = generation.fileLevels[key];
34572
- const row = resolveClaudeModelCapabilities(model2);
34573
- return Boolean(levels?.some((level) => level === "default" || level === host2 || level === row?.id));
34574
- }
34575
- function section2(stored, key) {
34576
- const value = stored[key];
34577
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
34578
- }
34579
- function resolveSettingsRecord(stored, generation, host2, model2) {
34580
- if (!generation)
34581
- return structuredClone(stored);
34582
- const context = generation.contexts[host2];
34583
- const row = resolveClaudeModelCapabilities(model2);
34584
- const values = {
34585
- ...(row ? context.models[row.id] : undefined) ?? context.noModel,
34586
- ...generation.protection[host2].values
34587
- };
34588
- const window2 = values.cache_keep_window[0];
34589
- const cacheKeep = {
34590
- ...section2(stored, "cacheKeep"),
34591
- enabled: values.cache_keep_enabled,
34592
- always: values.cache_keep_always,
34593
- subagents: values.cache_keep_subagents
34594
- };
34595
- delete cacheKeep.startHour;
34596
- delete cacheKeep.endHour;
34597
- if (window2) {
34598
- cacheKeep.startHour = window2.start_hour;
34599
- cacheKeep.endHour = window2.end_hour;
34600
- }
34601
- const logging = { ...section2(stored, "logging") };
34602
- delete logging.level;
34603
- if (values.log_level !== "default")
34604
- logging.level = values.log_level;
34605
- const thinkingBinding = { ...section2(stored, "thinkingBinding") };
34606
- delete thinkingBinding.prefixMismatchBehavior;
34607
- if (values.thinking_binding_prefix_mismatch_behavior !== "account-default")
34608
- thinkingBinding.prefixMismatchBehavior = values.thinking_binding_prefix_mismatch_behavior;
34609
- const moved = {
34610
- routing: {
34611
- ...section2(stored, "routing"),
34612
- mode: values.routing_mode,
34613
- maxSameAccountWait: values.max_same_account_wait === "off" ? "0" : values.max_same_account_wait === "15m" ? "15" : "max"
34614
- },
34615
- fallbackOn: values.fallback_on,
34616
- refresh: {
34617
- ...section2(stored, "refresh"),
34618
- enabled: values.refresh_enabled,
34619
- intervalMinutes: values.refresh_interval_minutes,
34620
- refreshBeforeExpiryMinutes: values.refresh_refresh_before_expiry_minutes
34621
- },
34622
- quota: {
34623
- ...section2(stored, "quota"),
34624
- enabled: values.quota_enabled,
34625
- checkIntervalMinutes: values.quota_check_interval_minutes,
34626
- refreshEveryNRequests: values.quota_refresh_every_n_requests,
34627
- minimumRemaining: {
34628
- five_hour: values.quota_minimum_remaining_five_hour,
34629
- seven_day: values.quota_minimum_remaining_seven_day,
34630
- scoped: values.quota_minimum_remaining_scoped
34631
- },
34632
- failClosedOnUnknownQuota: values.quota_fail_closed_on_unknown_quota,
34633
- showToasts: values.quota_show_toasts
34634
- },
34635
- quotaHeaderFeed: {
34636
- ...section2(stored, "quotaHeaderFeed"),
34637
- enabled: values.quota_header_feed_enabled
34638
- },
34639
- killswitch: {
34640
- ...section2(stored, "killswitch"),
34641
- enabled: values.killswitch_enabled,
34642
- main: {
34643
- five_hour: values.killswitch_default_five_hour,
34644
- seven_day: values.killswitch_default_seven_day,
34645
- scoped: values.killswitch_default_scoped
34646
- },
34647
- accounts: Object.fromEntries(values.killswitch_account_floors.filter((entry2) => entry2.host === host2 || entry2.host === "both").map(({ account, five_hour, seven_day, scoped }) => [
34648
- account,
34649
- { five_hour, seven_day, scoped }
34650
- ]))
34651
- },
34652
- claudeCache: {
34653
- ...section2(stored, "claudeCache"),
34654
- enabled: values.claude_cache_enabled,
34655
- mode: values.claude_cache_mode
34656
- },
34657
- cacheKeep,
34658
- dump: { ...section2(stored, "dump"), enabled: values.dump_enabled },
34659
- prime: { ...section2(stored, "prime"), enabled: values.prime_enabled },
34660
- claudeFast: {
34661
- ...section2(stored, "claudeFast"),
34662
- enabled: values.claude_fast_enabled
34663
- },
34664
- costZeroing: {
34665
- ...section2(stored, "costZeroing"),
34666
- enabled: values.cost_zeroing_enabled
34667
- },
34668
- logging,
34669
- thinkingBinding,
34670
- turnEndNote: {
34671
- ...section2(stored, "turnEndNote"),
34672
- tools: values.turn_end_note_tools
34673
- }
34674
- };
34675
- return structuredClone({ ...stored, ...moved });
34676
- }
34677
-
34678
- // src/native-runtime-settings.ts
34679
- function createNativeRuntimeSettings(options) {
34680
- const env = options.env ?? process.env;
34681
- const service = options.settingsService?.retain();
34682
- let effects;
34683
- let menuAuthority = false;
34684
- let writes = 0;
34685
- const generation = () => service && (menuAuthority || (options.settingsMode?.() ?? "user-file") === "user-file") ? service.snapshot() : undefined;
34686
- function resolve19(stored, model2) {
34687
- return resolveSettingsRecord(stored, generation(), options.host, model2);
34688
- }
34689
- function applyEffects() {
34690
- if (!generation())
34691
- return;
34692
- const settings = resolve19({ version: 1, accounts: [] });
34693
- const next = captureNativeSettingsEffectFields(settings);
34694
- const level = parseLogLevel(next.logLevel) ?? parseLogLevel(env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL) ?? "info";
34695
- const committed = { ...settings, logging: { level } };
34696
- if (effects)
34697
- applyCommittedNativeSettingsEffects(effects, committed);
34698
- else if (!env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)
34699
- setLogLevel2(level);
34700
- effects = captureNativeSettingsEffectFields(committed);
34701
- setDumpEnabled(settings.dump?.enabled === true);
34702
- }
34703
- function status() {
34704
- const current = generation();
34705
- if (!current)
34706
- return;
34707
- const context = current.contexts[options.host];
34708
- const modelOverrides = {};
34709
- for (const key of Object.keys(settingsDefinition.settings)) {
34710
- const definition = settingsDefinition.settings[key];
34711
- if (!("overrides" in definition) || !("model" in definition.overrides))
34712
- continue;
34713
- const rows = Object.entries(context.models).filter(([model2]) => current.fileLevels[key]?.includes(model2)).map(([model2, values]) => ({ model: model2, value: values[key] }));
34714
- modelOverrides[key] = rows;
34715
- }
34716
- return {
34717
- file: current.fileStatus,
34718
- values: {
34719
- ...context.noModel,
34720
- ...current.protection[options.host].values
34721
- },
34722
- modelOverrides
34723
- };
34724
- }
34725
- const unwatch = service?.watch(() => {
34726
- if (!writes)
34727
- applyEffects();
34728
- });
34729
- return {
34730
- resolve: resolve19,
34731
- status,
34732
- applyEffects,
34733
- file: () => generation()?.file,
34734
- async prepareWrite() {
34735
- if (!service || options.settingsMode?.() === "separate")
34736
- return;
34737
- if (!generation()) {
34738
- if (await resolveSettingsMode({
34739
- target: service.file,
34740
- separate: false
34741
- }) !== "user-file")
34742
- return;
34743
- menuAuthority = true;
34744
- await service.refresh();
34745
- }
34746
- return service;
34747
- },
34748
- async update(edits, before) {
34749
- if (!service)
34750
- throw new Error("Settings service is not available");
34751
- writes++;
34752
- let changed2 = false;
34753
- try {
34754
- changed2 = (await service.update(edits, options.host, { createMissing: true })).outcome === "updated";
34755
- } finally {
34756
- writes--;
34757
- }
34758
- const next = resolve19(before);
34759
- const withLevel = (settings) => ({
34760
- ...settings,
34761
- logging: {
34762
- level: parseLogLevel(sectionLevel(settings)) ?? parseLogLevel(env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL) ?? "info"
34763
- }
34764
- });
34765
- const committed = withLevel(next);
34766
- if (changed2)
34767
- applyCommittedNativeSettingsEffects(captureNativeSettingsEffectFields(withLevel(before)), committed);
34768
- effects = captureNativeSettingsEffectFields(committed);
34769
- setDumpEnabled(next.dump?.enabled === true);
34770
- },
34771
- close: () => {
34772
- unwatch?.();
34773
- return service?.dispose();
34774
- }
34775
- };
34776
- }
34777
- function sectionLevel(settings) {
34778
- const level = settings.logging?.level;
34779
- return typeof level === "string" ? level : undefined;
34780
- }
34781
-
34782
- // src/native-settings-write.ts
34783
- import { existsSync as existsSync4 } from "node:fs";
34784
- import { isDeepStrictEqual as isDeepStrictEqual4 } from "node:util";
34785
- import { parse as parse5 } from "jsonc-parser";
34786
-
34787
34543
  // src/settings-service.ts
34788
34544
  import { readFile as readFile16 } from "node:fs/promises";
34789
34545
  import { resolve as resolve19 } from "node:path";
@@ -34946,14 +34702,86 @@ function fileLevels(raw) {
34946
34702
  function protection(values) {
34947
34703
  return Object.fromEntries(SETTINGS_PROTECTION_KEYS.map((key) => [key, values[key]]));
34948
34704
  }
34949
- function settingsProtectionForRecreation(values, host2) {
34950
- return {
34951
- ...values,
34952
- killswitch_account_floors: values.killswitch_account_floors.filter((entry2) => entry2.host === host2 || entry2.host === "both").map((entry2) => ({
34953
- ...entry2,
34954
- host: entry2.account.startsWith("vault:") ? "both" : host2
34955
- }))
34956
- };
34705
+ function hostFloors(values, host2) {
34706
+ return values.killswitch_account_floors.filter((entry2) => entry2.host === host2 || entry2.host === "both").map(({ account, five_hour, seven_day, scoped }) => ({
34707
+ account,
34708
+ five_hour,
34709
+ seven_day,
34710
+ scoped
34711
+ }));
34712
+ }
34713
+ function sameJson(a, b) {
34714
+ return JSON.stringify(a) === JSON.stringify(b);
34715
+ }
34716
+ function planSettingsRecreation(writer, peer) {
34717
+ let peerDiffers = false;
34718
+ const edits = [];
34719
+ for (const setting of SETTINGS_PROTECTION_KEYS) {
34720
+ if (setting === "killswitch_account_floors")
34721
+ continue;
34722
+ const own = writer.values[setting];
34723
+ const other = peer.values[setting];
34724
+ if (sameJson(own, other)) {
34725
+ edits.push({ setting, value: own });
34726
+ continue;
34727
+ }
34728
+ peerDiffers = true;
34729
+ edits.push({ setting, level: "default", value: own }, { setting, level: peer.host, value: other });
34730
+ }
34731
+ const ownFloors = hostFloors(writer.values, writer.host);
34732
+ const otherFloors = hostFloors(peer.values, peer.host);
34733
+ const floors = [];
34734
+ const shared = new Set;
34735
+ for (const entry2 of ownFloors) {
34736
+ const identical = otherFloors.some((other) => other.account === entry2.account && sameJson(other, entry2));
34737
+ if (identical && entry2.account.startsWith("vault:")) {
34738
+ shared.add(entry2.account);
34739
+ floors.push({ ...entry2, host: "both" });
34740
+ } else
34741
+ floors.push({ ...entry2, host: writer.host });
34742
+ }
34743
+ for (const entry2 of otherFloors)
34744
+ if (!shared.has(entry2.account))
34745
+ floors.push({ ...entry2, host: peer.host });
34746
+ edits.push({ setting: "killswitch_account_floors", value: floors });
34747
+ return { edits, peerDiffers };
34748
+ }
34749
+ function settingsRecreationForWriter(values, host2) {
34750
+ return SETTINGS_PROTECTION_KEYS.map((setting) => ({
34751
+ setting,
34752
+ value: setting === "killswitch_account_floors" ? hostFloors(values, host2).map((entry2) => ({
34753
+ ...entry2,
34754
+ host: entry2.account.startsWith("vault:") ? "both" : host2
34755
+ })) : values[setting]
34756
+ }));
34757
+ }
34758
+ function settingsRecreationFloors(values, host2) {
34759
+ const peer = host2 === "opencode" ? "pi" : "opencode";
34760
+ const { edits } = planSettingsRecreation({ host: host2, values }, {
34761
+ host: peer,
34762
+ values: {
34763
+ ...values,
34764
+ killswitch_account_floors: hostFloors(values, host2).map((entry2) => ({
34765
+ ...entry2,
34766
+ host: peer
34767
+ }))
34768
+ }
34769
+ });
34770
+ const floors = edits.find((edit) => edit.setting === "killswitch_account_floors")?.value;
34771
+ return floors ?? [];
34772
+ }
34773
+ function planSettingsFileRecreation(writer, peer, hostsStopped = false) {
34774
+ if (writer.rung === 3)
34775
+ return { refused: "own-unknown" };
34776
+ if (peer.none || hostsStopped && peer.rung === 3 && !peer.unreadable)
34777
+ return { edits: settingsRecreationForWriter(writer.values, writer.host) };
34778
+ const plan = planSettingsRecreation(writer, peer);
34779
+ if (plan.peerDiffers)
34780
+ return { refused: peer.rung === 3 ? "peer-unknown" : "peer-differs" };
34781
+ return { edits: plan.edits };
34782
+ }
34783
+ function planSettingsMenuWrite(current, edits, carry) {
34784
+ return current.status === "missing" ? [...carry(), ...edits] : edits;
34957
34785
  }
34958
34786
  function mostRestrictiveSettingsProtection() {
34959
34787
  return {
@@ -35019,6 +34847,8 @@ class SharedSettingsService {
35019
34847
  handle;
35020
34848
  unwatch;
35021
34849
  listeners = new Set;
34850
+ fileListeners = new Set;
34851
+ readingListeners = new Set;
35022
34852
  current;
35023
34853
  running;
35024
34854
  pending = false;
@@ -35031,6 +34861,8 @@ class SharedSettingsService {
35031
34861
  this.options = options;
35032
34862
  this.handle = options.dependencies?.open ? options.dependencies.open(this.openOptions()) : openSettings(settingsDefinition, this.openOptions());
35033
34863
  this.unwatch = this.handle.watch(() => {
34864
+ for (const listener of this.fileListeners)
34865
+ listener();
35034
34866
  this.refresh();
35035
34867
  });
35036
34868
  this.ready = this.refresh();
@@ -35058,6 +34890,18 @@ class SharedSettingsService {
35058
34890
  this.listeners.delete(listener);
35059
34891
  };
35060
34892
  }
34893
+ onFileEvent(listener) {
34894
+ this.fileListeners.add(listener);
34895
+ return () => {
34896
+ this.fileListeners.delete(listener);
34897
+ };
34898
+ }
34899
+ onReading(listener) {
34900
+ this.readingListeners.add(listener);
34901
+ return () => {
34902
+ this.readingListeners.delete(listener);
34903
+ };
34904
+ }
35061
34905
  async bytes() {
35062
34906
  try {
35063
34907
  return {
@@ -35097,7 +34941,7 @@ class SharedSettingsService {
35097
34941
  return { contexts, report: this.handle.report() };
35098
34942
  }
35099
34943
  async pass() {
35100
- const readAt = performance.timeOrigin + performance.now();
34944
+ const readAt = Date.now();
35101
34945
  const before = await this.bytes();
35102
34946
  let resolved;
35103
34947
  let after;
@@ -35168,7 +35012,16 @@ class SharedSettingsService {
35168
35012
  }
35169
35013
  }
35170
35014
  const status = after.status !== "ready" ? after.status : report2.some((entry2) => entry2.reason === "unparseable") ? "unparseable" : report2.some((entry2) => entry2.reason === "unreadable") ? "unreadable" : "ready";
35171
- const usable = status === "ready" && !report2.some((entry2) => SETTINGS_PROTECTION_KEYS.some((key) => key === entry2.keyPath[0]));
35015
+ const version = raw.schema_version;
35016
+ const untrustedFile = source2 !== undefined && /^[\x20\t\r\n]*$/.test(source2.replace(/^\uFEFF/, "")) || typeof version === "number" && Number.isInteger(version) && version > 1 || report2.some((entry2) => entry2.reason === "invalid-schema-version");
35017
+ if (untrustedFile && status === "ready") {
35018
+ const identity5 = `untrusted:${this.file}`;
35019
+ if (!logged.has(identity5)) {
35020
+ logged.add(identity5);
35021
+ logger2.warn("settings", `Settings file "${this.file}" is empty or from another settings version; protection settings keep their last known values.`);
35022
+ }
35023
+ }
35024
+ const usable = status === "ready" && !untrustedFile && !report2.some((entry2) => SETTINGS_PROTECTION_KEYS.some((key) => key === entry2.keyPath[0]));
35172
35025
  const sets = {};
35173
35026
  for (const host2 of hosts) {
35174
35027
  const values = protection(contexts[host2].noModel);
@@ -35304,8 +35157,14 @@ class SharedSettingsService {
35304
35157
  ...candidate,
35305
35158
  fileStatus: status,
35306
35159
  readAt: undefined
35307
- }))
35160
+ })) {
35161
+ if (candidate.readAt > prior.readAt) {
35162
+ this.current = freeze({ ...prior, readAt: candidate.readAt });
35163
+ for (const listener of this.readingListeners)
35164
+ listener(this.current);
35165
+ }
35308
35166
  continue;
35167
+ }
35309
35168
  const generation = freeze({
35310
35169
  ...candidate,
35311
35170
  fileStatus: status,
@@ -35317,10 +35176,6 @@ class SharedSettingsService {
35317
35176
  this.lastGood.set(host2, generation.protection[host2].values);
35318
35177
  }
35319
35178
  logReports(generation.report);
35320
- if (generation.status === "missing" && !logged.has(`missing:${this.file}`)) {
35321
- logged.add(`missing:${this.file}`);
35322
- logger2.warn("settings", `Settings file is missing at "${this.file}"; non-protection settings use schema defaults. A menu write will recreate it.`);
35323
- }
35324
35179
  for (const listener of this.listeners) {
35325
35180
  if (this.closed)
35326
35181
  return;
@@ -35336,7 +35191,10 @@ class SharedSettingsService {
35336
35191
  }
35337
35192
  }
35338
35193
  }
35339
- async update(edits, host2, options, applied) {
35194
+ async update(edits, host2, options, applied, peerProtection = async () => ({
35195
+ values: mostRestrictiveSettingsProtection(),
35196
+ rung: 3
35197
+ })) {
35340
35198
  if (!edits.length)
35341
35199
  return { outcome: "unchanged" };
35342
35200
  const missing2 = (await this.bytes()).status === "missing";
@@ -35344,15 +35202,23 @@ class SharedSettingsService {
35344
35202
  if (missing2 && options.createMissing) {
35345
35203
  if (applied.rung === 3)
35346
35204
  throw new SettingsRecreationRefusal(this.file);
35347
- const values = settingsProtectionForRecreation(applied.values, host2);
35348
- carried = values;
35349
- edits = [
35350
- ...SETTINGS_PROTECTION_KEYS.map((setting) => ({
35351
- setting,
35352
- value: values[setting]
35353
- })),
35354
- ...edits
35355
- ];
35205
+ const peer = host2 === "opencode" ? "pi" : "opencode";
35206
+ const floorEdit = edits.find((edit) => edit.setting === "killswitch_account_floors" && ("value" in edit));
35207
+ const writerValues = floorEdit && "value" in floorEdit ? {
35208
+ ...applied.values,
35209
+ killswitch_account_floors: floorEdit.value
35210
+ } : applied.values;
35211
+ const plan = planSettingsFileRecreation({ host: host2, values: writerValues, rung: applied.rung }, { host: peer, ...await peerProtection(peer) }, options.hostsStopped);
35212
+ if ("refused" in plan)
35213
+ throw new SettingsRecreationRefusal(this.file);
35214
+ carried = Object.fromEntries(plan.edits.map((edit) => [edit.setting, edit.value]));
35215
+ edits = planSettingsMenuWrite({ status: "missing" }, edits.filter((edit) => edit !== floorEdit), () => plan.edits.map(({ setting, value }) => ({ setting, value })));
35216
+ }
35217
+ if (options.createMissing || options.expectedSource !== undefined || options.expectMissing) {
35218
+ const now = await this.bytes();
35219
+ const changed2 = options.expectedSource !== undefined ? now.status !== "ready" || now.bytes.toString("utf8") !== options.expectedSource : options.expectMissing ? now.status !== "missing" : now.status === "missing" !== missing2;
35220
+ if (changed2)
35221
+ throw new SettingsRefusal("settings-busy", "Settings changed while the write was planned");
35356
35222
  }
35357
35223
  const handle = options.createMissing ? this.options.dependencies?.open?.(this.openOptions(true)) ?? openSettings(settingsDefinition, this.openOptions(true)) : this.handle;
35358
35224
  const result = await handle.update(edits, { host: host2 });
@@ -35373,9 +35239,27 @@ class SharedSettingsService {
35373
35239
  this.cancelMissingRead = undefined;
35374
35240
  this.unwatch();
35375
35241
  this.listeners.clear();
35242
+ this.fileListeners.clear();
35243
+ this.readingListeners.clear();
35376
35244
  await this.running;
35377
35245
  }
35378
35246
  }
35247
+ async function recoverSettingsProtection(file, host2, recovery = {}, actingHost) {
35248
+ for (const [rung, read] of [
35249
+ [
35250
+ 1,
35251
+ recovery.readAppliedCopy ?? (actingHost === host2 ? () => readSettingsProtectionCopy(file, host2) : undefined)
35252
+ ],
35253
+ [2, recovery.readLegacyProtection]
35254
+ ]) {
35255
+ try {
35256
+ const values = await read?.(host2);
35257
+ if (values)
35258
+ return { values, rung };
35259
+ } catch {}
35260
+ }
35261
+ return { values: mostRestrictiveSettingsProtection(), rung: 3 };
35262
+ }
35379
35263
 
35380
35264
  class SettingsProtectionLease {
35381
35265
  shared;
@@ -35385,36 +35269,87 @@ class SettingsProtectionLease {
35385
35269
  pending = Promise.resolve();
35386
35270
  copies = new Set;
35387
35271
  copied;
35272
+ unsaved;
35273
+ cancelRetry;
35274
+ closed = false;
35388
35275
  constructor(shared, recovery = {}, options) {
35389
35276
  this.shared = shared;
35390
35277
  this.recovery = recovery;
35391
35278
  this.options = options;
35392
35279
  }
35393
35280
  async close() {
35281
+ this.closed = true;
35282
+ this.cancelRetry?.();
35283
+ this.cancelRetry = undefined;
35394
35284
  await this.pending;
35395
35285
  await Promise.all(this.copies);
35396
35286
  }
35397
35287
  persist(generation) {
35398
35288
  const host2 = this.options?.host;
35399
- if (!host2)
35289
+ if (!host2 || this.closed)
35400
35290
  return;
35401
35291
  const set = generation.protection[host2];
35402
35292
  if (!set.usable || set.rung !== 0)
35403
35293
  return;
35404
- const identity5 = JSON.stringify(set.values);
35294
+ const identity5 = JSON.stringify([generation.readAt, set.values]);
35405
35295
  if (identity5 === this.copied)
35406
35296
  return;
35297
+ this.unsaved = {
35298
+ file: generation.file,
35299
+ readAt: generation.readAt,
35300
+ values: set.values,
35301
+ identity: identity5
35302
+ };
35303
+ this.write(this.unsaved);
35304
+ }
35305
+ write(entry2) {
35306
+ const host2 = this.options?.host;
35307
+ if (!host2 || this.closed)
35308
+ return;
35309
+ const { identity: identity5 } = entry2;
35407
35310
  this.copied = identity5;
35311
+ this.cancelRetry?.();
35312
+ this.cancelRetry = undefined;
35408
35313
  const write = this.options?.dependencies?.writeAppliedCopy ?? writeSettingsProtectionCopy;
35409
- const task = Promise.resolve().then(() => write(generation.file, host2, { readAt: generation.readAt, values: set.values }, this.options?.lockTimeoutMs)).catch(() => {
35410
- const key = `copy:${generation.file}:${host2}`;
35411
- if (logged.has(key))
35412
- return;
35413
- logged.add(key);
35414
- logger2.warn("settings", `Could not save applied protection settings for ${host2} at "${generation.file}.applied.json"; the previous copy is unchanged.`);
35314
+ const task = Promise.resolve().then(() => write(entry2.file, host2, { readAt: entry2.readAt, values: entry2.values }, this.options?.lockTimeoutMs)).then(() => {
35315
+ if (this.unsaved === entry2)
35316
+ this.unsaved = undefined;
35317
+ }).catch(() => {
35318
+ const key = `copy:${entry2.file}:${host2}`;
35319
+ if (!logged.has(key)) {
35320
+ logged.add(key);
35321
+ logger2.warn("settings", `Could not save applied protection settings for ${host2} at "${entry2.file}.applied.json"; the previous copy is unchanged until a retry succeeds.`);
35322
+ }
35323
+ if (this.copied === identity5) {
35324
+ this.copied = undefined;
35325
+ this.scheduleRetry();
35326
+ }
35415
35327
  }).finally(() => this.copies.delete(task));
35416
35328
  this.copies.add(task);
35417
35329
  }
35330
+ scheduleRetry() {
35331
+ if (this.closed || this.cancelRetry)
35332
+ return;
35333
+ const schedule2 = this.options?.dependencies?.schedule ?? ((callback, delayMs) => {
35334
+ const timer = setTimeout(callback, delayMs);
35335
+ timer.unref?.();
35336
+ return () => clearTimeout(timer);
35337
+ });
35338
+ this.cancelRetry = schedule2(() => {
35339
+ this.cancelRetry = undefined;
35340
+ if (this.unsaved)
35341
+ this.write(this.unsaved);
35342
+ }, 60000);
35343
+ }
35344
+ reread(generation) {
35345
+ this.pending = this.pending.then(() => {
35346
+ if (!this.current || this.current.id !== generation.id)
35347
+ return;
35348
+ this.current = freeze({ ...this.current, readAt: generation.readAt });
35349
+ this.persist(this.current);
35350
+ });
35351
+ return this.pending;
35352
+ }
35418
35353
  snapshot() {
35419
35354
  if (!this.current)
35420
35355
  throw new Error("Settings startup has not finished");
@@ -35424,27 +35359,59 @@ class SettingsProtectionLease {
35424
35359
  this.pending = this.pending.then(() => this.apply(generation));
35425
35360
  return this.pending;
35426
35361
  }
35427
- async recover(host2) {
35362
+ async peerProtection(host2) {
35428
35363
  const good = this.shared.lastGoodProtection(host2);
35429
35364
  if (good)
35430
35365
  return { values: good, rung: 1 };
35431
- const previous = this.current?.protection[host2];
35432
- if (previous)
35433
- return previous;
35366
+ let unreadable = false;
35434
35367
  for (const [rung, read] of [
35435
35368
  [
35436
35369
  1,
35437
- this.recovery.readAppliedCopy ?? (this.options?.host === host2 ? () => readSettingsProtectionCopy(this.shared.file, host2) : undefined)
35370
+ this.recovery.readAppliedCopy ?? ((peer) => readSettingsProtectionCopy(this.shared.file, peer))
35438
35371
  ],
35439
- [2, this.recovery.readLegacyProtection]
35372
+ [2, this.recovery.readPeerLegacyProtection]
35440
35373
  ]) {
35441
35374
  try {
35442
35375
  const values = await read?.(host2);
35443
35376
  if (values)
35444
35377
  return { values, rung };
35445
- } catch {}
35378
+ } catch {
35379
+ unreadable = true;
35380
+ }
35446
35381
  }
35447
- return { values: mostRestrictiveSettingsProtection(), rung: 3 };
35382
+ return {
35383
+ values: mostRestrictiveSettingsProtection(),
35384
+ rung: 3,
35385
+ unreadable,
35386
+ none: !unreadable && this.recovery.readPeerLegacyProtection !== undefined
35387
+ };
35388
+ }
35389
+ async logMissing(generation) {
35390
+ const host2 = this.options?.host;
35391
+ const key = `missing:${generation.file}`;
35392
+ if (!host2 || logged.has(key))
35393
+ return;
35394
+ const peer = host2 === "opencode" ? "pi" : "opencode";
35395
+ const own = generation.protection[host2];
35396
+ const plan = planSettingsFileRecreation({ host: host2, values: own.values, rung: own.rung }, { host: peer, ...await this.peerProtection(peer) });
35397
+ if (logged.has(key) || this.closed)
35398
+ return;
35399
+ logged.add(key);
35400
+ const next = "refused" in plan ? `Menu writes that change settings are refused until the file is recreated by hand, because ${{
35401
+ "own-unknown": `${host2}'s protection settings could not be recovered`,
35402
+ "peer-unknown": `the protection settings of ${peer} are unknown`,
35403
+ "peer-differs": `${peer} applies different protection settings`
35404
+ }[plan.refused]}.` : "A menu write will recreate it.";
35405
+ logger2.warn("settings", `Settings file is missing at "${generation.file}"; non-protection settings use schema defaults. ${next}`);
35406
+ }
35407
+ async recover(host2) {
35408
+ const good = this.shared.lastGoodProtection(host2);
35409
+ if (good)
35410
+ return { values: good, rung: 1 };
35411
+ const previous = this.current?.protection[host2];
35412
+ if (previous)
35413
+ return previous;
35414
+ return recoverSettingsProtection(this.shared.file, host2, this.recovery, this.options?.host);
35448
35415
  }
35449
35416
  async apply(generation) {
35450
35417
  if (hosts.every((host2) => generation.protection[host2].usable)) {
@@ -35471,6 +35438,8 @@ class SettingsProtectionLease {
35471
35438
  }
35472
35439
  this.current = freeze({ ...generation, contexts, protection: sets });
35473
35440
  this.persist(this.current);
35441
+ if (generation.status === "missing")
35442
+ await this.logMissing(this.current).catch(() => {});
35474
35443
  }
35475
35444
  }
35476
35445
  function referenceCountedSettingsService(service) {
@@ -35505,96 +35474,810 @@ function referenceCountedSettingsService(service) {
35505
35474
  subscriptions.add(stop);
35506
35475
  return stop;
35507
35476
  },
35508
- dispose() {
35509
- if (closed2)
35510
- return closing ?? Promise.resolve();
35511
- closed2 = true;
35512
- for (const unsubscribe of subscriptions)
35513
- unsubscribe();
35514
- subscriptions.clear();
35515
- closing = --users === 0 ? service.dispose() : Promise.resolve();
35516
- return closing;
35517
- }
35477
+ onFileEvent(listener) {
35478
+ const unsubscribe = use().onFileEvent?.(listener) ?? (() => {});
35479
+ const stop = () => {
35480
+ unsubscribe();
35481
+ subscriptions.delete(stop);
35482
+ };
35483
+ subscriptions.add(stop);
35484
+ return stop;
35485
+ },
35486
+ dispose() {
35487
+ if (closed2)
35488
+ return closing ?? Promise.resolve();
35489
+ closed2 = true;
35490
+ for (const unsubscribe of subscriptions)
35491
+ unsubscribe();
35492
+ subscriptions.clear();
35493
+ closing = --users === 0 ? service.dispose() : Promise.resolve();
35494
+ return closing;
35495
+ }
35496
+ };
35497
+ }
35498
+ return reference();
35499
+ }
35500
+ async function openSettingsService(options) {
35501
+ if (options.separateInstall)
35502
+ return;
35503
+ const file = resolve19(options.file);
35504
+ let shared = services.get(file);
35505
+ if (!shared) {
35506
+ shared = new SharedSettingsService(file, options);
35507
+ services.set(file, shared);
35508
+ }
35509
+ const owned = shared;
35510
+ owned.users++;
35511
+ let closed2 = false;
35512
+ let closing;
35513
+ const subscriptions = new Set;
35514
+ const lease = new SettingsProtectionLease(owned, options.protection, options);
35515
+ const unsubscribeLease = owned.watch((generation) => lease.publish(generation));
35516
+ const unsubscribeReading = owned.onReading((generation) => {
35517
+ lease.reread(generation);
35518
+ });
35519
+ const use = () => {
35520
+ if (closed2)
35521
+ throw new Error("Settings service lease is disposed");
35522
+ return owned;
35523
+ };
35524
+ const dispose = () => {
35525
+ if (closed2)
35526
+ return closing ?? Promise.resolve();
35527
+ closed2 = true;
35528
+ unsubscribeLease();
35529
+ unsubscribeReading();
35530
+ for (const unsubscribe of subscriptions)
35531
+ unsubscribe();
35532
+ subscriptions.clear();
35533
+ if (--owned.users === 0) {
35534
+ if (services.get(file) === owned)
35535
+ services.delete(file);
35536
+ closing = owned.close();
35537
+ }
35538
+ closing = Promise.all([closing, lease.close()]).then(() => {});
35539
+ return closing;
35540
+ };
35541
+ try {
35542
+ await owned.ready;
35543
+ await lease.publish(owned.snapshot());
35544
+ } catch (error) {
35545
+ await dispose();
35546
+ throw error;
35547
+ }
35548
+ return referenceCountedSettingsService({
35549
+ file,
35550
+ resolve(host2, model2) {
35551
+ use();
35552
+ const context = lease.snapshot().contexts[host2];
35553
+ const row = resolveClaudeModelCapabilities(model2);
35554
+ return (row ? context.models[row.id] : undefined) ?? context.noModel;
35555
+ },
35556
+ snapshot: () => {
35557
+ use();
35558
+ return lease.snapshot();
35559
+ },
35560
+ status: () => {
35561
+ use();
35562
+ return lease.snapshot().fileStatus;
35563
+ },
35564
+ watch(listener) {
35565
+ const unsubscribe = use().watch(() => listener(lease.snapshot()));
35566
+ const stop = () => {
35567
+ unsubscribe();
35568
+ subscriptions.delete(stop);
35569
+ };
35570
+ subscriptions.add(stop);
35571
+ return stop;
35572
+ },
35573
+ onFileEvent(listener) {
35574
+ const unsubscribe = use().onFileEvent(listener);
35575
+ const stop = () => {
35576
+ unsubscribe();
35577
+ subscriptions.delete(stop);
35578
+ };
35579
+ subscriptions.add(stop);
35580
+ return stop;
35581
+ },
35582
+ refresh: () => use().refresh(),
35583
+ update: (edits, host2, options2 = {}) => use().update(edits, host2, options2, lease.snapshot().protection[host2], (peer) => lease.peerProtection(peer)),
35584
+ dispose
35585
+ });
35586
+ }
35587
+
35588
+ // src/settings-move-source.ts
35589
+ var SETTINGS_MOVE_PATHS = {
35590
+ routing_mode: ["routing", "mode"],
35591
+ max_same_account_wait: ["routing", "maxSameAccountWait"],
35592
+ fallback_on: ["fallbackOn"],
35593
+ refresh_enabled: ["refresh", "enabled"],
35594
+ refresh_interval_minutes: ["refresh", "intervalMinutes"],
35595
+ refresh_refresh_before_expiry_minutes: [
35596
+ "refresh",
35597
+ "refreshBeforeExpiryMinutes"
35598
+ ],
35599
+ quota_enabled: ["quota", "enabled"],
35600
+ quota_check_interval_minutes: ["quota", "checkIntervalMinutes"],
35601
+ quota_refresh_every_n_requests: ["quota", "refreshEveryNRequests"],
35602
+ quota_minimum_remaining_five_hour: ["quota", "minimumRemaining", "five_hour"],
35603
+ quota_minimum_remaining_seven_day: ["quota", "minimumRemaining", "seven_day"],
35604
+ quota_minimum_remaining_scoped: ["quota", "minimumRemaining", "scoped"],
35605
+ quota_fail_closed_on_unknown_quota: ["quota", "failClosedOnUnknownQuota"],
35606
+ quota_show_toasts: ["quota", "showToasts"],
35607
+ quota_header_feed_enabled: ["quotaHeaderFeed", "enabled"],
35608
+ killswitch_enabled: ["killswitch", "enabled"],
35609
+ killswitch_default_five_hour: ["killswitch", "main", "five_hour"],
35610
+ killswitch_default_seven_day: ["killswitch", "main", "seven_day"],
35611
+ killswitch_default_scoped: ["killswitch", "main", "scoped"],
35612
+ killswitch_account_floors: ["killswitch", "accounts"],
35613
+ claude_cache_enabled: ["claudeCache", "enabled"],
35614
+ claude_cache_mode: ["claudeCache", "mode"],
35615
+ cache_keep_enabled: ["cacheKeep", "enabled"],
35616
+ cache_keep_always: ["cacheKeep", "always"],
35617
+ cache_keep_window: ["cacheKeep", "startHour", "endHour"],
35618
+ cache_keep_subagents: ["cacheKeep", "subagents"],
35619
+ dump_enabled: ["dump", "enabled"],
35620
+ prime_enabled: ["prime", "enabled"],
35621
+ claude_fast_enabled: ["claudeFast", "enabled"],
35622
+ cost_zeroing_enabled: ["costZeroing", "enabled"],
35623
+ log_level: ["logging", "level"],
35624
+ thinking_binding_prefix_mismatch_behavior: [
35625
+ "thinkingBinding",
35626
+ "prefixMismatchBehavior"
35627
+ ],
35628
+ turn_end_note_tools: ["turnEndNote", "tools"]
35629
+ };
35630
+ var logged2 = new Set;
35631
+ var fields2 = ["five_hour", "seven_day", "scoped"];
35632
+ var aliases = { five_hour: "5h", seven_day: "1w", scoped: "scoped" };
35633
+ var invalidSection = Symbol("invalid legacy section");
35634
+ function record14(value) {
35635
+ return value !== null && typeof value === "object" && !Array.isArray(value);
35636
+ }
35637
+ function floor3(value) {
35638
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 100;
35639
+ }
35640
+ function held(root, path2) {
35641
+ let value = root;
35642
+ for (const key of path2) {
35643
+ if (!record14(value))
35644
+ return { value: invalidSection };
35645
+ if (!Object.hasOwn(value, key))
35646
+ return;
35647
+ value = value[key];
35648
+ }
35649
+ return { value };
35650
+ }
35651
+ function readSettingsMoveSource(text5, options) {
35652
+ const stored = JSON.parse(text5);
35653
+ const values = {};
35654
+ const restrictive = mostRestrictiveSettingsProtection();
35655
+ function report2(path2, reason) {
35656
+ if (options.quiet)
35657
+ return;
35658
+ const message = `Settings move from ${options.path}: ${path2} ${reason}.`;
35659
+ if (logged2.has(message))
35660
+ return;
35661
+ logged2.add(message);
35662
+ if (options.log)
35663
+ options.log.warn(message);
35664
+ else
35665
+ logger2.warn("settings", message);
35666
+ }
35667
+ if (!record14(stored)) {
35668
+ report2("<root>", "is not a settings map; omitted");
35669
+ return {};
35670
+ }
35671
+ function invalid3(key, path2) {
35672
+ if (Object.hasOwn(restrictive, key)) {
35673
+ const replacement = restrictive[key];
35674
+ values[key] = replacement;
35675
+ report2(path2, `is invalid; replaced with protection value ${JSON.stringify(replacement)}`);
35676
+ } else
35677
+ report2(path2, "is invalid; omitted");
35678
+ }
35679
+ for (const [key, path2] of Object.entries(SETTINGS_MOVE_PATHS)) {
35680
+ if (key.startsWith("killswitch_default_") || key.startsWith("quota_minimum_remaining_") || key === "killswitch_account_floors" || key === "cache_keep_window")
35681
+ continue;
35682
+ const entry2 = held(stored, path2);
35683
+ if (!entry2)
35684
+ continue;
35685
+ const value = entry2.value;
35686
+ let valid = true;
35687
+ try {
35688
+ if (key === "fallback_on") {
35689
+ valid = Array.isArray(value) && value.every((status) => Number.isInteger(status));
35690
+ } else if (key === "max_same_account_wait" && (value === 0 || value === 15)) {} else if (key === "log_level" && value === "default") {} else {
35691
+ validateNativeMigrationSettings({
35692
+ [path2[0]]: { [path2[1]]: value }
35693
+ });
35694
+ }
35695
+ } catch {
35696
+ valid = false;
35697
+ }
35698
+ if (!valid) {
35699
+ invalid3(key, path2.join("."));
35700
+ continue;
35701
+ }
35702
+ values[key] = key === "max_same_account_wait" ? value === "0" || value === 0 ? "off" : value === "15" || value === 15 ? "15m" : "cache" : [
35703
+ "claude_cache_enabled",
35704
+ "quota_enabled",
35705
+ "quota_fail_closed_on_unknown_quota"
35706
+ ].includes(key) ? value ? "on" : "off" : value;
35707
+ }
35708
+ function thresholds(value, path2, defaults3, account = false) {
35709
+ if (!record14(value)) {
35710
+ if (account)
35711
+ return;
35712
+ report2(path2, "is invalid; replaced with declared protection floors");
35713
+ return { ...defaults3 };
35714
+ }
35715
+ if (fields2.some((key) => key !== aliases[key] && Object.hasOwn(value, key) && Object.hasOwn(value, aliases[key])))
35716
+ report2(path2, "holds threshold aliases beside canonical keys; canonical keys win");
35717
+ const result = { ...defaults3 };
35718
+ let bad = false;
35719
+ for (const key of Object.keys(value)) {
35720
+ if (!["five_hour", "seven_day", "scoped", "5h", "1w"].includes(key)) {
35721
+ if (!account)
35722
+ report2(`${path2}.${key}`, "is unknown; omitted");
35723
+ bad = true;
35724
+ }
35725
+ }
35726
+ for (const key of fields2) {
35727
+ const source2 = Object.hasOwn(value, key) ? key : aliases[key];
35728
+ if (!Object.hasOwn(value, source2))
35729
+ continue;
35730
+ const amount = value[source2];
35731
+ if (floor3(amount))
35732
+ result[key] = amount;
35733
+ else {
35734
+ bad = true;
35735
+ if (!account)
35736
+ report2(`${path2}.${source2}`, `is invalid; replaced with protection value ${defaults3[key]}`);
35737
+ }
35738
+ }
35739
+ return account && bad ? undefined : result;
35740
+ }
35741
+ for (const [path2, prefix] of [
35742
+ [["killswitch", "main"], "killswitch_default"],
35743
+ [["quota", "minimumRemaining"], "quota_minimum_remaining"]
35744
+ ]) {
35745
+ const entry2 = held(stored, path2);
35746
+ if (!entry2)
35747
+ continue;
35748
+ const defaults3 = Object.fromEntries(fields2.map((key) => [
35749
+ key,
35750
+ settingsDefinition.settings[`${prefix}_${key}`].default
35751
+ ]));
35752
+ const result = thresholds(entry2.value, path2.join("."), defaults3);
35753
+ for (const key of fields2)
35754
+ values[`${prefix}_${key}`] = result[key];
35755
+ }
35756
+ const accounts = held(stored, ["killswitch", "accounts"]);
35757
+ if (accounts) {
35758
+ const defaults3 = {
35759
+ five_hour: settingsDefinition.settings.killswitch_default_five_hour.default,
35760
+ seven_day: settingsDefinition.settings.killswitch_default_seven_day.default,
35761
+ scoped: settingsDefinition.settings.killswitch_default_scoped.default
35762
+ };
35763
+ values.killswitch_account_floors = [];
35764
+ if (!record14(accounts.value))
35765
+ invalid3("killswitch_account_floors", "killswitch.accounts");
35766
+ else {
35767
+ const replacement = Object.fromEntries(fields2.map((key) => [
35768
+ key,
35769
+ Math.max(defaults3[key], values[`killswitch_default_${key}`] ?? defaults3[key])
35770
+ ]));
35771
+ values.killswitch_account_floors = Object.entries(accounts.value).map(([account, value]) => {
35772
+ const path2 = `killswitch.accounts.${account}`;
35773
+ const result = thresholds(value, path2, defaults3, true);
35774
+ if (!result)
35775
+ report2(path2, `is invalid; replaced with protection floors ${JSON.stringify(replacement)}`);
35776
+ return { account, host: options.host, ...result ?? replacement };
35777
+ });
35778
+ }
35779
+ }
35780
+ const start = held(stored, ["cacheKeep", "startHour"]);
35781
+ const end = held(stored, ["cacheKeep", "endHour"]);
35782
+ if (start || end) {
35783
+ const validHour = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
35784
+ if (validHour(start?.value) && validHour(end?.value))
35785
+ values.cache_keep_window = [
35786
+ { start_hour: start.value, end_hour: end.value }
35787
+ ];
35788
+ else
35789
+ invalid3("cache_keep_window", "cacheKeep.startHour/endHour");
35790
+ }
35791
+ return values;
35792
+ }
35793
+ function createSettingsMoveSource(options) {
35794
+ return {
35795
+ host: options.host,
35796
+ path: options.path,
35797
+ locks: options.locks,
35798
+ read: (text5) => readSettingsMoveSource(text5, options)
35799
+ };
35800
+ }
35801
+
35802
+ // src/settings-authority.ts
35803
+ function holdsMovedSettings(stored) {
35804
+ return Object.values(SETTINGS_MOVE_PATHS).some((path2) => {
35805
+ let value = stored;
35806
+ for (const key of path2.slice(0, 2)) {
35807
+ if (!value || typeof value !== "object" || !Object.hasOwn(value, key))
35808
+ return false;
35809
+ value = value[key];
35810
+ }
35811
+ return true;
35812
+ });
35813
+ }
35814
+ function differingLegacySettings(legacy, resolved, host2) {
35815
+ const floors = (entries) => Object.fromEntries(entries.filter((entry2) => entry2.host === host2 || entry2.host === "both").map(({ account, five_hour, seven_day, scoped }) => [
35816
+ account,
35817
+ { five_hour, seven_day, scoped }
35818
+ ]));
35819
+ return Object.keys(legacy).filter((key) => key === "killswitch_account_floors" ? Object.entries(floors(legacy[key] ?? [])).some(([account, value]) => !isDeepStrictEqual4(value, floors(resolved[key])[account])) : !isDeepStrictEqual4(legacy[key], resolved[key]));
35820
+ }
35821
+ function settingsNotImportedText(source2, target, differing) {
35822
+ return `Legacy settings in "${source2}" were not imported into "${target}"; the user settings file is authoritative.${differing?.length ? ` Differing settings: ${differing.join(", ")}.` : ""}`;
35823
+ }
35824
+
35825
+ // src/settings-mode.ts
35826
+ import { lstat as lstat17, mkdir as mkdir14 } from "node:fs/promises";
35827
+ async function exists4(path2) {
35828
+ try {
35829
+ await lstat17(path2);
35830
+ return true;
35831
+ } catch (error) {
35832
+ if (error.code === "ENOENT")
35833
+ return false;
35834
+ throw error;
35835
+ }
35836
+ }
35837
+ function hasSettingsMoveMarker(target, options = {}) {
35838
+ return (options.fs?.exists ?? exists4)(`${target}.moved`);
35839
+ }
35840
+ async function writeSettingsMoveMarker(target, options = {}) {
35841
+ if (await hasSettingsMoveMarker(target, options))
35842
+ return;
35843
+ const context = resolvePathOptions(options);
35844
+ await writeSettingsRecord(target, `${target}.moved`, {
35845
+ version: 1,
35846
+ target: await canonicalPath2(target, context),
35847
+ at: (options.now ?? Date.now)()
35848
+ }, options);
35849
+ }
35850
+ function settingsImportRecordPath(target, host2) {
35851
+ return `${target}.moved.${host2}`;
35852
+ }
35853
+ function hasSettingsImportRecord(target, host2, options = {}) {
35854
+ return (options.fs?.exists ?? exists4)(settingsImportRecordPath(target, host2));
35855
+ }
35856
+ async function writeSettingsImportRecord(target, host2, options = {}) {
35857
+ if (await hasSettingsImportRecord(target, host2, options))
35858
+ return;
35859
+ await writeSettingsRecord(target, settingsImportRecordPath(target, host2), {
35860
+ version: 1,
35861
+ host: host2,
35862
+ release: anthropicAuthRelease(),
35863
+ at: (options.now ?? Date.now)()
35864
+ }, options);
35865
+ }
35866
+ async function writeSettingsRecord(target, path2, record15, options) {
35867
+ const context = resolvePathOptions(options);
35868
+ const bytes = Buffer.from(`${JSON.stringify(record15)}
35869
+ `);
35870
+ const parent = context.paths.dirname(target);
35871
+ if (options.fs?.mkdir)
35872
+ await options.fs.mkdir(parent);
35873
+ else if (!await exists4(parent) && !await ensureWindowsOwnerOnlyDirectory(parent, {
35874
+ ...options.ownership,
35875
+ platform: context.platform
35876
+ }))
35877
+ await mkdir14(parent, { recursive: true, mode: 448 });
35878
+ try {
35879
+ if (options.fs?.writeMarker)
35880
+ await options.fs.writeMarker(path2, bytes);
35881
+ else
35882
+ await writeOwnerOnlyExclusive(path2, bytes, context.platform, {
35883
+ ownership: options.ownership
35884
+ });
35885
+ } catch (error) {
35886
+ if (error.code !== "EEXIST")
35887
+ throw error;
35888
+ }
35889
+ }
35890
+ async function resolveSettingsMode(paths, options = {}) {
35891
+ if (paths.separate)
35892
+ return "separate";
35893
+ if (options.moveCompleted)
35894
+ return "user-file";
35895
+ if (await (options.fs?.exists ?? exists4)(paths.target))
35896
+ return "user-file";
35897
+ return await hasSettingsMoveMarker(paths.target, options) ? "user-file" : "legacy";
35898
+ }
35899
+
35900
+ // src/settings-record.ts
35901
+ function settingsFileSets(generation, key, host2, model2) {
35902
+ const levels = generation.fileLevels[key];
35903
+ const row = resolveClaudeModelCapabilities(model2);
35904
+ return Boolean(levels?.some((level) => level === "default" || level === host2 || level === row?.id));
35905
+ }
35906
+ function section2(stored, key) {
35907
+ const value = stored[key];
35908
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
35909
+ }
35910
+ function legacyWait(value) {
35911
+ return value === "off" ? "0" : value === "15m" ? "15" : "max";
35912
+ }
35913
+ function quotaMinimums(values) {
35914
+ return {
35915
+ five_hour: values.quota_minimum_remaining_five_hour,
35916
+ seven_day: values.quota_minimum_remaining_seven_day,
35917
+ scoped: values.quota_minimum_remaining_scoped
35918
+ };
35919
+ }
35920
+ function killswitchRecord(stored, values, host2) {
35921
+ return {
35922
+ ...section2(stored, "killswitch"),
35923
+ enabled: values.killswitch_enabled,
35924
+ main: {
35925
+ five_hour: values.killswitch_default_five_hour,
35926
+ seven_day: values.killswitch_default_seven_day,
35927
+ scoped: values.killswitch_default_scoped
35928
+ },
35929
+ accounts: Object.fromEntries(values.killswitch_account_floors.filter((entry2) => entry2.host === host2 || entry2.host === "both").map(({ account, five_hour, seven_day, scoped }) => [
35930
+ account,
35931
+ { five_hour, seven_day, scoped }
35932
+ ]))
35933
+ };
35934
+ }
35935
+ function overlaySettingsProtection(stored, values, host2) {
35936
+ return structuredClone({
35937
+ ...stored,
35938
+ routing: {
35939
+ ...section2(stored, "routing"),
35940
+ maxSameAccountWait: legacyWait(values.max_same_account_wait)
35941
+ },
35942
+ quota: {
35943
+ ...section2(stored, "quota"),
35944
+ minimumRemaining: quotaMinimums(values),
35945
+ failClosedOnUnknownQuota: values.quota_fail_closed_on_unknown_quota
35946
+ },
35947
+ killswitch: killswitchRecord(stored, values, host2)
35948
+ });
35949
+ }
35950
+ function resolveSettingsRecord(stored, generation, host2, model2) {
35951
+ if (!generation)
35952
+ return structuredClone(stored);
35953
+ const context = generation.contexts[host2];
35954
+ const row = resolveClaudeModelCapabilities(model2);
35955
+ const values = {
35956
+ ...(row ? context.models[row.id] : undefined) ?? context.noModel,
35957
+ ...generation.protection[host2].values
35958
+ };
35959
+ const window2 = values.cache_keep_window[0];
35960
+ const cacheKeep = {
35961
+ ...section2(stored, "cacheKeep"),
35962
+ enabled: values.cache_keep_enabled,
35963
+ always: values.cache_keep_always,
35964
+ subagents: values.cache_keep_subagents
35965
+ };
35966
+ delete cacheKeep.startHour;
35967
+ delete cacheKeep.endHour;
35968
+ if (window2) {
35969
+ cacheKeep.startHour = window2.start_hour;
35970
+ cacheKeep.endHour = window2.end_hour;
35971
+ }
35972
+ const logging = { ...section2(stored, "logging") };
35973
+ delete logging.level;
35974
+ if (values.log_level !== "default")
35975
+ logging.level = values.log_level;
35976
+ const thinkingBinding = { ...section2(stored, "thinkingBinding") };
35977
+ delete thinkingBinding.prefixMismatchBehavior;
35978
+ if (values.thinking_binding_prefix_mismatch_behavior !== "account-default")
35979
+ thinkingBinding.prefixMismatchBehavior = values.thinking_binding_prefix_mismatch_behavior;
35980
+ const moved = {
35981
+ routing: {
35982
+ ...section2(stored, "routing"),
35983
+ mode: values.routing_mode,
35984
+ maxSameAccountWait: legacyWait(values.max_same_account_wait)
35985
+ },
35986
+ fallbackOn: values.fallback_on,
35987
+ refresh: {
35988
+ ...section2(stored, "refresh"),
35989
+ enabled: values.refresh_enabled,
35990
+ intervalMinutes: values.refresh_interval_minutes,
35991
+ refreshBeforeExpiryMinutes: values.refresh_refresh_before_expiry_minutes
35992
+ },
35993
+ quota: {
35994
+ ...section2(stored, "quota"),
35995
+ enabled: values.quota_enabled,
35996
+ checkIntervalMinutes: values.quota_check_interval_minutes,
35997
+ refreshEveryNRequests: values.quota_refresh_every_n_requests,
35998
+ minimumRemaining: quotaMinimums(values),
35999
+ failClosedOnUnknownQuota: values.quota_fail_closed_on_unknown_quota,
36000
+ showToasts: values.quota_show_toasts
36001
+ },
36002
+ quotaHeaderFeed: {
36003
+ ...section2(stored, "quotaHeaderFeed"),
36004
+ enabled: values.quota_header_feed_enabled
36005
+ },
36006
+ killswitch: killswitchRecord(stored, values, host2),
36007
+ claudeCache: {
36008
+ ...section2(stored, "claudeCache"),
36009
+ enabled: values.claude_cache_enabled,
36010
+ mode: values.claude_cache_mode
36011
+ },
36012
+ cacheKeep,
36013
+ dump: { ...section2(stored, "dump"), enabled: values.dump_enabled },
36014
+ prime: { ...section2(stored, "prime"), enabled: values.prime_enabled },
36015
+ claudeFast: {
36016
+ ...section2(stored, "claudeFast"),
36017
+ enabled: values.claude_fast_enabled
36018
+ },
36019
+ costZeroing: {
36020
+ ...section2(stored, "costZeroing"),
36021
+ enabled: values.cost_zeroing_enabled
36022
+ },
36023
+ logging,
36024
+ thinkingBinding,
36025
+ turnEndNote: {
36026
+ ...section2(stored, "turnEndNote"),
36027
+ tools: values.turn_end_note_tools
36028
+ }
36029
+ };
36030
+ return structuredClone({ ...stored, ...moved });
36031
+ }
36032
+
36033
+ // src/native-runtime-settings.ts
36034
+ function createNativeRuntimeSettings(options) {
36035
+ const env = options.env ?? process.env;
36036
+ let service = options.settingsService?.retain();
36037
+ let fallback = service ? undefined : options.settingsFallback;
36038
+ let reopenLegacy = service || fallback ? undefined : options.settingsReopen;
36039
+ let probedMode;
36040
+ const mode = () => probedMode ?? options.settingsMode?.() ?? "user-file";
36041
+ let effects;
36042
+ let userAuthority = mode() === "user-file";
36043
+ let closed2 = false;
36044
+ let checking;
36045
+ let cancelCheck;
36046
+ let loggedLateWrite = false;
36047
+ let writes = 0;
36048
+ const generation = () => service && (userAuthority || mode() === "user-file") && mode() !== "separate" ? service.snapshot() : undefined;
36049
+ function resolve20(stored, model2) {
36050
+ if (fallback && mode() !== "separate")
36051
+ return overlaySettingsProtection(stored, fallback.values, options.host);
36052
+ return resolveSettingsRecord(stored, generation(), options.host, model2);
36053
+ }
36054
+ function applyEffects() {
36055
+ if (!generation())
36056
+ return;
36057
+ const settings = resolve20({ version: 1, accounts: [] });
36058
+ const next = captureNativeSettingsEffectFields(settings);
36059
+ const level = parseLogLevel(next.logLevel) ?? parseLogLevel(env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL) ?? "info";
36060
+ const committed = { ...settings, logging: { level } };
36061
+ if (effects)
36062
+ applyCommittedNativeSettingsEffects(effects, committed);
36063
+ else if (!env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)
36064
+ setLogLevel2(level);
36065
+ effects = captureNativeSettingsEffectFields(committed);
36066
+ setDumpEnabled(settings.dump?.enabled === true);
36067
+ }
36068
+ function status() {
36069
+ const current = generation();
36070
+ if (!current)
36071
+ return;
36072
+ const context = current.contexts[options.host];
36073
+ const modelOverrides = {};
36074
+ for (const key of Object.keys(settingsDefinition.settings)) {
36075
+ const definition = settingsDefinition.settings[key];
36076
+ if (!("overrides" in definition) || !("model" in definition.overrides))
36077
+ continue;
36078
+ const rows = Object.entries(context.models).filter(([model2]) => current.fileLevels[key]?.includes(model2)).map(([model2, values]) => ({ model: model2, value: values[key] }));
36079
+ modelOverrides[key] = rows;
36080
+ }
36081
+ return {
36082
+ file: current.fileStatus,
36083
+ values: {
36084
+ ...context.noModel,
36085
+ ...current.protection[options.host].values
36086
+ },
36087
+ modelOverrides
35518
36088
  };
35519
36089
  }
35520
- return reference();
35521
- }
35522
- async function openSettingsService(options) {
35523
- if (options.separateInstall)
35524
- return;
35525
- const file = resolve19(options.file);
35526
- let shared = services.get(file);
35527
- if (!shared) {
35528
- shared = new SharedSettingsService(file, options);
35529
- services.set(file, shared);
36090
+ function recheck(refresh = true) {
36091
+ if (checking)
36092
+ return checking;
36093
+ if (closed2 || !service || mode() === "separate")
36094
+ return Promise.resolve();
36095
+ checking = (async () => {
36096
+ if (userAuthority)
36097
+ return;
36098
+ if (await resolveSettingsMode({ target: service.file, separate: false }, options.settingsAuthority?.options) !== "user-file")
36099
+ return;
36100
+ if (refresh)
36101
+ await service.refresh();
36102
+ userAuthority = true;
36103
+ cancelCheck?.();
36104
+ cancelCheck = undefined;
36105
+ if (!writes)
36106
+ applyEffects();
36107
+ })().finally(() => {
36108
+ checking = undefined;
36109
+ });
36110
+ return checking;
35530
36111
  }
35531
- const owned = shared;
35532
- owned.users++;
35533
- let closed2 = false;
35534
- let closing;
35535
- const subscriptions = new Set;
35536
- const lease = new SettingsProtectionLease(owned, options.protection, options);
35537
- const unsubscribeLease = owned.watch((generation) => lease.publish(generation));
35538
- const use = () => {
35539
- if (closed2)
35540
- throw new Error("Settings service lease is disposed");
35541
- return owned;
35542
- };
35543
- const dispose = () => {
35544
- if (closed2)
35545
- return closing ?? Promise.resolve();
35546
- closed2 = true;
35547
- unsubscribeLease();
35548
- for (const unsubscribe of subscriptions)
35549
- unsubscribe();
35550
- subscriptions.clear();
35551
- if (--owned.users === 0) {
35552
- if (services.get(file) === owned)
35553
- services.delete(file);
35554
- closing = owned.close();
36112
+ async function reopen() {
36113
+ if (closed2 || service)
36114
+ return;
36115
+ const current = fallback;
36116
+ if (current?.resolveAuthority) {
36117
+ const found = await current.resolveAuthority();
36118
+ if (closed2 || service || fallback !== current)
36119
+ return;
36120
+ if (found !== "user-file") {
36121
+ probedMode = found;
36122
+ userAuthority = false;
36123
+ fallback = undefined;
36124
+ if (found === "legacy")
36125
+ reopenLegacy = current.reopen;
36126
+ }
35555
36127
  }
35556
- closing = Promise.all([closing, lease.close()]).then(() => {});
35557
- return closing;
35558
- };
35559
- try {
35560
- await owned.ready;
35561
- await lease.publish(owned.snapshot());
35562
- } catch (error) {
35563
- await dispose();
35564
- throw error;
36128
+ const before = fallback;
36129
+ const open13 = before?.reopen ?? reopenLegacy;
36130
+ if (!open13)
36131
+ return;
36132
+ const next = await open13();
36133
+ if (!next)
36134
+ return;
36135
+ if (closed2 || service || fallback !== before) {
36136
+ await next.dispose();
36137
+ return;
36138
+ }
36139
+ service = next;
36140
+ fallback = undefined;
36141
+ reopenLegacy = undefined;
36142
+ subscribe(next);
36143
+ if (!writes)
36144
+ applyEffects();
35565
36145
  }
35566
- return referenceCountedSettingsService({
35567
- file,
35568
- resolve(host2, model2) {
35569
- use();
35570
- const context = lease.snapshot().contexts[host2];
35571
- const row = resolveClaudeModelCapabilities(model2);
35572
- return (row ? context.models[row.id] : undefined) ?? context.noModel;
36146
+ function scheduleCheck() {
36147
+ if (closed2 || mode() === "separate")
36148
+ return;
36149
+ if (!fallback && !reopenLegacy && (!service || userAuthority))
36150
+ return;
36151
+ const schedule2 = options.settingsAuthority?.schedule ?? ((callback, delayMs) => {
36152
+ const timer = setTimeout(() => void callback(), delayMs);
36153
+ timer.unref?.();
36154
+ return () => clearTimeout(timer);
36155
+ });
36156
+ cancelCheck = schedule2(async () => {
36157
+ cancelCheck = undefined;
36158
+ try {
36159
+ if (!service)
36160
+ await reopen();
36161
+ if (service)
36162
+ await recheck();
36163
+ } catch {} finally {
36164
+ scheduleCheck();
36165
+ }
36166
+ }, 60000);
36167
+ }
36168
+ let unwatch;
36169
+ let unonFileEvent;
36170
+ function subscribe(next) {
36171
+ unwatch = next.watch(() => {
36172
+ recheck(false).catch(() => {});
36173
+ if (!writes)
36174
+ applyEffects();
36175
+ });
36176
+ unonFileEvent = next.onFileEvent?.(() => {
36177
+ recheck().catch(() => {});
36178
+ });
36179
+ }
36180
+ if (service)
36181
+ subscribe(service);
36182
+ scheduleCheck();
36183
+ let ready = recheck();
36184
+ ready.catch(() => {
36185
+ ready = Promise.resolve();
36186
+ });
36187
+ return {
36188
+ resolve: resolve20,
36189
+ status,
36190
+ applyEffects,
36191
+ file: () => generation()?.file,
36192
+ async prepareAction() {
36193
+ await ready;
36194
+ await reopen().catch(() => {});
36195
+ await recheck();
35573
36196
  },
35574
- snapshot: () => {
35575
- use();
35576
- return lease.snapshot();
36197
+ fallbackFile: () => fallback?.file,
36198
+ async legacyAuthorityLost() {
36199
+ if (!service || mode() === "separate")
36200
+ return false;
36201
+ if (userAuthority)
36202
+ return true;
36203
+ return await resolveSettingsMode({ target: service.file, separate: false }, options.settingsAuthority?.options) === "user-file";
35577
36204
  },
35578
- status: () => {
35579
- use();
35580
- return lease.snapshot().fileStatus;
36205
+ async prepareWrite() {
36206
+ if (mode() === "separate")
36207
+ return;
36208
+ await reopen().catch(() => {});
36209
+ if (!service)
36210
+ return;
36211
+ await ready;
36212
+ await recheck();
36213
+ return generation() ? service : undefined;
35581
36214
  },
35582
- watch(listener) {
35583
- const unsubscribe = use().watch(() => listener(lease.snapshot()));
35584
- const stop = () => {
35585
- unsubscribe();
35586
- subscriptions.delete(stop);
35587
- };
35588
- subscriptions.add(stop);
35589
- return stop;
36215
+ async legacyWriteCommitted(source2, stored) {
36216
+ if (loggedLateWrite || !service)
36217
+ return;
36218
+ await recheck();
36219
+ const current = generation();
36220
+ if (!current)
36221
+ return;
36222
+ const legacy = readSettingsMoveSource(JSON.stringify(stored), {
36223
+ host: options.host,
36224
+ path: source2,
36225
+ quiet: true
36226
+ });
36227
+ const differing = differingLegacySettings(legacy, {
36228
+ ...current.contexts[options.host].noModel,
36229
+ ...current.protection[options.host].values
36230
+ }, options.host);
36231
+ if (!differing.length)
36232
+ return;
36233
+ loggedLateWrite = true;
36234
+ logger2.warn("settings", settingsNotImportedText(source2, service.file, differing));
35590
36235
  },
35591
- refresh: () => use().refresh(),
35592
- update: (edits, host2, options2 = {}) => use().update(edits, host2, options2, lease.snapshot().protection[host2]),
35593
- dispose
35594
- });
36236
+ async update(edits, before, planned = {}) {
36237
+ if (!service)
36238
+ throw new Error("Settings service is not available");
36239
+ writes++;
36240
+ let changed2 = false;
36241
+ try {
36242
+ changed2 = (await service.update(edits, options.host, {
36243
+ createMissing: true,
36244
+ ...planned
36245
+ })).outcome === "updated";
36246
+ } finally {
36247
+ writes--;
36248
+ }
36249
+ const next = resolve20(before);
36250
+ const withLevel = (settings) => ({
36251
+ ...settings,
36252
+ logging: {
36253
+ level: parseLogLevel(sectionLevel(settings)) ?? parseLogLevel(env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL) ?? "info"
36254
+ }
36255
+ });
36256
+ const committed = withLevel(next);
36257
+ if (changed2)
36258
+ applyCommittedNativeSettingsEffects(captureNativeSettingsEffectFields(withLevel(before)), committed);
36259
+ effects = captureNativeSettingsEffectFields(committed);
36260
+ setDumpEnabled(next.dump?.enabled === true);
36261
+ },
36262
+ close: async () => {
36263
+ closed2 = true;
36264
+ cancelCheck?.();
36265
+ unwatch?.();
36266
+ unonFileEvent?.();
36267
+ await checking?.catch(() => {});
36268
+ await service?.dispose();
36269
+ }
36270
+ };
36271
+ }
36272
+ function sectionLevel(settings) {
36273
+ const level = settings.logging?.level;
36274
+ return typeof level === "string" ? level : undefined;
35595
36275
  }
35596
36276
 
35597
36277
  // src/native-settings-write.ts
36278
+ import { existsSync as existsSync4 } from "node:fs";
36279
+ import { isDeepStrictEqual as isDeepStrictEqual5 } from "node:util";
36280
+ import { parse as parse5 } from "jsonc-parser";
35598
36281
  var paths = {
35599
36282
  routing_mode: ["routing", "mode"],
35600
36283
  max_same_account_wait: ["routing", "maxSameAccountWait"],
@@ -35696,22 +36379,22 @@ function put(settings, path2, value) {
35696
36379
  settings[key] = structuredClone(value);
35697
36380
  }
35698
36381
  function storeHeld(settings) {
35699
- const held = structuredClone(settings);
36382
+ const held2 = structuredClone(settings);
35700
36383
  for (const path2 of Object.values(paths))
35701
- put(held, path2, undefined);
36384
+ put(held2, path2, undefined);
35702
36385
  for (const path2 of [
35703
36386
  ["cacheKeep", "startHour"],
35704
36387
  ["cacheKeep", "endHour"],
35705
36388
  ["killswitch", "accounts"]
35706
36389
  ])
35707
- put(held, path2, undefined);
35708
- return held;
36390
+ put(held2, path2, undefined);
36391
+ return held2;
35709
36392
  }
35710
36393
  function changes(before, after, path2 = []) {
35711
36394
  return [...new Set([...Object.keys(before), ...Object.keys(after)])].flatMap((key) => {
35712
36395
  const left = before[key];
35713
36396
  const right = after[key];
35714
- if (isDeepStrictEqual4(left, right))
36397
+ if (isDeepStrictEqual5(left, right))
35715
36398
  return [];
35716
36399
  const child = [...path2, key];
35717
36400
  if (left && right && typeof left === "object" && typeof right === "object" && !Array.isArray(left) && !Array.isArray(right))
@@ -35734,7 +36417,7 @@ function planNativeSettingsWrite(before, after, generation, host2) {
35734
36417
  const right = flat(after);
35735
36418
  const edits = [];
35736
36419
  for (const key2 of Object.keys(left)) {
35737
- if (isDeepStrictEqual4(left[key2], right[key2]))
36420
+ if (isDeepStrictEqual5(left[key2], right[key2]))
35738
36421
  continue;
35739
36422
  edits.push(right[key2] === undefined ? { setting: key2, remove: true } : { setting: key2, value: right[key2] });
35740
36423
  }
@@ -35743,8 +36426,13 @@ function planNativeSettingsWrite(before, after, generation, host2) {
35743
36426
  const nextAccounts = accountFloors(after);
35744
36427
  const accounts = [
35745
36428
  ...new Set([...previousAccounts.keys(), ...nextAccounts.keys()])
35746
- ].filter((account) => !isDeepStrictEqual4(previousAccounts.get(account), nextAccounts.get(account)));
35747
- const plan = { edits, storeChanges, refusal: undefined };
36429
+ ].filter((account) => !isDeepStrictEqual5(previousAccounts.get(account), nextAccounts.get(account)));
36430
+ const plan = {
36431
+ edits,
36432
+ storeChanges,
36433
+ refusal: undefined,
36434
+ floorsFrom: undefined
36435
+ };
35748
36436
  if (!edits.length && !accounts.length && !storeChanges.length)
35749
36437
  return plan;
35750
36438
  const present = existsSync4(generation.file);
@@ -35752,10 +36440,14 @@ function planNativeSettingsWrite(before, after, generation, host2) {
35752
36440
  plan.refusal = malformedSettingsText(generation.file);
35753
36441
  return plan;
35754
36442
  }
35755
- for (const [index, edit] of [...edits.entries()].reverse()) {
35756
- if (!edit.remove)
36443
+ if (present && generation.status === "unreadable" && (accounts.length || edits.some((edit2) => edit2.remove))) {
36444
+ plan.refusal = SETTINGS_WRITE_FAILURES["settings-unavailable"].text(generation.file);
36445
+ return plan;
36446
+ }
36447
+ for (const [index, edit2] of [...edits.entries()].reverse()) {
36448
+ if (!edit2.remove)
35757
36449
  continue;
35758
- const key2 = edit.setting;
36450
+ const key2 = edit2.setting;
35759
36451
  const levels = present && generation.fileLevels[key2] || [];
35760
36452
  if (levels.includes(host2) && levels.includes("default")) {
35761
36453
  plan.refusal = refusedSettingsWriteText(key2, generation.file);
@@ -35771,18 +36463,29 @@ function planNativeSettingsWrite(before, after, generation, host2) {
35771
36463
  plan.refusal = invalidSettingsWriteText(key, generation.file);
35772
36464
  return plan;
35773
36465
  }
35774
- const raw = present && generation.source ? object3(parse5(generation.source.replace(/^\uFEFF/, ""), [], {
35775
- allowTrailingComma: true
35776
- })) : {};
35777
- let floors = structuredClone(present ? raw[key] ?? [] : settingsProtectionForRecreation(generation.protection[host2].values, host2).killswitch_account_floors);
36466
+ const floorsFrom = present && generation.source !== undefined ? { status: "ready", source: generation.source } : { status: "missing" };
36467
+ const edit = planSettingsAccountFloors(floorsFrom.status === "ready" && floorsFrom.source ? {
36468
+ status: "ready",
36469
+ document: parse5(floorsFrom.source.replace(/^\uFEFF/, ""), [], {
36470
+ allowTrailingComma: true
36471
+ })
36472
+ } : { status: "missing" }, new Map(accounts.map((account) => [account, nextAccounts.get(account)])), host2, settingsRecreationFloors(generation.protection[host2].values, host2));
36473
+ if (edit) {
36474
+ edits.push(edit);
36475
+ plan.floorsFrom = floorsFrom;
36476
+ }
36477
+ return plan;
36478
+ }
36479
+ function planSettingsAccountFloors(current, changes2, host2, recreation) {
36480
+ const key = "killswitch_account_floors";
36481
+ let floors = structuredClone(current.status === "ready" ? object3(current.document)[key] ?? [] : recreation);
35778
36482
  const original = structuredClone(floors);
35779
- for (const account of accounts) {
36483
+ for (const [account, value] of changes2) {
35780
36484
  floors = floors.flatMap((entry2) => entry2.account === account && entry2.host === "both" ? [
35781
36485
  { ...entry2, host: "opencode" },
35782
36486
  { ...entry2, host: "pi" }
35783
36487
  ] : [entry2]);
35784
36488
  const index = floors.findIndex((entry2) => entry2.account === account && entry2.host === host2);
35785
- const value = nextAccounts.get(account);
35786
36489
  if (value === undefined) {
35787
36490
  if (index !== -1)
35788
36491
  floors.splice(index, 1);
@@ -35794,9 +36497,7 @@ function planNativeSettingsWrite(before, after, generation, host2) {
35794
36497
  floors[index] = entry2;
35795
36498
  }
35796
36499
  }
35797
- if (!isDeepStrictEqual4(original, floors))
35798
- edits.push({ setting: key, value: floors });
35799
- return plan;
36500
+ return isDeepStrictEqual5(original, floors) ? undefined : { setting: key, value: floors };
35800
36501
  }
35801
36502
  function applyNativeStoreSettingsChanges(stored, changes2) {
35802
36503
  const next = structuredClone(stored);
@@ -35822,7 +36523,7 @@ import { randomUUID as randomUUID22 } from "node:crypto";
35822
36523
  import { SubcClient as SubcClient2 } from "@cortexkit/subc-client";
35823
36524
 
35824
36525
  // src/insula-quota.ts
35825
- function record14(value) {
36526
+ function record15(value) {
35826
36527
  return typeof value === "object" && value !== null && !Array.isArray(value);
35827
36528
  }
35828
36529
  function text5(value) {
@@ -35832,7 +36533,7 @@ function clampPercent3(value) {
35832
36533
  return Math.min(100, Math.max(0, value));
35833
36534
  }
35834
36535
  function windowReading(window2, checkedAt, expected) {
35835
- if (!record14(window2))
36536
+ if (!record15(window2))
35836
36537
  return;
35837
36538
  const usedPercent = window2.usedPercent;
35838
36539
  if (typeof usedPercent !== "number" || !Number.isFinite(usedPercent))
@@ -35856,7 +36557,7 @@ function scopedReadings(windows, checkedAt) {
35856
36557
  const seen = new Set;
35857
36558
  const scoped = [];
35858
36559
  for (const candidate of windows) {
35859
- if (!record14(candidate))
36560
+ if (!record15(candidate))
35860
36561
  continue;
35861
36562
  const identity5 = text5(candidate.id);
35862
36563
  if (!identity5)
@@ -35882,7 +36583,7 @@ function scopedReadings(windows, checkedAt) {
35882
36583
  return scoped;
35883
36584
  }
35884
36585
  function money2(value) {
35885
- if (!record14(value) || typeof value.minor !== "number" || !Number.isSafeInteger(value.minor) || value.minor < 0)
36586
+ if (!record15(value) || typeof value.minor !== "number" || !Number.isSafeInteger(value.minor) || value.minor < 0)
35886
36587
  return null;
35887
36588
  const exponent = value.exponent ?? 2;
35888
36589
  if (typeof exponent !== "number" || !Number.isInteger(exponent) || exponent < 0 || exponent > 20)
@@ -35892,8 +36593,8 @@ function money2(value) {
35892
36593
  function extraUsageReading(pools) {
35893
36594
  if (!Array.isArray(pools))
35894
36595
  return;
35895
- const pool = pools.find((candidate) => record14(candidate) && candidate.title === "Extra usage");
35896
- if (!record14(pool))
36596
+ const pool = pools.find((candidate) => record15(candidate) && candidate.title === "Extra usage");
36597
+ if (!record15(pool))
35897
36598
  return;
35898
36599
  const limit = money2(pool.total ?? pool.limit);
35899
36600
  const remaining = money2(pool.remaining);
@@ -35908,7 +36609,7 @@ function extraUsageReading(pools) {
35908
36609
  used = Math.max(0, limit.minor - remaining.minor);
35909
36610
  if (used === undefined)
35910
36611
  return;
35911
- const unit = text5(pool.unit) ?? text5(record14(pool.total) && pool.total.unit);
36612
+ const unit = text5(pool.unit) ?? text5(record15(pool.total) && pool.total.unit);
35912
36613
  const currency = unit && /^[A-Za-z]{3}$/.test(unit) ? unit : "USD";
35913
36614
  return {
35914
36615
  used: { amountMinor: used, currency, exponent },
@@ -36064,12 +36765,12 @@ function expectedSeed(input, boundary, refuse3) {
36064
36765
  const inventory = capture(top("inventory", "roster-incomplete"), ["view", "credentials", "skipped"], "roster-incomplete", refuse3);
36065
36766
  const view = inventory.view;
36066
36767
  const skipped = items(inventory.skipped, "roster-incomplete", refuse3);
36067
- const credentialRecords = items(inventory.credentials, "roster-incomplete", refuse3).map((record15) => capture(record15, ["credentialId", "credentialType", "accountIdentity", "state"], "roster-incomplete", refuse3));
36768
+ const credentialRecords = items(inventory.credentials, "roster-incomplete", refuse3).map((record16) => capture(record16, ["credentialId", "credentialType", "accountIdentity", "state"], "roster-incomplete", refuse3));
36068
36769
  if (!filled(view) || skipped.length > 0)
36069
36770
  refuse3("roster-incomplete");
36070
36771
  const listed = new Map;
36071
- for (const record15 of credentialRecords) {
36072
- const { credentialId, credentialType, accountIdentity, state } = record15;
36772
+ for (const record16 of credentialRecords) {
36773
+ const { credentialId, credentialType, accountIdentity, state } = record16;
36073
36774
  if (!filled(credentialId) || !filled(accountIdentity) || !filled(state) || listed.has(credentialId)) {
36074
36775
  refuse3("roster-incomplete");
36075
36776
  }
@@ -36080,7 +36781,7 @@ function expectedSeed(input, boundary, refuse3) {
36080
36781
  const primaryIdentity = primary.accountIdentity;
36081
36782
  boundary.fallback = "seed-conflict";
36082
36783
  const primaryRouteId = top("primaryRouteId", "seed-conflict");
36083
- const legacyRecords = items(top("legacyRows", "seed-conflict"), "seed-conflict", refuse3).map((record15) => capture(record15, [
36784
+ const legacyRecords = items(top("legacyRows", "seed-conflict"), "seed-conflict", refuse3).map((record16) => capture(record16, [
36084
36785
  "routeId",
36085
36786
  "scopedCredentialId",
36086
36787
  "anthropicAccountUuid",
@@ -37172,14 +37873,14 @@ function createNativeVaultRuntime(options) {
37172
37873
  if (!transport)
37173
37874
  return;
37174
37875
  const acquired = acquireInsulaQuotaSource(transport, hosted2 ? hostedInsulaCacheKey : tokenPath);
37175
- let held;
37876
+ let held2;
37176
37877
  try {
37177
37878
  assertTransport();
37178
37879
  if (!insula) {
37179
37880
  let released = false;
37180
37881
  let timer;
37181
37882
  let unwatch = () => {};
37182
- held = {
37883
+ held2 = {
37183
37884
  source: acquired.source,
37184
37885
  owner,
37185
37886
  generation,
@@ -37198,9 +37899,9 @@ function createNativeVaultRuntime(options) {
37198
37899
  }
37199
37900
  }
37200
37901
  };
37201
- insula = held;
37202
- const current = held;
37203
- unwatch = held.source.watch({
37902
+ insula = held2;
37903
+ const current = held2;
37904
+ unwatch = held2.source.watch({
37204
37905
  provider: "claude",
37205
37906
  setTimeoutImpl: options.setTimeout,
37206
37907
  clearTimeoutImpl: options.clearTimeout
@@ -37229,9 +37930,9 @@ function createNativeVaultRuntime(options) {
37229
37930
  } else
37230
37931
  acquired.release();
37231
37932
  } catch (error) {
37232
- if (held) {
37233
- held.release();
37234
- if (insula === held)
37933
+ if (held2) {
37934
+ held2.release();
37935
+ if (insula === held2)
37235
37936
  insula = undefined;
37236
37937
  } else
37237
37938
  acquired.release();
@@ -37303,26 +38004,26 @@ function createNativeVaultRuntime(options) {
37303
38004
  return;
37304
38005
  if (!watchers.size)
37305
38006
  return;
37306
- const held = {
38007
+ const held2 = {
37307
38008
  live: true,
37308
38009
  watch: undefined
37309
38010
  };
37310
- rosterWatch = held;
38011
+ rosterWatch = held2;
37311
38012
  try {
37312
- held.watch = custody.watchRoster({
38013
+ held2.watch = custody.watchRoster({
37313
38014
  view: () => rosterView,
37314
38015
  onView: async () => {
37315
38016
  try {
37316
38017
  while (polling)
37317
38018
  await polling.catch(() => {});
37318
- if (held.live)
38019
+ if (held2.live)
37319
38020
  await poll();
37320
38021
  } finally {
37321
38022
  options.onRosterNoticeHandled?.();
37322
38023
  }
37323
38024
  },
37324
38025
  onMode: (mode) => {
37325
- if (!held.live)
38026
+ if (!held2.live)
37326
38027
  return;
37327
38028
  rosterWatching = mode === "watching";
37328
38029
  schedulePoll();
@@ -37335,17 +38036,17 @@ function createNativeVaultRuntime(options) {
37335
38036
  }
37336
38037
  });
37337
38038
  } catch {
37338
- held.live = false;
37339
- if (rosterWatch === held)
38039
+ held2.live = false;
38040
+ if (rosterWatch === held2)
37340
38041
  rosterWatch = undefined;
37341
38042
  }
37342
38043
  }
37343
38044
  function closeRosterWatch() {
37344
- const held = rosterWatch;
38045
+ const held2 = rosterWatch;
37345
38046
  rosterWatch = undefined;
37346
- if (held) {
37347
- held.live = false;
37348
- held.watch?.close();
38047
+ if (held2) {
38048
+ held2.live = false;
38049
+ held2.watch?.close();
37349
38050
  }
37350
38051
  if (!rosterWatching)
37351
38052
  return;
@@ -37802,18 +38503,18 @@ function createNativeVaultRuntime(options) {
37802
38503
  const changed2 = await mutateVaultRoster(paths2.roster, async (current) => {
37803
38504
  await relocation.assertNotRelocated();
37804
38505
  assertCustodyOwner(owner, generation);
37805
- const held = current?.rows.find((entry2) => entry2.routeId === row.routeId);
37806
- if (!current || !held)
38506
+ const held2 = current?.rows.find((entry2) => entry2.routeId === row.routeId);
38507
+ if (!current || !held2)
37807
38508
  throw new ClaustrumConsumerError("route-unavailable", "Claustrum route is not in the roster");
37808
38509
  if (!enabled)
37809
- custody.forget(held.credentialId);
38510
+ custody.forget(held2.credentialId);
37810
38511
  return {
37811
38512
  next: {
37812
38513
  ...current,
37813
- declined: enabled ? acceptAccount(current.declined, [held.credentialId, ...held.aliases ?? []], held.accountIdentity) : declineAccount(current.declined, held.credentialId, held.accountIdentity),
37814
- rows: current.rows.map((entry2) => entry2 === held ? { ...entry2, enabled } : entry2)
38514
+ declined: enabled ? acceptAccount(current.declined, [held2.credentialId, ...held2.aliases ?? []], held2.accountIdentity) : declineAccount(current.declined, held2.credentialId, held2.accountIdentity),
38515
+ rows: current.rows.map((entry2) => entry2 === held2 ? { ...entry2, enabled } : entry2)
37815
38516
  },
37816
- result: held.enabled !== enabled
38517
+ result: held2.enabled !== enabled
37817
38518
  };
37818
38519
  }, {
37819
38520
  beforePublish: () => {
@@ -39762,13 +40463,13 @@ function settingsOverride(options) {
39762
40463
  return;
39763
40464
  if (isAbsoluteForPlatform(value, platform))
39764
40465
  return value;
39765
- let logged2 = ignoredOverrides.get(env);
39766
- if (!logged2) {
39767
- logged2 = new Set;
39768
- ignoredOverrides.set(env, logged2);
40466
+ let logged3 = ignoredOverrides.get(env);
40467
+ if (!logged3) {
40468
+ logged3 = new Set;
40469
+ ignoredOverrides.set(env, logged3);
39769
40470
  }
39770
- if (!logged2.has(value)) {
39771
- logged2.add(value);
40471
+ if (!logged3.has(value)) {
40472
+ logged3.add(value);
39772
40473
  const message = "ANTHROPIC_AUTH_SETTINGS_FILE is empty or relative; ignoring it (an absolute path is required).";
39773
40474
  if (options.warn)
39774
40475
  options.warn(message);
@@ -39896,6 +40597,7 @@ function acquireNativeAccountRuntime(options) {
39896
40597
  resolveSettings: (stored, model2) => use().resolveSettings?.(stored, model2) ?? stored,
39897
40598
  getSettingsStatus: () => use().getSettingsStatus?.(),
39898
40599
  applySettingsEffects: () => use().applySettingsEffects?.(),
40600
+ prepareSettingsAction: () => use().prepareSettingsAction?.() ?? Promise.resolve(),
39899
40601
  peek: () => use().peek?.(),
39900
40602
  authorizeLocal: (id2, request2) => use().authorizeLocal(id2, request2),
39901
40603
  authorizeApi: (id2, signal) => use().authorizeApi(id2, signal),
@@ -39938,12 +40640,20 @@ function nativeAccountPolicy(account, snapshot, modelId) {
39938
40640
  return { status: "allowed" };
39939
40641
  }
39940
40642
  function createNativeAccountRuntime(options) {
40643
+ const env = { ...options.vault?.env ?? process.env };
40644
+ const runtimeSettings = createNativeRuntimeSettings({ ...options, env });
40645
+ try {
40646
+ return buildNativeAccountRuntime(options, env, runtimeSettings);
40647
+ } catch (error) {
40648
+ runtimeSettings.close().catch(() => {});
40649
+ throw error;
40650
+ }
40651
+ }
40652
+ function buildNativeAccountRuntime(options, env, runtimeSettings) {
39941
40653
  const paths2 = Object.freeze({ ...options.paths });
39942
40654
  const onLockEvent = nativeLockObserver(options.local?.onLockEvent ?? options.vault?.onLockEvent);
39943
40655
  const withLock3 = observeNativeLocks(() => withLock, onLockEvent);
39944
40656
  const now = options.local?.now ?? options.vault?.now ?? Date.now;
39945
- const env = { ...options.vault?.env ?? process.env };
39946
- const runtimeSettings = createNativeRuntimeSettings({ ...options, env });
39947
40657
  const vaultPaths = nativeVaultPaths(paths2);
39948
40658
  const relocation = nativeRelocationGuard(paths2);
39949
40659
  const servesStateHome = stateLayoutOfPaths(paths2).kind === "state-home";
@@ -40386,6 +41096,7 @@ function createNativeAccountRuntime(options) {
40386
41096
  getSettingsStatus: runtimeSettings.status,
40387
41097
  resolveSettings: runtimeSettings.resolve,
40388
41098
  applySettingsEffects: runtimeSettings.applyEffects,
41099
+ prepareSettingsAction: runtimeSettings.prepareAction,
40389
41100
  async read(model2) {
40390
41101
  const view = await readView(model2);
40391
41102
  projectedFrom.set(view.snapshot, view);
@@ -40631,6 +41342,15 @@ function createNativeAccountRuntime(options) {
40631
41342
  async updateSettings(mutator) {
40632
41343
  const selected = await selectedStorage();
40633
41344
  const service = await runtimeSettings.prepareWrite();
41345
+ const fallbackFile = runtimeSettings.fallbackFile();
41346
+ if (!service && fallbackFile !== undefined) {
41347
+ const stored = await selected.store.readSettings();
41348
+ return {
41349
+ settings: stored.status === "ready" ? runtimeSettings.resolve(stored.settings) : {},
41350
+ outcome: "failed",
41351
+ reason: SETTINGS_WRITE_FAILURES["settings-unavailable"].text(fallbackFile)
41352
+ };
41353
+ }
40634
41354
  function activation(value) {
40635
41355
  const custody = value.claustrum;
40636
41356
  return [
@@ -40661,8 +41381,9 @@ function createNativeAccountRuntime(options) {
40661
41381
  if (plan.refusal)
40662
41382
  return { settings: before, outcome: "refused", reason: plan.refusal };
40663
41383
  try {
40664
- if (plan.edits.length)
40665
- await runtimeSettings.update(plan.edits, before);
41384
+ if (plan.edits.length) {
41385
+ await runtimeSettings.update(plan.edits, before, plan.floorsFrom?.status === "ready" ? { expectedSource: plan.floorsFrom.source } : plan.floorsFrom?.status === "missing" ? { expectMissing: true } : {});
41386
+ }
40666
41387
  } catch (error) {
40667
41388
  if (error instanceof SettingsRecreationRefusal)
40668
41389
  return {
@@ -40695,12 +41416,28 @@ function createNativeAccountRuntime(options) {
40695
41416
  };
40696
41417
  }
40697
41418
  const captured = {};
41419
+ let redirected = false;
40698
41420
  const result = await selected.store.updateSettings(async (settings) => {
41421
+ if (await runtimeSettings.legacyAuthorityLost()) {
41422
+ redirected = true;
41423
+ return settings;
41424
+ }
40699
41425
  captured.before = captureNativeSettingsEffectFields(settings);
40700
41426
  return legacyNativeSettings(await mutate(settings));
40701
41427
  });
41428
+ if (redirected) {
41429
+ await runtimeSettings.prepareAction();
41430
+ if (!await runtimeSettings.prepareWrite())
41431
+ throw new NativeCustodyError("route-unavailable");
41432
+ return runtime2.updateSettings(mutator);
41433
+ }
40702
41434
  if (result.outcome === "updated" && captured.before)
40703
41435
  applyCommittedNativeSettingsEffects(captured.before, result.settings);
41436
+ if (result.outcome === "updated") {
41437
+ try {
41438
+ await runtimeSettings.legacyWriteCommitted(selected.paths.config, result.settings);
41439
+ } catch {}
41440
+ }
40704
41441
  return result;
40705
41442
  },
40706
41443
  async setLoggingLevel(level) {
@@ -41249,6 +41986,14 @@ class NativeMigrationError extends Error {
41249
41986
  this.name = "NativeMigrationError";
41250
41987
  }
41251
41988
  }
41989
+
41990
+ class NativeSetupSettingsWriteError extends Error {
41991
+ code = "setup-settings-write-failed";
41992
+ constructor() {
41993
+ super("Credential transfer is committed, but setup settings were not saved. Run setup again to retry before retiring the legacy source.");
41994
+ this.name = "NativeSetupSettingsWriteError";
41995
+ }
41996
+ }
41252
41997
  var preflights = new WeakMap;
41253
41998
  async function nativePoolHoldsAccountData({
41254
41999
  paths: paths2
@@ -41477,6 +42222,8 @@ async function capture2(input, checkPool = false) {
41477
42222
  state: state.data,
41478
42223
  hostAuth: auth.data
41479
42224
  });
42225
+ if (input.writeSetupSettings)
42226
+ projection.settings = splitNativeMigrationSettings(projection.settings).retained;
41480
42227
  const mainRouteId = projection.mainRouteId;
41481
42228
  const main = projection.accounts.find((account) => account.id === mainRouteId);
41482
42229
  if ((input.requestVaultActivation || journal?.activation?.kind === "requested") && main?.credential?.type === "oauth" && !main.identity)
@@ -41751,6 +42498,27 @@ async function runNativeMigration(input, hooks = {}) {
41751
42498
  if (nativeSettingsDigest !== undefined && await settingsDigest() !== nativeSettingsDigest)
41752
42499
  refuse3("settings-changed");
41753
42500
  const step = async (label) => hooks.onStep?.(label);
42501
+ const writeSetupSettings = async () => {
42502
+ if (!operation.writeSetupSettings)
42503
+ return;
42504
+ const source2 = await readNativeMigrationSource("config", operation.legacyConfigPath ?? paths2.legacyConfig);
42505
+ owned(source2);
42506
+ if (source2.data === undefined)
42507
+ return;
42508
+ if (source2.digest !== (journal ? journal.sources.config : captured.config.digest))
42509
+ refuse3("invalid-source");
42510
+ const { moved } = splitNativeMigrationSettings(source2.data);
42511
+ await step("before:setup-settings");
42512
+ try {
42513
+ const result = await operation.writeSetupSettings(Object.freeze(moved));
42514
+ if (result.outcome !== "saved")
42515
+ throw new NativeSetupSettingsWriteError;
42516
+ } catch {
42517
+ throw new NativeSetupSettingsWriteError;
42518
+ }
42519
+ await requireUnchangedNativeMigrationSource(source2);
42520
+ await step("after:setup-settings");
42521
+ };
41754
42522
  const journalHooks = {
41755
42523
  assertOwned: async () => {
41756
42524
  await checkPaths(operation, captured);
@@ -41772,6 +42540,7 @@ async function runNativeMigration(input, hooks = {}) {
41772
42540
  return journal;
41773
42541
  }
41774
42542
  if (journal?.phase === "committed") {
42543
+ await writeSetupSettings();
41775
42544
  journal = await retire(operation, journal, assertMigration, hooks);
41776
42545
  if (journal.activation === null)
41777
42546
  await repair(operation, assertMigration, hooks);
@@ -42035,6 +42804,7 @@ async function runNativeMigration(input, hooks = {}) {
42035
42804
  });
42036
42805
  return journal;
42037
42806
  });
42807
+ await writeSetupSettings();
42038
42808
  return await retire(operation, journal, assertMigration, hooks);
42039
42809
  });
42040
42810
  } catch (error) {
@@ -42072,7 +42842,7 @@ function refuse4(code) {
42072
42842
  function isRecord18(value) {
42073
42843
  return value !== null && typeof value === "object" && !Array.isArray(value);
42074
42844
  }
42075
- function sameJson(left, right) {
42845
+ function sameJson2(left, right) {
42076
42846
  return nativeMigrationCanonicalJson(left) === nativeMigrationCanonicalJson(right);
42077
42847
  }
42078
42848
  function proofRows(rows) {
@@ -42381,7 +43151,7 @@ function classifyRows(plan, rows) {
42381
43151
  const present = new Set;
42382
43152
  for (const row of proofRows(rows)) {
42383
43153
  const proof = expected.get(row.id);
42384
- if (!proof || !sameJson(proof, row))
43154
+ if (!proof || !sameJson2(proof, row))
42385
43155
  refuse4("credential-changed");
42386
43156
  present.add(row.id);
42387
43157
  }
@@ -42510,7 +43280,7 @@ async function runNativeCustodyActivation(options, hooks = {}) {
42510
43280
  };
42511
43281
  const requireRoster = async (plan2, allowAbsent) => {
42512
43282
  const roster = await readRoster(paths2);
42513
- if (roster === undefined ? !allowAbsent : !sameJson(roster, plan2.roster))
43283
+ if (roster === undefined ? !allowAbsent : !sameJson2(roster, plan2.roster))
42514
43284
  refuse4("roster-conflict");
42515
43285
  };
42516
43286
  const runtimeDigest = async () => nativeMigrationDigest(await readRuntime(paths2));
@@ -42534,7 +43304,7 @@ async function runNativeCustodyActivation(options, hooks = {}) {
42534
43304
  };
42535
43305
  await requireMigrationProof();
42536
43306
  const plan2 = await preparePlan(input, journal, store);
42537
- if (migrationProof !== undefined && !sameJson(plan2.localProof, migrationProof))
43307
+ if (migrationProof !== undefined && !sameJson2(plan2.localProof, migrationProof))
42538
43308
  refuse4("migration-proof-changed");
42539
43309
  const requirePrepared = async () => {
42540
43310
  await requireMigrationProof();
@@ -42596,7 +43366,7 @@ async function runNativeCustodyActivation(options, hooks = {}) {
42596
43366
  await mutateVaultRoster(paths2.roster, async (current2, rosterLease) => {
42597
43367
  const projected = rosterProjection(current2);
42598
43368
  if (projected) {
42599
- if (!sameJson(projected, plan.roster))
43369
+ if (!sameJson2(projected, plan.roster))
42600
43370
  refuse4("roster-conflict");
42601
43371
  return { result: undefined };
42602
43372
  }
@@ -42705,8 +43475,8 @@ async function runNativeCustodyActivation(options, hooks = {}) {
42705
43475
  await step("before:authority-rename");
42706
43476
  await requirePublished(plan.settings.target);
42707
43477
  await fence();
42708
- for (const held of leases)
42709
- await held.assertOwned();
43478
+ for (const held2 of leases)
43479
+ await held2.assertOwned();
42710
43480
  },
42711
43481
  onWriteStep: async (write) => step(`${write}:journal:committed`)
42712
43482
  });
@@ -42739,8 +43509,8 @@ async function commitMode(paths2, routingPath, plan, context) {
42739
43509
  await context.fence();
42740
43510
  if (!leases)
42741
43511
  refuse4("ownership-lost");
42742
- for (const held of leases)
42743
- await held.assertOwned();
43512
+ for (const held2 of leases)
43513
+ await held2.assertOwned();
42744
43514
  }
42745
43515
  });
42746
43516
  let failure;
@@ -43364,7 +44134,7 @@ function readPlain(value, allowed3) {
43364
44134
  const prototype = Object.getPrototypeOf(value);
43365
44135
  if (prototype !== Object.prototype && prototype !== null)
43366
44136
  return "malformed";
43367
- const fields2 = new Map;
44137
+ const fields3 = new Map;
43368
44138
  let unknownKey = false;
43369
44139
  for (const key of Reflect.ownKeys(value)) {
43370
44140
  if (typeof key !== "string")
@@ -43375,9 +44145,9 @@ function readPlain(value, allowed3) {
43375
44145
  if (!allowed3.includes(key))
43376
44146
  unknownKey = true;
43377
44147
  else
43378
- fields2.set(key, descriptor.value);
44148
+ fields3.set(key, descriptor.value);
43379
44149
  }
43380
- return unknownKey ? "unknown-key" : fields2;
44150
+ return unknownKey ? "unknown-key" : fields3;
43381
44151
  }
43382
44152
  function readArray(value) {
43383
44153
  if (value === null || typeof value !== "object")
@@ -43431,13 +44201,13 @@ function readKillswitchEntries(value) {
43431
44201
  return;
43432
44202
  const entries = [];
43433
44203
  for (const item of items2) {
43434
- const fields2 = readPlain(item, ENTRY_KEYS);
43435
- if (!(fields2 instanceof Map))
44204
+ const fields3 = readPlain(item, ENTRY_KEYS);
44205
+ if (!(fields3 instanceof Map))
43436
44206
  return;
43437
- const account = fields2.get("account");
43438
- const fh = fields2.get("fh");
43439
- const sd = fields2.get("sd");
43440
- const scoped = fields2.get("scoped");
44207
+ const account = fields3.get("account");
44208
+ const fh = fields3.get("fh");
44209
+ const sd = fields3.get("sd");
44210
+ const scoped = fields3.get("scoped");
43441
44211
  if (!isKillswitchAccount(account))
43442
44212
  return;
43443
44213
  if (!isDigitInteger(fh) || !isDigitInteger(sd))
@@ -43521,14 +44291,14 @@ var CONTEXT_KEYS = [
43521
44291
  "signal"
43522
44292
  ];
43523
44293
  function readContext(value) {
43524
- const fields2 = readPlain(value, CONTEXT_KEYS);
43525
- if (!(fields2 instanceof Map))
43526
- return;
43527
- const interactive = fields2.get("interactive");
43528
- const custodyMode = fields2.get("custodyMode");
43529
- const confirmed = fields2.get("confirmed");
43530
- const sessionId = fields2.get("sessionId");
43531
- const rawSignal = fields2.get("signal");
44294
+ const fields3 = readPlain(value, CONTEXT_KEYS);
44295
+ if (!(fields3 instanceof Map))
44296
+ return;
44297
+ const interactive = fields3.get("interactive");
44298
+ const custodyMode = fields3.get("custodyMode");
44299
+ const confirmed = fields3.get("confirmed");
44300
+ const sessionId = fields3.get("sessionId");
44301
+ const rawSignal = fields3.get("signal");
43532
44302
  if (typeof interactive !== "boolean")
43533
44303
  return;
43534
44304
  if (custodyMode !== "local" && custodyMode !== "claustrum")
@@ -43630,9 +44400,9 @@ var DISCONNECT_RESULTS = new Set([
43630
44400
  "conflict"
43631
44401
  ]);
43632
44402
  function readOutcome(action, outcome) {
43633
- const fields2 = readPlain(outcome, ["ok", "text"]);
43634
- const ok = fields2 instanceof Map ? fields2.get("ok") : undefined;
43635
- const text6 = fields2 instanceof Map ? fields2.get("text") : undefined;
44403
+ const fields3 = readPlain(outcome, ["ok", "text"]);
44404
+ const ok = fields3 instanceof Map ? fields3.get("ok") : undefined;
44405
+ const text6 = fields3 instanceof Map ? fields3.get("text") : undefined;
43636
44406
  if (typeof ok !== "boolean" || typeof text6 !== "string")
43637
44407
  return Object.freeze({ status: "failed", action, code: "invalid-outcome" });
43638
44408
  return Object.freeze({ status: "executed", action, ok, text: text6 });
@@ -43675,12 +44445,12 @@ function disconnectFailureCode(error) {
43675
44445
  return "execution-failed";
43676
44446
  }
43677
44447
  function createNativeMenuExecutor(options) {
43678
- const fields2 = readPlain(options, ["host", "dispatch", "disconnectVault"]);
43679
- if (!(fields2 instanceof Map))
44448
+ const fields3 = readPlain(options, ["host", "dispatch", "disconnectVault"]);
44449
+ if (!(fields3 instanceof Map))
43680
44450
  throw new TypeError("Native menu executor options are invalid");
43681
- const host2 = fields2.get("host");
43682
- const dispatch = fields2.get("dispatch");
43683
- const disconnectVault = fields2.get("disconnectVault");
44451
+ const host2 = fields3.get("host");
44452
+ const dispatch = fields3.get("dispatch");
44453
+ const disconnectVault = fields3.get("disconnectVault");
43684
44454
  if (!HOSTS2.has(host2))
43685
44455
  throw invalidOption2("host");
43686
44456
  if (typeof dispatch !== "function" || utilTypes7.isProxy(dispatch))
@@ -43738,27 +44508,189 @@ function createNativeMenuExecutor(options) {
43738
44508
  code: "execution-failed"
43739
44509
  });
43740
44510
  }
43741
- return readOutcome(next.action, outcome);
43742
- };
43743
- return Object.freeze({ execute: Object.freeze(execute) });
43744
- }
43745
- // src/native-settings.ts
43746
- function nativeSettingsRecord(value) {
43747
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
43748
- }
43749
- function mergeNativeSettingsSection(settings, section3, patch) {
43750
- return {
43751
- ...settings,
43752
- [section3]: { ...nativeSettingsRecord(settings[section3]), ...patch }
43753
- };
43754
- }
43755
- function nativeCacheKeepAlways(settings) {
43756
- const {
43757
- startHour: _start,
43758
- endHour: _end,
43759
- ...keep
43760
- } = nativeSettingsRecord(settings.cacheKeep);
43761
- return { ...settings, cacheKeep: { ...keep, enabled: true, always: true } };
44511
+ return readOutcome(next.action, outcome);
44512
+ };
44513
+ return Object.freeze({ execute: Object.freeze(execute) });
44514
+ }
44515
+ // src/native-settings.ts
44516
+ function nativeSettingsRecord(value) {
44517
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
44518
+ }
44519
+ function mergeNativeSettingsSection(settings, section3, patch) {
44520
+ return {
44521
+ ...settings,
44522
+ [section3]: { ...nativeSettingsRecord(settings[section3]), ...patch }
44523
+ };
44524
+ }
44525
+ function nativeCacheKeepAlways(settings) {
44526
+ const {
44527
+ startHour: _start,
44528
+ endHour: _end,
44529
+ ...keep
44530
+ } = nativeSettingsRecord(settings.cacheKeep);
44531
+ return { ...settings, cacheKeep: { ...keep, enabled: true, always: true } };
44532
+ }
44533
+ // src/native-setup-settings.ts
44534
+ import { isDeepStrictEqual as isDeepStrictEqual6 } from "node:util";
44535
+ import { parse as parse6 } from "jsonc-parser";
44536
+ var thresholds = ({ five_hour, seven_day, scoped }) => ({
44537
+ five_hour,
44538
+ seven_day,
44539
+ scoped
44540
+ });
44541
+ async function writeNativeSetupSettings(options) {
44542
+ const paths2 = options.paths ?? await resolveSettingsPaths(options.host, options);
44543
+ const mode = await resolveSettingsMode(paths2, options.authority);
44544
+ const result = {
44545
+ target: mode === "user-file" ? "user-file" : "legacy-store",
44546
+ outcome: "saved",
44547
+ skipped: [],
44548
+ differing: []
44549
+ };
44550
+ const warn = (message) => {
44551
+ if (options.log)
44552
+ options.log.warn(message);
44553
+ else
44554
+ logger2.warn("settings", message);
44555
+ };
44556
+ let service;
44557
+ try {
44558
+ validateNativeMigrationSettings(options.settings);
44559
+ const { moved } = splitNativeMigrationSettings(options.settings);
44560
+ if (mode !== "user-file") {
44561
+ if (Object.keys(moved).length)
44562
+ await options.writeLegacySettings(moved);
44563
+ return result;
44564
+ }
44565
+ service = await openSettingsService({
44566
+ file: paths2.target,
44567
+ host: options.host,
44568
+ protection: options.protection
44569
+ });
44570
+ if (!service)
44571
+ throw new Error("Settings service did not open");
44572
+ const generation = service.snapshot();
44573
+ if (generation.status === "unparseable" || generation.fileStatus.duplicateKeys.length) {
44574
+ return {
44575
+ ...result,
44576
+ outcome: "refused",
44577
+ reason: malformedSettingsText(paths2.target)
44578
+ };
44579
+ }
44580
+ if (generation.status === "unreadable")
44581
+ return {
44582
+ ...result,
44583
+ outcome: "failed",
44584
+ reason: SETTINGS_WRITE_FAILURES["settings-unavailable"].text(paths2.target)
44585
+ };
44586
+ const missing3 = generation.status === "missing";
44587
+ if (!missing3)
44588
+ await writeSettingsMoveMarker(paths2.target, options.authority);
44589
+ const values = readSettingsMoveSource(JSON.stringify(moved), {
44590
+ host: options.host,
44591
+ path: options.source,
44592
+ log: { warn }
44593
+ });
44594
+ const raw = generation.source ? parse6(generation.source.replace(/^\uFEFF/, ""), [], {
44595
+ allowTrailingComma: true
44596
+ }) ?? {} : {};
44597
+ const edits = [];
44598
+ const skip = (key, legacy, held2, account) => {
44599
+ if (!result.skipped.includes(key)) {
44600
+ result.skipped.push(key);
44601
+ warn(`Setup skipped setting "${key}" in "${paths2.target}": ${missing3 ? "the carried protection set" : "the user settings file"} already supplies it for ${options.host}.`);
44602
+ }
44603
+ if (!isDeepStrictEqual6(legacy, held2))
44604
+ result.differing.push({
44605
+ key,
44606
+ ...account === undefined ? {} : { account },
44607
+ legacy,
44608
+ file: held2
44609
+ });
44610
+ };
44611
+ for (const key of Object.keys(values)) {
44612
+ const value = values[key];
44613
+ if (missing3 && SETTINGS_PROTECTION_KEYS.includes(key)) {
44614
+ if (key === "killswitch_account_floors") {
44615
+ const floors = generation.protection[options.host].values[key];
44616
+ if (!values[key]?.length)
44617
+ skip(key, [], []);
44618
+ for (const entry2 of values[key] ?? []) {
44619
+ const held2 = floors.find((existing) => existing.account === entry2.account && (existing.host === options.host || existing.host === "both"));
44620
+ skip(key, thresholds(entry2), held2 && thresholds(held2), entry2.account);
44621
+ }
44622
+ continue;
44623
+ }
44624
+ skip(key, value, generation.protection[options.host].values[key]);
44625
+ continue;
44626
+ }
44627
+ if (key === "killswitch_account_floors" && Object.hasOwn(raw, key)) {
44628
+ if (generation.report.some((entry2) => entry2.keyPath[0] === key))
44629
+ return {
44630
+ ...result,
44631
+ outcome: "refused",
44632
+ reason: invalidSettingsWriteText(key, paths2.target)
44633
+ };
44634
+ const floors = structuredClone(raw[key]);
44635
+ const appended = [];
44636
+ for (const entry2 of values[key] ?? []) {
44637
+ const held2 = floors.find((existing) => existing.account === entry2.account && (existing.host === options.host || existing.host === "both"));
44638
+ if (held2) {
44639
+ skip(key, thresholds(entry2), thresholds(held2), entry2.account);
44640
+ } else
44641
+ appended.push({ ...entry2, host: options.host });
44642
+ }
44643
+ if (appended.length)
44644
+ edits.push({ setting: key, value: [...floors, ...appended] });
44645
+ continue;
44646
+ }
44647
+ const levels = generation.fileLevels[key] ?? [];
44648
+ if (levels.includes("default") || levels.includes(options.host)) {
44649
+ const held2 = raw[key];
44650
+ skip(key, value, held2 && typeof held2 === "object" && !Array.isArray(held2) ? held2[levels.includes(options.host) ? options.host : "default"] : held2);
44651
+ } else {
44652
+ const edit = options.host === "pi" && key !== "killswitch_account_floors" ? undefined : { setting: key, value };
44653
+ if (edit)
44654
+ edits.push(edit);
44655
+ else {
44656
+ const note = "Pi's value was not imported because the settings file had no Pi entry for it.";
44657
+ result.skipped.push(key);
44658
+ result.differing.push({
44659
+ key,
44660
+ legacy: value,
44661
+ file: service.resolve("pi")[key],
44662
+ note
44663
+ });
44664
+ warn(`Setup skipped setting "${key}" in "${paths2.target}": ${note}`);
44665
+ }
44666
+ }
44667
+ }
44668
+ if (edits.length)
44669
+ await service.update(edits, options.host, {
44670
+ createMissing: missing3,
44671
+ hostsStopped: true
44672
+ });
44673
+ else if (missing3 && Object.keys(values).length)
44674
+ await service.update([
44675
+ {
44676
+ setting: "killswitch_enabled",
44677
+ value: generation.protection[options.host].values.killswitch_enabled
44678
+ }
44679
+ ], options.host, { createMissing: true, hostsStopped: true });
44680
+ return result;
44681
+ } catch (error) {
44682
+ if (error instanceof SettingsRecreationRefusal)
44683
+ return { ...result, outcome: "refused", reason: error.message };
44684
+ const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
44685
+ const failure = SETTINGS_WRITE_FAILURES[code] ?? SETTINGS_WRITE_FAILURES["settings-unavailable"];
44686
+ return {
44687
+ ...result,
44688
+ outcome: failure.outcome,
44689
+ reason: failure.text(paths2.target)
44690
+ };
44691
+ } finally {
44692
+ await service?.dispose();
44693
+ }
43762
44694
  }
43763
44695
  // src/native-ui.ts
43764
44696
  import { types as utilTypes8 } from "node:util";
@@ -44525,7 +45457,7 @@ function sameDirectory(observed, identity5) {
44525
45457
  function errorCode4(error) {
44526
45458
  return typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
44527
45459
  }
44528
- function held() {
45460
+ function held2() {
44529
45461
  return Object.assign(new Error("Pi auth lock held"), { code: "ELOCKED" });
44530
45462
  }
44531
45463
  async function remove(path2) {
@@ -44543,7 +45475,7 @@ async function acquire(path2, stale) {
44543
45475
  if (errorCode4(error) !== "EEXIST")
44544
45476
  throw error;
44545
45477
  if (stale <= 0)
44546
- throw held();
45478
+ throw held2();
44547
45479
  let mtime;
44548
45480
  try {
44549
45481
  mtime = (await stat13(path2)).mtime.getTime();
@@ -44553,7 +45485,7 @@ async function acquire(path2, stale) {
44553
45485
  throw error2;
44554
45486
  }
44555
45487
  if (!(mtime < Date.now() - stale))
44556
- throw held();
45488
+ throw held2();
44557
45489
  await remove(path2);
44558
45490
  return acquire(path2, 0);
44559
45491
  }
@@ -46094,9 +47026,9 @@ class QuotaHeaderFeedRegistry {
46094
47026
  await this.reapStaleSiblingLeases(directory);
46095
47027
  let entries = {};
46096
47028
  try {
46097
- const record15 = JSON.parse(await readFile17(this.filePath, "utf8"));
46098
- if (record15.version === QUOTA_HEADER_FEED_SCHEMA_VERSION && record15.entries && typeof record15.entries === "object")
46099
- entries = record15.entries;
47029
+ const record16 = JSON.parse(await readFile17(this.filePath, "utf8"));
47030
+ if (record16.version === QUOTA_HEADER_FEED_SCHEMA_VERSION && record16.entries && typeof record16.entries === "object")
47031
+ entries = record16.entries;
46100
47032
  } catch {}
46101
47033
  entries[accountKey] = cleanEntry;
46102
47034
  const tempPath = `${this.filePath}.${randomUUID25()}.tmp`;
@@ -46150,10 +47082,10 @@ class QuotaHeaderFeedRegistry {
46150
47082
  const newest = new Map;
46151
47083
  await Promise.all(names2.map(async (name) => {
46152
47084
  try {
46153
- const record15 = JSON.parse(await readFile17(join30(directory, name), "utf8"));
46154
- if (record15.version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || !record15.entries || typeof record15.entries !== "object")
47085
+ const record16 = JSON.parse(await readFile17(join30(directory, name), "utf8"));
47086
+ if (record16.version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || !record16.entries || typeof record16.entries !== "object")
46155
47087
  return;
46156
- for (const [accountKey, candidate] of Object.entries(record15.entries)) {
47088
+ for (const [accountKey, candidate] of Object.entries(record16.entries)) {
46157
47089
  if (!candidate || typeof candidate !== "object" || candidate.schema_version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || candidate.provider !== "anthropic" || !validIdentity(candidate))
46158
47090
  continue;
46159
47091
  const observed = candidate.observed_at_ms;
@@ -46548,13 +47480,13 @@ function isInvalidJsonBody(text6) {
46548
47480
  }
46549
47481
  if (!parsed || typeof parsed !== "object")
46550
47482
  return false;
46551
- const record15 = parsed;
46552
- const error = record15.error;
46553
- if (record15.type === "error" && error && typeof error === "object" && typeof error.type === "string" && typeof error.message === "string") {
47483
+ const record16 = parsed;
47484
+ const error = record16.error;
47485
+ if (record16.type === "error" && error && typeof error === "object" && typeof error.type === "string" && typeof error.message === "string") {
46554
47486
  const message = error.message;
46555
47487
  return INVALID_JSON_MESSAGES.some((prefix) => message.startsWith(prefix));
46556
47488
  }
46557
- return typeof record15.error === "string" && record15.reason === "bad_json" && BAD_JSON_TEXT.test(record15.error);
47489
+ return typeof record16.error === "string" && record16.reason === "bad_json" && BAD_JSON_TEXT.test(record16.error);
46558
47490
  }
46559
47491
  async function classifyGzipRejection(response) {
46560
47492
  const { status } = response;
@@ -46974,8 +47906,8 @@ async function holderFenceBlockers(input) {
46974
47906
  }
46975
47907
  for (const value of contents?.entries ?? []) {
46976
47908
  const life = holderEntryLiveness(value);
46977
- const record15 = value;
46978
- const listed = Array.isArray(record15?.files) ? record15.files.filter((file) => typeof file === "string") : undefined;
47909
+ const record16 = value;
47910
+ const listed = Array.isArray(record16?.files) ? record16.files.filter((file) => typeof file === "string") : undefined;
46979
47911
  if (!life || !listed) {
46980
47912
  blockers.push({
46981
47913
  kind: "holder",
@@ -46995,7 +47927,7 @@ async function holderFenceBlockers(input) {
46995
47927
  kind: "holder",
46996
47928
  holderFile,
46997
47929
  pid: life.pid,
46998
- role: typeof record15.role === "string" ? record15.role : null,
47930
+ role: typeof record16.role === "string" ? record16.role : null,
46999
47931
  file: overlap
47000
47932
  });
47001
47933
  }
@@ -47066,7 +47998,8 @@ async function readArtifact(path2, blockers) {
47066
47998
  return;
47067
47999
  }
47068
48000
  }
47069
- async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidAlive, clock = {}) {
48001
+ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidAlive, clock = {}, acceptsRelease) {
48002
+ const exempt = (value) => stamped(value) && (!acceptsRelease || acceptsRelease(value.writer.release));
47070
48003
  const blockers = [];
47071
48004
  const portDirs = [...locations.rpcDirs];
47072
48005
  for (const root of locations.rpcRoots)
@@ -47077,10 +48010,10 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
47077
48010
  if (!/^port-\d+\.json$/.test(name))
47078
48011
  continue;
47079
48012
  const path2 = join32(dir, name);
47080
- const record15 = await readArtifact(path2, blockers);
47081
- if (record15 === undefined || stamped(record15.value))
48013
+ const record16 = await readArtifact(path2, blockers);
48014
+ if (record16 === undefined || exempt(record16.value))
47082
48015
  continue;
47083
- const { value, startedAt } = record15;
48016
+ const { value, startedAt } = record16;
47084
48017
  const pid = value.pid;
47085
48018
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0) {
47086
48019
  blockers.push({ kind: "artifact-scan", path: path2, reason: "invalid" });
@@ -47096,11 +48029,11 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
47096
48029
  if (!match)
47097
48030
  continue;
47098
48031
  const path2 = join32(dir, name);
47099
- const record15 = await readArtifact(path2, blockers);
47100
- if (record15 === undefined || stamped(record15.value))
48032
+ const record16 = await readArtifact(path2, blockers);
48033
+ if (record16 === undefined || exempt(record16.value))
47101
48034
  continue;
47102
48035
  const pid = Number(match[1]);
47103
- if (!recordPredatesBoot(record15.startedAt, clock) && pidAlive2(pid))
48036
+ if (!recordPredatesBoot(record16.startedAt, clock) && pidAlive2(pid))
47104
48037
  blockers.push({ kind: "pre-n-artifact", artifact: path2, pid });
47105
48038
  }
47106
48039
  }
@@ -47156,13 +48089,16 @@ async function checkSettingsMoveFence(options) {
47156
48089
  };
47157
48090
  }
47158
48091
  const floorText = options.floor ?? SETTINGS_MOVE_FIRST_RELEASE;
47159
- const floor3 = parseRelease(floorText);
47160
- if (!floor3)
48092
+ const floor4 = parseRelease(floorText);
48093
+ if (!floor4)
47161
48094
  return { open: false, blockers: [{ kind: "floor", release: floorText }] };
47162
48095
  const context = resolvePathOptions(options);
47163
- const self = options.self ?? {
47164
- pid: process.pid,
47165
- incarnation: await processIncarnation(process.pid)
48096
+ const self = {
48097
+ ...options.self ?? {
48098
+ pid: process.pid,
48099
+ incarnation: await processIncarnation(process.pid)
48100
+ },
48101
+ instance: options.self?.instance ?? holderInstance()
47166
48102
  };
47167
48103
  let holderFiles;
47168
48104
  try {
@@ -47203,13 +48139,13 @@ async function checkSettingsMoveFence(options) {
47203
48139
  });
47204
48140
  continue;
47205
48141
  }
47206
- if (life.pid === self.pid && life.incarnation === self.incarnation)
48142
+ if (life.pid === self.pid && life.incarnation === self.incarnation && value.instance === self.instance)
47207
48143
  continue;
47208
48144
  if (!await holderEntryIsLive(life, options.liveness))
47209
48145
  continue;
47210
48146
  const releaseText = value.release;
47211
48147
  const release2 = typeof releaseText === "string" ? parseRelease(releaseText) : undefined;
47212
- if (!release2 || compareRelease(release2, floor3) < 0) {
48148
+ if (!release2 || compareRelease(release2, floor4) < 0) {
47213
48149
  blockers.push({
47214
48150
  kind: "settings-holder",
47215
48151
  holderFile,
@@ -47220,7 +48156,10 @@ async function checkSettingsMoveFence(options) {
47220
48156
  }
47221
48157
  }
47222
48158
  }
47223
- const artifactBlockers = await preNArtifactBlockers(options.artifacts ?? defaultPreNArtifactLocations(context.env, context.home), options.liveness?.pidAlive, options.liveness);
48159
+ const artifactBlockers = await preNArtifactBlockers(options.artifacts ?? defaultPreNArtifactLocations(context.env, context.home), options.liveness?.pidAlive, options.liveness, (release2) => {
48160
+ const parsed = typeof release2 === "string" ? parseRelease(release2) : undefined;
48161
+ return !!parsed && compareRelease(parsed, floor4) >= 0;
48162
+ });
47224
48163
  for (const blocker of artifactBlockers) {
47225
48164
  if (blocker.kind === "pre-n-artifact" || blocker.kind === "artifact-scan")
47226
48165
  blockers.push(blocker);
@@ -47288,254 +48227,151 @@ function mapSettingsMoveSources(sources2) {
47288
48227
  pi: []
47289
48228
  };
47290
48229
  let accountSource;
47291
- for (const [source2, legacy] of sources2.entries()) {
47292
- if (!legacy.present)
47293
- continue;
47294
- const values = legacy.value;
47295
- for (const [setting, value] of Object.entries(values)) {
47296
- if (setting === "killswitch_account_floors") {
47297
- accountSource ??= source2;
47298
- floors[legacy.host] = values.killswitch_account_floors ?? [];
47299
- } else
47300
- entries.push({ source: source2, setting, value });
47301
- }
47302
- }
47303
- if (accountSource !== undefined) {
47304
- const pi = new Map(floors.pi.map((entry2) => [entry2.account, entry2]));
47305
- const accounts = floors.opencode.map((entry2) => {
47306
- const peer = pi.get(entry2.account);
47307
- if (entry2.account.startsWith("vault:") && peer && entry2.five_hour === peer.five_hour && entry2.seven_day === peer.seven_day && entry2.scoped === peer.scoped) {
47308
- pi.delete(entry2.account);
47309
- return { ...entry2, host: "both" };
47310
- }
47311
- return { ...entry2, host: "opencode" };
47312
- });
47313
- accounts.push(...[...pi.values()].map((entry2) => ({ ...entry2, host: "pi" })));
47314
- entries.push({
47315
- source: accountSource,
47316
- setting: "killswitch_account_floors",
47317
- value: accounts
47318
- });
47319
- }
47320
- return { entries, unmapped: [] };
47321
- }
47322
- // src/settings-move-sources.ts
47323
- import { lstat as lstat22 } from "node:fs/promises";
47324
-
47325
- // src/settings-move-source.ts
47326
- var SETTINGS_MOVE_PATHS = {
47327
- routing_mode: ["routing", "mode"],
47328
- max_same_account_wait: ["routing", "maxSameAccountWait"],
47329
- fallback_on: ["fallbackOn"],
47330
- refresh_enabled: ["refresh", "enabled"],
47331
- refresh_interval_minutes: ["refresh", "intervalMinutes"],
47332
- refresh_refresh_before_expiry_minutes: [
47333
- "refresh",
47334
- "refreshBeforeExpiryMinutes"
47335
- ],
47336
- quota_enabled: ["quota", "enabled"],
47337
- quota_check_interval_minutes: ["quota", "checkIntervalMinutes"],
47338
- quota_refresh_every_n_requests: ["quota", "refreshEveryNRequests"],
47339
- quota_minimum_remaining_five_hour: ["quota", "minimumRemaining", "five_hour"],
47340
- quota_minimum_remaining_seven_day: ["quota", "minimumRemaining", "seven_day"],
47341
- quota_minimum_remaining_scoped: ["quota", "minimumRemaining", "scoped"],
47342
- quota_fail_closed_on_unknown_quota: ["quota", "failClosedOnUnknownQuota"],
47343
- quota_show_toasts: ["quota", "showToasts"],
47344
- quota_header_feed_enabled: ["quotaHeaderFeed", "enabled"],
47345
- killswitch_enabled: ["killswitch", "enabled"],
47346
- killswitch_default_five_hour: ["killswitch", "main", "five_hour"],
47347
- killswitch_default_seven_day: ["killswitch", "main", "seven_day"],
47348
- killswitch_default_scoped: ["killswitch", "main", "scoped"],
47349
- killswitch_account_floors: ["killswitch", "accounts"],
47350
- claude_cache_enabled: ["claudeCache", "enabled"],
47351
- claude_cache_mode: ["claudeCache", "mode"],
47352
- cache_keep_enabled: ["cacheKeep", "enabled"],
47353
- cache_keep_always: ["cacheKeep", "always"],
47354
- cache_keep_window: ["cacheKeep", "startHour", "endHour"],
47355
- cache_keep_subagents: ["cacheKeep", "subagents"],
47356
- dump_enabled: ["dump", "enabled"],
47357
- prime_enabled: ["prime", "enabled"],
47358
- claude_fast_enabled: ["claudeFast", "enabled"],
47359
- cost_zeroing_enabled: ["costZeroing", "enabled"],
47360
- log_level: ["logging", "level"],
47361
- thinking_binding_prefix_mismatch_behavior: [
47362
- "thinkingBinding",
47363
- "prefixMismatchBehavior"
47364
- ],
47365
- turn_end_note_tools: ["turnEndNote", "tools"]
47366
- };
47367
- var logged2 = new Set;
47368
- var fields2 = ["five_hour", "seven_day", "scoped"];
47369
- var aliases = { five_hour: "5h", seven_day: "1w", scoped: "scoped" };
47370
- var invalidSection = Symbol("invalid legacy section");
47371
- function record15(value) {
47372
- return value !== null && typeof value === "object" && !Array.isArray(value);
47373
- }
47374
- function floor3(value) {
47375
- return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 100;
47376
- }
47377
- function held2(root, path2) {
47378
- let value = root;
47379
- for (const key of path2) {
47380
- if (!record15(value))
47381
- return { value: invalidSection };
47382
- if (!Object.hasOwn(value, key))
47383
- return;
47384
- value = value[key];
47385
- }
47386
- return { value };
47387
- }
47388
- function readSettingsMoveSource(text6, options) {
47389
- const stored = JSON.parse(text6);
47390
- const values = {};
47391
- const restrictive = mostRestrictiveSettingsProtection();
47392
- function report2(path2, reason) {
47393
- const message = `Settings move from ${options.path}: ${path2} ${reason}.`;
47394
- if (logged2.has(message))
47395
- return;
47396
- logged2.add(message);
47397
- if (options.log)
47398
- options.log.warn(message);
47399
- else
47400
- logger2.warn("settings", message);
47401
- }
47402
- if (!record15(stored)) {
47403
- report2("<root>", "is not a settings map; omitted");
47404
- return {};
47405
- }
47406
- function invalid4(key, path2) {
47407
- if (Object.hasOwn(restrictive, key)) {
47408
- const replacement = restrictive[key];
47409
- values[key] = replacement;
47410
- report2(path2, `is invalid; replaced with protection value ${JSON.stringify(replacement)}`);
47411
- } else
47412
- report2(path2, "is invalid; omitted");
47413
- }
47414
- for (const [key, path2] of Object.entries(SETTINGS_MOVE_PATHS)) {
47415
- if (key.startsWith("killswitch_default_") || key.startsWith("quota_minimum_remaining_") || key === "killswitch_account_floors" || key === "cache_keep_window")
47416
- continue;
47417
- const entry2 = held2(stored, path2);
47418
- if (!entry2)
47419
- continue;
47420
- const value = entry2.value;
47421
- let valid = true;
47422
- try {
47423
- if (key === "fallback_on") {
47424
- valid = Array.isArray(value) && value.every((status) => Number.isInteger(status));
47425
- } else if (key === "max_same_account_wait" && (value === 0 || value === 15)) {} else if (key === "log_level" && value === "default") {} else {
47426
- validateNativeMigrationSettings({
47427
- [path2[0]]: { [path2[1]]: value }
47428
- });
47429
- }
47430
- } catch {
47431
- valid = false;
47432
- }
47433
- if (!valid) {
47434
- invalid4(key, path2.join("."));
47435
- continue;
47436
- }
47437
- values[key] = key === "max_same_account_wait" ? value === "0" || value === 0 ? "off" : value === "15" || value === 15 ? "15m" : "cache" : [
47438
- "claude_cache_enabled",
47439
- "quota_enabled",
47440
- "quota_fail_closed_on_unknown_quota"
47441
- ].includes(key) ? value ? "on" : "off" : value;
47442
- }
47443
- function thresholds(value, path2, defaults3, account = false) {
47444
- if (!record15(value)) {
47445
- if (account)
47446
- return;
47447
- report2(path2, "is invalid; replaced with declared protection floors");
47448
- return { ...defaults3 };
47449
- }
47450
- if (fields2.some((key) => key !== aliases[key] && Object.hasOwn(value, key) && Object.hasOwn(value, aliases[key])))
47451
- report2(path2, "holds threshold aliases beside canonical keys; canonical keys win");
47452
- const result = { ...defaults3 };
47453
- let bad = false;
47454
- for (const key of Object.keys(value)) {
47455
- if (!["five_hour", "seven_day", "scoped", "5h", "1w"].includes(key)) {
47456
- if (!account)
47457
- report2(`${path2}.${key}`, "is unknown; omitted");
47458
- bad = true;
47459
- }
47460
- }
47461
- for (const key of fields2) {
47462
- const source2 = Object.hasOwn(value, key) ? key : aliases[key];
47463
- if (!Object.hasOwn(value, source2))
47464
- continue;
47465
- const amount = value[source2];
47466
- if (floor3(amount))
47467
- result[key] = amount;
47468
- else {
47469
- bad = true;
47470
- if (!account)
47471
- report2(`${path2}.${source2}`, `is invalid; replaced with protection value ${defaults3[key]}`);
47472
- }
47473
- }
47474
- return account && bad ? undefined : result;
47475
- }
47476
- for (const [path2, prefix] of [
47477
- [["killswitch", "main"], "killswitch_default"],
47478
- [["quota", "minimumRemaining"], "quota_minimum_remaining"]
47479
- ]) {
47480
- const entry2 = held2(stored, path2);
47481
- if (!entry2)
47482
- continue;
47483
- const defaults3 = Object.fromEntries(fields2.map((key) => [
47484
- key,
47485
- settingsDefinition.settings[`${prefix}_${key}`].default
47486
- ]));
47487
- const result = thresholds(entry2.value, path2.join("."), defaults3);
47488
- for (const key of fields2)
47489
- values[`${prefix}_${key}`] = result[key];
47490
- }
47491
- const accounts = held2(stored, ["killswitch", "accounts"]);
47492
- if (accounts) {
47493
- const defaults3 = {
47494
- five_hour: settingsDefinition.settings.killswitch_default_five_hour.default,
47495
- seven_day: settingsDefinition.settings.killswitch_default_seven_day.default,
47496
- scoped: settingsDefinition.settings.killswitch_default_scoped.default
47497
- };
47498
- values.killswitch_account_floors = [];
47499
- if (!record15(accounts.value))
47500
- invalid4("killswitch_account_floors", "killswitch.accounts");
47501
- else {
47502
- const replacement = Object.fromEntries(fields2.map((key) => [
47503
- key,
47504
- Math.max(defaults3[key], values[`killswitch_default_${key}`] ?? defaults3[key])
47505
- ]));
47506
- values.killswitch_account_floors = Object.entries(accounts.value).map(([account, value]) => {
47507
- const path2 = `killswitch.accounts.${account}`;
47508
- const result = thresholds(value, path2, defaults3, true);
47509
- if (!result)
47510
- report2(path2, `is invalid; replaced with protection floors ${JSON.stringify(replacement)}`);
47511
- return { account, host: options.host, ...result ?? replacement };
47512
- });
48230
+ for (const [source2, legacy] of sources2.entries()) {
48231
+ if (!legacy.present)
48232
+ continue;
48233
+ const values = legacy.value;
48234
+ for (const [setting, value] of Object.entries(values)) {
48235
+ if (setting === "killswitch_account_floors") {
48236
+ accountSource ??= source2;
48237
+ floors[legacy.host] = values.killswitch_account_floors ?? [];
48238
+ } else
48239
+ entries.push({ source: source2, setting, value });
47513
48240
  }
47514
48241
  }
47515
- const start = held2(stored, ["cacheKeep", "startHour"]);
47516
- const end = held2(stored, ["cacheKeep", "endHour"]);
47517
- if (start || end) {
47518
- const validHour = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
47519
- if (validHour(start?.value) && validHour(end?.value))
47520
- values.cache_keep_window = [
47521
- { start_hour: start.value, end_hour: end.value }
47522
- ];
47523
- else
47524
- invalid4("cache_keep_window", "cacheKeep.startHour/endHour");
48242
+ if (accountSource !== undefined) {
48243
+ const pi = new Map(floors.pi.map((entry2) => [entry2.account, entry2]));
48244
+ const accounts = floors.opencode.map((entry2) => {
48245
+ const peer = pi.get(entry2.account);
48246
+ if (entry2.account.startsWith("vault:") && peer && entry2.five_hour === peer.five_hour && entry2.seven_day === peer.seven_day && entry2.scoped === peer.scoped) {
48247
+ pi.delete(entry2.account);
48248
+ return { ...entry2, host: "both" };
48249
+ }
48250
+ return { ...entry2, host: "opencode" };
48251
+ });
48252
+ accounts.push(...[...pi.values()].map((entry2) => ({ ...entry2, host: "pi" })));
48253
+ entries.push({
48254
+ source: accountSource,
48255
+ setting: "killswitch_account_floors",
48256
+ value: accounts
48257
+ });
47525
48258
  }
47526
- return values;
48259
+ return { entries, unmapped: [] };
47527
48260
  }
47528
- function createSettingsMoveSource(options) {
48261
+ // src/settings-move-run.ts
48262
+ import { readFile as readFile20 } from "node:fs/promises";
48263
+
48264
+ // src/settings-host-import.ts
48265
+ var ranks = {
48266
+ quota_fail_closed_on_unknown_quota: { off: 0, default: 1, on: 2 },
48267
+ max_same_account_wait: { cache: 0, "15m": 1, off: 2 }
48268
+ };
48269
+ function stricter(key, legacy, file) {
48270
+ if (typeof legacy === "boolean")
48271
+ return legacy && file === false;
48272
+ if (typeof legacy === "number")
48273
+ return typeof file === "number" && legacy > file;
48274
+ const rank = ranks[key];
48275
+ if (!rank || typeof legacy !== "string" || typeof file !== "string")
48276
+ return false;
48277
+ return (rank[legacy] ?? 0) > (rank[file] ?? 0);
48278
+ }
48279
+ function planSettingsHostImport(input) {
48280
+ const { host: host2, legacy, resolved } = input;
48281
+ const keys5 = [];
48282
+ const edits = [];
48283
+ for (const key of SETTINGS_PROTECTION_KEYS) {
48284
+ if (key === "killswitch_account_floors")
48285
+ continue;
48286
+ if (input.fileLevels[key]?.includes(host2))
48287
+ continue;
48288
+ if (!stricter(key, legacy[key], resolved[key]))
48289
+ continue;
48290
+ keys5.push(key);
48291
+ edits.push({ setting: key, level: host2, value: legacy[key] });
48292
+ }
48293
+ const covered = new Set(resolved.killswitch_account_floors.filter((entry2) => entry2.host === host2 || entry2.host === "both").map((entry2) => entry2.account));
48294
+ const missing3 = legacy.killswitch_account_floors.filter((entry2) => (entry2.host === host2 || entry2.host === "both") && !covered.has(entry2.account) && (entry2.five_hour > resolved.killswitch_default_five_hour || entry2.seven_day > resolved.killswitch_default_seven_day || entry2.scoped > resolved.killswitch_default_scoped));
48295
+ if (missing3.length) {
48296
+ keys5.push("killswitch_account_floors");
48297
+ edits.push({
48298
+ setting: "killswitch_account_floors",
48299
+ value: [
48300
+ ...resolved.killswitch_account_floors,
48301
+ ...missing3.map((entry2) => ({ ...entry2, host: host2 }))
48302
+ ]
48303
+ });
48304
+ }
48305
+ return { keys: keys5, edits };
48306
+ }
48307
+
48308
+ // src/settings-move-sources.ts
48309
+ import { lstat as lstat22, readFile as readFile19 } from "node:fs/promises";
48310
+
48311
+ // src/settings-protection-legacy.ts
48312
+ function legacySettingsProtection(settings, host2, mode = "local") {
48313
+ const storage = {
48314
+ version: 1,
48315
+ accounts: [],
48316
+ ...nativeAccountSettings(settings)
48317
+ };
48318
+ const main = getKillswitchThresholdsForAccount(storage);
48319
+ const minimum = getQuotaMinimumRemainingThresholds(storage);
47529
48320
  return {
47530
- host: options.host,
47531
- path: options.path,
47532
- locks: options.locks,
47533
- read: (text6) => readSettingsMoveSource(text6, options)
48321
+ killswitch_enabled: isKillswitchEnabled(storage),
48322
+ killswitch_default_five_hour: main.five_hour,
48323
+ killswitch_default_seven_day: main.seven_day,
48324
+ killswitch_default_scoped: main.scoped,
48325
+ killswitch_account_floors: Object.keys(storage.killswitch?.accounts ?? {}).map((account) => ({
48326
+ account,
48327
+ host: mode === "claustrum" ? "both" : host2,
48328
+ ...getKillswitchThresholdsForAccount(storage, account)
48329
+ })),
48330
+ quota_minimum_remaining_five_hour: minimum.five_hour,
48331
+ quota_minimum_remaining_seven_day: minimum.seven_day,
48332
+ quota_minimum_remaining_scoped: normalizeKillswitchThresholds(storage.quota?.minimumRemaining).scoped,
48333
+ quota_fail_closed_on_unknown_quota: toThreeWay(storage.quota?.failClosedOnUnknownQuota),
48334
+ max_same_account_wait: {
48335
+ "0": "off",
48336
+ "15": "15m",
48337
+ max: "cache"
48338
+ }[getMaxSameAccountWait(storage)]
47534
48339
  };
47535
48340
  }
48341
+ async function readLegacySettingsProtection(options) {
48342
+ try {
48343
+ const mode = await (options.readMode ?? readNativeEnrollmentMode)(options.host, options.env ?? process.env);
48344
+ if (mode === "claustrum")
48345
+ await options.initializeVaultSettings();
48346
+ const store = mode === "claustrum" ? options.vaultStore : options.localStore;
48347
+ const read = await store.readSettings();
48348
+ if (read.status !== "ready")
48349
+ return;
48350
+ return legacySettingsProtection(read.settings, options.host, mode);
48351
+ } catch {
48352
+ return;
48353
+ }
48354
+ }
47536
48355
 
47537
48356
  // src/settings-move-sources.ts
47538
48357
  var loggedSkips = new Set;
48358
+ async function peerStoreAbsent(host2, store, options) {
48359
+ try {
48360
+ const pool = await resolveNativePoolPaths(store.account, store.state, await peerLayout(host2, options));
48361
+ for (const config of [pool.config, nativeVaultPaths(pool).config]) {
48362
+ try {
48363
+ await lstat22(config);
48364
+ return false;
48365
+ } catch (error) {
48366
+ if (error.code !== "ENOENT")
48367
+ return false;
48368
+ }
48369
+ }
48370
+ return true;
48371
+ } catch {
48372
+ return false;
48373
+ }
48374
+ }
47539
48375
  async function peerLayout(host2, options) {
47540
48376
  if (host2 === "pi")
47541
48377
  return LEGACY_STATE_LAYOUT;
@@ -47561,15 +48397,60 @@ async function peerLayout(host2, options) {
47561
48397
  return LEGACY_STATE_LAYOUT;
47562
48398
  throw new Error("The peer state layout transition is unfinished");
47563
48399
  }
47564
- async function prepareSettingsMoveSources(options) {
47565
- const paths2 = options.paths ?? await resolveSettingsPaths(options.host, options);
48400
+ async function readPeerLegacySettingsProtection(options) {
48401
+ const paths2 = await resolveSettingsPaths(options.host, options);
47566
48402
  if (paths2.separate)
47567
- return { status: "separate", sources: [] };
48403
+ return;
48404
+ const store = paths2.defaults[options.host];
48405
+ const mode = await (options.readMode ?? readNativeEnrollmentMode)(options.host, enrollmentEnv(options));
48406
+ const pool = await resolveNativePoolPaths(store.account, store.state, await peerLayout(options.host, options));
48407
+ const selected = mode === "claustrum" ? nativeVaultPaths(pool) : pool;
48408
+ let text6;
48409
+ try {
48410
+ text6 = await readFile19(selected.config, "utf8");
48411
+ } catch (error) {
48412
+ if (error.code === "ENOENT" && mode === "local")
48413
+ return;
48414
+ throw error;
48415
+ }
48416
+ const stored = JSON.parse(text6);
48417
+ if (!stored || typeof stored !== "object" || Array.isArray(stored))
48418
+ throw new Error("The legacy settings store is not a settings map");
48419
+ return legacySettingsProtection(stored, options.host, mode);
48420
+ }
48421
+ async function readOwnLegacySettingsProtection(options) {
48422
+ const paths2 = options.paths ?? await resolveSettingsPaths(options.host, options);
48423
+ const mode = await (options.readMode ?? readNativeEnrollmentMode)(options.host, enrollmentEnv(options));
48424
+ const pool = options.ownPoolPaths ?? await resolveNativePoolPaths(paths2.own.account, paths2.own.state);
48425
+ const read = async (config) => {
48426
+ try {
48427
+ return await readFile19(config, "utf8");
48428
+ } catch (error) {
48429
+ if (error.code === "ENOENT")
48430
+ return;
48431
+ throw error;
48432
+ }
48433
+ };
48434
+ const text6 = (mode === "claustrum" ? await read(nativeVaultPaths(pool).config) : undefined) ?? await read(pool.config);
48435
+ if (text6 === undefined)
48436
+ return;
48437
+ const stored = JSON.parse(text6);
48438
+ if (!stored || typeof stored !== "object" || Array.isArray(stored))
48439
+ throw new Error("The legacy settings store is not a settings map");
48440
+ return legacySettingsProtection(stored, options.host, mode);
48441
+ }
48442
+ function enrollmentEnv(options) {
47568
48443
  const context = resolvePathOptions(options);
47569
- const env = {
48444
+ return {
47570
48445
  ...context.env,
47571
48446
  XDG_STATE_HOME: context.env.XDG_STATE_HOME || context.paths.join(context.home, ".local", "state")
47572
48447
  };
48448
+ }
48449
+ async function prepareSettingsMoveSources(options) {
48450
+ const paths2 = options.paths ?? await resolveSettingsPaths(options.host, options);
48451
+ if (paths2.separate)
48452
+ return { status: "separate", sources: [] };
48453
+ const env = enrollmentEnv(options);
47573
48454
  const warn = (message) => options.log ? options.log.warn(message) : logger2.warn("settings", message);
47574
48455
  const skip = (host2, path2, reason) => {
47575
48456
  const message = `Settings move skipped ${host2} source ${path2}: ${reason}.`;
@@ -47592,7 +48473,7 @@ async function prepareSettingsMoveSources(options) {
47592
48473
  cause
47593
48474
  };
47594
48475
  }
47595
- if (ownMode === "claustrum") {
48476
+ if (ownMode === "claustrum" && !options.inspectOnly) {
47596
48477
  try {
47597
48478
  await options.initializeVaultSettings();
47598
48479
  } catch (cause) {
@@ -47606,6 +48487,7 @@ async function prepareSettingsMoveSources(options) {
47606
48487
  }
47607
48488
  }
47608
48489
  const sources2 = [];
48490
+ const peerUnavailable = (host2, reason, cause) => options.inspectOnly ? undefined : { status: "unavailable", sources: [], host: host2, reason, cause };
47609
48491
  for (const host2 of ["opencode", "pi"]) {
47610
48492
  const own = host2 === options.host;
47611
48493
  if (!own && paths2.sourceRule === "own")
@@ -47614,7 +48496,12 @@ async function prepareSettingsMoveSources(options) {
47614
48496
  let mode;
47615
48497
  try {
47616
48498
  mode = own ? ownMode : await readMode(host2, env);
47617
- } catch {
48499
+ } catch (cause) {
48500
+ if (!await peerStoreAbsent(host2, store, options)) {
48501
+ const refused2 = peerUnavailable(host2, "custody-unreadable", cause);
48502
+ if (refused2)
48503
+ return refused2;
48504
+ }
47618
48505
  skip(host2, store.account, "custody mode is unreadable");
47619
48506
  continue;
47620
48507
  }
@@ -47626,8 +48513,14 @@ async function prepareSettingsMoveSources(options) {
47626
48513
  } catch (error) {
47627
48514
  if (error.code === "ENOENT") {
47628
48515
  skip(host2, selected.config, mode === "claustrum" ? "vault settings have not been seeded" : "file is missing");
47629
- if (!own && mode === "claustrum")
48516
+ if (!own && mode === "claustrum") {
48517
+ if (await peerStoreAbsent(host2, store, options))
48518
+ continue;
48519
+ const refused2 = peerUnavailable(host2, "vault-unseeded", error);
48520
+ if (refused2)
48521
+ return refused2;
47630
48522
  continue;
48523
+ }
47631
48524
  }
47632
48525
  }
47633
48526
  sources2.push(createSettingsMoveSource({
@@ -47645,6 +48538,9 @@ async function prepareSettingsMoveSources(options) {
47645
48538
  reason: "paths-unreadable",
47646
48539
  cause
47647
48540
  };
48541
+ const refused2 = peerUnavailable(host2, "paths-unreadable", cause);
48542
+ if (refused2)
48543
+ return refused2;
47648
48544
  skip(host2, store.account, "store paths or state layout are unreadable");
47649
48545
  }
47650
48546
  }
@@ -47652,10 +48548,10 @@ async function prepareSettingsMoveSources(options) {
47652
48548
  }
47653
48549
 
47654
48550
  // src/settings-move-run.ts
47655
- var logged3 = new Set;
47656
48551
  async function runSettingsMoveAtStartup(options) {
47657
48552
  const paths2 = options.paths ?? await resolveSettingsPaths(options.host, options);
47658
48553
  const authority = { ...options, ...options.authority };
48554
+ const logged3 = new Set;
47659
48555
  const warn = (message) => {
47660
48556
  const key = `${paths2.target}\x00${message}`;
47661
48557
  if (logged3.has(key))
@@ -47666,18 +48562,91 @@ async function runSettingsMoveAtStartup(options) {
47666
48562
  else
47667
48563
  logger2.warn("settings", message);
47668
48564
  };
47669
- const result = (mode, outcome2, move2) => ({
48565
+ const result = (mode2, outcome2, move2) => ({
47670
48566
  paths: paths2,
47671
- mode,
47672
- mayOpenService: mode !== "separate",
48567
+ mode: mode2,
48568
+ mayOpenService: mode2 !== "separate" && outcome2 !== "import-refused",
47673
48569
  outcome: outcome2,
47674
48570
  ...move2 ? { move: move2 } : {}
47675
48571
  });
48572
+ const startOnFile = async (outcome2, move2) => {
48573
+ const marked = await hasSettingsMoveMarker(paths2.target, authority);
48574
+ const service = await openSettingsService({ file: paths2.target });
48575
+ if (!service)
48576
+ throw new Error("Settings service did not open");
48577
+ try {
48578
+ const generation = service.snapshot();
48579
+ if (!marked && generation.status === "ready") {
48580
+ try {
48581
+ await writeSettingsMoveMarker(paths2.target, authority);
48582
+ } catch {
48583
+ warn(`Could not write settings move marker ${paths2.target}.moved.`);
48584
+ }
48585
+ }
48586
+ const refused2 = await importOwnStore(service, generation);
48587
+ if (refused2)
48588
+ return refused2;
48589
+ if (generation.status !== "missing") {
48590
+ const prepared2 = await prepareSettingsMoveSources({
48591
+ ...options,
48592
+ paths: marked ? { ...paths2, sourceRule: "own" } : paths2,
48593
+ inspectOnly: true,
48594
+ log: { warn: () => {} }
48595
+ });
48596
+ for (const source2 of prepared2.sources) {
48597
+ try {
48598
+ const text6 = await readFile20(source2.path, "utf8");
48599
+ if (!holdsMovedSettings(JSON.parse(text6)))
48600
+ continue;
48601
+ const host2 = source2.host;
48602
+ const values = readSettingsMoveSource(text6, {
48603
+ host: host2,
48604
+ path: source2.path,
48605
+ quiet: true
48606
+ });
48607
+ const differing = differingLegacySettings(values, service.resolve(host2), host2);
48608
+ if (!marked || differing.length)
48609
+ warn(settingsNotImportedText(source2.path, paths2.target, differing));
48610
+ } catch {}
48611
+ }
48612
+ }
48613
+ } finally {
48614
+ await service.dispose();
48615
+ }
48616
+ return result("user-file", outcome2 ?? (marked ? "marker-present" : "done-already"), move2);
48617
+ };
48618
+ const importOwnStore = async (service, generation) => {
48619
+ const host2 = options.host;
48620
+ if (generation.status !== "ready" || !generation.protection[host2].usable)
48621
+ return;
48622
+ if (await hasSettingsImportRecord(paths2.target, host2, authority))
48623
+ return;
48624
+ let legacy;
48625
+ try {
48626
+ legacy = await readOwnLegacySettingsProtection({ ...options, paths: paths2 });
48627
+ } catch {
48628
+ return;
48629
+ }
48630
+ const resolved = service.resolve(host2);
48631
+ const plan2 = legacy ? planSettingsHostImport({
48632
+ host: host2,
48633
+ legacy,
48634
+ resolved: Object.fromEntries(SETTINGS_PROTECTION_KEYS.map((key) => [key, resolved[key]])),
48635
+ fileLevels: generation.fileLevels
48636
+ }) : { keys: [], edits: [] };
48637
+ if (plan2.keys.length) {
48638
+ warn(`Settings file ${paths2.target} is not used by ${host2}: its legacy settings protect more for ${plan2.keys.join(", ")}. ${host2} keeps its legacy settings; set these for ${host2} in the settings file to start using it.`);
48639
+ return result("legacy", "import-refused");
48640
+ }
48641
+ try {
48642
+ await writeSettingsImportRecord(paths2.target, host2, authority);
48643
+ } catch {}
48644
+ return;
48645
+ };
47676
48646
  if (paths2.separate)
47677
48647
  return result("separate", "separate-install");
47678
- if (await resolveSettingsMode(paths2, authority) === "user-file") {
47679
- return result("user-file", await hasSettingsMoveMarker(paths2.target, authority) ? "marker-present" : "done-already");
47680
- }
48648
+ if (await resolveSettingsMode(paths2, authority) === "user-file")
48649
+ return startOnFile(undefined);
47681
48650
  const stores = [paths2.own.account];
47682
48651
  if (paths2.sourceRule === "default")
47683
48652
  stores.push(paths2.defaults.opencode.account, paths2.defaults.pi.account);
@@ -47687,14 +48656,46 @@ async function runSettingsMoveAtStartup(options) {
47687
48656
  const prepared = await (options.dependencies?.prepareSources ?? prepareSettingsMoveSources)({ ...options, paths: paths2 });
47688
48657
  if (prepared.status !== "ready") {
47689
48658
  if (prepared.status === "unavailable")
47690
- warn(`Settings move unavailable for ${options.host}: ${prepared.reason}.`);
48659
+ warn(`Settings move unavailable for ${prepared.host}: ${prepared.reason}; keeping legacy settings until the next start.`);
47691
48660
  return result("legacy", "source-unavailable");
47692
48661
  }
48662
+ let holderFiles;
48663
+ try {
48664
+ holderFiles = await settingsMoveHolderFiles({
48665
+ ...options,
48666
+ ...options.fence,
48667
+ stores
48668
+ });
48669
+ const context = resolvePathOptions(options);
48670
+ for (const file of holderFiles) {
48671
+ const folder = context.paths.dirname(file);
48672
+ if (options.authority?.fs?.mkdir)
48673
+ await options.authority.fs.mkdir(folder);
48674
+ else
48675
+ await ensureHolderDirectory(folder, {
48676
+ ...options.authority?.ownership,
48677
+ platform: context.platform
48678
+ });
48679
+ }
48680
+ } catch {
48681
+ return result("legacy", "fence-closed");
48682
+ }
48683
+ const [first, ...rest] = prepared.sources;
48684
+ const sources2 = first ? [
48685
+ {
48686
+ ...first,
48687
+ locks: [
48688
+ ...holderFiles.map((path2) => ({ path: path2, name: HOLDER_LOCK_NAME })),
48689
+ ...first.locks
48690
+ ]
48691
+ },
48692
+ ...rest
48693
+ ] : [];
47693
48694
  const move = await (options.dependencies?.move ?? moveSettingsOnce)({
47694
48695
  definition: settingsDefinition,
47695
48696
  target: paths2.target,
47696
48697
  separateInstall: false,
47697
- sources: prepared.sources,
48698
+ sources: sources2,
47698
48699
  map: mapSettingsMoveSources,
47699
48700
  fence: async () => !await hasSettingsMoveMarker(paths2.target, authority) && await fence(),
47700
48701
  log: { info: () => {}, warn }
@@ -47705,55 +48706,99 @@ async function runSettingsMoveAtStartup(options) {
47705
48706
  } catch {
47706
48707
  warn(`Could not write settings move marker ${paths2.target}.moved.`);
47707
48708
  }
48709
+ for (const host2 of new Set(sources2.map((source2) => source2.host))) {
48710
+ try {
48711
+ await writeSettingsImportRecord(paths2.target, host2, authority);
48712
+ } catch {}
48713
+ }
47708
48714
  return result("user-file", move.outcome, move);
47709
48715
  }
47710
48716
  if (move.outcome === "failed" || move.outcome === "busy")
47711
48717
  warn(`Settings move ${move.outcome} for ${paths2.target}; keeping legacy settings until the next start.`);
47712
- return result(await resolveSettingsMode(paths2, authority), move.outcome, move);
47713
- }
47714
- // src/settings-protection-legacy.ts
47715
- function legacySettingsProtection(settings, host2, mode = "local") {
47716
- const storage = {
47717
- version: 1,
47718
- accounts: [],
47719
- ...nativeAccountSettings(settings)
48718
+ const mode = await resolveSettingsMode(paths2, authority);
48719
+ if (mode === "user-file")
48720
+ return startOnFile(move.outcome, move);
48721
+ return result(mode, move.outcome, move);
48722
+ }
48723
+ // src/settings-start.ts
48724
+ var warned3 = false;
48725
+ function __resetSettingsStartWarningForTest() {
48726
+ warned3 = false;
48727
+ }
48728
+ async function startSettings(options) {
48729
+ const move = options.start?.move ?? runSettingsMoveAtStartup;
48730
+ const open16 = options.start?.open ?? openSettingsService;
48731
+ const serviceOptions = (file2) => ({
48732
+ file: file2,
48733
+ host: options.host,
48734
+ protection: options.protection,
48735
+ lockTimeoutMs: options.lockTimeoutMs
48736
+ });
48737
+ let file = "";
48738
+ let moved = false;
48739
+ try {
48740
+ const started = await move(options);
48741
+ file = started.paths.target;
48742
+ moved = started.mode === "user-file";
48743
+ if (!started.mayOpenService)
48744
+ return { mode: started.mode, file };
48745
+ const service = await open16(serviceOptions(file));
48746
+ if (!service)
48747
+ return { mode: started.mode, file };
48748
+ return { mode: started.mode, file, service };
48749
+ } catch {
48750
+ if (!warned3) {
48751
+ warned3 = true;
48752
+ logger2.warn("settings", "Settings startup failed; protection settings use their last applied values until the settings file can be opened.");
48753
+ }
48754
+ }
48755
+ const reopen = async () => {
48756
+ if (!file)
48757
+ return;
48758
+ try {
48759
+ return await open16(serviceOptions(file));
48760
+ } catch {
48761
+ return;
48762
+ }
47720
48763
  };
47721
- const main = getKillswitchThresholdsForAccount(storage);
47722
- const minimum = getQuotaMinimumRemainingThresholds(storage);
47723
- return {
47724
- killswitch_enabled: isKillswitchEnabled(storage),
47725
- killswitch_default_five_hour: main.five_hour,
47726
- killswitch_default_seven_day: main.seven_day,
47727
- killswitch_default_scoped: main.scoped,
47728
- killswitch_account_floors: Object.keys(storage.killswitch?.accounts ?? {}).map((account) => ({
47729
- account,
47730
- host: mode === "claustrum" ? "both" : host2,
47731
- ...getKillswitchThresholdsForAccount(storage, account)
47732
- })),
47733
- quota_minimum_remaining_five_hour: minimum.five_hour,
47734
- quota_minimum_remaining_seven_day: minimum.seven_day,
47735
- quota_minimum_remaining_scoped: normalizeKillswitchThresholds(storage.quota?.minimumRemaining).scoped,
47736
- quota_fail_closed_on_unknown_quota: toThreeWay(storage.quota?.failClosedOnUnknownQuota),
47737
- max_same_account_wait: {
47738
- "0": "off",
47739
- "15": "15m",
47740
- max: "cache"
47741
- }[getMaxSameAccountWait(storage)]
48764
+ const probe2 = async () => {
48765
+ const paths2 = options.paths ?? await resolveSettingsPaths(options.host, options);
48766
+ file = paths2.target;
48767
+ return resolveSettingsMode(paths2, { ...options, ...options.authority });
47742
48768
  };
47743
- }
47744
- async function readLegacySettingsProtection(options) {
47745
- try {
47746
- const mode = await (options.readMode ?? readNativeEnrollmentMode)(options.host, options.env ?? process.env);
47747
- if (mode === "claustrum")
47748
- await options.initializeVaultSettings();
47749
- const store = mode === "claustrum" ? options.vaultStore : options.localStore;
47750
- const read = await store.readSettings();
47751
- if (read.status !== "ready")
47752
- return;
47753
- return legacySettingsProtection(read.settings, options.host, mode);
47754
- } catch {
47755
- return;
48769
+ let mode = "user-file";
48770
+ let unknown = false;
48771
+ if (!moved) {
48772
+ try {
48773
+ mode = await probe2();
48774
+ } catch {
48775
+ mode = "user-file";
48776
+ unknown = true;
48777
+ if (!file) {
48778
+ try {
48779
+ file = getSettingsFilePath(options);
48780
+ } catch {}
48781
+ }
48782
+ }
47756
48783
  }
48784
+ if (mode === "legacy")
48785
+ return { mode, file, reopen };
48786
+ if (mode !== "user-file")
48787
+ return { mode, file };
48788
+ const recovered = await recoverSettingsProtection(file, options.host, options.protection, file ? options.host : undefined);
48789
+ return {
48790
+ mode,
48791
+ file,
48792
+ fallback: {
48793
+ get file() {
48794
+ return file;
48795
+ },
48796
+ rung: recovered.rung,
48797
+ values: recovered.values,
48798
+ reopen,
48799
+ ...unknown ? { resolveAuthority: probe2 } : {}
48800
+ }
48801
+ };
47757
48802
  }
47758
48803
  // src/start.ts
47759
48804
  var CLAUDE_START_COMMAND_NAME = "claude-start";
@@ -47794,7 +48839,7 @@ import { basename as basename17, dirname as dirname27, join as join35 } from "no
47794
48839
 
47795
48840
  // src/state-layout-move.ts
47796
48841
  import { randomUUID as randomUUID27 } from "node:crypto";
47797
- import { lstat as lstat23, readdir as readdir10, readFile as readFile19, stat as stat16, unlink as unlink12 } from "node:fs/promises";
48842
+ import { lstat as lstat23, readdir as readdir10, readFile as readFile21, stat as stat16, unlink as unlink12 } from "node:fs/promises";
47798
48843
  import { basename as basename16, dirname as dirname26, join as join33, sep as sep2 } from "node:path";
47799
48844
  var ACCOUNT_FILE = "anthropic-auth.json";
47800
48845
  var ACCOUNT_STATE_FILE = "anthropic-auth-state.json";
@@ -48264,7 +49309,7 @@ async function rollbackPreparing(record16, dataset, ctx) {
48264
49309
  } else {
48265
49310
  let copy;
48266
49311
  try {
48267
- copy = await readFile19(file.to);
49312
+ copy = await readFile21(file.to);
48268
49313
  } catch {
48269
49314
  throw new StateLayoutRollbackRefused(file.to, `its copy, needed to undo the tombstone over ${file.from}, is missing`);
48270
49315
  }
@@ -48455,12 +49500,12 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
48455
49500
  for (const file of files) {
48456
49501
  if (file.sha256 === null)
48457
49502
  continue;
48458
- const bytes = await readFile19(file.from);
49503
+ const bytes = await readFile21(file.from);
48459
49504
  if (sha256Hex(bytes) !== file.sha256)
48460
49505
  throw new MoveRefused(`${file.from} changed while it was copied`);
48461
49506
  const stage = relocatingPath(file.to, attempt);
48462
49507
  await createOwnerOnlyFile(ctx.fs, stage, bytes);
48463
- const back = await readFile19(stage);
49508
+ const back = await readFile21(stage);
48464
49509
  if (!back.equals(bytes))
48465
49510
  throw new MoveRefused(`the copy of ${file.from} reads back differently`);
48466
49511
  await owned2(ctx, { kind: "rename", from: stage, to: file.to }, expectAbsent(file.to));
@@ -48572,7 +49617,7 @@ async function rollbackAfterFailure(preparing, dataset, ctx) {
48572
49617
 
48573
49618
  // src/state-layout-restore.ts
48574
49619
  import { randomUUID as randomUUID28 } from "node:crypto";
48575
- import { readFile as readFile20 } from "node:fs/promises";
49620
+ import { readFile as readFile22 } from "node:fs/promises";
48576
49621
  import { homedir as homedir8 } from "node:os";
48577
49622
  import { join as join34 } from "node:path";
48578
49623
  var DATA_ROLES = [
@@ -48916,12 +49961,12 @@ async function startRestore(record16, dataset, ctx, options) {
48916
49961
  }, ctx.fs);
48917
49962
  await stateLayoutStep(ctx, "restore:restoring-written");
48918
49963
  for (const file of files) {
48919
- const bytes = await readFile20(file.to);
49964
+ const bytes = await readFile22(file.to);
48920
49965
  if (sha256Hex(bytes) !== file.sha256)
48921
49966
  throw refused2(`${file.to} changed while it was being restored; run ${RESTORE_LEGACY_COMMAND} again.`, [file.to]);
48922
49967
  await ctx.stack.assertAll();
48923
49968
  await createOwnerOnlyFile(ctx.fs, file.staging, bytes);
48924
- const back = await readFile20(file.staging);
49969
+ const back = await readFile22(file.staging);
48925
49970
  if (!back.equals(bytes))
48926
49971
  throw refused2(`the restored copy of ${file.to} reads back differently; run ${RESTORE_LEGACY_COMMAND} again.`, [file.staging]);
48927
49972
  await stateLayoutStep(ctx, `restore:staged:${file.role}`);
@@ -49889,6 +50934,8 @@ export {
49889
50934
  writerStamp,
49890
50935
  writeSettingsProtectionCopy,
49891
50936
  writeSettingsMoveMarker,
50937
+ writeSettingsImportRecord,
50938
+ writeNativeSetupSettings,
49892
50939
  writeNativeHostAuth,
49893
50940
  writeDumpFile,
49894
50941
  withSessionCacheReportHandoff,
@@ -49927,6 +50974,7 @@ export {
49927
50974
  stateHomeTargetFor,
49928
50975
  stateHomeFilePaths,
49929
50976
  stateHomeDatasetFiles,
50977
+ startSettings,
49930
50978
  startRoutingWait,
49931
50979
  snapshotHasServableLocalOAuth,
49932
50980
  signRequestBody,
@@ -49934,8 +50982,10 @@ export {
49934
50982
  shouldEmit,
49935
50983
  setupUsage,
49936
50984
  setupEnrollment,
49937
- settingsProtectionForRecreation,
50985
+ settingsRecreationForWriter,
50986
+ settingsRecreationFloors,
49938
50987
  settingsMoveHolderFiles,
50988
+ settingsImportRecordPath,
49939
50989
  settingsFileSets,
49940
50990
  settingsDefinition,
49941
50991
  setRelocationMoveEnabledForTests,
@@ -50004,6 +51054,7 @@ export {
50004
51054
  refreshClaudeOAuthToken,
50005
51055
  refreshBackoffActive,
50006
51056
  redactPayload,
51057
+ recoverSettingsProtection,
50007
51058
  recordProcessStateLayout,
50008
51059
  recordPredatesBoot,
50009
51060
  readWindowsOwnerOnly,
@@ -50013,6 +51064,8 @@ export {
50013
51064
  readSettingsMoveSource,
50014
51065
  readSessionCachePolicy,
50015
51066
  readRelocationPointer,
51067
+ readPeerLegacySettingsProtection,
51068
+ readOwnLegacySettingsProtection,
50016
51069
  readNativeMigrationJournal,
50017
51070
  readNativeHostAuthKind,
50018
51071
  readNativeEnrollmentMode,
@@ -50053,6 +51106,9 @@ export {
50053
51106
  prepareSettingsMoveSources,
50054
51107
  prepareNativeMigration,
50055
51108
  prepareMessageThreadRequest,
51109
+ planSettingsRecreation,
51110
+ planSettingsMenuWrite,
51111
+ planSettingsFileRecreation,
50056
51112
  pinsEffortOnEveryRequest,
50057
51113
  peekRoutingAccount,
50058
51114
  parseSseFrame,
@@ -50071,6 +51127,7 @@ export {
50071
51127
  parseCache1hCommandAction,
50072
51128
  parseApplyRequest,
50073
51129
  parseAccountCommandAction,
51130
+ overlaySettingsProtection,
50074
51131
  orderClaudeCodeBody,
50075
51132
  openSettingsService,
50076
51133
  openNativePiAuthSlot,
@@ -50177,12 +51234,14 @@ export {
50177
51234
  hostRetryResponse,
50178
51235
  hostRetryHeaders,
50179
51236
  homeDefaultConfigDir,
51237
+ holderInstance,
50180
51238
  holderEntryLiveness,
50181
51239
  holderEntryIsLive,
50182
51240
  hashRefreshToken,
50183
51241
  hashBody,
50184
51242
  hasThinkingBindingControls,
50185
51243
  hasSettingsMoveMarker,
51244
+ hasSettingsImportRecord,
50186
51245
  hasReplayableThinkingBlocks,
50187
51246
  hasPrivateSettingsConfigHome,
50188
51247
  hasNoLocalCredential,
@@ -50385,6 +51444,7 @@ export {
50385
51444
  acquireNativeAccountRuntime,
50386
51445
  abortableFetch,
50387
51446
  __setLogTestSink,
51447
+ __resetSettingsStartWarningForTest,
50388
51448
  WORKER_SCRIPT,
50389
51449
  VAULT_HOST_STATUS,
50390
51450
  VAULT_HOST_CONNECT_REFUSAL,
@@ -50461,6 +51521,7 @@ export {
50461
51521
  NativeVaultQuotaPolicyError,
50462
51522
  NativeVaultNoAccountError,
50463
51523
  NativeTransientAccountError,
51524
+ NativeSetupSettingsWriteError,
50464
51525
  NativeRuntimeError,
50465
51526
  NativeQuotaObservations,
50466
51527
  NativePrivateFilesUnavailableError,