ohmyswitch 0.3.0 → 0.3.1

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.
Files changed (2) hide show
  1. package/oms.mjs +1512 -1082
  2. package/package.json +1 -1
package/oms.mjs CHANGED
@@ -15,7 +15,6 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
15
15
  import { constants as constants$1, zstdDecompress } from "node:zlib";
16
16
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
17
17
  import { EventEmitter, on } from "node:events";
18
- import { setGlobalProxyFromEnv } from "node:http";
19
18
  //#region \0rolldown/runtime.js
20
19
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
21
20
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
@@ -1888,17 +1887,18 @@ async function choicesOf(param, required, scope) {
1888
1887
  throw new CliError("precondition_failed", param.empty ?? `There is nothing to choose for "${param.summary}"`);
1889
1888
  }
1890
1889
  const optionOf = (choice, index) => ({
1891
- value: index,
1890
+ value: String(index),
1892
1891
  label: choice.label,
1893
1892
  hint: choice.disabled ?? choice.hint,
1894
1893
  disabled: Boolean(choice.disabled)
1895
1894
  });
1895
+ const requireAutocompleteMatch = (value) => value === void 0 ? "No matching option" : void 0;
1896
1896
  async function askOne(param, required, scope) {
1897
1897
  const choices = await choicesOf(param, required, scope);
1898
1898
  if (!choices) return unchanged;
1899
1899
  const initial = await param.initial?.(scope);
1900
- const initialIndex = choices.findIndex((choice) => choice.value === initial);
1901
- const skip = -1;
1900
+ const initialIndex = choices.findIndex((choice) => !choice.disabled && choice.value === initial);
1901
+ const skip = "skip";
1902
1902
  const options = choices.map(optionOf);
1903
1903
  if (!required && initialIndex < 0) options.push({
1904
1904
  value: skip,
@@ -1906,19 +1906,20 @@ async function askOne(param, required, scope) {
1906
1906
  hint: void 0,
1907
1907
  disabled: false
1908
1908
  });
1909
- const initialValue = initialIndex >= 0 ? initialIndex : void 0;
1910
- const index = await prompted(() => options.length > filterableFrom ? autocomplete({
1909
+ const initialValue = initialIndex >= 0 ? String(initialIndex) : void 0;
1910
+ const selected = await prompted(() => options.length > filterableFrom ? autocomplete({
1911
1911
  message: param.summary,
1912
1912
  options,
1913
1913
  initialValue,
1914
- placeholder: "Type to filter"
1914
+ placeholder: "Type to filter",
1915
+ validate: requireAutocompleteMatch
1915
1916
  }) : select({
1916
1917
  message: param.summary,
1917
1918
  options,
1918
1919
  initialValue
1919
1920
  }));
1920
- if (index === skip || index === initialIndex) return unchanged;
1921
- const choice = choices[index];
1921
+ if (selected === void 0 || selected === skip || !required && selected === initialValue) return unchanged;
1922
+ const choice = choices[Number(selected)];
1922
1923
  if (!choice.keys.length) return unchanged;
1923
1924
  return {
1924
1925
  value: choice.value,
@@ -1938,9 +1939,9 @@ async function askMany(param, required, scope) {
1938
1939
  /** Tick options in a list, filterable when long; returns them in list order, not the order they were ticked. */
1939
1940
  async function pickSeveral(message, choices, ticked, required) {
1940
1941
  const options = choices.map(optionOf);
1941
- const initialValues = choices.flatMap((choice, index) => ticked(choice) ? [index] : []);
1942
+ const initialValues = choices.flatMap((choice, index) => ticked(choice) ? [String(index)] : []);
1942
1943
  for (;;) {
1943
- const indexes = await prompted(() => options.length > filterableFrom ? autocompleteMultiselect({
1944
+ const selected = await prompted(() => options.length > filterableFrom ? autocompleteMultiselect({
1944
1945
  message,
1945
1946
  options,
1946
1947
  initialValues,
@@ -1952,11 +1953,11 @@ async function pickSeveral(message, choices, ticked, required) {
1952
1953
  initialValues,
1953
1954
  required: false
1954
1955
  }));
1955
- if (required && !indexes.length) {
1956
+ if (required && !selected.length) {
1956
1957
  log.warn("Select at least one (space toggles an option).");
1957
1958
  continue;
1958
1959
  }
1959
- return indexes.toSorted((a, b) => a - b).map((index) => choices[index]);
1960
+ return selected.map(Number).toSorted((a, b) => a - b).map((index) => choices[index]);
1960
1961
  }
1961
1962
  }
1962
1963
  /**
@@ -1991,7 +1992,7 @@ async function askSuggested(param, required, suggested) {
1991
1992
  }
1992
1993
  /** Pick one suggested value for a text parameter; undefined when the user chooses to type one instead. */
1993
1994
  async function askSuggestedOne(param, required, suggested) {
1994
- const [skip, other] = [-1, -2];
1995
+ const [skip, other] = ["skip", "other"];
1995
1996
  const options = suggested.choices.map(optionOf);
1996
1997
  if (suggested.open) options.push({
1997
1998
  value: other,
@@ -2005,17 +2006,18 @@ async function askSuggestedOne(param, required, suggested) {
2005
2006
  hint: void 0,
2006
2007
  disabled: false
2007
2008
  });
2008
- const index = await prompted(() => options.length > filterableFrom ? autocomplete({
2009
+ const selected = await prompted(() => options.length > filterableFrom ? autocomplete({
2009
2010
  message: param.summary,
2010
2011
  options,
2011
- placeholder: "Type to filter"
2012
+ placeholder: "Type to filter",
2013
+ validate: requireAutocompleteMatch
2012
2014
  }) : select({
2013
2015
  message: param.summary,
2014
2016
  options
2015
2017
  }));
2016
- if (index === other) return void 0;
2017
- if (index === skip) return unchanged;
2018
- const raw = suggested.choices[index].value;
2018
+ if (selected === void 0 || selected === other) return void 0;
2019
+ if (selected === skip) return unchanged;
2020
+ const raw = suggested.choices[Number(selected)].value;
2019
2021
  return {
2020
2022
  value: parseRaw(param, raw),
2021
2023
  raws: [raw]
@@ -2415,16 +2417,44 @@ else
2415
2417
  compdef _oms ${programs.join(" ")}
2416
2418
  fi`;
2417
2419
  const bashScript = `__oms_dequote() {
2418
- case $1 in
2419
- \\'*) local word=\${1#\\'}; printf '%s' "\${word%\\'}" ;;
2420
- \\"*) local word=\${1#\\"}; printf '%s' "\${word%\\"}" ;;
2421
- *) printf '%s' "\${1//\\\\/}" ;;
2420
+ local word=$1
2421
+ case $word in
2422
+ \\'*) word=\${word#\\'}; printf '%s' "\${word%\\'}" ;;
2423
+ \\"*)
2424
+ word=\${word#\\"}; word=\${word%\\"}
2425
+ local out='' i=0 len=\${#word} ch
2426
+ while (( i < len )); do
2427
+ ch=\${word:i:1}
2428
+ if [[ $ch == '\\' && $((i + 1)) -lt len ]]; then
2429
+ case \${word:i+1:1} in
2430
+ \\"|\\\\|\\$|\\\`) out+=\${word:i+1:1}; i=$((i + 2)); continue ;;
2431
+ esac
2432
+ fi
2433
+ out+=$ch
2434
+ i=$((i + 1))
2435
+ done
2436
+ printf '%s' "$out"
2437
+ ;;
2438
+ *)
2439
+ local out='' i=0 len=\${#word} ch
2440
+ while (( i < len )); do
2441
+ ch=\${word:i:1}
2442
+ if [[ $ch == '\\' && $((i + 1)) -lt len ]]; then
2443
+ out+=\${word:i+1:1}
2444
+ i=$((i + 2))
2445
+ else
2446
+ out+=$ch
2447
+ i=$((i + 1))
2448
+ fi
2449
+ done
2450
+ printf '%s' "$out"
2451
+ ;;
2422
2452
  esac
2423
2453
  }
2424
2454
 
2425
2455
  _oms() {
2426
- local cur words cword word line
2427
- local -a args=() lines=()
2456
+ local cur words cword word line escaped sq="'\\\\''"
2457
+ local -a args=()
2428
2458
  if declare -F _get_comp_words_by_ref >/dev/null 2>&1; then
2429
2459
  _get_comp_words_by_ref -n =: cur words cword
2430
2460
  else
@@ -2435,16 +2465,22 @@ _oms() {
2435
2465
  for word in "\${words[@]:1:cword}"; do
2436
2466
  args+=("$(__oms_dequote "$word")")
2437
2467
  done
2438
- local IFS=$'\\n'
2439
- lines=($("\${words[0]}" ${completeRequest} "\${args[@]}" 2>/dev/null))
2440
2468
  COMPREPLY=()
2441
- for line in "\${lines[@]}"; do
2469
+ while IFS= read -r line; do
2470
+ [[ -n $line ]] || continue
2442
2471
  line=\${line%%$'\\t'*}
2443
2472
  case $cur in
2444
- [\\'\\"]*) COMPREPLY+=("$line") ;;
2473
+ \\'*) COMPREPLY+=("'\${line//\\'/$sq}'") ;;
2474
+ \\"*)
2475
+ escaped=\${line//\\\\/\\\\\\\\}
2476
+ escaped=\${escaped//\\"/\\\\\\"}
2477
+ escaped=\${escaped//\\$/\\\\\\$}
2478
+ escaped=\${escaped//\\\`/\\\\\\\`}
2479
+ COMPREPLY+=("\\"$escaped\\"")
2480
+ ;;
2445
2481
  *) COMPREPLY+=("$(printf '%q' "$line")") ;;
2446
2482
  esac
2447
- done
2483
+ done < <("\${words[0]}" ${completeRequest} "\${args[@]}" 2>/dev/null)
2448
2484
  if declare -F __ltrim_colon_completions >/dev/null 2>&1; then
2449
2485
  __ltrim_colon_completions "$cur"
2450
2486
  fi
@@ -2718,6 +2754,8 @@ const apply = command({
2718
2754
  replace: flag({ summary: "Take over an existing entry with the same key" })
2719
2755
  },
2720
2756
  async run({ provider, all, harnesses, replace }, scope) {
2757
+ if (all && harnesses.length) throw new CliError("usage", "Pass either --all or specific harnesses", "Run \"oms apply --help\" for usage.");
2758
+ if (all && replace) throw new CliError("usage", "--replace cannot be combined with --all; apply to a single harness with --replace instead", "Run \"oms apply --help\" for usage.");
2721
2759
  const ctx = await scope.services();
2722
2760
  const index = await harnessIndex(scope);
2723
2761
  const targets = all ? [...index.values()].filter((harness) => !provider.harnesses.includes(harness.id) && !blocker(harness, provider)) : harnesses;
@@ -2729,7 +2767,7 @@ const apply = command({
2729
2767
  try {
2730
2768
  applied.push({
2731
2769
  ...ref,
2732
- ...await attempt(replace)
2770
+ ...await attempt(!all && replace)
2733
2771
  });
2734
2772
  } catch (error) {
2735
2773
  if (!(error instanceof AppError && error.kind === "conflict")) {
@@ -2804,6 +2842,7 @@ const applicationCommands = [
2804
2842
  })
2805
2843
  },
2806
2844
  async run({ provider, all, harnesses }, scope) {
2845
+ if (all && harnesses.length) throw new CliError("usage", "Pass either --all or specific harnesses", "Run \"oms unapply --help\" for usage.");
2807
2846
  const ctx = await scope.services();
2808
2847
  const index = await harnessIndex(scope);
2809
2848
  const ids = all ? provider.harnesses : harnesses.map((harness) => harness.id);
@@ -2970,7 +3009,7 @@ const list$3 = command({
2970
3009
  if (!remote) return effectiveModels;
2971
3010
  let listed;
2972
3011
  try {
2973
- ({listed} = await scope.progress((stage) => ctx.providers.modelChanges(provider.id, { onStage: modelStages(provider, stage) })));
3012
+ listed = await scope.progress((stage) => ctx.providers.remoteModels(provider.id, { onStage: modelStages(provider, stage) }));
2974
3013
  } catch (error) {
2975
3014
  throw new CliError("bad_gateway", `Could not list the models of "${provider.name}": ${toCliError(error).message}`);
2976
3015
  }
@@ -3050,25 +3089,20 @@ const add$2 = command({
3050
3089
  async run({ provider, models }, scope) {
3051
3090
  const ctx = await scope.services();
3052
3091
  const { models: listed, metadataError } = await fetched(scope);
3053
- const saved = ctx.providers.get(provider.id).models.map((model) => model.id);
3054
- const added = models.filter((id) => !saved.includes(id));
3055
- if (!added.length) return {
3092
+ const result = await ctx.providers.addListedModels(provider.id, listed, models);
3093
+ if (!result.added.length) return {
3056
3094
  provider: {
3057
- id: provider.id,
3058
- name: provider.name
3095
+ id: result.id,
3096
+ name: result.name
3059
3097
  },
3060
- modelCount: saved.length,
3098
+ modelCount: result.modelCount,
3061
3099
  rewritten: [],
3062
3100
  failures: [],
3063
- added
3101
+ added: result.added
3064
3102
  };
3065
3103
  return {
3066
- ...await savedResult(scope, await ctx.providers.pickModels({
3067
- providerId: provider.id,
3068
- listed,
3069
- selected: [...saved, ...added]
3070
- }), { metadataError }),
3071
- added
3104
+ ...await savedResult(scope, result, { metadataError }),
3105
+ added: result.added
3072
3106
  };
3073
3107
  },
3074
3108
  render(result, out) {
@@ -3097,14 +3131,8 @@ const remove$2 = command({
3097
3131
  })
3098
3132
  },
3099
3133
  async run({ provider, models }, scope) {
3100
- const ctx = await scope.services();
3101
- const removed = new Set(models);
3102
- const kept = ctx.providers.get(provider.id).models.filter((model) => !removed.has(model.id));
3103
3134
  return {
3104
- ...await savedResult(scope, await ctx.providers.setModels({
3105
- providerId: provider.id,
3106
- models: kept
3107
- })),
3135
+ ...await savedResult(scope, await (await scope.services()).providers.removeModelIds(provider.id, models)),
3108
3136
  removed: models
3109
3137
  };
3110
3138
  },
@@ -3163,10 +3191,12 @@ const model$1 = group({
3163
3191
  summary: "Review how the provider's model list changed",
3164
3192
  params: {
3165
3193
  provider: providerParam(),
3194
+ ignore: flag({ summary: "Take none of the changes, and do not offer them again" }),
3166
3195
  add: selectMany({
3167
3196
  summary: "New models to add",
3168
3197
  placeholder: "model",
3169
3198
  optional: true,
3199
+ ask: (values) => !values.ignore,
3170
3200
  complete: false,
3171
3201
  choices: async (scope) => (await changes(scope)).added.map(modelChoice)
3172
3202
  }),
@@ -3174,13 +3204,14 @@ const model$1 = group({
3174
3204
  summary: "Models no longer listed to remove",
3175
3205
  placeholder: "model",
3176
3206
  optional: true,
3207
+ ask: (values) => !values.ignore,
3177
3208
  complete: false,
3178
3209
  choices: async (scope) => (await changes(scope)).removed.map(modelChoice),
3179
3210
  initial: async (scope) => (await changes(scope)).removed.map((model) => model.id)
3180
- }),
3181
- ignore: flag({ summary: "Take none of the changes, and do not offer them again" })
3211
+ })
3182
3212
  },
3183
- async run({ provider, add, remove, ignore }, scope) {
3213
+ async run({ provider, ignore, add, remove }, scope) {
3214
+ if (ignore && (add.length || remove.length)) throw new CliError("usage", "Pass either --ignore or --add/--remove", "Run \"oms model review --help\" for usage.");
3184
3215
  const ctx = await scope.services();
3185
3216
  const found = await changes(scope);
3186
3217
  const pending = {
@@ -3241,205 +3272,558 @@ const model$1 = group({
3241
3272
  ]
3242
3273
  });
3243
3274
  //#endregion
3244
- //#region node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/util.js
3245
- function getEnumValues(entries) {
3246
- const numericValues = Object.values(entries).filter((v) => typeof v === "number");
3247
- return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
3248
- }
3249
- function joinValues(array, separator = "|") {
3250
- return array.map((val) => stringifyPrimitive(val)).join(separator);
3251
- }
3252
- function jsonStringifyReplacer(_, value) {
3253
- if (typeof value === "bigint") return value.toString();
3254
- return value;
3255
- }
3256
- var Cached = class {
3257
- constructor(getter) {
3258
- this._getter = getter;
3259
- this._value = void 0;
3260
- }
3261
- get value() {
3262
- const getter = this._getter;
3263
- if (getter !== void 0) {
3264
- this._value = getter();
3265
- this._getter = void 0;
3266
- }
3267
- return this._value;
3275
+ //#region src/cli/commands/override.ts
3276
+ const chosen$1 = (scope) => scope.values.provider;
3277
+ const provider$1 = (disabled) => select$1({
3278
+ summary: "Provider",
3279
+ optional: true,
3280
+ target: true,
3281
+ placeholder: "provider",
3282
+ details: "Its name or id; without it, the override is global and applies to every provider's model",
3283
+ async choices(scope) {
3284
+ const providers = await providerChoices(scope, disabled);
3285
+ if (!providers.length) return [];
3286
+ return [{
3287
+ value: void 0,
3288
+ keys: [],
3289
+ label: "All providers",
3290
+ hint: "global"
3291
+ }, ...providers];
3268
3292
  }
3269
- };
3270
- function cached(getter) {
3271
- return new Cached(getter);
3272
- }
3273
- function nullish(input) {
3274
- return input === null || input === void 0;
3275
- }
3276
- function cleanRegex(source) {
3277
- const start = source.startsWith("^") ? 1 : 0;
3278
- const end = source.endsWith("$") ? source.length - 1 : source.length;
3279
- return source.slice(start, end);
3280
- }
3281
- function floatSafeRemainder(val, step) {
3282
- const ratio = val / step;
3283
- const roundedRatio = Math.round(ratio);
3284
- const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);
3285
- if (Math.abs(ratio - roundedRatio) < tolerance) return 0;
3286
- return ratio - roundedRatio;
3287
- }
3288
- function assignProp(target, prop, value) {
3289
- Object.defineProperty(target, prop, {
3290
- value,
3291
- writable: true,
3292
- enumerable: true,
3293
- configurable: true
3294
- });
3295
- }
3296
- /**
3297
- * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.
3298
- *
3299
- * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.
3300
- */
3301
- function rawShape(def) {
3302
- const desc = Object.getOwnPropertyDescriptor(def, "shape");
3303
- return desc?.get ? desc.get.raw : desc?.value;
3304
- }
3305
- function sourceShape(schema) {
3306
- return rawShape(schema._zod.def) ?? schema._zod.def.shape;
3307
- }
3308
- function deferProp(target, key, getter) {
3309
- Object.defineProperty(target, key, {
3310
- get() {
3311
- const value = getter();
3312
- assignProp(this, key, value);
3313
- return value;
3314
- },
3315
- enumerable: true,
3316
- configurable: true
3317
- });
3293
+ });
3294
+ /** The overrides in the chosen scope: the provider's own, or the global ones. */
3295
+ async function overridesOf(scope) {
3296
+ const ctx = await scope.services();
3297
+ const provider = chosen$1(scope);
3298
+ return provider ? ctx.providers.get(provider.id).modelOverrides : ctx.providers.modelOverrides();
3318
3299
  }
3319
- function putProp(target, key, value) {
3320
- if (key in target) assignProp(target, key, value);
3321
- else target[key] = value;
3300
+ /** One model's override in the chosen scope, empty when it has none. */
3301
+ async function currentOverride(scope, model) {
3302
+ const overrides = await overridesOf(scope);
3303
+ return Object.hasOwn(overrides, model) ? overrides[model] : {};
3322
3304
  }
3305
+ const describeOverride = (override) => [
3306
+ override.name,
3307
+ override.contextWindow && `${formatTokens(override.contextWindow)} context`,
3308
+ override.maxOutput && `${formatTokens(override.maxOutput)} output`
3309
+ ].filter(Boolean).join(", ");
3323
3310
  /**
3324
- * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.
3325
- *
3326
- * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.
3311
+ * Models an override can be set for: the provider's saved models, or for a global one, every model a provider
3312
+ * saves and every model that already has a global override.
3327
3313
  */
3328
- function mirrorShape(target, source, keys, wrap) {
3329
- const raw = sourceShape(source);
3330
- for (const key of keys) {
3331
- const desc = Object.getOwnPropertyDescriptor(raw, key);
3332
- if (!desc.enumerable) continue;
3333
- if (desc.get) deferProp(target, key, () => {
3334
- const value = source._zod.def.shape[key];
3335
- return wrap ? wrap(value, key) : value;
3336
- });
3337
- else putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);
3338
- }
3339
- }
3340
- function mirrorProps(target, source) {
3341
- for (const key of Reflect.ownKeys(source)) {
3342
- const desc = Object.getOwnPropertyDescriptor(source, key);
3343
- if (!desc.enumerable) continue;
3344
- if (desc.get) deferProp(target, key, () => source[key]);
3345
- else putProp(target, key, desc.value);
3346
- }
3347
- }
3348
- function mergeDefs(...defs) {
3349
- const mergedDescriptors = {};
3350
- for (const def of defs) {
3351
- const descriptors = Object.getOwnPropertyDescriptors(def);
3352
- Object.assign(mergedDescriptors, descriptors);
3353
- }
3354
- return Object.defineProperties({}, mergedDescriptors);
3355
- }
3356
- function esc(str) {
3357
- return JSON.stringify(str);
3358
- }
3359
- function slugify(input) {
3360
- return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
3361
- }
3362
- const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
3363
- function isObject$1(data) {
3364
- return typeof data === "object" && data !== null && !Array.isArray(data);
3314
+ async function settableModels(scope) {
3315
+ const ctx = await scope.services();
3316
+ const provider = chosen$1(scope);
3317
+ const overrides = await overridesOf(scope);
3318
+ const models = provider ? ctx.providers.get(provider.id).models : ctx.providers.baseModels();
3319
+ const ids = new Set(models.map((model) => model.id));
3320
+ const others = provider ? [] : Object.keys(overrides).filter((id) => !ids.has(id));
3321
+ return [...models, ...others.map((id) => ({ id }))].map((model) => ({
3322
+ ...modelChoice(model),
3323
+ hint: Object.hasOwn(overrides, model.id) ? "overridden" : modelChoice(model).hint
3324
+ }));
3365
3325
  }
3366
- const allowsEval = /* @__PURE__*/ cached(() => {
3367
- if (globalConfig.jitless) return false;
3368
- if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
3369
- try {
3370
- new Function("");
3371
- return true;
3372
- } catch (_) {
3373
- return false;
3326
+ const modelId$3 = (raw) => {
3327
+ const trimmed = raw.trim();
3328
+ if (!trimmed || trimmed.length > 256) throw new ParamError("must contain 1 to 256 characters");
3329
+ return trimmed;
3330
+ };
3331
+ /** An override field: unset leaves it as it is; an empty value, as null, clears it. */
3332
+ const tokens = (summary, field) => text$1({
3333
+ summary,
3334
+ optional: true,
3335
+ details: "An empty value clears it",
3336
+ initial: async (scope) => (await currentOverride(scope, scope.values.model))[field]?.toString(),
3337
+ parse: (raw) => {
3338
+ const trimmed = raw.trim();
3339
+ if (!trimmed) return null;
3340
+ if (!/^\d+$/.test(trimmed) || !Number.isSafeInteger(Number(trimmed)) || Number(trimmed) < 1) throw new ParamError("must be a positive integer");
3341
+ return Number(trimmed);
3374
3342
  }
3375
3343
  });
3376
- function isPlainObject(o) {
3377
- if (isObject$1(o) === false) return false;
3378
- const ctor = o.constructor;
3379
- if (ctor === void 0) return true;
3380
- if (typeof ctor !== "function") return true;
3381
- const prot = ctor.prototype;
3382
- if (isObject$1(prot) === false) return false;
3383
- if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
3384
- return true;
3385
- }
3386
- function shallowClone(o) {
3387
- if (isPlainObject(o)) return { ...o };
3388
- if (Array.isArray(o)) return [...o];
3389
- if (o instanceof Map) return new Map(o);
3390
- if (o instanceof Set) return new Set(o);
3391
- return o;
3392
- }
3393
- const propertyKeyTypes = /* @__PURE__*/ new Set([
3394
- "string",
3395
- "number",
3396
- "symbol"
3397
- ]);
3398
- function escapeRegex(str) {
3399
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3400
- }
3401
- function clone(inst, def, params) {
3402
- const cl = new inst._zod.constr(def ?? inst._zod.def);
3403
- if (!def || params?.parent) cl._zod.parent = inst;
3404
- return cl;
3405
- }
3406
- function normalizeParams(_params) {
3407
- const params = _params;
3408
- if (!params) return {};
3409
- if (typeof params === "string") return { error: () => params };
3410
- if (params?.message !== void 0) {
3411
- if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params");
3412
- params.error = params.message;
3413
- }
3414
- delete params.message;
3415
- if (typeof params.error === "string") return {
3416
- ...params,
3417
- error: () => params.error
3344
+ function formatResult(result, harnesses) {
3345
+ return {
3346
+ affected: result.affected,
3347
+ failures: result.failures.map((failure) => ({
3348
+ provider: {
3349
+ id: failure.providerId,
3350
+ name: failure.providerName
3351
+ },
3352
+ ...refOf(failure.harnessId, harnesses),
3353
+ message: failure.message
3354
+ }))
3418
3355
  };
3419
- return params;
3420
- }
3421
- function stringifyPrimitive(value) {
3422
- if (typeof value === "bigint") return value.toString() + "n";
3423
- if (typeof value === "string") return `"${value}"`;
3424
- return `${value}`;
3425
3356
  }
3426
- function optionalKeys(shape) {
3427
- return Object.keys(shape).filter((k) => {
3428
- return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional";
3429
- });
3357
+ function renderOutcome(verb, result, out, scope) {
3358
+ if (scope.provider) out.success(`${verb} override for "${scope.model}" on "${scope.provider.name}".`);
3359
+ else if (result.affected) out.success(`${verb} global override for "${scope.model}" (updated ${plural(result.affected, "provider")}).`);
3360
+ else out.success(`${verb} global override for "${scope.model}".`);
3361
+ for (const failure of result.failures) out.warn(`${failure.provider.name} / ${failure.name}: ${failure.message}`);
3430
3362
  }
3431
- const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({
3432
- safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
3433
- int32: [-2147483648, 2147483647],
3434
- uint32: [0, 4294967295],
3435
- float32: [-34028234663852886e22, 34028234663852886e22],
3436
- float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
3437
- }))();
3438
- const BIGINT_FORMAT_RANGES = {
3439
- int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")],
3440
- uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")]
3441
- };
3442
- function pick(schema, mask) {
3363
+ const override = group({
3364
+ name: "override",
3365
+ summary: "Manage global and provider model overrides",
3366
+ children: [
3367
+ command({
3368
+ name: "list",
3369
+ summary: "List global or provider model overrides",
3370
+ params: { provider: provider$1() },
3371
+ run: (_values, scope) => overridesOf(scope),
3372
+ render(result, out, { provider }) {
3373
+ const rows = Object.entries(result);
3374
+ if (!rows.length) {
3375
+ out.hint(provider ? `"${provider.name}" has no model overrides.` : "No global model overrides.");
3376
+ return;
3377
+ }
3378
+ out.table([
3379
+ "MODEL",
3380
+ "NAME",
3381
+ "CONTEXT",
3382
+ "OUTPUT"
3383
+ ], rows.map(([model, value]) => [
3384
+ model,
3385
+ value.name ?? "-",
3386
+ value.contextWindow?.toString() ?? "-",
3387
+ value.maxOutput?.toString() ?? "-"
3388
+ ]));
3389
+ }
3390
+ }),
3391
+ command({
3392
+ name: "set",
3393
+ summary: "Set fields of a model's override, keeping the others",
3394
+ params: {
3395
+ provider: provider$1((provider) => provider.modelCount ? void 0 : "has no models"),
3396
+ model: text$1({
3397
+ summary: "Model",
3398
+ positional: true,
3399
+ placeholder: "model",
3400
+ details: "Its id, exactly; for a provider override, one of its saved models",
3401
+ parse: modelId$3,
3402
+ complete: settableModels,
3403
+ suggest: async (scope) => ({
3404
+ choices: await settableModels(scope),
3405
+ open: !chosen$1(scope)
3406
+ })
3407
+ }),
3408
+ name: text$1({
3409
+ summary: "Display name",
3410
+ optional: true,
3411
+ details: "An empty value clears it",
3412
+ initial: async (scope) => (await currentOverride(scope, scope.values.model)).name,
3413
+ parse: (raw) => {
3414
+ const trimmed = raw.trim();
3415
+ if (trimmed.length > 256) throw new ParamError("must contain at most 256 characters");
3416
+ return trimmed || null;
3417
+ }
3418
+ }),
3419
+ context: tokens("Maximum context in tokens", "contextWindow"),
3420
+ output: tokens("Maximum output in tokens", "maxOutput")
3421
+ },
3422
+ async run({ provider, model, name, context, output }, scope) {
3423
+ const patch = {
3424
+ name,
3425
+ contextWindow: context,
3426
+ maxOutput: output
3427
+ };
3428
+ if (Object.values(patch).every((value) => value === void 0)) {
3429
+ if (scope.session.interactive) return void 0;
3430
+ throw new CliError("usage", "Nothing to change", "Pass --name, --context or --output.");
3431
+ }
3432
+ const ctx = await scope.services();
3433
+ if (provider && !ctx.providers.get(provider.id).models.some((item) => item.id === model)) throw new CliError("not_found", `Model "${model}" is not saved in "${provider.name}"`);
3434
+ const outcome = await ctx.providers.patchModelOverride({
3435
+ providerId: provider?.id,
3436
+ modelId: model,
3437
+ patch
3438
+ });
3439
+ if (outcome.empty) {
3440
+ const scoped = provider ? ` --provider ${shellQuote(provider.name)}` : "";
3441
+ throw new CliError("usage", "Every field of the override would be cleared", `Remove it with "oms override remove ${shellQuote(model)}${scoped}".`);
3442
+ }
3443
+ return formatResult(outcome, await harnessIndex(scope));
3444
+ },
3445
+ render(result, out, { provider, model }) {
3446
+ if (!result) {
3447
+ out.hint("Nothing changed.");
3448
+ return;
3449
+ }
3450
+ renderOutcome("Saved", result, out, {
3451
+ provider,
3452
+ model
3453
+ });
3454
+ },
3455
+ failed: (result) => Boolean(result?.failures.length)
3456
+ }),
3457
+ command({
3458
+ name: "remove",
3459
+ aliases: ["rm"],
3460
+ summary: "Remove an override and restore inheritance",
3461
+ params: {
3462
+ provider: provider$1(),
3463
+ model: select$1({
3464
+ summary: "Model",
3465
+ positional: true,
3466
+ placeholder: "model",
3467
+ details: "Its id",
3468
+ empty: "There is no override to remove.",
3469
+ async choices(scope) {
3470
+ return Object.entries(await overridesOf(scope)).map(([id, override]) => ({
3471
+ value: id,
3472
+ keys: [id],
3473
+ label: id,
3474
+ hint: describeOverride(override) || void 0
3475
+ }));
3476
+ }
3477
+ })
3478
+ },
3479
+ confirm: ({ provider, model }) => `Remove the ${provider ? `provider "${provider.name}"` : "global"} override for "${model}"?`,
3480
+ async run({ provider, model }, scope) {
3481
+ const ctx = await scope.services();
3482
+ const harnesses = await harnessIndex(scope);
3483
+ if (!provider) return formatResult(await ctx.providers.removeModelOverride(model), harnesses);
3484
+ const saved = await ctx.providers.setProviderModelOverride({
3485
+ providerId: provider.id,
3486
+ modelId: model,
3487
+ override: {}
3488
+ });
3489
+ return formatResult({
3490
+ affected: 1,
3491
+ failures: saved.harnessFailures.map((failure) => ({
3492
+ providerId: saved.id,
3493
+ providerName: saved.name,
3494
+ ...failure
3495
+ }))
3496
+ }, harnesses);
3497
+ },
3498
+ render(result, out, { provider, model }) {
3499
+ renderOutcome("Removed", result, out, {
3500
+ provider,
3501
+ model
3502
+ });
3503
+ },
3504
+ failed: (result) => result.failures.length > 0
3505
+ })
3506
+ ]
3507
+ });
3508
+ //#endregion
3509
+ //#region src/cli/commands/paths.ts
3510
+ const paths = command({
3511
+ name: "paths",
3512
+ summary: "Show where ohmyswitch keeps its files",
3513
+ params: {},
3514
+ run(_values, scope) {
3515
+ const { dirs } = scope.session.config;
3516
+ return {
3517
+ ...dirs,
3518
+ plugins: join(dirs.config, "plugins.yml"),
3519
+ pluginPatches: join(dirs.config, "plugins.patch.yml"),
3520
+ store: join(dirs.data, "store.json")
3521
+ };
3522
+ },
3523
+ render(result, out) {
3524
+ out.fields([
3525
+ ["Providers", result.store],
3526
+ ["Plugins", result.plugins],
3527
+ ["Plugin patches", result.pluginPatches],
3528
+ ["Cache", result.cache],
3529
+ ["Logs (GUI)", result.logs]
3530
+ ]);
3531
+ }
3532
+ });
3533
+ //#endregion
3534
+ //#region src/cli/commands/plugin.ts
3535
+ const lockedReason = "decided by plugins.patch.yml";
3536
+ function stateOf(entry) {
3537
+ switch (entry.state) {
3538
+ case "active": return "enabled";
3539
+ case "disabled": return "disabled";
3540
+ case "failed": return `failed${entry.error ? `: ${entry.error}` : ""}`;
3541
+ default: return "loading";
3542
+ }
3543
+ }
3544
+ function warnFileErrors(out, plugins) {
3545
+ if (plugins.fileError) out.warn(`${plugins.path} cannot be read: ${plugins.fileError}`);
3546
+ if (plugins.patchError) out.warn(`${plugins.patchPath} cannot be read: ${plugins.patchError}`);
3547
+ }
3548
+ const list$1 = command({
3549
+ name: "list",
3550
+ aliases: ["ls"],
3551
+ summary: "List plugins",
3552
+ params: {},
3553
+ async run(_values, scope) {
3554
+ return (await scope.services()).plugins.list();
3555
+ },
3556
+ render(plugins, out) {
3557
+ warnFileErrors(out, plugins);
3558
+ out.table([
3559
+ "PLUGIN",
3560
+ "ID",
3561
+ "STATE",
3562
+ "NOTE"
3563
+ ], plugins.entries.map((entry) => [
3564
+ entry.title,
3565
+ entry.id,
3566
+ stateOf(entry),
3567
+ entry.locked ? lockedReason : ""
3568
+ ]));
3569
+ }
3570
+ });
3571
+ function assertPluginsReadable(plugins) {
3572
+ const broken = plugins.fileError ? plugins.path : plugins.patchError ? plugins.patchPath : void 0;
3573
+ if (broken) throw new CliError("precondition_failed", `${broken} has errors; fix it first`);
3574
+ }
3575
+ async function pluginChoices(scope) {
3576
+ const plugins = await (await scope.services()).plugins.list();
3577
+ assertPluginsReadable(plugins);
3578
+ return plugins.entries.map((entry) => ({
3579
+ value: entry,
3580
+ keys: [
3581
+ entry.id,
3582
+ entry.title,
3583
+ entry.name
3584
+ ],
3585
+ label: entry.title,
3586
+ hint: stateOf(entry),
3587
+ disabled: entry.locked ? lockedReason : void 0
3588
+ }));
3589
+ }
3590
+ function switchCommand(enabled) {
3591
+ return command({
3592
+ name: enabled ? "enable" : "disable",
3593
+ summary: `${enabled ? "Enable" : "Disable"} a plugin`,
3594
+ params: { plugin: select$1({
3595
+ summary: "Plugin",
3596
+ positional: true,
3597
+ placeholder: "plugin",
3598
+ details: "Its id or name",
3599
+ empty: "Every plugin is decided by plugins.patch.yml.",
3600
+ choices: pluginChoices
3601
+ }) },
3602
+ async run({ plugin }, scope) {
3603
+ const ctx = await scope.services();
3604
+ assertPluginsReadable(await ctx.plugins.list());
3605
+ await ctx.plugins.setEnabled(plugin.id, enabled);
3606
+ return {
3607
+ id: plugin.id,
3608
+ title: plugin.title,
3609
+ enabled
3610
+ };
3611
+ },
3612
+ render(result, out) {
3613
+ out.success(`${enabled ? "Enabled" : "Disabled"} ${result.title}.`);
3614
+ }
3615
+ });
3616
+ }
3617
+ const plugin = group({
3618
+ name: "plugin",
3619
+ aliases: ["plugins"],
3620
+ summary: "Enable or disable plugins",
3621
+ children: [
3622
+ list$1,
3623
+ switchCommand(true),
3624
+ switchCommand(false)
3625
+ ]
3626
+ });
3627
+ //#endregion
3628
+ //#region node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/util.js
3629
+ function getEnumValues(entries) {
3630
+ const numericValues = Object.values(entries).filter((v) => typeof v === "number");
3631
+ return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
3632
+ }
3633
+ function joinValues(array, separator = "|") {
3634
+ return array.map((val) => stringifyPrimitive(val)).join(separator);
3635
+ }
3636
+ function jsonStringifyReplacer(_, value) {
3637
+ if (typeof value === "bigint") return value.toString();
3638
+ return value;
3639
+ }
3640
+ var Cached = class {
3641
+ constructor(getter) {
3642
+ this._getter = getter;
3643
+ this._value = void 0;
3644
+ }
3645
+ get value() {
3646
+ const getter = this._getter;
3647
+ if (getter !== void 0) {
3648
+ this._value = getter();
3649
+ this._getter = void 0;
3650
+ }
3651
+ return this._value;
3652
+ }
3653
+ };
3654
+ function cached(getter) {
3655
+ return new Cached(getter);
3656
+ }
3657
+ function nullish(input) {
3658
+ return input === null || input === void 0;
3659
+ }
3660
+ function cleanRegex(source) {
3661
+ const start = source.startsWith("^") ? 1 : 0;
3662
+ const end = source.endsWith("$") ? source.length - 1 : source.length;
3663
+ return source.slice(start, end);
3664
+ }
3665
+ function floatSafeRemainder(val, step) {
3666
+ const ratio = val / step;
3667
+ const roundedRatio = Math.round(ratio);
3668
+ const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);
3669
+ if (Math.abs(ratio - roundedRatio) < tolerance) return 0;
3670
+ return ratio - roundedRatio;
3671
+ }
3672
+ function assignProp(target, prop, value) {
3673
+ Object.defineProperty(target, prop, {
3674
+ value,
3675
+ writable: true,
3676
+ enumerable: true,
3677
+ configurable: true
3678
+ });
3679
+ }
3680
+ /**
3681
+ * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.
3682
+ *
3683
+ * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.
3684
+ */
3685
+ function rawShape(def) {
3686
+ const desc = Object.getOwnPropertyDescriptor(def, "shape");
3687
+ return desc?.get ? desc.get.raw : desc?.value;
3688
+ }
3689
+ function sourceShape(schema) {
3690
+ return rawShape(schema._zod.def) ?? schema._zod.def.shape;
3691
+ }
3692
+ function deferProp(target, key, getter) {
3693
+ Object.defineProperty(target, key, {
3694
+ get() {
3695
+ const value = getter();
3696
+ assignProp(this, key, value);
3697
+ return value;
3698
+ },
3699
+ enumerable: true,
3700
+ configurable: true
3701
+ });
3702
+ }
3703
+ function putProp(target, key, value) {
3704
+ if (key in target) assignProp(target, key, value);
3705
+ else target[key] = value;
3706
+ }
3707
+ /**
3708
+ * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.
3709
+ *
3710
+ * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.
3711
+ */
3712
+ function mirrorShape(target, source, keys, wrap) {
3713
+ const raw = sourceShape(source);
3714
+ for (const key of keys) {
3715
+ const desc = Object.getOwnPropertyDescriptor(raw, key);
3716
+ if (!desc.enumerable) continue;
3717
+ if (desc.get) deferProp(target, key, () => {
3718
+ const value = source._zod.def.shape[key];
3719
+ return wrap ? wrap(value, key) : value;
3720
+ });
3721
+ else putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);
3722
+ }
3723
+ }
3724
+ function mirrorProps(target, source) {
3725
+ for (const key of Reflect.ownKeys(source)) {
3726
+ const desc = Object.getOwnPropertyDescriptor(source, key);
3727
+ if (!desc.enumerable) continue;
3728
+ if (desc.get) deferProp(target, key, () => source[key]);
3729
+ else putProp(target, key, desc.value);
3730
+ }
3731
+ }
3732
+ function mergeDefs(...defs) {
3733
+ const mergedDescriptors = {};
3734
+ for (const def of defs) {
3735
+ const descriptors = Object.getOwnPropertyDescriptors(def);
3736
+ Object.assign(mergedDescriptors, descriptors);
3737
+ }
3738
+ return Object.defineProperties({}, mergedDescriptors);
3739
+ }
3740
+ function esc(str) {
3741
+ return JSON.stringify(str);
3742
+ }
3743
+ function slugify(input) {
3744
+ return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
3745
+ }
3746
+ const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
3747
+ function isObject$1(data) {
3748
+ return typeof data === "object" && data !== null && !Array.isArray(data);
3749
+ }
3750
+ const allowsEval = /* @__PURE__*/ cached(() => {
3751
+ if (globalConfig.jitless) return false;
3752
+ if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
3753
+ try {
3754
+ new Function("");
3755
+ return true;
3756
+ } catch (_) {
3757
+ return false;
3758
+ }
3759
+ });
3760
+ function isPlainObject(o) {
3761
+ if (isObject$1(o) === false) return false;
3762
+ const ctor = o.constructor;
3763
+ if (ctor === void 0) return true;
3764
+ if (typeof ctor !== "function") return true;
3765
+ const prot = ctor.prototype;
3766
+ if (isObject$1(prot) === false) return false;
3767
+ if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
3768
+ return true;
3769
+ }
3770
+ function shallowClone(o) {
3771
+ if (isPlainObject(o)) return { ...o };
3772
+ if (Array.isArray(o)) return [...o];
3773
+ if (o instanceof Map) return new Map(o);
3774
+ if (o instanceof Set) return new Set(o);
3775
+ return o;
3776
+ }
3777
+ const propertyKeyTypes = /* @__PURE__*/ new Set([
3778
+ "string",
3779
+ "number",
3780
+ "symbol"
3781
+ ]);
3782
+ function escapeRegex(str) {
3783
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3784
+ }
3785
+ function clone(inst, def, params) {
3786
+ const cl = new inst._zod.constr(def ?? inst._zod.def);
3787
+ if (!def || params?.parent) cl._zod.parent = inst;
3788
+ return cl;
3789
+ }
3790
+ function normalizeParams(_params) {
3791
+ const params = _params;
3792
+ if (!params) return {};
3793
+ if (typeof params === "string") return { error: () => params };
3794
+ if (params?.message !== void 0) {
3795
+ if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params");
3796
+ params.error = params.message;
3797
+ }
3798
+ delete params.message;
3799
+ if (typeof params.error === "string") return {
3800
+ ...params,
3801
+ error: () => params.error
3802
+ };
3803
+ return params;
3804
+ }
3805
+ function stringifyPrimitive(value) {
3806
+ if (typeof value === "bigint") return value.toString() + "n";
3807
+ if (typeof value === "string") return `"${value}"`;
3808
+ return `${value}`;
3809
+ }
3810
+ function optionalKeys(shape) {
3811
+ return Object.keys(shape).filter((k) => {
3812
+ return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional";
3813
+ });
3814
+ }
3815
+ const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({
3816
+ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
3817
+ int32: [-2147483648, 2147483647],
3818
+ uint32: [0, 4294967295],
3819
+ float32: [-34028234663852886e22, 34028234663852886e22],
3820
+ float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
3821
+ }))();
3822
+ const BIGINT_FORMAT_RANGES = {
3823
+ int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")],
3824
+ uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")]
3825
+ };
3826
+ function pick(schema, mask) {
3443
3827
  const currDef = schema._zod.def;
3444
3828
  const checks = currDef.checks;
3445
3829
  if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements");
@@ -6998,6 +7382,17 @@ function _array(Class, element, params) {
6998
7382
  });
6999
7383
  }
7000
7384
  // @__NO_SIDE_EFFECTS__
7385
+ function _custom(Class, fn, _params) {
7386
+ const norm = normalizeParams(_params);
7387
+ norm.abort ?? (norm.abort = true);
7388
+ return new Class({
7389
+ type: "custom",
7390
+ check: "custom",
7391
+ fn,
7392
+ ...norm
7393
+ });
7394
+ }
7395
+ // @__NO_SIDE_EFFECTS__
7001
7396
  function _refine(Class, fn, _params) {
7002
7397
  return new Class({
7003
7398
  type: "custom",
@@ -8824,616 +9219,291 @@ function prefault(innerType, defaultValue) {
8824
9219
  return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
8825
9220
  }
8826
9221
  });
8827
- }
8828
- const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => {
8829
- $ZodNonOptional.init(inst, def);
8830
- ZodType.init(inst, def);
8831
- inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params);
8832
- inst.unwrap = () => inst._zod.def.innerType;
8833
- });
8834
- function nonoptional(innerType, params) {
8835
- return new ZodNonOptional({
8836
- type: "nonoptional",
8837
- innerType,
8838
- ...normalizeParams(params)
8839
- });
8840
- }
8841
- const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => {
8842
- $ZodCatch.init(inst, def);
8843
- ZodType.init(inst, def);
8844
- inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params);
8845
- inst.unwrap = () => inst._zod.def.innerType;
8846
- inst.removeCatch = inst.unwrap;
8847
- });
8848
- function _catch(innerType, catchValue) {
8849
- return new ZodCatch({
8850
- type: "catch",
8851
- innerType,
8852
- catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue)
8853
- });
8854
- }
8855
- const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => {
8856
- $ZodPipe.init(inst, def);
8857
- ZodType.init(inst, def);
8858
- inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params);
8859
- inst.in = def.in;
8860
- inst.out = def.out;
8861
- });
8862
- function pipe(in_, out) {
8863
- return new ZodPipe({
8864
- type: "pipe",
8865
- in: in_,
8866
- out
8867
- });
8868
- }
8869
- const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => {
8870
- $ZodReadonly.init(inst, def);
8871
- ZodType.init(inst, def);
8872
- inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params);
8873
- inst.unwrap = () => inst._zod.def.innerType;
8874
- });
8875
- function readonly(innerType) {
8876
- return new ZodReadonly({
8877
- type: "readonly",
8878
- innerType
8879
- });
8880
- }
8881
- const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => {
8882
- $ZodCustom.init(inst, def);
8883
- ZodType.init(inst, def);
8884
- inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params);
8885
- });
8886
- function refine(fn, _params = {}) {
8887
- return /* @__PURE__ */ _refine(ZodCustom, fn, _params);
8888
- }
8889
- function superRefine(fn, params) {
8890
- return /* @__PURE__ */ _superRefine(fn, params);
8891
- }
8892
- //#endregion
8893
- //#region node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/iso.js
8894
- function datetime(params) {
8895
- return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params);
8896
- }
8897
- //#endregion
8898
- //#region src/core/harnesses/types.ts
8899
- /**
8900
- * A harness id, such as `opencode`. Harnesses are registered at runtime, so the set is open; stored applications of
8901
- * a harness that is not registered are kept as they are.
8902
- */
8903
- const harnessId = string().regex(/^[a-z][a-z0-9-]{0,31}$/);
8904
- //#endregion
8905
- //#region src/core/provider.ts
8906
- const providerName = string().trim().min(1, { error: "请填写名称" }).max(128, { error: "名称最多 128 个字符" });
8907
- /**
8908
- * An http(s) root address without a trailing slash. A trailing `/v1` or `/v1beta` is dropped: endpoints and
8909
- * harness adapters append the version path themselves, so keeping it would double it.
8910
- */
8911
- const baseUrl = string().trim().pipe(url({
8912
- protocol: /^https?$/,
8913
- error: "请填写 http 或 https 地址"
8914
- })).transform((value) => value.replace(/\/+$/, "").replace(/\/(v1|v1beta)$/, ""));
8915
- /**
8916
- * Where a provider's icon comes from: an image, or a web page whose declared icon is used. An empty value means
8917
- * unset, in which case the icon of the Base URL's site is used.
8918
- */
8919
- const iconUrl = string().trim().max(2048, { error: "地址最多 2048 个字符" }).transform((value) => value || void 0).pipe(url({
8920
- protocol: /^https?$/,
8921
- error: "请填写 http 或 https 地址"
8922
- }).optional());
8923
- /** Input kinds a model accepts. Text is always accepted; the others are listed when supported. */
8924
- const modelInputs = [
8925
- "text",
8926
- "image",
8927
- "pdf"
8928
- ];
8929
- /** A native reasoning effort value, such as `low`, `xhigh` or `none`. */
8930
- const reasoningEffort = string().regex(/^[A-Za-z0-9_-]{1,32}$/, { error: "推理等级只能包含字母、数字、- 和 _" });
8931
- /**
8932
- * How the model's API controls reasoning, in the models.dev format. Harness adapters translate these into their
8933
- * own settings (Pi's `thinkingLevelMap`, OpenCode's `variants`); ohmyswitch stores them harness-neutral.
8934
- * On a model, an empty list means reasoning cannot be controlled; an unset list means unknown.
8935
- */
8936
- const reasoningOption = discriminatedUnion("type", [
8937
- object$1({
8938
- type: literal("effort"),
8939
- values: array(reasoningEffort).min(1).max(16)
8940
- }),
8941
- object$1({ type: literal("toggle") }),
8942
- object$1({
8943
- type: literal("budget_tokens"),
8944
- min: number$1().int().nonnegative().optional(),
8945
- max: number$1().int().positive().optional()
8946
- })
8947
- ]);
8948
- /**
8949
- * Whether reasoning must be sent back with later turns. `true` uses the protocol's own form; `field` names the
8950
- * response field to echo, such as `reasoning_content` on OpenAI-compatible APIs.
8951
- */
8952
- const interleaved = union([literal(true), object$1({ field: string().regex(/^[a-z_]{1,64}$/) })]);
8953
- /**
8954
- * A model and the metadata harness configs need. Every field but `id` is optional: unknown stays unset rather
8955
- * than guessed, and harnesses fall back to their own defaults.
8956
- */
8957
- const modelInfo = object$1({
8958
- id: string().min(1).max(256),
8959
- name: string().max(256).optional(),
8960
- contextWindow: number$1().int().positive().optional(),
8961
- maxOutput: number$1().int().positive().optional(),
8962
- reasoning: boolean().optional(),
8963
- reasoningOptions: array(reasoningOption).max(8).optional(),
8964
- interleaved: interleaved.optional(),
8965
- input: array(_enum(modelInputs)).optional(),
8966
- toolCall: boolean().optional()
8967
- });
8968
- /** Both override scopes are limited to display name and token limits. */
8969
- const modelOverride = modelInfo.pick({
8970
- name: true,
8971
- contextWindow: true,
8972
- maxOutput: true
8973
- });
8974
- const providerModelOverride = modelOverride;
8975
- /** A provider as persisted. The API key is stored in plain text; harness configs hold it in plain text anyway. */
8976
- const storedProvider = object$1({
8977
- id: uuid(),
8978
- name: providerName,
8979
- /** The root address requests go to; endpoints are appended to it. */
8980
- baseUrl,
8981
- endpoint: _enum(endpoints),
8982
- /**
8983
- * The model vendor, shown as the badge on the provider's icon and compared by import links. Unset means the
8984
- * badge follows the endpoint. It is display information: it is not written into harness configs.
8985
- */
8986
- vendor: _enum(vendors).optional(),
8987
- apiKey: string(),
8988
- /** An image or web page to take the icon from; unset uses the Base URL's site. */
8989
- iconUrl: url({ protocol: /^https?$/ }).optional(),
8990
- /** Metadata snapshots; discovery and models.dev sync never modify the separate overrides. */
8991
- models: array(modelInfo),
8992
- /** Kept when a model is deselected, so selecting it again restores its explicit settings. */
8993
- modelOverrides: record$2(string().min(1).max(256), providerModelOverride).default({}),
8994
- /**
8995
- * The model ids the provider's model list held when the user last reviewed it. Models listed since are offered
8996
- * as new, and saved models that were listed but no longer are offered for removal. Unset until the list is first
8997
- * read; that first read only records it.
8998
- */
8999
- listedModels: array(string().min(1).max(256)).max(2e3).optional(),
9000
- /**
9001
- * Harnesses this provider is applied to, with the key ohmyswitch owns in each harness config. Entries of
9002
- * harnesses that are not registered are kept, so the application survives until the harness is back.
9003
- */
9004
- harnesses: record$2(harnessId, object$1({ key: string().min(1).max(64) })).default({}),
9005
- createdAt: datetime()
9006
- });
9007
- /** Apply explicit fields in order: snapshot → global → provider. */
9008
- function effectiveModel(model, globalOverrides, providerOverrides = {}) {
9009
- let result = model;
9010
- for (const overrides of [globalOverrides, providerOverrides]) {
9011
- const override = Object.hasOwn(overrides, model.id) ? overrides[model.id] : void 0;
9012
- if (override) result = {
9013
- ...result,
9014
- ...Object.fromEntries(Object.entries(override).filter(([, value]) => value !== void 0))
9015
- };
9016
- }
9017
- return result;
9018
- }
9019
- //#endregion
9020
- //#region src/core/providers/schemas.ts
9021
- const providerIdInput = object$1({ providerId: uuid() });
9022
- /** The fields of a provider the editor saves together; they are not all connection details. */
9023
- const connectionInput = object$1({
9024
- name: providerName,
9025
- baseUrl,
9026
- apiKey: string().trim().min(1, { error: "请填写 API Key" }).max(4096),
9027
- endpoint: _enum(endpoints, { error: "请选择端点" }),
9028
- /** Unset follows the endpoint, which is also how an import link without one compares. */
9029
- vendor: _enum(vendors).optional(),
9030
- /** Unset or empty uses the icon of the Base URL's site. */
9031
- iconUrl: iconUrl.optional()
9032
- });
9033
- const createProviderInput = connectionInput.extend({
9034
- /** Models to start with, such as those an import link lists; their metadata is filled from models.dev. */
9035
- modelIds: array(string().trim().min(1).max(256)).max(2e3).optional().transform((ids) => ids ? [...new Set(ids)] : void 0),
9036
- /**
9037
- * The provider's model list as fetched while adding it (`ProviderService.listModels`), recorded as reviewed. With
9038
- * it, the models are the ids in `selected` and `modelIds` is not used.
9039
- */
9040
- listed: array(modelInfo).max(2e3).optional().transform((models) => models ? [...new Map(models.map((model) => [model.id, model])).values()] : void 0),
9041
- selected: array(string().min(1).max(256)).max(2e3).optional().transform((ids) => ids ? [...new Set(ids)] : void 0)
9042
- });
9043
- const updateProviderInput = connectionInput.extend(providerIdInput.shape);
9044
- object$1({ providerIds: array(uuid()).max(1e3).refine((ids) => new Set(ids).size === ids.length, { error: "供应商顺序中有重复项" }) });
9045
- providerIdInput.extend({ models: array(modelInfo).max(2e3).transform((models) => [...new Map(models.map((model) => [model.id, model])).values()]) });
9046
- const modelId$3 = string().min(1).max(256);
9047
- const modelOverrideInput = object$1({
9048
- modelId: modelId$3,
9049
- override: modelOverride.refine((value) => Object.values(value).some((field) => field !== void 0), { error: "请至少填写一项覆盖信息" })
9050
- });
9051
- object$1({ modelId: modelId$3 });
9052
- /** Replace one model's provider overrides. An empty object restores inheritance for every field. */
9053
- const providerModelOverrideInput = providerIdInput.extend({
9054
- modelId: modelId$3,
9055
- override: providerModelOverride.strict()
9056
- });
9057
- providerIdInput.extend({
9058
- listed: array(modelInfo).max(2e3),
9059
- selected: array(modelId$3).max(2e3).transform((ids) => [...new Set(ids)])
9060
- });
9061
- providerIdInput.extend({
9062
- add: array(modelInfo).max(2e3),
9063
- remove: array(modelId$3).max(2e3),
9064
- listed: array(modelId$3).max(2e3).transform((ids) => [...new Set(ids)])
9065
- });
9066
- object$1({ candidates: array(object$1({ sources: array(object$1({
9067
- harnessId,
9068
- key: string().min(1).max(64)
9069
- })).min(1).max(16) })).min(1, { error: "请选择要导入的供应商" }).max(200) });
9070
- //#endregion
9071
- //#region src/cli/commands/override.ts
9072
- const chosen$1 = (scope) => scope.values.provider;
9073
- const provider$1 = (disabled) => select$1({
9074
- summary: "Provider",
9075
- optional: true,
9076
- target: true,
9077
- placeholder: "provider",
9078
- details: "Its name or id; without it, the override is global and applies to every provider's model",
9079
- async choices(scope) {
9080
- const providers = await providerChoices(scope, disabled);
9081
- if (!providers.length) return [];
9082
- return [{
9083
- value: void 0,
9084
- keys: [],
9085
- label: "All providers",
9086
- hint: "global"
9087
- }, ...providers];
9088
- }
9222
+ }
9223
+ const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => {
9224
+ $ZodNonOptional.init(inst, def);
9225
+ ZodType.init(inst, def);
9226
+ inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params);
9227
+ inst.unwrap = () => inst._zod.def.innerType;
9089
9228
  });
9090
- /** The overrides in the chosen scope: the provider's own, or the global ones. */
9091
- async function overridesOf(scope) {
9092
- const ctx = await scope.services();
9093
- const provider = chosen$1(scope);
9094
- return provider ? ctx.providers.get(provider.id).modelOverrides : ctx.providers.modelOverrides();
9229
+ function nonoptional(innerType, params) {
9230
+ return new ZodNonOptional({
9231
+ type: "nonoptional",
9232
+ innerType,
9233
+ ...normalizeParams(params)
9234
+ });
9095
9235
  }
9096
- /** One model's override in the chosen scope, empty when it has none. */
9097
- async function currentOverride(scope, model) {
9098
- const overrides = await overridesOf(scope);
9099
- return Object.hasOwn(overrides, model) ? overrides[model] : {};
9236
+ const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => {
9237
+ $ZodCatch.init(inst, def);
9238
+ ZodType.init(inst, def);
9239
+ inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params);
9240
+ inst.unwrap = () => inst._zod.def.innerType;
9241
+ inst.removeCatch = inst.unwrap;
9242
+ });
9243
+ function _catch(innerType, catchValue) {
9244
+ return new ZodCatch({
9245
+ type: "catch",
9246
+ innerType,
9247
+ catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue)
9248
+ });
9100
9249
  }
9101
- const describeOverride = (override) => [
9102
- override.name,
9103
- override.contextWindow && `${formatTokens(override.contextWindow)} context`,
9104
- override.maxOutput && `${formatTokens(override.maxOutput)} output`
9105
- ].filter(Boolean).join(", ");
9106
- /**
9107
- * Models an override can be set for: the provider's saved models, or for a global one, every model a provider
9108
- * saves and every model that already has a global override.
9109
- */
9110
- async function settableModels(scope) {
9111
- const ctx = await scope.services();
9112
- const provider = chosen$1(scope);
9113
- const overrides = await overridesOf(scope);
9114
- const models = provider ? ctx.providers.get(provider.id).models : ctx.providers.baseModels();
9115
- const ids = new Set(models.map((model) => model.id));
9116
- const others = provider ? [] : Object.keys(overrides).filter((id) => !ids.has(id));
9117
- return [...models, ...others.map((id) => ({ id }))].map((model) => ({
9118
- ...modelChoice(model),
9119
- hint: Object.hasOwn(overrides, model.id) ? "overridden" : modelChoice(model).hint
9120
- }));
9250
+ const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => {
9251
+ $ZodPipe.init(inst, def);
9252
+ ZodType.init(inst, def);
9253
+ inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params);
9254
+ inst.in = def.in;
9255
+ inst.out = def.out;
9256
+ });
9257
+ function pipe(in_, out) {
9258
+ return new ZodPipe({
9259
+ type: "pipe",
9260
+ in: in_,
9261
+ out
9262
+ });
9121
9263
  }
9122
- const modelId$2 = (raw) => {
9123
- if (!raw.trim() || raw.length > 256) throw new ParamError("Model id must contain 1 to 256 characters.");
9124
- return raw;
9125
- };
9126
- /** An override field: unset leaves it as it is; an empty value, as null, clears it. */
9127
- const tokens = (summary, field) => text$1({
9128
- summary,
9129
- optional: true,
9130
- details: "An empty value clears it",
9131
- initial: async (scope) => (await currentOverride(scope, scope.values.model))[field]?.toString(),
9132
- parse: (raw) => {
9133
- if (!raw.trim()) return null;
9134
- if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw)) || Number(raw) < 1) throw new ParamError("Must be a positive integer.");
9135
- return Number(raw);
9136
- }
9264
+ const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => {
9265
+ $ZodReadonly.init(inst, def);
9266
+ ZodType.init(inst, def);
9267
+ inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params);
9268
+ inst.unwrap = () => inst._zod.def.innerType;
9137
9269
  });
9138
- const override = group({
9139
- name: "override",
9140
- summary: "Manage global and provider model overrides",
9141
- children: [
9142
- command({
9143
- name: "list",
9144
- summary: "List global or provider model overrides",
9145
- params: { provider: provider$1() },
9146
- run: (_values, scope) => overridesOf(scope),
9147
- render(result, out, { provider }) {
9148
- const rows = Object.entries(result);
9149
- if (!rows.length) {
9150
- out.hint(provider ? `"${provider.name}" has no model overrides.` : "No global model overrides.");
9151
- return;
9152
- }
9153
- out.table([
9154
- "MODEL",
9155
- "NAME",
9156
- "CONTEXT",
9157
- "OUTPUT"
9158
- ], rows.map(([model, value]) => [
9159
- model,
9160
- value.name ?? "-",
9161
- value.contextWindow?.toString() ?? "-",
9162
- value.maxOutput?.toString() ?? "-"
9163
- ]));
9164
- }
9165
- }),
9166
- command({
9167
- name: "set",
9168
- summary: "Set fields of a model's override, keeping the others",
9169
- params: {
9170
- provider: provider$1((provider) => provider.modelCount ? void 0 : "has no models"),
9171
- model: text$1({
9172
- summary: "Model",
9173
- positional: true,
9174
- placeholder: "model",
9175
- details: "Its id, exactly; for a provider override, one of its saved models",
9176
- parse: modelId$2,
9177
- complete: settableModels,
9178
- suggest: async (scope) => ({
9179
- choices: await settableModels(scope),
9180
- open: !chosen$1(scope)
9181
- })
9182
- }),
9183
- name: text$1({
9184
- summary: "Display name",
9185
- optional: true,
9186
- details: "An empty value clears it",
9187
- initial: async (scope) => (await currentOverride(scope, scope.values.model)).name,
9188
- parse: (raw) => {
9189
- if (raw.length > 256) throw new ParamError("Name must contain at most 256 characters.");
9190
- return raw.trim() || null;
9191
- }
9192
- }),
9193
- context: tokens("Maximum context in tokens", "contextWindow"),
9194
- output: tokens("Maximum output in tokens", "maxOutput")
9195
- },
9196
- async run({ provider, model, name, context, output }, scope) {
9197
- const changes = {
9198
- name,
9199
- contextWindow: context,
9200
- maxOutput: output
9201
- };
9202
- if (Object.values(changes).every((value) => value === void 0)) {
9203
- if (scope.session.interactive) return void 0;
9204
- throw new CliError("usage", "Nothing to change", "Pass --name, --context or --output.");
9205
- }
9206
- const ctx = await scope.services();
9207
- if (provider && !ctx.providers.get(provider.id).models.some((item) => item.id === model)) throw new CliError("usage", "This model is not saved in the provider. Add or select it first.");
9208
- const next = { ...await currentOverride(scope, model) };
9209
- for (const [field, value] of Object.entries(changes)) if (value === null) delete next[field];
9210
- else if (value !== void 0) next[field] = value;
9211
- if (!Object.keys(next).length) {
9212
- const scoped = provider ? ` --provider ${shellQuote(provider.name)}` : "";
9213
- throw new CliError("usage", "Every field of the override would be cleared", `Remove it with "oms override remove ${shellQuote(model)}${scoped}".`);
9214
- }
9215
- if (!provider) return ctx.providers.setModelOverride(modelOverrideInput.parse({
9216
- modelId: model,
9217
- override: next
9218
- }));
9219
- const saved = await ctx.providers.setProviderModelOverride(providerModelOverrideInput.parse({
9220
- providerId: provider.id,
9221
- modelId: model,
9222
- override: next
9223
- }));
9224
- return {
9225
- affected: 1,
9226
- failures: saved.harnessFailures.map((failure) => ({
9227
- providerId: saved.id,
9228
- providerName: saved.name,
9229
- ...failure
9230
- }))
9231
- };
9232
- },
9233
- render(result, out) {
9234
- if (!result) {
9235
- out.hint("Nothing changed.");
9236
- return;
9237
- }
9238
- out.success(`Saved override for ${plural(result.affected, "provider")}.`);
9239
- for (const failure of result.failures) out.warn(`${failure.providerName} / ${failure.harnessId}: ${failure.message}`);
9240
- },
9241
- failed: (result) => Boolean(result?.failures.length)
9242
- }),
9243
- command({
9244
- name: "remove",
9245
- aliases: ["rm"],
9246
- summary: "Remove an override and restore inheritance",
9247
- params: {
9248
- provider: provider$1(),
9249
- model: select$1({
9250
- summary: "Model",
9251
- positional: true,
9252
- placeholder: "model",
9253
- details: "Its id",
9254
- empty: "There is no override to remove.",
9255
- async choices(scope) {
9256
- return Object.entries(await overridesOf(scope)).map(([id, override]) => ({
9257
- value: id,
9258
- keys: [id],
9259
- label: id,
9260
- hint: describeOverride(override) || void 0
9261
- }));
9262
- }
9263
- })
9264
- },
9265
- confirm: ({ provider, model }) => `Remove the ${provider ? `provider "${provider.name}"` : "global"} override for "${model}"?`,
9266
- async run({ provider, model }, scope) {
9267
- const ctx = await scope.services();
9268
- if (!provider) return ctx.providers.removeModelOverride(model);
9269
- const saved = await ctx.providers.setProviderModelOverride(providerModelOverrideInput.parse({
9270
- providerId: provider.id,
9271
- modelId: model,
9272
- override: {}
9273
- }));
9274
- return {
9275
- affected: 1,
9276
- failures: saved.harnessFailures.map((failure) => ({
9277
- providerId: saved.id,
9278
- providerName: saved.name,
9279
- ...failure
9280
- }))
9281
- };
9282
- },
9283
- render(result, out) {
9284
- out.success(`Removed override for ${plural(result.affected, "provider")}.`);
9285
- for (const failure of result.failures) out.warn(`${failure.providerName} / ${failure.harnessId}: ${failure.message}`);
9286
- },
9287
- failed: (result) => result.failures.length > 0
9288
- })
9289
- ]
9270
+ function readonly(innerType) {
9271
+ return new ZodReadonly({
9272
+ type: "readonly",
9273
+ innerType
9274
+ });
9275
+ }
9276
+ const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => {
9277
+ $ZodCustom.init(inst, def);
9278
+ ZodType.init(inst, def);
9279
+ inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params);
9290
9280
  });
9281
+ function custom(fn, _params) {
9282
+ return /* @__PURE__ */ _custom(ZodCustom, fn ?? (() => true), _params);
9283
+ }
9284
+ function refine(fn, _params = {}) {
9285
+ return /* @__PURE__ */ _refine(ZodCustom, fn, _params);
9286
+ }
9287
+ function superRefine(fn, params) {
9288
+ return /* @__PURE__ */ _superRefine(fn, params);
9289
+ }
9291
9290
  //#endregion
9292
- //#region src/cli/commands/paths.ts
9293
- const paths = command({
9294
- name: "paths",
9295
- summary: "Show where ohmyswitch keeps its files",
9296
- params: {},
9297
- run(_values, scope) {
9298
- const { dirs } = scope.session.config;
9299
- return {
9300
- ...dirs,
9301
- plugins: join(dirs.config, "plugins.yml"),
9302
- pluginPatches: join(dirs.config, "plugins.patch.yml"),
9303
- store: join(dirs.data, "store.json")
9304
- };
9305
- },
9306
- render(result, out) {
9307
- out.fields([
9308
- ["Providers", result.store],
9309
- ["Plugins", result.plugins],
9310
- ["Plugin patches", result.pluginPatches],
9311
- ["Cache", result.cache],
9312
- ["Logs (GUI)", result.logs]
9313
- ]);
9314
- }
9315
- });
9291
+ //#region node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/iso.js
9292
+ function datetime(params) {
9293
+ return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params);
9294
+ }
9316
9295
  //#endregion
9317
- //#region src/cli/commands/plugin.ts
9318
- const lockedReason = "decided by plugins.patch.yml";
9319
- function stateOf(entry) {
9320
- switch (entry.state) {
9321
- case "active": return "enabled";
9322
- case "disabled": return "disabled";
9323
- case "failed": return `failed${entry.error ? `: ${entry.error}` : ""}`;
9324
- default: return "loading";
9296
+ //#region src/cli/framework/validate.ts
9297
+ const unitOf = (origin) => {
9298
+ if (origin === "string") return " characters";
9299
+ if (origin === "array" || origin === "set") return " items";
9300
+ return "";
9301
+ };
9302
+ /**
9303
+ * An English description of a validation issue. Core schemas carry messages for the GUI; the CLI words its own
9304
+ * from the issue code, so it reads the same in every command.
9305
+ */
9306
+ function describeIssue(issue) {
9307
+ switch (issue.code) {
9308
+ case "too_small":
9309
+ if (issue.origin === "string" && Number(issue.minimum) <= 1) return "must not be empty";
9310
+ return `must be at least ${issue.minimum}${unitOf(issue.origin)}`;
9311
+ case "too_big": return `must be at most ${issue.maximum}${unitOf(issue.origin)}`;
9312
+ case "invalid_format": return issue.format === "url" ? "must be an http or https URL" : `must be a valid ${issue.format}`;
9313
+ case "invalid_type": return `must be ${issue.expected === "array" ? "a list" : `a ${issue.expected}`}`;
9314
+ case "invalid_value": return `must be one of ${issue.values.map(String).join(", ")}`;
9315
+ default: return "is invalid";
9325
9316
  }
9326
9317
  }
9327
- function warnFileErrors(out, plugins) {
9328
- if (plugins.fileError) out.warn(`${plugins.path} cannot be read: ${plugins.fileError}`);
9329
- if (plugins.patchError) out.warn(`${plugins.patchPath} cannot be read: ${plugins.patchError}`);
9318
+ /** Parse one parameter value with a core schema, or throw a ParamError describing the first issue. */
9319
+ function parseWith(schema, value) {
9320
+ const result = schema.safeParse(value);
9321
+ if (result.success) return result.data;
9322
+ const [issue] = result.error.issues;
9323
+ throw new ParamError(issue ? describeIssue(issue) : "is invalid");
9330
9324
  }
9331
- const list$1 = command({
9332
- name: "list",
9333
- aliases: ["ls"],
9334
- summary: "List plugins",
9335
- params: {},
9336
- async run(_values, scope) {
9337
- return (await scope.services()).plugins.list();
9338
- },
9339
- render(plugins, out) {
9340
- warnFileErrors(out, plugins);
9341
- out.table([
9342
- "PLUGIN",
9343
- "ID",
9344
- "STATE",
9345
- "NOTE"
9346
- ], plugins.entries.map((entry) => [
9347
- entry.title,
9348
- entry.id,
9349
- stateOf(entry),
9350
- entry.locked ? lockedReason : ""
9351
- ]));
9352
- }
9325
+ //#endregion
9326
+ //#region src/core/harnesses/types.ts
9327
+ /**
9328
+ * A harness id, such as `opencode`. Harnesses are registered at runtime, so the set is open; stored applications of
9329
+ * a harness that is not registered are kept as they are.
9330
+ */
9331
+ const harnessId = string().regex(/^[a-z][a-z0-9-]{0,31}$/);
9332
+ //#endregion
9333
+ //#region src/core/provider.ts
9334
+ const providerName = string().trim().min(1, { error: "请填写名称" }).max(128, { error: "名称最多 128 个字符" });
9335
+ /**
9336
+ * An http(s) root address without a trailing slash. A trailing `/v1` or `/v1beta` is dropped: endpoints and
9337
+ * harness adapters append the version path themselves, so keeping it would double it.
9338
+ */
9339
+ const baseUrl = string().trim().pipe(url({
9340
+ protocol: /^https?$/,
9341
+ error: "请填写 http 或 https 地址"
9342
+ })).transform((value) => value.replace(/\/+$/, "").replace(/\/(v1|v1beta)$/, ""));
9343
+ /**
9344
+ * Where a provider's icon comes from: an image, or a web page whose declared icon is used. An empty value means
9345
+ * unset, in which case the icon of the Base URL's site is used.
9346
+ */
9347
+ const iconUrl = string().trim().max(2048, { error: "地址最多 2048 个字符" }).transform((value) => value || void 0).pipe(url({
9348
+ protocol: /^https?$/,
9349
+ error: "请填写 http 或 https 地址"
9350
+ }).optional());
9351
+ /** Input kinds a model accepts. Text is always accepted; the others are listed when supported. */
9352
+ const modelInputs = [
9353
+ "text",
9354
+ "image",
9355
+ "pdf"
9356
+ ];
9357
+ /** A native reasoning effort value, such as `low`, `xhigh` or `none`. */
9358
+ const reasoningEffort = string().regex(/^[A-Za-z0-9_-]{1,32}$/, { error: "推理等级只能包含字母、数字、- 和 _" });
9359
+ /**
9360
+ * How the model's API controls reasoning, in the models.dev format. Harness adapters translate these into their
9361
+ * own settings (Pi's `thinkingLevelMap`, OpenCode's `variants`); ohmyswitch stores them harness-neutral.
9362
+ * On a model, an empty list means reasoning cannot be controlled; an unset list means unknown.
9363
+ */
9364
+ const reasoningOption = discriminatedUnion("type", [
9365
+ object$1({
9366
+ type: literal("effort"),
9367
+ values: array(reasoningEffort).min(1).max(16)
9368
+ }),
9369
+ object$1({ type: literal("toggle") }),
9370
+ object$1({
9371
+ type: literal("budget_tokens"),
9372
+ min: number$1().int().nonnegative().optional(),
9373
+ max: number$1().int().positive().optional()
9374
+ })
9375
+ ]);
9376
+ /**
9377
+ * Whether reasoning must be sent back with later turns. `true` uses the protocol's own form; `field` names the
9378
+ * response field to echo, such as `reasoning_content` on OpenAI-compatible APIs.
9379
+ */
9380
+ const interleaved = union([literal(true), object$1({ field: string().regex(/^[a-z_]{1,64}$/) })]);
9381
+ const modelName = string().trim().max(256, { error: "名称最多 256 个字符" }).transform((value) => value || void 0);
9382
+ /**
9383
+ * A model and the metadata harness configs need. Every field but `id` is optional: unknown stays unset rather
9384
+ * than guessed, and harnesses fall back to their own defaults.
9385
+ */
9386
+ const modelInfo = object$1({
9387
+ id: string().min(1).max(256),
9388
+ name: modelName.optional(),
9389
+ contextWindow: number$1().int().positive().optional(),
9390
+ maxOutput: number$1().int().positive().optional(),
9391
+ reasoning: boolean().optional(),
9392
+ reasoningOptions: array(reasoningOption).max(8).optional(),
9393
+ interleaved: interleaved.optional(),
9394
+ input: array(_enum(modelInputs)).optional(),
9395
+ toolCall: boolean().optional()
9353
9396
  });
9354
- async function pluginChoices(scope) {
9355
- const { entries } = await (await scope.services()).plugins.list();
9356
- return entries.map((entry) => ({
9357
- value: entry,
9358
- keys: [
9359
- entry.id,
9360
- entry.title,
9361
- entry.name
9362
- ],
9363
- label: entry.title,
9364
- hint: stateOf(entry),
9365
- disabled: entry.locked ? lockedReason : void 0
9366
- }));
9397
+ /** Both override scopes are limited to display name and token limits. */
9398
+ const modelOverride = modelInfo.pick({
9399
+ name: true,
9400
+ contextWindow: true,
9401
+ maxOutput: true
9402
+ });
9403
+ /** Strip undefined fields so persisted overrides only carry explicit values. */
9404
+ function compactModelOverride(override) {
9405
+ const result = {};
9406
+ if (override.name !== void 0) result.name = override.name;
9407
+ if (override.contextWindow !== void 0) result.contextWindow = override.contextWindow;
9408
+ if (override.maxOutput !== void 0) result.maxOutput = override.maxOutput;
9409
+ return result;
9367
9410
  }
9368
- function switchCommand(enabled) {
9369
- return command({
9370
- name: enabled ? "enable" : "disable",
9371
- summary: `${enabled ? "Enable" : "Disable"} a plugin`,
9372
- params: { plugin: select$1({
9373
- summary: "Plugin",
9374
- positional: true,
9375
- placeholder: "plugin",
9376
- details: "Its id or name",
9377
- empty: "Every plugin is decided by plugins.patch.yml.",
9378
- choices: pluginChoices
9379
- }) },
9380
- async run({ plugin }, scope) {
9381
- const ctx = await scope.services();
9382
- const plugins = await ctx.plugins.list();
9383
- const broken = plugins.fileError ? plugins.path : plugins.patchError ? plugins.patchPath : void 0;
9384
- if (broken) throw new CliError("precondition_failed", `${broken} has errors; fix it first`);
9385
- await ctx.plugins.setEnabled(plugin.id, enabled);
9386
- return {
9387
- id: plugin.id,
9388
- title: plugin.title,
9389
- enabled
9390
- };
9391
- },
9392
- render(result, out) {
9393
- out.success(`${enabled ? "Enabled" : "Disabled"} ${result.title}.`);
9394
- }
9395
- });
9411
+ /** A provider as persisted. The API key is stored in plain text; harness configs hold it in plain text anyway. */
9412
+ const storedProvider = object$1({
9413
+ id: uuid(),
9414
+ name: providerName,
9415
+ /** The root address requests go to; endpoints are appended to it. */
9416
+ baseUrl,
9417
+ endpoint: _enum(endpoints),
9418
+ /**
9419
+ * The model vendor, shown as the badge on the provider's icon and compared by import links. Unset means the
9420
+ * badge follows the endpoint. It is display information: it is not written into harness configs.
9421
+ */
9422
+ vendor: _enum(vendors).optional(),
9423
+ apiKey: string(),
9424
+ /** An image or web page to take the icon from; unset uses the Base URL's site. */
9425
+ iconUrl: url({ protocol: /^https?$/ }).optional(),
9426
+ /** Metadata snapshots; discovery and models.dev sync never modify the separate overrides. */
9427
+ models: array(modelInfo),
9428
+ /** Kept when a model is deselected, so selecting it again restores its explicit settings. */
9429
+ modelOverrides: record$2(string().min(1).max(256), modelOverride).default({}),
9430
+ /**
9431
+ * The model ids the provider's model list held when the user last reviewed it. Models listed since are offered
9432
+ * as new, and saved models that were listed but no longer are offered for removal. Unset until the list is first
9433
+ * read; that first read only records it.
9434
+ */
9435
+ listedModels: array(string().min(1).max(256)).max(2e3).optional(),
9436
+ /**
9437
+ * Harnesses this provider is applied to, with the key ohmyswitch owns in each harness config. Entries of
9438
+ * harnesses that are not registered are kept, so the application survives until the harness is back.
9439
+ */
9440
+ harnesses: record$2(harnessId, object$1({ key: string().min(1).max(64) })).default({}),
9441
+ createdAt: datetime()
9442
+ });
9443
+ /** Apply explicit fields in order: snapshot → global → provider. */
9444
+ function effectiveModel(model, globalOverrides, providerOverrides = {}) {
9445
+ let result = model;
9446
+ for (const overrides of [globalOverrides, providerOverrides]) {
9447
+ const override = Object.hasOwn(overrides, model.id) ? overrides[model.id] : void 0;
9448
+ if (override) result = {
9449
+ ...result,
9450
+ ...compactModelOverride(override)
9451
+ };
9452
+ }
9453
+ return result;
9396
9454
  }
9397
- const plugin = group({
9398
- name: "plugin",
9399
- aliases: ["plugins"],
9400
- summary: "Enable or disable plugins",
9401
- children: [
9402
- list$1,
9403
- switchCommand(true),
9404
- switchCommand(false)
9405
- ]
9455
+ //#endregion
9456
+ //#region src/core/providers/schemas.ts
9457
+ const providerIdInput = object$1({ providerId: uuid() });
9458
+ /** The fields of a provider the editor saves together; they are not all connection details. */
9459
+ const connectionInput = object$1({
9460
+ name: providerName,
9461
+ baseUrl,
9462
+ apiKey: string().trim().min(1, { error: "请填写 API Key" }).max(4096),
9463
+ endpoint: _enum(endpoints, { error: "请选择端点" }),
9464
+ /** Unset follows the endpoint, which is also how an import link without one compares. */
9465
+ vendor: _enum(vendors).optional(),
9466
+ /** Unset or empty uses the icon of the Base URL's site. */
9467
+ iconUrl: iconUrl.optional()
9468
+ });
9469
+ const createProviderInput = connectionInput.extend({
9470
+ /** Models to start with, such as those an import link lists; their metadata is filled from models.dev. */
9471
+ modelIds: array(string().trim().min(1).max(256)).max(2e3).optional().transform((ids) => ids ? [...new Set(ids)] : void 0),
9472
+ /**
9473
+ * The provider's model list as fetched while adding it (`ProviderService.listModels`), recorded as reviewed. With
9474
+ * it, the models are the ids in `selected` and `modelIds` is not used.
9475
+ */
9476
+ listed: array(modelInfo).max(2e3).optional().transform((models) => models ? [...new Map(models.map((model) => [model.id, model])).values()] : void 0),
9477
+ selected: array(string().min(1).max(256)).max(2e3).optional().transform((ids) => ids ? [...new Set(ids)] : void 0)
9478
+ });
9479
+ const updateProviderInput = connectionInput.extend(providerIdInput.shape);
9480
+ object$1({ providerIds: array(uuid()).max(1e3).refine((ids) => new Set(ids).size === ids.length, { error: "供应商顺序中有重复项" }) });
9481
+ providerIdInput.extend({ models: array(modelInfo).max(2e3).transform((models) => [...new Map(models.map((model) => [model.id, model])).values()]) });
9482
+ const modelId$2 = string().min(1).max(256);
9483
+ const overrideModelId = string().trim().min(1, { error: "请填写模型 ID" }).max(256, { error: "模型 ID 最多 256 个字符" });
9484
+ const strictModelOverride = modelOverride.strict().transform(compactModelOverride);
9485
+ object$1({
9486
+ modelId: overrideModelId,
9487
+ override: strictModelOverride.refine((value) => Object.keys(value).length > 0, { error: "请至少填写一项覆盖信息" })
9488
+ });
9489
+ object$1({ modelId: modelId$2 });
9490
+ providerIdInput.extend({
9491
+ modelId: modelId$2,
9492
+ override: strictModelOverride
9493
+ });
9494
+ providerIdInput.extend({
9495
+ listed: array(modelInfo).max(2e3),
9496
+ selected: array(modelId$2).max(2e3).transform((ids) => [...new Set(ids)])
9406
9497
  });
9407
- //#endregion
9408
- //#region src/cli/framework/validate.ts
9409
- const unitOf = (origin) => {
9410
- if (origin === "string") return " characters";
9411
- if (origin === "array" || origin === "set") return " items";
9412
- return "";
9413
- };
9414
- /**
9415
- * An English description of a validation issue. Core schemas carry messages for the GUI; the CLI words its own
9416
- * from the issue code, so it reads the same in every command.
9417
- */
9418
- function describeIssue(issue) {
9419
- switch (issue.code) {
9420
- case "too_small":
9421
- if (issue.origin === "string" && Number(issue.minimum) <= 1) return "must not be empty";
9422
- return `must be at least ${issue.minimum}${unitOf(issue.origin)}`;
9423
- case "too_big": return `must be at most ${issue.maximum}${unitOf(issue.origin)}`;
9424
- case "invalid_format": return issue.format === "url" ? "must be an http or https URL" : `must be a valid ${issue.format}`;
9425
- case "invalid_type": return `must be ${issue.expected === "array" ? "a list" : `a ${issue.expected}`}`;
9426
- case "invalid_value": return `must be one of ${issue.values.map(String).join(", ")}`;
9427
- default: return "is invalid";
9428
- }
9429
- }
9430
- /** Parse one parameter value with a core schema, or throw a ParamError describing the first issue. */
9431
- function parseWith(schema, value) {
9432
- const result = schema.safeParse(value);
9433
- if (result.success) return result.data;
9434
- const [issue] = result.error.issues;
9435
- throw new ParamError(issue ? describeIssue(issue) : "is invalid");
9436
- }
9498
+ providerIdInput.extend({
9499
+ add: array(modelInfo).max(2e3),
9500
+ remove: array(modelId$2).max(2e3),
9501
+ listed: array(modelId$2).max(2e3).transform((ids) => [...new Set(ids)])
9502
+ });
9503
+ object$1({ candidates: array(object$1({ sources: array(object$1({
9504
+ harnessId,
9505
+ key: string().min(1).max(64)
9506
+ })).min(1).max(16) })).min(1, { error: "请选择要导入的供应商" }).max(200) });
9437
9507
  //#endregion
9438
9508
  //#region src/cli/commands/provider.ts
9439
9509
  const modelId$1 = string().trim().min(1).max(256);
@@ -9621,7 +9691,7 @@ const add$1 = command({
9621
9691
  vendor: values.vendor === "follow" ? void 0 : values.vendor,
9622
9692
  apiKey: values.apiKey,
9623
9693
  iconUrl: values.iconUrl,
9624
- ...fetched ? {
9694
+ ...fetched && (values.allModels || fetched.models.length > 0) ? {
9625
9695
  listed: fetched.models,
9626
9696
  selected: values.allModels ? fetched.models.map((model) => model.id) : values.models
9627
9697
  } : { modelIds: values.models }
@@ -9694,16 +9764,14 @@ const edit = command({
9694
9764
  throw new CliError("usage", "Nothing to change", "Pass --name, --base-url, --endpoint, --vendor, --icon-url, --api-key-stdin or --api-key-env.");
9695
9765
  }
9696
9766
  if (changes.name !== void 0) await assertNameFree(scope, changes.name, provider.id);
9697
- const current = ctx.providers.connection(provider.id);
9698
- const result = await ctx.providers.update(updateProviderInput.parse({
9699
- providerId: provider.id,
9700
- name: changes.name ?? current.name,
9701
- baseUrl: changes.baseUrl ?? current.baseUrl,
9702
- endpoint: changes.endpoint ?? current.endpoint,
9703
- vendor: changes.vendor === "follow" ? void 0 : changes.vendor ?? current.vendor,
9704
- apiKey: changes.apiKey ?? current.apiKey,
9705
- iconUrl: changes.iconUrl ?? current.iconUrl
9706
- }));
9767
+ const result = await ctx.providers.patchConnection(provider.id, {
9768
+ name: changes.name,
9769
+ baseUrl: changes.baseUrl,
9770
+ endpoint: changes.endpoint,
9771
+ vendor: changes.vendor === "follow" ? null : changes.vendor,
9772
+ apiKey: changes.apiKey,
9773
+ iconUrl: changes.iconUrl === "" ? null : changes.iconUrl
9774
+ });
9707
9775
  const harnesses = await harnessIndex(scope);
9708
9776
  const { harnessFailures, ...summary } = result;
9709
9777
  return {
@@ -9859,7 +9927,7 @@ function usageReport(sources, days, until) {
9859
9927
  for (const source of sources) {
9860
9928
  const seen = /* @__PURE__ */ new Set();
9861
9929
  for (const { time, model, tokens, identity } of source.records) {
9862
- if (!Number.isFinite(time) || time < lowerBound || time > until.getTime() || !tokens.total) continue;
9930
+ if (!Number.isFinite(time) || time <= 0 || time < lowerBound || time > until.getTime() || !tokens.total) continue;
9863
9931
  if (identity && seen.has(identity)) continue;
9864
9932
  if (identity) seen.add(identity);
9865
9933
  earliest = Math.min(earliest, time);
@@ -9886,7 +9954,7 @@ function usageReport(sources, days, until) {
9886
9954
  harnesses: Array.from(row.harnesses, ([name, totals]) => ({
9887
9955
  name,
9888
9956
  totals
9889
- })).sort((a, b) => b.totals.total - a.totals.total)
9957
+ })).sort((a, b) => b.totals.total - a.totals.total || a.name.localeCompare(b.name))
9890
9958
  })).sort((a, b) => b.totals.total - a.totals.total || (a.id ?? "").localeCompare(b.id ?? "")),
9891
9959
  incompleteSources: sources.filter((source) => source.incomplete).map((source) => source.name)
9892
9960
  };
@@ -10068,10 +10136,11 @@ function appDirs(home, env, platform) {
10068
10136
  function loadConfig() {
10069
10137
  const home = homedir();
10070
10138
  return {
10071
- version: "0.3.0",
10139
+ version: "0.3.1",
10072
10140
  dirs: appDirs(home, process.env, process.platform),
10073
10141
  home,
10074
- env: { ...process.env }
10142
+ env: { ...process.env },
10143
+ platform: process.platform
10075
10144
  };
10076
10145
  }
10077
10146
  //#endregion
@@ -10336,7 +10405,7 @@ async function execute(command, path, invocation, session) {
10336
10405
  values[key] = param.multiple ? [] : void 0;
10337
10406
  continue;
10338
10407
  }
10339
- values[key] = answer.value ?? (param.multiple ? [] : void 0);
10408
+ values[key] = answer.value === void 0 ? param.multiple ? [] : void 0 : answer.value;
10340
10409
  if (answer.value !== void 0) written.set(key, answer.raws);
10341
10410
  continue;
10342
10411
  }
@@ -14102,24 +14171,78 @@ function withOwnedFields(target, owned, values) {
14102
14171
  return result;
14103
14172
  }
14104
14173
  //#endregion
14174
+ //#region src/core/harnesses/usage/sqlite.ts
14175
+ const busyTimeoutMs = 1e3;
14176
+ const isMissing = (error) => error?.code === "ENOENT";
14177
+ async function fileSignature(path) {
14178
+ try {
14179
+ const info = await stat(path, { bigint: true });
14180
+ return [
14181
+ info.dev,
14182
+ info.ino,
14183
+ info.size,
14184
+ info.mtimeNs,
14185
+ info.ctimeNs
14186
+ ].join(":");
14187
+ } catch (error) {
14188
+ if (isMissing(error)) return void 0;
14189
+ throw error;
14190
+ }
14191
+ }
14192
+ /** Revision covering both the main SQLite file and its WAL sidecar, or undefined when the database does not exist. */
14193
+ async function databaseRevision(path) {
14194
+ const main = await fileSignature(path);
14195
+ if (!main) return void 0;
14196
+ const wal = await fileSignature(`${path}-wal`);
14197
+ return wal ? `${main}|${wal}` : main;
14198
+ }
14199
+ /** Lazy load SQLite so starting the CLI for unrelated commands never opens a database. */
14200
+ async function readDatabase(path, read) {
14201
+ if (!await fileSignature(path)) return void 0;
14202
+ const { DatabaseSync } = await import("node:sqlite");
14203
+ const db = new DatabaseSync(path, {
14204
+ readOnly: true,
14205
+ timeout: busyTimeoutMs
14206
+ });
14207
+ try {
14208
+ return read(db);
14209
+ } finally {
14210
+ db.close();
14211
+ }
14212
+ }
14213
+ //#endregion
14105
14214
  //#region src/core/harnesses/usage/files.ts
14215
+ const fileConcurrency = 8;
14106
14216
  const object = (value) => isJsonObject(value) ? value : {};
14107
14217
  const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
14108
14218
  const modelId = (value) => typeof value === "string" && value.length ? value : null;
14109
14219
  const missing = (error) => error?.code === "ENOENT";
14220
+ /** Parse a positive millisecond timestamp from a finite number or date string; invalid values return NaN. */
14221
+ function timestamp$1(value) {
14222
+ if (typeof value === "number") return Number.isFinite(value) && value > 0 ? value : NaN;
14223
+ if (typeof value === "string" && value.trim()) {
14224
+ const parsed = Date.parse(value);
14225
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : NaN;
14226
+ }
14227
+ return NaN;
14228
+ }
14110
14229
  /** Do not follow directory symlinks or discover a transcript outside the selected root. */
14111
- async function* walkFiles(dir) {
14230
+ async function* walkFiles(dir, onError) {
14112
14231
  let entries;
14113
14232
  try {
14114
14233
  entries = await readdir(dir, { withFileTypes: true });
14115
14234
  } catch (error) {
14116
14235
  if (missing(error)) return;
14236
+ if (onError) {
14237
+ onError(dir, error);
14238
+ return;
14239
+ }
14117
14240
  throw error;
14118
14241
  }
14119
14242
  for (const entry of entries) {
14120
14243
  const path = join(dir, entry.name);
14121
14244
  if (entry.isFile()) yield path;
14122
- else if (entry.isDirectory()) yield* walkFiles(path);
14245
+ else if (entry.isDirectory()) yield* walkFiles(path, onError);
14123
14246
  }
14124
14247
  }
14125
14248
  /** A complete corrupt row invalidates the file. A writer's incomplete last line can be retried on the next scan. */
@@ -14150,14 +14273,21 @@ async function readJsonLines(source, visit) {
14150
14273
  visit(object(row));
14151
14274
  }
14152
14275
  }
14153
- /** Cache counters only. A new scan retires files that disappeared and re-parses changed files in full. */
14276
+ /** Cache counters only. A new scan retires files that disappeared and re-parses changed sources in full. */
14154
14277
  var UsageScan = class {
14155
14278
  cache = /* @__PURE__ */ new Map();
14156
14279
  records = [];
14157
14280
  incomplete = false;
14158
14281
  previous;
14159
- constructor(previous) {
14282
+ onError;
14283
+ constructor(previous, onError) {
14160
14284
  this.previous = previous;
14285
+ this.onError = onError;
14286
+ }
14287
+ /** Mark this scan as incomplete and surface the failure to the caller's logger. */
14288
+ fail(source, error) {
14289
+ this.incomplete = true;
14290
+ this.onError?.(source, error);
14161
14291
  }
14162
14292
  async file(path, parse) {
14163
14293
  try {
@@ -14170,14 +14300,60 @@ var UsageScan = class {
14170
14300
  info.ctimeNs
14171
14301
  ].join(":");
14172
14302
  const existing = this.previous.get(path);
14173
- const entry = existing?.revision === revision ? existing : {
14174
- revision,
14175
- records: await parse(path)
14176
- };
14303
+ let entry;
14304
+ if (existing?.revision === revision) entry = existing;
14305
+ else {
14306
+ const parsed = await parse(path);
14307
+ entry = Array.isArray(parsed) ? {
14308
+ revision,
14309
+ records: parsed
14310
+ } : {
14311
+ revision,
14312
+ records: parsed.records,
14313
+ matched: parsed.matched
14314
+ };
14315
+ }
14316
+ this.cache.set(path, entry);
14317
+ for (const record of entry.records) this.records.push(record);
14318
+ return entry.matched ?? true;
14319
+ } catch (error) {
14320
+ if (!missing(error)) this.fail(path, error);
14321
+ return false;
14322
+ }
14323
+ }
14324
+ /** Parse many files with bounded concurrency; returns whether at least one matched this reader. */
14325
+ async files(paths, parse, concurrency = fileConcurrency) {
14326
+ let matched = false;
14327
+ let cursor = 0;
14328
+ const workers = Array.from({ length: Math.min(concurrency, paths.length) }, async () => {
14329
+ while (cursor < paths.length) {
14330
+ const path = paths[cursor++];
14331
+ if (await this.file(path, parse)) matched = true;
14332
+ }
14333
+ });
14334
+ await Promise.all(workers);
14335
+ return matched;
14336
+ }
14337
+ /** Read a SQLite database only when its main file or WAL sidecar changed since the previous scan. */
14338
+ async database(path, read) {
14339
+ try {
14340
+ const revision = await databaseRevision(path);
14341
+ if (!revision) return;
14342
+ const existing = this.previous.get(path);
14343
+ let entry;
14344
+ if (existing?.revision === revision) entry = existing;
14345
+ else {
14346
+ const records = await readDatabase(path, read);
14347
+ if (!records) return;
14348
+ entry = {
14349
+ revision,
14350
+ records
14351
+ };
14352
+ }
14177
14353
  this.cache.set(path, entry);
14178
14354
  for (const record of entry.records) this.records.push(record);
14179
14355
  } catch (error) {
14180
- if (!missing(error)) this.incomplete = true;
14356
+ if (!missing(error)) this.fail(path, error);
14181
14357
  }
14182
14358
  }
14183
14359
  };
@@ -14251,6 +14427,8 @@ async function writeFileAtomic(path, data, options = {}) {
14251
14427
  }
14252
14428
  //#endregion
14253
14429
  //#region src/core/file-lock.ts
14430
+ /** A malformed/empty lock (e.g. a crash between open and PID write) older than this can be reclaimed. */
14431
+ const staleMalformedLockMs = 3e4;
14254
14432
  /**
14255
14433
  * A cross-process writer lock compatible with DeepSeek Harness (`@deepseek-ai/dsh-atomic-write`'s `withFileLock`):
14256
14434
  * a sibling `<path>.lock` created exclusively, holding the holder's PID. A lock whose holder no longer exists is
@@ -14301,9 +14479,20 @@ function holderExited(record) {
14301
14479
  return error.code === "ESRCH";
14302
14480
  }
14303
14481
  }
14482
+ async function isStaleMalformedLock(lockPath, record) {
14483
+ if (/^\d+\n$/.test(record)) return false;
14484
+ try {
14485
+ return Date.now() - (await stat(lockPath)).mtimeMs >= staleMalformedLockMs;
14486
+ } catch {
14487
+ return false;
14488
+ }
14489
+ }
14490
+ async function canReclaim(lockPath, record) {
14491
+ return holderExited(record) || await isStaleMalformedLock(lockPath, record);
14492
+ }
14304
14493
  async function takeOverExitedLock(lockPath) {
14305
14494
  const record = await readLockRecord(lockPath);
14306
- if (record === void 0 || !holderExited(record)) return false;
14495
+ if (record === void 0 || !await canReclaim(lockPath, record)) return false;
14307
14496
  const claim = `${lockPath}.takeover-${createHash("sha256").update(record).digest("hex").slice(0, 16)}`;
14308
14497
  try {
14309
14498
  await writeFile(claim, `${process.pid}\n`, {
@@ -14315,7 +14504,7 @@ async function takeOverExitedLock(lockPath) {
14315
14504
  throw error;
14316
14505
  }
14317
14506
  try {
14318
- if (await readLockRecord(lockPath) !== record || !holderExited(record)) return false;
14507
+ if (await readLockRecord(lockPath) !== record || !await canReclaim(lockPath, record)) return false;
14319
14508
  await rm(lockPath, { force: true });
14320
14509
  return true;
14321
14510
  } finally {
@@ -14348,7 +14537,12 @@ var ConfigEditor = class {
14348
14537
  const next = change(text);
14349
14538
  if (next === void 0 || next === text) return;
14350
14539
  if (await readConfigText(file.path) !== text) throw new AppError("precondition_failed", `${harnessName} 的配置文件刚被修改,请重试`);
14351
- const mode = text === void 0 ? file.adapter.newFileMode : (await stat(file.path)).mode & 511;
14540
+ let mode = file.adapter.newFileMode;
14541
+ if (text !== void 0) try {
14542
+ mode = (await stat(file.path)).mode & 511;
14543
+ } catch (error) {
14544
+ throw new AppError("precondition_failed", `无法读取 ${file.path}`, { cause: error });
14545
+ }
14352
14546
  try {
14353
14547
  await writeFileAtomic(file.path, next, { mode });
14354
14548
  } catch (error) {
@@ -14358,9 +14552,18 @@ var ConfigEditor = class {
14358
14552
  const locked = async () => {
14359
14553
  if (!file.lockPath) return run();
14360
14554
  try {
14361
- return await withFileLock(file.lockPath, run);
14555
+ await mkdir(dirname(file.lockPath), { recursive: true });
14556
+ } catch (error) {
14557
+ throw new AppError("precondition_failed", `无法写入 ${file.path}`, { cause: error });
14558
+ }
14559
+ let started = false;
14560
+ try {
14561
+ return await withFileLock(file.lockPath, () => {
14562
+ started = true;
14563
+ return run();
14564
+ });
14362
14565
  } catch (error) {
14363
- if (error instanceof AppError) throw error;
14566
+ if (started || error instanceof AppError) throw error;
14364
14567
  throw new AppError("precondition_failed", `${harnessName} 正在写入 ${file.path},请稍后重试`, { cause: error });
14365
14568
  }
14366
14569
  };
@@ -14375,7 +14578,8 @@ const failureMessage = (error) => error instanceof AppError ? error.message : "
14375
14578
  const harnessOptions = object$1({
14376
14579
  /** Home directory used to locate harness configs. */
14377
14580
  home: string(),
14378
- env: record$2(string(), string().optional())
14581
+ env: record$2(string(), string().optional()),
14582
+ platform: custom((value) => typeof value === "string")
14379
14583
  });
14380
14584
  /**
14381
14585
  * The harnesses ohmyswitch can write to, registered by their plugins, and the applications of providers to them.
@@ -14384,11 +14588,13 @@ const harnessOptions = object$1({
14384
14588
  var HarnessService = class extends Service {
14385
14589
  static inject = ["store", "modelsDev"];
14386
14590
  static Config = harnessOptions;
14591
+ logger;
14387
14592
  environment;
14388
14593
  editor = new ConfigEditor();
14389
14594
  registrations = /* @__PURE__ */ new Map();
14390
14595
  constructor(ctx, options) {
14391
14596
  super(ctx, "harnesses");
14597
+ this.logger = ctx.logger("harnesses");
14392
14598
  this.environment = options;
14393
14599
  }
14394
14600
  /**
@@ -14401,7 +14607,8 @@ var HarnessService = class extends Service {
14401
14607
  const registration = {
14402
14608
  harness,
14403
14609
  running: /* @__PURE__ */ new Set(),
14404
- usageCache: /* @__PURE__ */ new Map()
14610
+ usageCache: /* @__PURE__ */ new Map(),
14611
+ applyQueue: Promise.resolve()
14405
14612
  };
14406
14613
  return this.ctx.effect(() => {
14407
14614
  this.registrations.set(harness.id, registration);
@@ -14412,8 +14619,13 @@ var HarnessService = class extends Service {
14412
14619
  }, `ctx.harnesses.register(${JSON.stringify(harness.id)})`);
14413
14620
  }
14414
14621
  async usage(days) {
14415
- const until = /* @__PURE__ */ new Date();
14416
- return usageReport(await Promise.all([...this.registrations.values()].map((registration) => this.track(registration.harness.id, async (harness) => {
14622
+ return usageReport(await Promise.all(this.harnesses().map((descriptor) => this.track(descriptor.id, async (harness) => {
14623
+ const registration = this.registrations.get(harness.id);
14624
+ if (!registration) return {
14625
+ name: harness.name,
14626
+ records: [],
14627
+ incomplete: false
14628
+ };
14417
14629
  registration.readingUsage ??= this.scanUsage(registration).finally(() => {
14418
14630
  registration.readingUsage = void 0;
14419
14631
  });
@@ -14423,16 +14635,20 @@ var HarnessService = class extends Service {
14423
14635
  records: scan.records,
14424
14636
  incomplete: scan.incomplete
14425
14637
  };
14426
- }))), days, until);
14638
+ }))), days, /* @__PURE__ */ new Date());
14427
14639
  }
14428
14640
  async scanUsage(registration) {
14429
- const scan = new UsageScan(registration.usageCache);
14641
+ const scan = new UsageScan(registration.usageCache, (source, error) => {
14642
+ this.logger.warn(`Failed to read ${registration.harness.id} usage from ${source}`, error);
14643
+ });
14644
+ let crashed = false;
14430
14645
  try {
14431
14646
  await registration.harness.readUsage?.(this.environment, scan);
14432
- } catch {
14433
- scan.incomplete = true;
14647
+ } catch (error) {
14648
+ crashed = true;
14649
+ scan.fail(registration.harness.id, error);
14434
14650
  }
14435
- registration.usageCache = scan.cache;
14651
+ if (!crashed || scan.cache.size > 0) registration.usageCache = scan.cache;
14436
14652
  return scan;
14437
14653
  }
14438
14654
  /** Each harness, whether it is present on this machine, where its config is, and which endpoints it cannot serve. */
@@ -14491,9 +14707,16 @@ var HarnessService = class extends Service {
14491
14707
  * file already has an entry with that key that ohmyswitch does not own, `replace` must confirm taking it over.
14492
14708
  */
14493
14709
  apply(providerId, harnessId, replace) {
14494
- return this.track(harnessId, (harness) => this.applyTo(providerId, harness, replace));
14710
+ return this.track(harnessId, (harness) => {
14711
+ const registration = this.registrations.get(harnessId);
14712
+ if (!registration) return Promise.reject(new AppError("not_found", "不支持这个 Harness"));
14713
+ const run = registration.applyQueue.then(() => this.applyTo(providerId, harness, replace));
14714
+ registration.applyQueue = run.catch(() => {});
14715
+ return run;
14716
+ });
14495
14717
  }
14496
14718
  async applyTo(providerId, harness, replace) {
14719
+ await this.ctx.store.refresh();
14497
14720
  const harnessId = harness.id;
14498
14721
  const provider = this.effective(this.provider(providerId));
14499
14722
  if (!await isDirectory(harness.homeDir(this.environment))) throw new AppError("precondition_failed", `未发现 ${harness.name}`);
@@ -15305,6 +15528,7 @@ function push(map, key, entry) {
15305
15528
  //#endregion
15306
15529
  //#region src/core/models-dev/service.ts
15307
15530
  const maxAgeMs = 36e5;
15531
+ const retryAfterFailureMs = 6e5;
15308
15532
  const maxBytes = 33554432;
15309
15533
  const cacheFile = object$1({
15310
15534
  /** Bumped whenever the reduced entry shape changes, so older caches are downloaded again. */
@@ -15316,8 +15540,8 @@ const modelsDevOptions = object$1({
15316
15540
  /** Where the reduced catalog is cached between runs. */
15317
15541
  cachePath: string() });
15318
15542
  /**
15319
- * The models.dev catalog, reduced and cached on disk for a day. When a refresh fails, a stale copy is used;
15320
- * only a failure with no copy at all is an error.
15543
+ * The models.dev catalog, reduced and cached on disk for an hour. When a refresh fails, a stale copy is used with a
15544
+ * backoff window; only a failure with no copy at all is an error.
15321
15545
  */
15322
15546
  var ModelsDevService = class extends Service {
15323
15547
  static inject = ["http"];
@@ -15326,6 +15550,7 @@ var ModelsDevService = class extends Service {
15326
15550
  path;
15327
15551
  snapshot;
15328
15552
  loadedFromDisk = false;
15553
+ failedAt;
15329
15554
  pending;
15330
15555
  constructor(ctx, options) {
15331
15556
  super(ctx, "modelsDev");
@@ -15343,10 +15568,13 @@ var ModelsDevService = class extends Service {
15343
15568
  this.loadedFromDisk = true;
15344
15569
  this.snapshot ??= await this.readCache();
15345
15570
  }
15346
- if (this.snapshot && Date.now() - this.snapshot.fetchedAt < maxAgeMs) return this.snapshot.index;
15571
+ const now = Date.now();
15572
+ if (this.snapshot && now - this.snapshot.fetchedAt < maxAgeMs) return this.snapshot.index;
15573
+ if (this.snapshot && this.failedAt !== void 0 && now - this.failedAt < retryAfterFailureMs) return this.snapshot.index;
15347
15574
  try {
15348
15575
  const entries = await this.download();
15349
15576
  const fetchedAt = /* @__PURE__ */ new Date();
15577
+ this.failedAt = void 0;
15350
15578
  this.snapshot = {
15351
15579
  fetchedAt: fetchedAt.getTime(),
15352
15580
  index: new ModelsDevIndex(entries)
@@ -15360,6 +15588,7 @@ var ModelsDevService = class extends Service {
15360
15588
  return this.snapshot.index;
15361
15589
  } catch (error) {
15362
15590
  if (this.snapshot) {
15591
+ this.failedAt = Date.now();
15363
15592
  this.logger.warn("Failed to refresh models.dev, using the cached copy", error);
15364
15593
  return this.snapshot.index;
15365
15594
  }
@@ -22314,10 +22543,11 @@ function dshReasoningEfforts(model) {
22314
22543
  if (model.reasoning !== true) return void 0;
22315
22544
  const options = model.reasoningOptions;
22316
22545
  const fixed = { high: "high" };
22317
- if (!options || options.length && options.every((option) => option.type === "budget_tokens")) return {
22546
+ const defaults = {
22318
22547
  off: null,
22319
22548
  ...Object.fromEntries(graded$1.map((level) => [level, level]))
22320
22549
  };
22550
+ if (!options) return defaults;
22321
22551
  const efforts = options.find((option) => option.type === "effort")?.values;
22322
22552
  const hasToggle = options.some((option) => option.type === "toggle");
22323
22553
  if (efforts) {
@@ -22328,6 +22558,7 @@ function dshReasoningEfforts(model) {
22328
22558
  ...Object.fromEntries(offered.map((level) => [level, level]))
22329
22559
  };
22330
22560
  }
22561
+ if (options.some((option) => option.type === "budget_tokens")) return defaults;
22331
22562
  if (hasToggle) return {
22332
22563
  off: null,
22333
22564
  ...fixed
@@ -22349,7 +22580,7 @@ function dshModel(model, api, existing) {
22349
22580
  const input = model.input?.filter((kind) => kind === "text" || kind === "image");
22350
22581
  const target = withOwnedFields(existing, ownedModelFields$2, {
22351
22582
  id: model.id,
22352
- name: model.name,
22583
+ name: model.name || void 0,
22353
22584
  contextWindow: model.contextWindow,
22354
22585
  maxTokens: model.maxOutput,
22355
22586
  input: input?.length ? input : void 0,
@@ -22455,10 +22686,22 @@ const dshCredentialsAdapter = {
22455
22686
  //#endregion
22456
22687
  //#region src/core/harness-dsh/zstd.ts
22457
22688
  const decompress = promisify(zstdDecompress);
22689
+ const zstdMagic = 4247762216;
22690
+ const skippableMagicMask = 4294967280;
22691
+ const skippableMagicBase = 407710288;
22458
22692
  /** DSH appends a standard Zstandard frame per batch. Walk RFC 8878 block lengths, independent of payload bytes. */
22459
- function frameEnd(bytes, start) {
22693
+ function nextFrame(bytes, start) {
22460
22694
  if (bytes.length - start < 4) return void 0;
22461
- if (bytes.readUInt32LE(start) !== 4247762216) throw new Error("Invalid DSH frame magic");
22695
+ const magic = bytes.readUInt32LE(start);
22696
+ if ((magic & skippableMagicMask) === skippableMagicBase) {
22697
+ if (bytes.length - start < 8) return void 0;
22698
+ const end = start + 8 + bytes.readUInt32LE(start + 4);
22699
+ return end <= bytes.length ? {
22700
+ end,
22701
+ skippable: true
22702
+ } : void 0;
22703
+ }
22704
+ if (magic !== zstdMagic) throw new Error("Invalid DSH frame magic");
22462
22705
  if (bytes.length - start < 5) return void 0;
22463
22706
  const header = bytes.readUInt8(start + 4);
22464
22707
  if ((header & 24) !== 0) throw new Error("Invalid DSH frame descriptor");
@@ -22473,9 +22716,13 @@ function frameEnd(bytes, start) {
22473
22716
  const kind = block >>> 1 & 3;
22474
22717
  if (kind === 3) throw new Error("Invalid DSH block type");
22475
22718
  offset += 3 + (kind === 1 ? 1 : block >>> 3);
22719
+ if (offset > bytes.length) return void 0;
22476
22720
  if (block & 1) {
22477
22721
  const end = offset + (header & 4 ? 4 : 0);
22478
- return end <= bytes.length ? end : void 0;
22722
+ return end <= bytes.length ? {
22723
+ end,
22724
+ skippable: false
22725
+ } : void 0;
22479
22726
  }
22480
22727
  }
22481
22728
  }
@@ -22484,14 +22731,14 @@ async function* readSessionFrames(path) {
22484
22731
  const bytes = await readFile(path);
22485
22732
  let offset = 0;
22486
22733
  while (offset < bytes.length) {
22487
- const end = frameEnd(bytes, offset);
22488
- if (end === void 0) {
22734
+ const frame = nextFrame(bytes, offset);
22735
+ if (!frame) {
22489
22736
  const tail = await decompress(bytes.subarray(offset), { finishFlush: constants$1.ZSTD_e_flush });
22490
22737
  yield tail.subarray(0, tail.lastIndexOf(10) + 1);
22491
22738
  return;
22492
22739
  }
22493
- yield await decompress(bytes.subarray(offset, end));
22494
- offset = end;
22740
+ if (!frame.skippable) yield await decompress(bytes.subarray(offset, frame.end));
22741
+ offset = frame.end;
22495
22742
  }
22496
22743
  }
22497
22744
  //#endregion
@@ -22513,7 +22760,8 @@ async function sessionUsage(path) {
22513
22760
  if (event.type === "request/header") route = modelId(object(object(data.header).config).model) ?? route;
22514
22761
  if (event.type === "session/end-seed" && data.inherited === true) inherited = false;
22515
22762
  if (inherited || typeof event.seq === "number" && event.seq < seedLength) return;
22516
- if (event.type === "llm/retry-started" && last && last.turn === data.turn && last.step === data.step) last = void 0;
22763
+ const hasStep = data.turn !== void 0 && data.step !== void 0;
22764
+ if (event.type === "llm/retry-started" && hasStep && last && last.turn === data.turn && last.step === data.step) last = void 0;
22517
22765
  let sample = data.usage;
22518
22766
  let model = route;
22519
22767
  switch (event.type) {
@@ -22544,7 +22792,7 @@ async function sessionUsage(path) {
22544
22792
  const cacheWrite = count(usage.cacheWriteTokens);
22545
22793
  const total = count(usage.totalTokens) || input + output + cacheRead + cacheWrite;
22546
22794
  const record = {
22547
- time: Number(event.time),
22795
+ time: timestamp$1(event.time),
22548
22796
  model,
22549
22797
  tokens: {
22550
22798
  input,
@@ -22554,8 +22802,10 @@ async function sessionUsage(path) {
22554
22802
  total
22555
22803
  }
22556
22804
  };
22557
- if (event.type === "compaction/summary") records.push(record);
22558
- else if (last && last.turn === data.turn && last.step === data.step) records[last.index] = record;
22805
+ if (event.type === "compaction/summary" || !hasStep) {
22806
+ last = void 0;
22807
+ records.push(record);
22808
+ } else if (last && last.turn === data.turn && last.step === data.step) records[last.index] = record;
22559
22809
  else {
22560
22810
  last = {
22561
22811
  turn: data.turn,
@@ -22567,20 +22817,42 @@ async function sessionUsage(path) {
22567
22817
  });
22568
22818
  return records;
22569
22819
  }
22820
+ async function fileMtimeNs(path) {
22821
+ try {
22822
+ return (await stat(path, { bigint: true })).mtimeNs;
22823
+ } catch {
22824
+ return -1n;
22825
+ }
22826
+ }
22570
22827
  async function readDshUsage(home, scan) {
22571
22828
  const files = /* @__PURE__ */ new Map();
22572
- for await (const path of walkFiles(join(home, "sessions"))) {
22573
- const match = /^session(?:\.v(\d+))?\.jsonl(?:\.zstd)?$/.exec(basename(path));
22829
+ for await (const path of walkFiles(join(home, "sessions"), (dir, error) => scan.fail(dir, error))) {
22830
+ const match = /^session(?:\.v(\d+))?\.jsonl(\.zstd)?$/.exec(basename(path));
22574
22831
  if (!match) continue;
22575
22832
  const dir = dirname(path);
22576
22833
  const version = Number(match[1] ?? 0);
22834
+ const compressed = Boolean(match[2]);
22577
22835
  const current = files.get(dir);
22578
- if (!current || current.version < version) files.set(dir, {
22836
+ if (current && current.version > version) continue;
22837
+ if (!current || current.version < version) {
22838
+ files.set(dir, {
22839
+ version,
22840
+ compressed,
22841
+ mtimeNs: -1n,
22842
+ path
22843
+ });
22844
+ continue;
22845
+ }
22846
+ const [currentMtime, candidateMtime] = await Promise.all([current.mtimeNs >= 0n ? current.mtimeNs : fileMtimeNs(current.path), fileMtimeNs(path)]);
22847
+ current.mtimeNs = currentMtime;
22848
+ if (candidateMtime > currentMtime || candidateMtime === currentMtime && current.compressed && !compressed) files.set(dir, {
22579
22849
  version,
22850
+ compressed,
22851
+ mtimeNs: candidateMtime,
22580
22852
  path
22581
22853
  });
22582
22854
  }
22583
- for (const { path } of files.values()) await scan.file(path, sessionUsage);
22855
+ await scan.files([...files.values()].map((file) => file.path), sessionUsage);
22584
22856
  }
22585
22857
  //#endregion
22586
22858
  //#region src/core/harness-dsh/descriptor.ts
@@ -23002,35 +23274,15 @@ const ompAdapter = {
23002
23274
  newFileMode: 384
23003
23275
  };
23004
23276
  //#endregion
23005
- //#region src/core/harnesses/usage/sqlite.ts
23006
- /** Lazy load SQLite so starting the CLI for unrelated commands never opens a database. */
23007
- async function readDatabase(path, read) {
23008
- try {
23009
- await access(path);
23010
- } catch (error) {
23011
- if (missing(error)) return;
23012
- throw error;
23013
- }
23014
- const { DatabaseSync } = await import("node:sqlite");
23015
- const db = new DatabaseSync(path, { readOnly: true });
23016
- try {
23017
- read(db);
23018
- } finally {
23019
- db.close();
23020
- }
23021
- }
23022
- //#endregion
23023
23277
  //#region src/core/harnesses/usage/transcript.ts
23024
- /** Pi and omp share the assistant envelope but have different auxiliary usage entries. */
23025
- async function readTranscript(path, harness, sharedDirectory = false) {
23278
+ /** Read a JSONL session transcript according to the given dialect. */
23279
+ async function readTranscript(path, dialect, sharedDirectory = false) {
23026
23280
  const records = [];
23027
- let ompSession = false;
23281
+ let sawMarker = false;
23028
23282
  await readJsonLines(path, (entry) => {
23029
- if (entry.type === "title" || entry.runtime || entry.type === "model_usage") ompSession = true;
23283
+ if (dialect.detectSessionMarker?.(entry)) sawMarker = true;
23030
23284
  const message = object(entry.message);
23031
- const assistant = entry.type === "message" && message.role === "assistant";
23032
- const auxiliary = harness === "omp" ? entry.type === "model_usage" : entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "message" && message.role === "toolResult";
23033
- if (!assistant && !auxiliary) return;
23285
+ if (!(entry.type === "message" && message.role === "assistant") && !dialect.isAuxiliary(entry, message)) return;
23034
23286
  const payload = entry.type === "message" ? message : entry;
23035
23287
  if (!payload.usage) return;
23036
23288
  const usage = object(payload.usage);
@@ -23038,13 +23290,11 @@ async function readTranscript(path, harness, sharedDirectory = false) {
23038
23290
  const output = count(usage.output);
23039
23291
  const cacheRead = count(usage.cacheRead);
23040
23292
  const cacheWrite = count(usage.cacheWrite);
23041
- const orchestration = object(usage.orchestration);
23042
- const sum = input + output + cacheRead + cacheWrite;
23043
- const total = harness === "omp" ? count(usage.totalTokens) || sum + count(orchestration.input) + count(orchestration.output) + count(orchestration.cacheRead) : sum || count(usage.totalTokens);
23293
+ const total = dialect.totalTokens(usage, input + output + cacheRead + cacheWrite);
23044
23294
  if (!total) return;
23045
- const entryTime = typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : NaN;
23046
- const messageTime = typeof payload.timestamp === "number" ? payload.timestamp : NaN;
23047
- const time = harness === "omp" && Number.isFinite(messageTime) ? messageTime : Number.isFinite(entryTime) ? entryTime : messageTime;
23295
+ const entryTime = timestamp$1(entry.timestamp);
23296
+ const messageTime = timestamp$1(payload.timestamp);
23297
+ const time = dialect.preferMessageTimestamp && Number.isFinite(messageTime) ? messageTime : Number.isFinite(entryTime) ? entryTime : messageTime;
23048
23298
  const model = modelId(payload.responseModel) ?? modelId(payload.model);
23049
23299
  const identity = typeof entry.id === "string" ? JSON.stringify([entry.id, time]) : createHash("sha256").update(JSON.stringify(entry)).digest("hex");
23050
23300
  records.push({
@@ -23060,22 +23310,38 @@ async function readTranscript(path, harness, sharedDirectory = false) {
23060
23310
  }
23061
23311
  });
23062
23312
  });
23063
- if (sharedDirectory && ompSession !== (harness === "omp")) return [];
23064
- return records;
23313
+ return !sharedDirectory || (dialect.acceptSession?.(sawMarker) ?? true) ? {
23314
+ records,
23315
+ matched: true
23316
+ } : {
23317
+ records: [],
23318
+ matched: false
23319
+ };
23065
23320
  }
23066
23321
  //#endregion
23067
23322
  //#region src/core/harness-omp/usage.ts
23323
+ const ompDialect = {
23324
+ isAuxiliary: (entry) => entry.type === "model_usage",
23325
+ totalTokens: (usage, sum) => {
23326
+ const orchestration = object(usage.orchestration);
23327
+ return count(usage.totalTokens) || sum + count(orchestration.input) + count(orchestration.output) + count(orchestration.cacheRead);
23328
+ },
23329
+ preferMessageTimestamp: true,
23330
+ detectSessionMarker: (entry) => entry.type === "title" || Boolean(entry.runtime) || entry.type === "model_usage",
23331
+ acceptSession: (sawMarker) => sawMarker
23332
+ };
23068
23333
  async function readOmpProfile(sessions, profile, shared, scan) {
23069
- let found = false;
23070
- for await (const path of walkFiles(sessions)) {
23334
+ const paths = [];
23335
+ for await (const path of walkFiles(sessions, (dir, error) => scan.fail(dir, error))) {
23071
23336
  if (!path.endsWith(".jsonl") || relative(sessions, path).split(sep).some((part) => part.startsWith(".omp-gc-compress-"))) continue;
23072
- found = true;
23073
- await scan.file(path, (file) => readTranscript(file, "omp", shared));
23074
- }
23075
- if (found) return;
23076
- await readDatabase(join(profile, "stats.db"), (db) => {
23077
- for (const row of db.prepare("SELECT entry_id,timestamp,model,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,total_tokens FROM messages").iterate()) scan.records.push({
23078
- time: Number(row.timestamp),
23337
+ paths.push(path);
23338
+ }
23339
+ if (await scan.files(paths, (file) => readTranscript(file, ompDialect, shared))) return;
23340
+ await scan.database(join(profile, "stats.db"), (db) => {
23341
+ if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='messages'").get()) return [];
23342
+ const records = [];
23343
+ for (const row of db.prepare("SELECT entry_id,timestamp,model,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,total_tokens FROM messages").iterate()) records.push({
23344
+ time: timestamp$1(row.timestamp),
23079
23345
  identity: JSON.stringify([row.entry_id, row.timestamp]),
23080
23346
  model: modelId(row.model),
23081
23347
  tokens: {
@@ -23086,8 +23352,32 @@ async function readOmpProfile(sessions, profile, shared, scan) {
23086
23352
  total: count(row.total_tokens)
23087
23353
  }
23088
23354
  });
23355
+ return records;
23089
23356
  });
23090
23357
  }
23358
+ async function readOmpUsage(environment, scan, layout) {
23359
+ const { root, main, profileName } = layout;
23360
+ const xdg = environment.env.XDG_DATA_HOME;
23361
+ const xdgRoot = xdg && isAbsolute(xdg) && environment.platform !== "win32" ? join(xdg, "omp") : void 0;
23362
+ const profiles = /* @__PURE__ */ new Set();
23363
+ for (const base of [root, xdgRoot]) {
23364
+ if (!base) continue;
23365
+ const profilesDir = join(base, "profiles");
23366
+ try {
23367
+ for (const entry of await readdir(profilesDir, { withFileTypes: true })) if (entry.isDirectory() && profileName.test(entry.name) && !entry.name.endsWith(".")) profiles.add(entry.name);
23368
+ } catch (error) {
23369
+ if (!missing(error)) scan.fail(profilesDir, error);
23370
+ }
23371
+ }
23372
+ for (const name of [null, ...[...profiles].sort()]) {
23373
+ const profile = name ? join(root, "profiles", name) : root;
23374
+ const agent = name ? join(profile, "agent") : main;
23375
+ const shared = !name && isAbsolute(environment.env.PI_CODING_AGENT_DIR ?? "");
23376
+ const xdgProfile = xdgRoot && (name ? join(xdgRoot, "profiles", name) : xdgRoot);
23377
+ const useXdg = agent === join(profile, "agent") && xdgProfile && await isDirectory(xdgProfile);
23378
+ await readOmpProfile(join(useXdg ? xdgProfile : agent, "sessions"), useXdg ? xdgProfile : profile, shared && !useXdg, scan);
23379
+ }
23380
+ }
23091
23381
  //#endregion
23092
23382
  //#region src/core/harness-omp/descriptor.ts
23093
23383
  /** omp's config root: `PI_CONFIG_DIR` (default `.omp`), always under the home directory. */
@@ -23132,33 +23422,11 @@ const OmpHarnessPlugin = harnessPlugin({
23132
23422
  name: "omp",
23133
23423
  homepage: "https://omp.sh",
23134
23424
  homeDir: configRoot,
23135
- async readUsage(environment, scan) {
23136
- const root = configRoot(environment);
23137
- const main = defaultAgentDir(environment);
23138
- const xdg = environment.env.XDG_DATA_HOME;
23139
- const xdgRoot = xdg && isAbsolute(xdg) && process.platform !== "win32" ? join(xdg, "omp") : void 0;
23140
- const profiles = /* @__PURE__ */ new Set();
23141
- for (const base of [root, xdgRoot]) {
23142
- if (!base) continue;
23143
- try {
23144
- for (const entry of await readdir(join(base, "profiles"), { withFileTypes: true })) if (entry.isDirectory() && profileName.test(entry.name) && !entry.name.endsWith(".")) profiles.add(entry.name);
23145
- } catch (error) {
23146
- if (error.code !== "ENOENT") throw error;
23147
- }
23148
- }
23149
- for (const name of [null, ...profiles]) {
23150
- const profile = name ? join(root, "profiles", name) : root;
23151
- const agent = name ? join(profile, "agent") : main;
23152
- const shared = !name && isAbsolute(environment.env.PI_CODING_AGENT_DIR ?? "");
23153
- const xdgProfile = xdgRoot && (name ? join(xdgRoot, "profiles", name) : xdgRoot);
23154
- const useXdg = agent === join(profile, "agent") && xdgProfile && await isDirectory(xdgProfile);
23155
- try {
23156
- await readOmpProfile(join(useXdg ? xdgProfile : agent, "sessions"), useXdg ? xdgProfile : profile, shared && !useXdg, scan);
23157
- } catch {
23158
- scan.incomplete = true;
23159
- }
23160
- }
23161
- },
23425
+ readUsage: (environment, scan) => readOmpUsage(environment, scan, {
23426
+ root: configRoot(environment),
23427
+ main: defaultAgentDir(environment),
23428
+ profileName
23429
+ }),
23162
23430
  async configFiles(environment) {
23163
23431
  const agentDirs = await profileAgentDirs(configRoot(environment));
23164
23432
  const main = defaultAgentDir(environment);
@@ -23202,11 +23470,11 @@ function budgets(model, option, spell, ceiling = output(model)) {
23202
23470
  return [variant("high", spell(high)), variant("max", spell(maximum))];
23203
23471
  }
23204
23472
  function claudeInfo(model) {
23205
- const familyFirst = /(?:claude-)?(opus|sonnet|haiku|fable|mythos)-(\d+)(?:[.-](\d+))?/i.exec(model.id);
23206
- const versionFirst = /claude-(\d+)(?:[.-](\d+))?-(opus|sonnet|haiku|fable|mythos)/i.exec(model.id);
23207
- const family = (familyFirst?.[1] ?? versionFirst?.[3])?.toLowerCase();
23208
- const major = Number(familyFirst?.[2] ?? versionFirst?.[1]);
23209
- const minor = Number(familyFirst?.[3] ?? versionFirst?.[2] ?? 0);
23473
+ const versionFirst = /claude-(\d{1,2})(?:[.-](\d{1,2}))?(?!\d)-(opus|sonnet|haiku|fable|mythos)(?![a-z])/i.exec(model.id);
23474
+ const familyFirst = /(?:claude-)?(opus|sonnet|haiku|fable|mythos)-(\d{1,2})(?!\d)(?:[.-](\d{1,2})(?!\d))?/i.exec(model.id);
23475
+ const family = (versionFirst ? versionFirst[3] : familyFirst?.[1])?.toLowerCase();
23476
+ const major = Number(versionFirst ? versionFirst[1] : familyFirst?.[2]);
23477
+ const minor = Number((versionFirst ? versionFirst[2] : familyFirst?.[3]) ?? 0);
23210
23478
  return {
23211
23479
  family,
23212
23480
  major,
@@ -23388,7 +23656,7 @@ function openCodeModel(model, protocol, existing) {
23388
23656
  "compatibility",
23389
23657
  "variants"
23390
23658
  ], {
23391
- name: model.name,
23659
+ name: model.name || void 0,
23392
23660
  capabilities: nonEmpty(capabilities),
23393
23661
  limit: nonEmpty(limit),
23394
23662
  compatibility: nonEmpty(compatibility),
@@ -23520,22 +23788,25 @@ const auxiliaryEvents = `
23520
23788
  async function readOpenCodeUsage({ home, env }, scan) {
23521
23789
  if (env.OPENCODE_DB === ":memory:") return;
23522
23790
  const data = join(resolveDirOverride(home, env.XDG_DATA_HOME) ?? join(home, ".local", "share"), "opencode");
23523
- await readDatabase(resolve(data, env.OPENCODE_DB || "opencode.db"), (db) => {
23791
+ const dbPath = env.OPENCODE_DB ? resolve(data, resolveDirOverride(home, env.OPENCODE_DB) ?? env.OPENCODE_DB) : join(data, "opencode.db");
23792
+ await scan.database(dbPath, (db) => {
23524
23793
  const tables = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map((row) => row.name));
23525
23794
  const v2 = tables.has("session_v2") && tables.has("session_message");
23526
- const sources = v2 ? [messages] : [legacyMessages];
23795
+ const sources = v2 ? [messages] : tables.has("message") ? [legacyMessages] : [];
23796
+ if (!sources.length) return [];
23527
23797
  if (v2 && tables.has("event")) sources.push(auxiliaryEvents);
23528
23798
  const query = db.prepare(`WITH usage(time, model, tokens) AS (${sources.join(" UNION ALL ")})
23529
23799
  SELECT time, model, json_extract(tokens,'$.input') AS input, json_extract(tokens,'$.output') AS output,
23530
23800
  json_extract(tokens,'$.reasoning') AS reasoning, json_extract(tokens,'$.cache.read') AS cacheRead,
23531
23801
  json_extract(tokens,'$.cache.write') AS cacheWrite FROM usage WHERE tokens IS NOT NULL`);
23802
+ const records = [];
23532
23803
  for (const row of query.iterate()) {
23533
23804
  const input = count(row.input);
23534
23805
  const output = count(row.output) + count(row.reasoning);
23535
23806
  const cacheRead = count(row.cacheRead);
23536
23807
  const cacheWrite = count(row.cacheWrite);
23537
- scan.records.push({
23538
- time: Number(row.time),
23808
+ records.push({
23809
+ time: timestamp$1(row.time),
23539
23810
  model: modelId(row.model),
23540
23811
  tokens: {
23541
23812
  input,
@@ -23546,6 +23817,7 @@ async function readOpenCodeUsage({ home, env }, scan) {
23546
23817
  }
23547
23818
  });
23548
23819
  }
23820
+ return records;
23549
23821
  });
23550
23822
  }
23551
23823
  //#endregion
@@ -23699,7 +23971,7 @@ function piModel(model, api, existing) {
23699
23971
  const input = model.input?.filter((kind) => kind === "text" || kind === "image");
23700
23972
  const target = withOwnedFields(existing, ownedModelFields, {
23701
23973
  id: model.id,
23702
- name: model.name,
23974
+ name: model.name || void 0,
23703
23975
  reasoning: model.reasoning,
23704
23976
  thinkingLevelMap: piThinkingLevelMap(model),
23705
23977
  input: input?.length ? input : void 0,
@@ -23828,15 +24100,28 @@ const piAdapter = {
23828
24100
  };
23829
24101
  //#endregion
23830
24102
  //#region src/core/harness-pi/usage.ts
24103
+ const piDialect = {
24104
+ isAuxiliary: (entry, message) => entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "message" && message.role === "toolResult",
24105
+ totalTokens: (usage, sum) => sum || count(usage.totalTokens),
24106
+ detectSessionMarker: (entry) => entry.type === "title" || Boolean(entry.runtime) || entry.type === "model_usage",
24107
+ acceptSession: (sawMarker) => !sawMarker
24108
+ };
23831
24109
  async function readPiUsage(agent, { home, env }, scan) {
23832
24110
  let configured = env.PI_CODING_AGENT_SESSION_DIR;
23833
24111
  if (!configured) {
23834
- const settings = await readTextIfExists(join(agent, "settings.json"));
23835
- configured = object(parseJsonc(settings ?? "{}")).sessionDir;
24112
+ const settingsPath = join(agent, "settings.json");
24113
+ try {
24114
+ const settings = await readTextIfExists(settingsPath);
24115
+ configured = object(parseJsonc(settings ?? "{}")).sessionDir;
24116
+ } catch (error) {
24117
+ scan.fail(settingsPath, error);
24118
+ }
23836
24119
  }
23837
24120
  const root = resolveDirOverride(home, typeof configured === "string" ? configured : void 0) ?? join(agent, "sessions");
23838
24121
  const shared = isAbsolute(env.PI_CODING_AGENT_DIR ?? "") && root === join(agent, "sessions");
23839
- for await (const path of walkFiles(root)) if (path.endsWith(".jsonl")) await scan.file(path, (file) => readTranscript(file, "pi", shared));
24122
+ const paths = [];
24123
+ for await (const path of walkFiles(root, (dir, error) => scan.fail(dir, error))) if (path.endsWith(".jsonl")) paths.push(path);
24124
+ await scan.files(paths, (file) => readTranscript(file, piDialect, shared));
23840
24125
  }
23841
24126
  //#endregion
23842
24127
  //#region src/core/harness-pi/descriptor.ts
@@ -27052,7 +27337,7 @@ var PluginService = class extends Service {
27052
27337
  /** The Include that mounts the entries, once both files could be read, and its fiber. */
27053
27338
  tree;
27054
27339
  treeFiber;
27055
- mounting;
27340
+ queue = Promise.resolve();
27056
27341
  /** The patches of `plugins.patch.yml` last read successfully. */
27057
27342
  patches = [];
27058
27343
  /** Why each file is not applied, while it cannot be read. */
@@ -27074,8 +27359,8 @@ var PluginService = class extends Service {
27074
27359
  });
27075
27360
  await this.readPatches();
27076
27361
  this.fileError = errorOf(await this.readEntries());
27077
- if (!this.fileError && !this.patchError) await this.mount();
27078
- yield this.watch();
27362
+ if (!this.fileError && !this.patchError) await this.enqueue(() => this.mountTree());
27363
+ if (this.options.watch) yield this.watch();
27079
27364
  }
27080
27365
  /** Every entry, sorted by name like the harnesses they provide. */
27081
27366
  async list() {
@@ -27089,14 +27374,16 @@ var PluginService = class extends Service {
27089
27374
  };
27090
27375
  }
27091
27376
  /** Enable or disable an entry through the loader, which writes `plugins.yml` back. */
27092
- async setEnabled(id, enabled) {
27093
- const tree = this.find(id);
27094
- if (this.fileError) throw new AppError("precondition_failed", "plugins.yml 有错误,修正后才能启用或停用插件");
27095
- if (this.patchError) throw new AppError("precondition_failed", "plugins.patch.yml 有错误,修正后才能启用或停用插件");
27096
- if (!this.switchable(id)) throw new AppError("precondition_failed", "这个插件是否启用由 plugins.patch.yml 决定,请在其中修改");
27097
- await tree.update(id, { disabled: enabled ? null : true });
27098
- await tree.flush();
27099
- this.changed();
27377
+ setEnabled(id, enabled) {
27378
+ return this.enqueue(async () => {
27379
+ const tree = this.find(id);
27380
+ if (this.fileError) throw new AppError("precondition_failed", "plugins.yml 有错误,修正后才能启用或停用插件");
27381
+ if (this.patchError) throw new AppError("precondition_failed", "plugins.patch.yml 有错误,修正后才能启用或停用插件");
27382
+ if (!this.switchable(id)) throw new AppError("precondition_failed", "这个插件是否启用由 plugins.patch.yml 决定,请在其中修改");
27383
+ await tree.update(id, { disabled: enabled ? null : true });
27384
+ await tree.flush();
27385
+ this.changed();
27386
+ });
27100
27387
  }
27101
27388
  /** Fires whenever the list or the state of a plugin may have changed. */
27102
27389
  async *events(signal) {
@@ -27106,11 +27393,11 @@ var PluginService = class extends Service {
27106
27393
  if (!signal.aborted) throw error;
27107
27394
  }
27108
27395
  }
27109
- mount() {
27110
- this.mounting ??= this.mountTree().finally(() => {
27111
- this.mounting = void 0;
27112
- });
27113
- return this.mounting;
27396
+ /** Serialize mutations and reloads of the underlying Include tree. */
27397
+ enqueue(operation) {
27398
+ const run = this.queue.then(operation);
27399
+ this.queue = run.catch(() => {});
27400
+ return run;
27114
27401
  }
27115
27402
  async mountTree() {
27116
27403
  if (this.tree) return;
@@ -27127,32 +27414,44 @@ var PluginService = class extends Service {
27127
27414
  return plugin;
27128
27415
  }
27129
27416
  }
27130
- this.treeFiber = await this.ctx.plugin(PluginTree, {
27131
- path: pathToFileURL(this.options.path).href,
27132
- initial: [...this.builtins.values()].map(entryOf),
27133
- patches: this.patches
27134
- });
27135
- await this.addMissing();
27136
- this.changed();
27417
+ try {
27418
+ this.treeFiber = await this.ctx.plugin(PluginTree, {
27419
+ path: pathToFileURL(this.options.path).href,
27420
+ initial: [...this.builtins.values()].map(entryOf),
27421
+ patches: this.patches
27422
+ });
27423
+ await this.addMissing();
27424
+ this.changed();
27425
+ } catch (error) {
27426
+ const fiber = this.treeFiber;
27427
+ this.tree = void 0;
27428
+ this.treeFiber = void 0;
27429
+ if (fiber) await fiber.dispose().catch(() => {});
27430
+ throw error;
27431
+ }
27137
27432
  }
27138
27433
  /** `plugins.yml` changed: apply it, or load the plugins if it was what kept them from loading. */
27139
- async reloadEntries() {
27140
- this.fileError = errorOf(await this.readEntries());
27141
- if (this.tree) await this.tree.refresh();
27142
- else if (!this.fileError && !this.patchError) await this.mount();
27143
- this.changed();
27434
+ reloadEntries() {
27435
+ return this.enqueue(async () => {
27436
+ this.fileError = errorOf(await this.readEntries());
27437
+ if (this.tree) await this.tree.refresh();
27438
+ else if (!this.fileError && !this.patchError) await this.mountTree();
27439
+ this.changed();
27440
+ });
27144
27441
  }
27145
27442
  /** `plugins.patch.yml` changed: apply the new patches in place, keeping entries whose options did not change. */
27146
- async reloadPatches() {
27147
- await this.readPatches();
27148
- if (!this.patchError) {
27149
- if (this.tree && this.treeFiber) await this.treeFiber.update({
27150
- ...this.tree.config,
27151
- patches: this.patches
27152
- }, true);
27153
- else if (!this.fileError) await this.mount();
27154
- }
27155
- this.changed();
27443
+ reloadPatches() {
27444
+ return this.enqueue(async () => {
27445
+ await this.readPatches();
27446
+ if (!this.patchError) {
27447
+ if (this.tree && this.treeFiber) await this.treeFiber.update({
27448
+ ...this.tree.config,
27449
+ patches: this.patches
27450
+ }, true);
27451
+ else if (!this.fileError) await this.mountTree();
27452
+ }
27453
+ this.changed();
27454
+ });
27156
27455
  }
27157
27456
  async readPatches() {
27158
27457
  const result = await readList(this.options.patchPath);
@@ -27253,14 +27552,14 @@ var PluginService = class extends Service {
27253
27552
  const timers = /* @__PURE__ */ new Map();
27254
27553
  const watchers = [...new Set([...handlers.keys()].map((path) => dirname(path)))].map((dir) => {
27255
27554
  const watcher = watch(dir, (_event, name) => {
27256
- const path = [...handlers.keys()].find((file) => dirname(file) === dir && basename(file) === name);
27257
- const handler = path && handlers.get(path);
27258
- if (!path || !handler) return;
27259
- clearTimeout(timers.get(path));
27260
- const timer = setTimeout(() => {
27261
- handler().catch((error) => this.logger.warn("Failed to apply %s", path, error));
27262
- }, reloadDelayMs$1);
27263
- timers.set(path, timer);
27555
+ const matched = [...handlers.entries()].filter(([file]) => dirname(file) === dir && (!name || basename(file) === name));
27556
+ for (const [path, handler] of matched) {
27557
+ clearTimeout(timers.get(path));
27558
+ const timer = setTimeout(() => {
27559
+ handler().catch((error) => this.logger.warn("Failed to apply %s", path, error));
27560
+ }, reloadDelayMs$1);
27561
+ timers.set(path, timer);
27562
+ }
27264
27563
  });
27265
27564
  watcher.on("error", (error) => this.logger.warn("Stopped watching %s", dir, error));
27266
27565
  return watcher;
@@ -27294,9 +27593,9 @@ async function readList(path) {
27294
27593
  } catch (error) {
27295
27594
  return { error: error instanceof Error ? error.message : String(error) };
27296
27595
  }
27297
- if (!Array.isArray(value)) return { error: "The file must be a list" };
27596
+ if (!Array.isArray(value)) return { error: "文件顶层必须是列表" };
27298
27597
  const index = value.findIndex((item) => typeof item !== "object" || item === null || Array.isArray(item));
27299
- if (index >= 0) return { error: `Item ${index + 1} must be a mapping` };
27598
+ if (index >= 0) return { error: `第 ${index + 1} 项必须是映射对象` };
27300
27599
  return { list: value };
27301
27600
  }
27302
27601
  //#endregion
@@ -27429,12 +27728,15 @@ const googlePage = object$1({
27429
27728
  })).default([]),
27430
27729
  nextPageToken: string().optional()
27431
27730
  });
27432
- const model = (id, name, contextWindow, maxOutput) => ({
27433
- id,
27434
- ...name && name !== id ? { name } : {},
27435
- ...contextWindow ? { contextWindow } : {},
27436
- ...maxOutput ? { maxOutput } : {}
27437
- });
27731
+ const model = (id, name, contextWindow, maxOutput) => {
27732
+ const displayName = name?.trim().slice(0, 256);
27733
+ return {
27734
+ id,
27735
+ ...displayName && displayName !== id ? { name: displayName } : {},
27736
+ ...contextWindow ? { contextWindow } : {},
27737
+ ...maxOutput ? { maxOutput } : {}
27738
+ };
27739
+ };
27438
27740
  const specs = {
27439
27741
  openai: {
27440
27742
  url: (base) => new URL(`${base}/v1/models`),
@@ -27588,6 +27890,23 @@ const modelOverrideFields = [
27588
27890
  "contextWindow",
27589
27891
  "maxOutput"
27590
27892
  ];
27893
+ function setRecordProperty(target, key, value) {
27894
+ Object.defineProperty(target, key, {
27895
+ value,
27896
+ enumerable: true,
27897
+ configurable: true,
27898
+ writable: true
27899
+ });
27900
+ }
27901
+ function applyOverridePatch(current, patch) {
27902
+ const next = { ...current };
27903
+ for (const field of modelOverrideFields) {
27904
+ const value = patch[field];
27905
+ if (value === null) delete next[field];
27906
+ else if (value !== void 0) next[field] = value;
27907
+ }
27908
+ return compactModelOverride(next);
27909
+ }
27591
27910
  const connectionOf = (source) => JSON.stringify([
27592
27911
  source.baseUrl,
27593
27912
  source.endpoint,
@@ -27634,13 +27953,14 @@ var ProviderService = class extends Service {
27634
27953
  /** The detail view of a provider, with its models. */
27635
27954
  get(providerId) {
27636
27955
  const provider = this.find(this.ctx.store.data.providers, providerId);
27956
+ const globalModelOverrides = {};
27957
+ for (const model of provider.models) if (Object.hasOwn(this.ctx.store.data.modelOverrides, model.id)) setRecordProperty(globalModelOverrides, model.id, this.ctx.store.data.modelOverrides[model.id]);
27637
27958
  return {
27638
27959
  ...this.summary(provider),
27639
27960
  models: provider.models,
27640
27961
  modelOverrides: provider.modelOverrides,
27641
- globalModelOverrides: this.ctx.store.data.modelOverrides,
27642
- inheritedModels: provider.models.map((model) => effectiveModel(model, this.ctx.store.data.modelOverrides)),
27643
- effectiveModels: provider.models.map((model) => effectiveModel(model, this.ctx.store.data.modelOverrides, provider.modelOverrides)),
27962
+ globalModelOverrides,
27963
+ effectiveModels: provider.models.map((model) => effectiveModel(model, globalModelOverrides, provider.modelOverrides)),
27644
27964
  listedModels: provider.listedModels
27645
27965
  };
27646
27966
  }
@@ -27648,13 +27968,10 @@ var ProviderService = class extends Service {
27648
27968
  return this.ctx.store.data.modelOverrides;
27649
27969
  }
27650
27970
  async setModelOverride(input) {
27971
+ const override = compactModelOverride(input.override);
27972
+ if (!Object.keys(override).length) throw new AppError("bad_request", "请至少填写一项覆盖信息");
27651
27973
  const providers = await this.ctx.store.update((draft) => {
27652
- Object.defineProperty(draft.modelOverrides, input.modelId, {
27653
- value: input.override,
27654
- enumerable: true,
27655
- configurable: true,
27656
- writable: true
27657
- });
27974
+ setRecordProperty(draft.modelOverrides, input.modelId, override);
27658
27975
  return draft.providers.filter((provider) => provider.models.some((model) => model.id === input.modelId));
27659
27976
  });
27660
27977
  return this.syncOverrideProviders(providers);
@@ -27668,20 +27985,40 @@ var ProviderService = class extends Service {
27668
27985
  }
27669
27986
  /** Replace local overrides without touching the snapshot; {} restores inheritance. */
27670
27987
  setProviderModelOverride(input) {
27988
+ const override = compactModelOverride(input.override);
27671
27989
  return this.save(input.providerId, (provider) => {
27672
- const fields = Object.entries(input.override).filter(([, value]) => value !== void 0);
27673
- if (!fields.length) {
27990
+ if (!Object.keys(override).length) {
27674
27991
  delete provider.modelOverrides[input.modelId];
27675
27992
  return;
27676
27993
  }
27677
27994
  if (!provider.models.some((model) => model.id === input.modelId)) throw new AppError("not_found", "模型不存在或已移除");
27678
- Object.defineProperty(provider.modelOverrides, input.modelId, {
27679
- value: Object.fromEntries(fields),
27680
- enumerable: true,
27681
- configurable: true,
27682
- writable: true
27683
- });
27995
+ setRecordProperty(provider.modelOverrides, input.modelId, override);
27996
+ });
27997
+ }
27998
+ /**
27999
+ * Merge field-level changes onto the latest stored override inside `store.update`. When every field would be
28000
+ * cleared, leaves the store untouched and reports `{ empty: true }` so the caller can guide deletion instead.
28001
+ */
28002
+ async patchModelOverride(input) {
28003
+ const providers = await this.ctx.store.update((draft) => {
28004
+ if (input.providerId === void 0) {
28005
+ const next = applyOverridePatch(Object.hasOwn(draft.modelOverrides, input.modelId) ? draft.modelOverrides[input.modelId] : void 0, input.patch);
28006
+ if (!Object.keys(next).length) return void 0;
28007
+ setRecordProperty(draft.modelOverrides, input.modelId, next);
28008
+ return draft.providers.filter((provider) => provider.models.some((model) => model.id === input.modelId));
28009
+ }
28010
+ const provider = this.find(draft.providers, input.providerId);
28011
+ if (!provider.models.some((model) => model.id === input.modelId)) throw new AppError("not_found", "模型不存在或已移除");
28012
+ const next = applyOverridePatch(Object.hasOwn(provider.modelOverrides, input.modelId) ? provider.modelOverrides[input.modelId] : void 0, input.patch);
28013
+ if (!Object.keys(next).length) return void 0;
28014
+ setRecordProperty(provider.modelOverrides, input.modelId, next);
28015
+ return [provider];
27684
28016
  });
28017
+ if (!providers) return { empty: true };
28018
+ return {
28019
+ empty: false,
28020
+ ...await this.syncOverrideProviders(providers)
28021
+ };
27685
28022
  }
27686
28023
  async syncOverrideProviders(providers) {
27687
28024
  const failures = [];
@@ -27739,12 +28076,43 @@ var ProviderService = class extends Service {
27739
28076
  ...changesSince(provider.models, provider.listedModels, listed)
27740
28077
  };
27741
28078
  }
28079
+ /**
28080
+ * The provider's current listed models without writing `listedModels` to `store.json` (read-only inspection).
28081
+ */
28082
+ remoteModels(providerId, progress = {}) {
28083
+ return this.listing(providerId, progress);
28084
+ }
27742
28085
  /** Keep the chosen models of the provider's list, as it was shown, and rewrite the harnesses. */
27743
28086
  pickModels(input) {
27744
28087
  return this.save(input.providerId, (provider) => {
27745
28088
  provider.models = pickedModels(provider.models, input.listed, input.selected);
27746
28089
  });
27747
28090
  }
28091
+ /** Atomically add listed models to the latest stored provider list, keeping existing models intact. */
28092
+ async addListedModels(providerId, listed, ids) {
28093
+ let added = [];
28094
+ const saved = await this.ctx.store.update((draft) => {
28095
+ const provider = this.find(draft.providers, providerId);
28096
+ const existing = new Set(provider.models.map((model) => model.id));
28097
+ added = [...new Set(ids)].filter((id) => !existing.has(id));
28098
+ if (!added.length) return provider;
28099
+ provider.models = pickedModels(provider.models, listed, [...existing, ...added]);
28100
+ return provider;
28101
+ });
28102
+ const harnessFailures = added.length ? await this.ctx.harnesses.syncProvider(saved) : [];
28103
+ return {
28104
+ ...this.summary(saved),
28105
+ harnessFailures,
28106
+ added
28107
+ };
28108
+ }
28109
+ /** Atomically remove model ids from the latest stored provider list and rewrite applied harnesses. */
28110
+ removeModelIds(providerId, ids) {
28111
+ const removed = new Set(ids);
28112
+ return this.save(providerId, (provider) => {
28113
+ provider.models = provider.models.filter((model) => !removed.has(model.id));
28114
+ });
28115
+ }
27748
28116
  /** Replace the provider's model list and rewrite it in the harnesses it is applied to. */
27749
28117
  setModels(input) {
27750
28118
  return this.save(input.providerId, (provider) => {
@@ -27807,18 +28175,33 @@ var ProviderService = class extends Service {
27807
28175
  const changed = () => new AppError("conflict", "Harness 的配置刚被修改,请重新选择");
27808
28176
  if (chosen.some((candidate) => !candidate?.connection || candidate.reason)) throw changed();
27809
28177
  const enrich = await this.enricher();
27810
- const ids = await this.ctx.store.update((draft) => {
28178
+ const savedProviders = await this.ctx.store.update((draft) => {
27811
28179
  const names = new Set(draft.providers.map((provider) => provider.name));
27812
- return chosen.map((candidate) => {
28180
+ const takenKeys = /* @__PURE__ */ new Map();
28181
+ for (const provider of draft.providers) for (const [harnessId, application] of Object.entries(provider.harnesses)) {
28182
+ const set = takenKeys.get(harnessId) ?? /* @__PURE__ */ new Set();
28183
+ set.add(application.key);
28184
+ takenKeys.set(harnessId, set);
28185
+ }
28186
+ const touched = /* @__PURE__ */ new Map();
28187
+ for (const candidate of chosen) {
27813
28188
  const connection = candidate.connection;
28189
+ for (const source of candidate.sources) if (takenKeys.get(source.harnessId)?.has(source.key)) throw changed();
27814
28190
  const applications = Object.fromEntries(candidate.sources.map((source) => [source.harnessId, { key: source.key }]));
27815
28191
  const models = candidate.models.map(enrich);
27816
28192
  if (candidate.target) {
27817
28193
  const target = draft.providers.find((provider) => provider.id === candidate.target?.providerId);
27818
28194
  if (!target) throw changed();
28195
+ if (candidate.sources.some((source) => target.harnesses[source.harnessId])) throw changed();
27819
28196
  Object.assign(target.harnesses, applications);
27820
28197
  target.models = withImportedModels(target.models, models);
27821
- return target.id;
28198
+ for (const source of candidate.sources) {
28199
+ const set = takenKeys.get(source.harnessId) ?? /* @__PURE__ */ new Set();
28200
+ set.add(source.key);
28201
+ takenKeys.set(source.harnessId, set);
28202
+ }
28203
+ touched.set(target.id, structuredClone(target));
28204
+ continue;
27822
28205
  }
27823
28206
  const name = uniqueName(candidate.name, names);
27824
28207
  names.add(name);
@@ -27832,17 +28215,20 @@ var ProviderService = class extends Service {
27832
28215
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
27833
28216
  };
27834
28217
  draft.providers.push(provider);
27835
- return provider.id;
27836
- });
28218
+ for (const source of candidate.sources) {
28219
+ const set = takenKeys.get(source.harnessId) ?? /* @__PURE__ */ new Set();
28220
+ set.add(source.key);
28221
+ takenKeys.set(source.harnessId, set);
28222
+ }
28223
+ touched.set(provider.id, structuredClone(provider));
28224
+ }
28225
+ return [...touched.values()];
27837
28226
  });
27838
- const failures = /* @__PURE__ */ new Map();
27839
- for (const id of new Set(ids)) {
27840
- const provider = this.find(this.ctx.store.data.providers, id);
27841
- for (const failure of await this.ctx.harnesses.syncProvider(provider)) if (!failures.has(failure.harnessId)) failures.set(failure.harnessId, failure);
27842
- }
28227
+ const harnessFailures = [];
28228
+ for (const provider of savedProviders) harnessFailures.push(...await this.ctx.harnesses.syncProvider(provider));
27843
28229
  return {
27844
- providers: [...new Set(ids)].map((id) => this.summary(this.find(this.ctx.store.data.providers, id))),
27845
- harnessFailures: [...failures.values()]
28230
+ providers: savedProviders.map((provider) => this.summary(provider)),
28231
+ harnessFailures
27846
28232
  };
27847
28233
  }
27848
28234
  /**
@@ -27864,17 +28250,34 @@ var ProviderService = class extends Service {
27864
28250
  }
27865
28251
  /** Save the connection fields and rewrite the harnesses the provider is applied to. */
27866
28252
  update(input) {
27867
- return this.save(input.providerId, (provider, providers) => {
27868
- if (providers.some((item) => item.id !== provider.id && item.name === input.name)) throw new AppError("conflict", `已有名为「${input.name}」的供应商`);
27869
- if (provider.baseUrl !== input.baseUrl || provider.endpoint !== input.endpoint) delete provider.listedModels;
27870
- provider.name = input.name;
27871
- provider.baseUrl = input.baseUrl;
27872
- provider.apiKey = input.apiKey;
27873
- provider.endpoint = input.endpoint;
27874
- if (input.vendor) provider.vendor = input.vendor;
27875
- else delete provider.vendor;
27876
- if (input.iconUrl) provider.iconUrl = input.iconUrl;
27877
- else delete provider.iconUrl;
28253
+ return this.patchConnection(input.providerId, {
28254
+ name: input.name,
28255
+ baseUrl: input.baseUrl,
28256
+ apiKey: input.apiKey,
28257
+ endpoint: input.endpoint,
28258
+ vendor: input.vendor ?? null,
28259
+ iconUrl: input.iconUrl ?? null
28260
+ });
28261
+ }
28262
+ /**
28263
+ * Atomically merge partial connection edits onto the latest stored provider inside `store.update`.
28264
+ * `undefined` keeps the stored field; `null` clears optional fields (`vendor`, `iconUrl`).
28265
+ */
28266
+ patchConnection(providerId, patch) {
28267
+ return this.save(providerId, (provider, providers) => {
28268
+ const nextName = patch.name ?? provider.name;
28269
+ if (providers.some((item) => item.id !== provider.id && item.name === nextName)) throw new AppError("conflict", `已有名为「${nextName}」的供应商`);
28270
+ const nextBaseUrl = patch.baseUrl ?? provider.baseUrl;
28271
+ const nextEndpoint = patch.endpoint ?? provider.endpoint;
28272
+ if (provider.baseUrl !== nextBaseUrl || provider.endpoint !== nextEndpoint) delete provider.listedModels;
28273
+ provider.name = nextName;
28274
+ provider.baseUrl = nextBaseUrl;
28275
+ provider.apiKey = patch.apiKey ?? provider.apiKey;
28276
+ provider.endpoint = nextEndpoint;
28277
+ if (patch.vendor === null) delete provider.vendor;
28278
+ else if (patch.vendor !== void 0) provider.vendor = patch.vendor;
28279
+ if (patch.iconUrl === null || patch.iconUrl === "") delete provider.iconUrl;
28280
+ else if (patch.iconUrl !== void 0) provider.iconUrl = patch.iconUrl;
27878
28281
  });
27879
28282
  }
27880
28283
  /**
@@ -27929,6 +28332,7 @@ var ProviderService = class extends Service {
27929
28332
  }
27930
28333
  /** Delete the provider, removing it from every harness it is applied to first. */
27931
28334
  async delete(providerId) {
28335
+ await this.ctx.store.refresh();
27932
28336
  await this.ctx.harnesses.removeProvider(this.find(this.ctx.store.data.providers, providerId));
27933
28337
  await this.ctx.store.update((draft) => {
27934
28338
  const index = draft.providers.findIndex((item) => item.id === providerId);
@@ -28141,6 +28545,10 @@ var Store = class {
28141
28545
  idle() {
28142
28546
  return this.queue.then(() => {});
28143
28547
  }
28548
+ /** Reload `store.json` from disk if another process wrote to it after the last read. */
28549
+ sync() {
28550
+ return this.enqueue(() => this.refresh());
28551
+ }
28144
28552
  /** Read the file again; if another process changed it, take its data. */
28145
28553
  async refresh() {
28146
28554
  const text = await readTextIfExists(this.path);
@@ -28212,12 +28620,15 @@ var StoreService = class extends Service {
28212
28620
  }
28213
28621
  async *[Service.init]() {
28214
28622
  await this.state.load();
28215
- if (this.options.watch) yield await this.state.watch((error) => this.logger.warn("Cannot take in %s", this.state.path, error));
28216
28623
  yield () => this.state.idle();
28624
+ if (this.options.watch) yield await this.state.watch((error) => this.logger.warn("Cannot take in %s", this.state.path, error));
28217
28625
  }
28218
28626
  get data() {
28219
28627
  return this.state.data;
28220
28628
  }
28629
+ refresh() {
28630
+ return this.state.sync();
28631
+ }
28221
28632
  update(mutate) {
28222
28633
  return this.state.update(mutate);
28223
28634
  }
@@ -28265,7 +28676,8 @@ const App = {
28265
28676
  ctx.plugin(IconService, { cacheDir: join(config.dirs.cache, "icons") });
28266
28677
  ctx.plugin(HarnessService, {
28267
28678
  home: config.home,
28268
- env: config.env
28679
+ env: config.env,
28680
+ platform: config.platform
28269
28681
  });
28270
28682
  ctx.plugin(Loader);
28271
28683
  ctx.plugin(PluginService, {
@@ -28299,13 +28711,27 @@ function exporter(verbose) {
28299
28711
  }
28300
28712
  /** How long to wait for the harness plugins to finish loading before running anyway. */
28301
28713
  const settleTimeoutMs = 5e3;
28714
+ async function isSettled(ctx) {
28715
+ const { entries } = await ctx.plugins.list();
28716
+ return !entries.some((entry) => entry.state === "loading" || entry.state === "pending");
28717
+ }
28302
28718
  /** Wait until no plugin of `plugins.yml` is still loading, so every enabled harness is registered. */
28303
28719
  async function settle(ctx) {
28304
- const deadline = Date.now() + settleTimeoutMs;
28305
- while (Date.now() < deadline) {
28306
- const { entries } = await ctx.plugins.list();
28307
- if (!entries.some((entry) => entry.state === "loading" || entry.state === "pending")) return;
28308
- await setTimeout$1(10);
28720
+ const controller = new AbortController();
28721
+ const timeout = setTimeout(() => controller.abort(), settleTimeoutMs);
28722
+ timeout.unref();
28723
+ try {
28724
+ const updates = ctx.plugins.events(controller.signal);
28725
+ if (await isSettled(ctx)) {
28726
+ controller.abort();
28727
+ return;
28728
+ }
28729
+ for await (const _ of updates) if (await isSettled(ctx)) {
28730
+ controller.abort();
28731
+ return;
28732
+ }
28733
+ } finally {
28734
+ clearTimeout(timeout);
28309
28735
  }
28310
28736
  }
28311
28737
  /**
@@ -28336,13 +28762,16 @@ function boot(config, verbose) {
28336
28762
  "providers"
28337
28763
  ], (ctx) => {
28338
28764
  settle(ctx).then(() => {
28765
+ if (settled) return;
28339
28766
  settled = true;
28340
28767
  resolve({
28341
28768
  ctx,
28342
28769
  dispose: () => fiber.dispose().then(() => {})
28343
28770
  });
28344
28771
  }, (error) => {
28772
+ if (settled) return;
28345
28773
  settled = true;
28774
+ fiber.dispose().catch(() => {});
28346
28775
  reject(error);
28347
28776
  });
28348
28777
  });
@@ -28403,6 +28832,7 @@ async function main() {
28403
28832
  output.error(`oms needs Node.js ${minimumNode.join(".")} or later; this is ${process.versions.node}.`);
28404
28833
  return 1;
28405
28834
  }
28835
+ const { setGlobalProxyFromEnv } = await import("node:http");
28406
28836
  const config = loadConfig();
28407
28837
  setGlobalProxyFromEnv(config.env);
28408
28838
  return runCli(commands, process.argv.slice(2), {