ohmyswitch 0.1.0 → 0.2.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 +514 -167
  2. package/package.json +2 -2
package/oms.mjs CHANGED
@@ -217,6 +217,35 @@ const endpoints = [
217
217
  "/v1beta/generateContent"
218
218
  ];
219
219
  //#endregion
220
+ //#region src/core/vendors.ts
221
+ /**
222
+ * The model vendor a provider serves. It is shown as the badge on the provider's icon, and an import link names it
223
+ * to update an existing provider. The order is the display order; append new vendors at the end.
224
+ */
225
+ const vendors = [
226
+ "openai",
227
+ "anthropic",
228
+ "google",
229
+ "deepseek",
230
+ "qwen",
231
+ "moonshot",
232
+ "zhipu",
233
+ "xai",
234
+ "mistral",
235
+ "meta",
236
+ "groq",
237
+ "minimax",
238
+ "doubao",
239
+ "hunyuan",
240
+ "baidu",
241
+ "openrouter",
242
+ "siliconcloud",
243
+ "stepfun",
244
+ "cohere",
245
+ "yi",
246
+ "baichuan"
247
+ ];
248
+ //#endregion
220
249
  //#region src/cli/commands/shared.ts
221
250
  /** Protocol names of the endpoints, as the GUI shows them. */
222
251
  const endpointLabels = {
@@ -225,6 +254,44 @@ const endpointLabels = {
225
254
  "/v1/messages": "Anthropic Messages",
226
255
  "/v1beta/generateContent": "Google Generative AI"
227
256
  };
257
+ /** Vendor names, as the GUI shows them. */
258
+ const vendorLabels = {
259
+ openai: "OpenAI",
260
+ anthropic: "Anthropic",
261
+ google: "Google",
262
+ deepseek: "DeepSeek",
263
+ qwen: "Qwen",
264
+ moonshot: "Moonshot",
265
+ zhipu: "Zhipu",
266
+ xai: "xAI",
267
+ mistral: "Mistral",
268
+ meta: "Meta",
269
+ groq: "Groq",
270
+ minimax: "MiniMax",
271
+ doubao: "Doubao",
272
+ hunyuan: "Hunyuan",
273
+ baidu: "Baidu",
274
+ openrouter: "OpenRouter",
275
+ siliconcloud: "SiliconCloud",
276
+ stepfun: "StepFun",
277
+ cohere: "Cohere",
278
+ yi: "Yi",
279
+ baichuan: "Baichuan"
280
+ };
281
+ /** What --vendor accepts to leave the vendor unset, so the badge follows the endpoint. */
282
+ const followEndpoint = "follow";
283
+ const vendorChoices = () => [{
284
+ value: followEndpoint,
285
+ keys: [followEndpoint, "auto"],
286
+ label: "Follow the endpoint",
287
+ hint: "The badge of the endpoint's vendor"
288
+ }, ...vendors.map((vendor) => ({
289
+ value: vendor,
290
+ keys: [vendor],
291
+ label: vendorLabels[vendor],
292
+ hint: vendor === vendorLabels[vendor] ? void 0 : vendor
293
+ }))];
294
+ const vendorDetails = `One of ${listing(vendors)}, or ${followEndpoint} to show the endpoint's vendor`;
228
295
  /** How an application's entry looks now. */
229
296
  const applicationStateLabels = {
230
297
  applied: "applied",
@@ -589,7 +656,7 @@ function renderSaved(result, out, message) {
589
656
  if (result.rewritten.length) out.hint(`Rewrote ${listing(result.rewritten.map((harness) => harness.name))}.`);
590
657
  warnProblems(out, result.failures);
591
658
  }
592
- const list$2 = command({
659
+ const list$3 = command({
593
660
  name: "list",
594
661
  aliases: ["ls"],
595
662
  summary: "List a provider's models",
@@ -599,8 +666,8 @@ const list$2 = command({
599
666
  },
600
667
  async run({ provider, remote }, scope) {
601
668
  const ctx = await scope.services();
602
- const { models } = ctx.providers.get(provider.id);
603
- if (!remote) return models;
669
+ const { models, effectiveModels } = ctx.providers.get(provider.id);
670
+ if (!remote) return effectiveModels;
604
671
  let listed;
605
672
  try {
606
673
  ({listed} = await scope.progress((stage) => ctx.providers.modelChanges(provider.id, { onStage: modelStages(provider, stage) })));
@@ -711,7 +778,7 @@ const add$1 = command({
711
778
  },
712
779
  failed: (result) => result.failures.length > 0
713
780
  });
714
- const remove$1 = command({
781
+ const remove$2 = command({
715
782
  name: "remove",
716
783
  aliases: ["rm"],
717
784
  summary: "Remove models from a provider",
@@ -784,10 +851,10 @@ const model$1 = group({
784
851
  aliases: ["models"],
785
852
  summary: "Manage a provider's models",
786
853
  children: [
787
- list$2,
854
+ list$3,
788
855
  pick$1,
789
856
  add$1,
790
- remove$1,
857
+ remove$2,
791
858
  sync,
792
859
  command({
793
860
  name: "review",
@@ -870,122 +937,6 @@ const model$1 = group({
870
937
  ]
871
938
  });
872
939
  //#endregion
873
- //#region src/cli/commands/paths.ts
874
- const paths = command({
875
- name: "paths",
876
- summary: "Show where ohmyswitch keeps its files",
877
- params: {},
878
- run(_values, scope) {
879
- const { dirs } = scope.session.config;
880
- return {
881
- ...dirs,
882
- plugins: join(dirs.config, "plugins.yml"),
883
- pluginPatches: join(dirs.config, "plugins.patch.yml"),
884
- store: join(dirs.data, "store.json")
885
- };
886
- },
887
- render(result, out) {
888
- out.fields([
889
- ["Providers", result.store],
890
- ["Plugins", result.plugins],
891
- ["Plugin patches", result.pluginPatches],
892
- ["Cache", result.cache],
893
- ["Logs (GUI)", result.logs]
894
- ]);
895
- }
896
- });
897
- //#endregion
898
- //#region src/cli/commands/plugin.ts
899
- const lockedReason = "decided by plugins.patch.yml";
900
- function stateOf(entry) {
901
- switch (entry.state) {
902
- case "active": return "enabled";
903
- case "disabled": return "disabled";
904
- case "failed": return `failed${entry.error ? `: ${entry.error}` : ""}`;
905
- default: return "loading";
906
- }
907
- }
908
- function warnFileErrors(out, plugins) {
909
- if (plugins.fileError) out.warn(`${plugins.path} cannot be read: ${plugins.fileError}`);
910
- if (plugins.patchError) out.warn(`${plugins.patchPath} cannot be read: ${plugins.patchError}`);
911
- }
912
- const list$1 = command({
913
- name: "list",
914
- aliases: ["ls"],
915
- summary: "List plugins",
916
- params: {},
917
- async run(_values, scope) {
918
- return (await scope.services()).plugins.list();
919
- },
920
- render(plugins, out) {
921
- warnFileErrors(out, plugins);
922
- out.table([
923
- "PLUGIN",
924
- "ID",
925
- "STATE",
926
- "NOTE"
927
- ], plugins.entries.map((entry) => [
928
- entry.title,
929
- entry.id,
930
- stateOf(entry),
931
- entry.locked ? lockedReason : ""
932
- ]));
933
- }
934
- });
935
- async function pluginChoices(scope) {
936
- const { entries } = await (await scope.services()).plugins.list();
937
- return entries.map((entry) => ({
938
- value: entry,
939
- keys: [
940
- entry.id,
941
- entry.title,
942
- entry.name
943
- ],
944
- label: entry.title,
945
- hint: stateOf(entry),
946
- disabled: entry.locked ? lockedReason : void 0
947
- }));
948
- }
949
- function switchCommand(enabled) {
950
- return command({
951
- name: enabled ? "enable" : "disable",
952
- summary: `${enabled ? "Enable" : "Disable"} a plugin`,
953
- params: { plugin: select$1({
954
- summary: "Plugin",
955
- positional: true,
956
- placeholder: "plugin",
957
- details: "Its id or name",
958
- empty: "Every plugin is decided by plugins.patch.yml.",
959
- choices: pluginChoices
960
- }) },
961
- async run({ plugin }, scope) {
962
- const ctx = await scope.services();
963
- const plugins = await ctx.plugins.list();
964
- const broken = plugins.fileError ? plugins.path : plugins.patchError ? plugins.patchPath : void 0;
965
- if (broken) throw new CliError("precondition_failed", `${broken} has errors; fix it first`);
966
- await ctx.plugins.setEnabled(plugin.id, enabled);
967
- return {
968
- id: plugin.id,
969
- title: plugin.title,
970
- enabled
971
- };
972
- },
973
- render(result, out) {
974
- out.success(`${enabled ? "Enabled" : "Disabled"} ${result.title}.`);
975
- }
976
- });
977
- }
978
- const plugin = group({
979
- name: "plugin",
980
- aliases: ["plugins"],
981
- summary: "Enable or disable plugins",
982
- children: [
983
- list$1,
984
- switchCommand(true),
985
- switchCommand(false)
986
- ]
987
- });
988
- //#endregion
989
940
  //#region node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/util.js
990
941
  function getEnumValues(entries) {
991
942
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
@@ -6640,36 +6591,6 @@ function datetime(params) {
6640
6591
  return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params);
6641
6592
  }
6642
6593
  //#endregion
6643
- //#region src/cli/framework/validate.ts
6644
- const unitOf = (origin) => {
6645
- if (origin === "string") return " characters";
6646
- if (origin === "array" || origin === "set") return " items";
6647
- return "";
6648
- };
6649
- /**
6650
- * An English description of a validation issue. Core schemas carry messages for the GUI; the CLI words its own
6651
- * from the issue code, so it reads the same in every command.
6652
- */
6653
- function describeIssue(issue) {
6654
- switch (issue.code) {
6655
- case "too_small":
6656
- if (issue.origin === "string" && Number(issue.minimum) <= 1) return "must not be empty";
6657
- return `must be at least ${issue.minimum}${unitOf(issue.origin)}`;
6658
- case "too_big": return `must be at most ${issue.maximum}${unitOf(issue.origin)}`;
6659
- case "invalid_format": return issue.format === "url" ? "must be an http or https URL" : `must be a valid ${issue.format}`;
6660
- case "invalid_type": return `must be ${issue.expected === "array" ? "a list" : `a ${issue.expected}`}`;
6661
- case "invalid_value": return `must be one of ${issue.values.map(String).join(", ")}`;
6662
- default: return "is invalid";
6663
- }
6664
- }
6665
- /** Parse one parameter value with a core schema, or throw a ParamError describing the first issue. */
6666
- function parseWith(schema, value) {
6667
- const result = schema.safeParse(value);
6668
- if (result.success) return result.data;
6669
- const [issue] = result.error.issues;
6670
- throw new ParamError(issue ? describeIssue(issue) : "is invalid");
6671
- }
6672
- //#endregion
6673
6594
  //#region src/core/harnesses/types.ts
6674
6595
  /**
6675
6596
  * A harness id, such as `opencode`. Harnesses are registered at runtime, so the set is open; stored applications of
@@ -6740,6 +6661,13 @@ const modelInfo = object({
6740
6661
  input: array(_enum(modelInputs)).optional(),
6741
6662
  toolCall: boolean().optional()
6742
6663
  });
6664
+ /** Both override scopes are limited to display name and token limits. */
6665
+ const modelOverride = modelInfo.pick({
6666
+ name: true,
6667
+ contextWindow: true,
6668
+ maxOutput: true
6669
+ });
6670
+ const providerModelOverride = modelOverride;
6743
6671
  /** A provider as persisted. The API key is stored in plain text; harness configs hold it in plain text anyway. */
6744
6672
  const storedProvider = object({
6745
6673
  id: uuid(),
@@ -6747,10 +6675,18 @@ const storedProvider = object({
6747
6675
  /** The root address requests go to; endpoints are appended to it. */
6748
6676
  baseUrl,
6749
6677
  endpoint: _enum(endpoints),
6678
+ /**
6679
+ * The model vendor, shown as the badge on the provider's icon and compared by import links. Unset means the
6680
+ * badge follows the endpoint. It is display information: it is not written into harness configs.
6681
+ */
6682
+ vendor: _enum(vendors).optional(),
6750
6683
  apiKey: string(),
6751
6684
  /** An image or web page to take the icon from; unset uses the Base URL's site. */
6752
6685
  iconUrl: url({ protocol: /^https?$/ }).optional(),
6686
+ /** Metadata snapshots; discovery and models.dev sync never modify the separate overrides. */
6753
6687
  models: array(modelInfo),
6688
+ /** Kept when a model is deselected, so selecting it again restores its explicit settings. */
6689
+ modelOverrides: record$2(string().min(1).max(256), providerModelOverride).default({}),
6754
6690
  /**
6755
6691
  * The model ids the provider's model list held when the user last reviewed it. Models listed since are offered
6756
6692
  * as new, and saved models that were listed but no longer are offered for removal. Unset until the list is first
@@ -6764,15 +6700,29 @@ const storedProvider = object({
6764
6700
  harnesses: record$2(harnessId, object({ key: string().min(1).max(64) })).default({}),
6765
6701
  createdAt: datetime()
6766
6702
  });
6703
+ /** Apply explicit fields in order: snapshot → global → provider. */
6704
+ function effectiveModel(model, globalOverrides, providerOverrides = {}) {
6705
+ let result = model;
6706
+ for (const overrides of [globalOverrides, providerOverrides]) {
6707
+ const override = Object.hasOwn(overrides, model.id) ? overrides[model.id] : void 0;
6708
+ if (override) result = {
6709
+ ...result,
6710
+ ...Object.fromEntries(Object.entries(override).filter(([, value]) => value !== void 0))
6711
+ };
6712
+ }
6713
+ return result;
6714
+ }
6767
6715
  //#endregion
6768
6716
  //#region src/core/providers/schemas.ts
6769
6717
  const providerIdInput = object({ providerId: uuid() });
6770
- /** The connection fields of a provider, edited and saved together. */
6718
+ /** The fields of a provider the editor saves together; they are not all connection details. */
6771
6719
  const connectionInput = object({
6772
6720
  name: providerName,
6773
6721
  baseUrl,
6774
6722
  apiKey: string().trim().min(1, { error: "请填写 API Key" }).max(4096),
6775
6723
  endpoint: _enum(endpoints, { error: "请选择端点" }),
6724
+ /** Unset follows the endpoint, which is also how an import link without one compares. */
6725
+ vendor: _enum(vendors).optional(),
6776
6726
  /** Unset or empty uses the icon of the Base URL's site. */
6777
6727
  iconUrl: iconUrl.optional()
6778
6728
  });
@@ -6790,6 +6740,16 @@ const updateProviderInput = connectionInput.extend(providerIdInput.shape);
6790
6740
  object({ providerIds: array(uuid()).max(1e3).refine((ids) => new Set(ids).size === ids.length, { error: "供应商顺序中有重复项" }) });
6791
6741
  providerIdInput.extend({ models: array(modelInfo).max(2e3).transform((models) => [...new Map(models.map((model) => [model.id, model])).values()]) });
6792
6742
  const modelId$1 = string().min(1).max(256);
6743
+ object({
6744
+ modelId: modelId$1,
6745
+ override: modelOverride.refine((value) => Object.values(value).some((field) => field !== void 0), { error: "请至少填写一项覆盖信息" })
6746
+ });
6747
+ object({ modelId: modelId$1 });
6748
+ /** Replace one model's provider overrides. An empty object restores inheritance for every field. */
6749
+ const providerModelOverrideInput = providerIdInput.extend({
6750
+ modelId: modelId$1,
6751
+ override: providerModelOverride.strict()
6752
+ });
6793
6753
  providerIdInput.extend({
6794
6754
  listed: array(modelInfo).max(2e3),
6795
6755
  selected: array(modelId$1).max(2e3).transform((ids) => [...new Set(ids)])
@@ -6804,6 +6764,292 @@ object({ candidates: array(object({ sources: array(object({
6804
6764
  key: string().min(1).max(64)
6805
6765
  })).min(1).max(16) })).min(1, { error: "请选择要导入的供应商" }).max(200) });
6806
6766
  //#endregion
6767
+ //#region src/cli/commands/override.ts
6768
+ const provider$1 = () => select$1({
6769
+ summary: "Override only this provider (default: global)",
6770
+ optional: true,
6771
+ ask: false,
6772
+ placeholder: "provider",
6773
+ details: "Its name or id",
6774
+ empty: noProviders,
6775
+ choices: providerChoices
6776
+ });
6777
+ const id = () => text$1({
6778
+ summary: "Model id (exact match)",
6779
+ positional: true,
6780
+ placeholder: "model",
6781
+ parse: (raw) => {
6782
+ if (!raw.trim() || raw.length > 256) throw new ParamError("Model id must contain 1 to 256 characters.");
6783
+ return raw;
6784
+ }
6785
+ });
6786
+ const tokens = (summary) => text$1({
6787
+ summary,
6788
+ optional: true,
6789
+ ask: false,
6790
+ parse: (raw) => {
6791
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw)) || Number(raw) < 1) throw new ParamError("Must be a positive integer.");
6792
+ return Number(raw);
6793
+ }
6794
+ });
6795
+ const override = group({
6796
+ name: "override",
6797
+ summary: "Manage global and provider model overrides",
6798
+ children: [
6799
+ command({
6800
+ name: "list",
6801
+ summary: "List global or provider model overrides",
6802
+ params: { provider: provider$1() },
6803
+ async run({ provider }, scope) {
6804
+ const ctx = await scope.services();
6805
+ return provider ? ctx.providers.get(provider.id).modelOverrides : ctx.providers.modelOverrides();
6806
+ },
6807
+ render(result, out) {
6808
+ out.table([
6809
+ "MODEL",
6810
+ "NAME",
6811
+ "CONTEXT",
6812
+ "OUTPUT"
6813
+ ], Object.entries(result).map(([model, value]) => [
6814
+ model,
6815
+ value.name ?? "-",
6816
+ value.contextWindow?.toString() ?? "-",
6817
+ value.maxOutput?.toString() ?? "-"
6818
+ ]));
6819
+ }
6820
+ }),
6821
+ command({
6822
+ name: "set",
6823
+ summary: "Replace the entire override for a model",
6824
+ params: {
6825
+ provider: provider$1(),
6826
+ model: id(),
6827
+ name: text$1({
6828
+ summary: "Display name",
6829
+ optional: true,
6830
+ ask: false,
6831
+ parse: (raw) => {
6832
+ if (!raw.trim() || raw.length > 256) throw new ParamError("Name must contain 1 to 256 characters.");
6833
+ return raw.trim();
6834
+ }
6835
+ }),
6836
+ context: tokens("Maximum context in tokens"),
6837
+ output: tokens("Maximum output in tokens")
6838
+ },
6839
+ async run({ provider, model, name, context, output }, scope) {
6840
+ const override = {
6841
+ ...name !== void 0 && { name },
6842
+ ...context !== void 0 && { contextWindow: context },
6843
+ ...output !== void 0 && { maxOutput: output }
6844
+ };
6845
+ if (!Object.keys(override).length) throw new CliError("usage", "Specify at least one override field, or use \"override remove\" to restore inheritance.");
6846
+ const ctx = await scope.services();
6847
+ if (!provider) return ctx.providers.setModelOverride({
6848
+ modelId: model,
6849
+ override
6850
+ });
6851
+ if (!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.");
6852
+ const saved = await ctx.providers.setProviderModelOverride(providerModelOverrideInput.parse({
6853
+ providerId: provider.id,
6854
+ modelId: model,
6855
+ override
6856
+ }));
6857
+ return {
6858
+ affected: 1,
6859
+ failures: saved.harnessFailures.map((failure) => ({
6860
+ providerId: saved.id,
6861
+ providerName: saved.name,
6862
+ ...failure
6863
+ }))
6864
+ };
6865
+ },
6866
+ render(result, out) {
6867
+ out.success(`Saved override for ${result.affected} providers.`);
6868
+ for (const failure of result.failures) out.warn(`${failure.providerName} / ${failure.harnessId}: ${failure.message}`);
6869
+ },
6870
+ failed: (result) => result.failures.length > 0
6871
+ }),
6872
+ command({
6873
+ name: "remove",
6874
+ aliases: ["rm"],
6875
+ summary: "Remove an override and restore inheritance",
6876
+ params: {
6877
+ provider: provider$1(),
6878
+ model: id()
6879
+ },
6880
+ confirm: ({ provider, model }) => `Remove the ${provider ? `provider "${provider.name}"` : "global"} override for "${model}"?`,
6881
+ async run({ provider, model }, scope) {
6882
+ const ctx = await scope.services();
6883
+ if (!provider) return ctx.providers.removeModelOverride(model);
6884
+ const saved = await ctx.providers.setProviderModelOverride(providerModelOverrideInput.parse({
6885
+ providerId: provider.id,
6886
+ modelId: model,
6887
+ override: {}
6888
+ }));
6889
+ return {
6890
+ affected: 1,
6891
+ failures: saved.harnessFailures.map((failure) => ({
6892
+ providerId: saved.id,
6893
+ providerName: saved.name,
6894
+ ...failure
6895
+ }))
6896
+ };
6897
+ },
6898
+ render(result, out) {
6899
+ out.success(`Removed override for ${result.affected} providers.`);
6900
+ for (const failure of result.failures) out.warn(`${failure.providerName} / ${failure.harnessId}: ${failure.message}`);
6901
+ },
6902
+ failed: (result) => result.failures.length > 0
6903
+ })
6904
+ ]
6905
+ });
6906
+ //#endregion
6907
+ //#region src/cli/commands/paths.ts
6908
+ const paths = command({
6909
+ name: "paths",
6910
+ summary: "Show where ohmyswitch keeps its files",
6911
+ params: {},
6912
+ run(_values, scope) {
6913
+ const { dirs } = scope.session.config;
6914
+ return {
6915
+ ...dirs,
6916
+ plugins: join(dirs.config, "plugins.yml"),
6917
+ pluginPatches: join(dirs.config, "plugins.patch.yml"),
6918
+ store: join(dirs.data, "store.json")
6919
+ };
6920
+ },
6921
+ render(result, out) {
6922
+ out.fields([
6923
+ ["Providers", result.store],
6924
+ ["Plugins", result.plugins],
6925
+ ["Plugin patches", result.pluginPatches],
6926
+ ["Cache", result.cache],
6927
+ ["Logs (GUI)", result.logs]
6928
+ ]);
6929
+ }
6930
+ });
6931
+ //#endregion
6932
+ //#region src/cli/commands/plugin.ts
6933
+ const lockedReason = "decided by plugins.patch.yml";
6934
+ function stateOf(entry) {
6935
+ switch (entry.state) {
6936
+ case "active": return "enabled";
6937
+ case "disabled": return "disabled";
6938
+ case "failed": return `failed${entry.error ? `: ${entry.error}` : ""}`;
6939
+ default: return "loading";
6940
+ }
6941
+ }
6942
+ function warnFileErrors(out, plugins) {
6943
+ if (plugins.fileError) out.warn(`${plugins.path} cannot be read: ${plugins.fileError}`);
6944
+ if (plugins.patchError) out.warn(`${plugins.patchPath} cannot be read: ${plugins.patchError}`);
6945
+ }
6946
+ const list$1 = command({
6947
+ name: "list",
6948
+ aliases: ["ls"],
6949
+ summary: "List plugins",
6950
+ params: {},
6951
+ async run(_values, scope) {
6952
+ return (await scope.services()).plugins.list();
6953
+ },
6954
+ render(plugins, out) {
6955
+ warnFileErrors(out, plugins);
6956
+ out.table([
6957
+ "PLUGIN",
6958
+ "ID",
6959
+ "STATE",
6960
+ "NOTE"
6961
+ ], plugins.entries.map((entry) => [
6962
+ entry.title,
6963
+ entry.id,
6964
+ stateOf(entry),
6965
+ entry.locked ? lockedReason : ""
6966
+ ]));
6967
+ }
6968
+ });
6969
+ async function pluginChoices(scope) {
6970
+ const { entries } = await (await scope.services()).plugins.list();
6971
+ return entries.map((entry) => ({
6972
+ value: entry,
6973
+ keys: [
6974
+ entry.id,
6975
+ entry.title,
6976
+ entry.name
6977
+ ],
6978
+ label: entry.title,
6979
+ hint: stateOf(entry),
6980
+ disabled: entry.locked ? lockedReason : void 0
6981
+ }));
6982
+ }
6983
+ function switchCommand(enabled) {
6984
+ return command({
6985
+ name: enabled ? "enable" : "disable",
6986
+ summary: `${enabled ? "Enable" : "Disable"} a plugin`,
6987
+ params: { plugin: select$1({
6988
+ summary: "Plugin",
6989
+ positional: true,
6990
+ placeholder: "plugin",
6991
+ details: "Its id or name",
6992
+ empty: "Every plugin is decided by plugins.patch.yml.",
6993
+ choices: pluginChoices
6994
+ }) },
6995
+ async run({ plugin }, scope) {
6996
+ const ctx = await scope.services();
6997
+ const plugins = await ctx.plugins.list();
6998
+ const broken = plugins.fileError ? plugins.path : plugins.patchError ? plugins.patchPath : void 0;
6999
+ if (broken) throw new CliError("precondition_failed", `${broken} has errors; fix it first`);
7000
+ await ctx.plugins.setEnabled(plugin.id, enabled);
7001
+ return {
7002
+ id: plugin.id,
7003
+ title: plugin.title,
7004
+ enabled
7005
+ };
7006
+ },
7007
+ render(result, out) {
7008
+ out.success(`${enabled ? "Enabled" : "Disabled"} ${result.title}.`);
7009
+ }
7010
+ });
7011
+ }
7012
+ const plugin = group({
7013
+ name: "plugin",
7014
+ aliases: ["plugins"],
7015
+ summary: "Enable or disable plugins",
7016
+ children: [
7017
+ list$1,
7018
+ switchCommand(true),
7019
+ switchCommand(false)
7020
+ ]
7021
+ });
7022
+ //#endregion
7023
+ //#region src/cli/framework/validate.ts
7024
+ const unitOf = (origin) => {
7025
+ if (origin === "string") return " characters";
7026
+ if (origin === "array" || origin === "set") return " items";
7027
+ return "";
7028
+ };
7029
+ /**
7030
+ * An English description of a validation issue. Core schemas carry messages for the GUI; the CLI words its own
7031
+ * from the issue code, so it reads the same in every command.
7032
+ */
7033
+ function describeIssue(issue) {
7034
+ switch (issue.code) {
7035
+ case "too_small":
7036
+ if (issue.origin === "string" && Number(issue.minimum) <= 1) return "must not be empty";
7037
+ return `must be at least ${issue.minimum}${unitOf(issue.origin)}`;
7038
+ case "too_big": return `must be at most ${issue.maximum}${unitOf(issue.origin)}`;
7039
+ case "invalid_format": return issue.format === "url" ? "must be an http or https URL" : `must be a valid ${issue.format}`;
7040
+ case "invalid_type": return `must be ${issue.expected === "array" ? "a list" : `a ${issue.expected}`}`;
7041
+ case "invalid_value": return `must be one of ${issue.values.map(String).join(", ")}`;
7042
+ default: return "is invalid";
7043
+ }
7044
+ }
7045
+ /** Parse one parameter value with a core schema, or throw a ParamError describing the first issue. */
7046
+ function parseWith(schema, value) {
7047
+ const result = schema.safeParse(value);
7048
+ if (result.success) return result.data;
7049
+ const [issue] = result.error.issues;
7050
+ throw new ParamError(issue ? describeIssue(issue) : "is invalid");
7051
+ }
7052
+ //#endregion
6807
7053
  //#region src/cli/commands/provider.ts
6808
7054
  const modelId = string().trim().min(1).max(256);
6809
7055
  const chosen = (scope) => scope.values.provider;
@@ -6852,13 +7098,14 @@ const show = command({
6852
7098
  const ctx = await scope.services();
6853
7099
  const harnesses = await harnessIndex(scope);
6854
7100
  const detail = ctx.providers.get(provider.id);
6855
- const { iconUrl } = ctx.providers.connection(provider.id);
7101
+ const { iconUrl, vendor } = ctx.providers.connection(provider.id);
6856
7102
  const applications = (await ctx.harnesses.applications())[provider.id] ?? [];
6857
7103
  return {
6858
7104
  id: detail.id,
6859
7105
  name: detail.name,
6860
7106
  baseUrl: detail.baseUrl,
6861
7107
  endpoint: detail.endpoint,
7108
+ vendor,
6862
7109
  iconUrl: iconUrl || void 0,
6863
7110
  ...showKey ? { apiKey: ctx.providers.connection(provider.id).apiKey } : {},
6864
7111
  createdAt: detail.createdAt,
@@ -6867,7 +7114,7 @@ const show = command({
6867
7114
  key,
6868
7115
  state
6869
7116
  })),
6870
- models: detail.models
7117
+ models: detail.effectiveModels
6871
7118
  };
6872
7119
  },
6873
7120
  render(provider, out) {
@@ -6876,6 +7123,7 @@ const show = command({
6876
7123
  ["ID", provider.id],
6877
7124
  ["Base URL", provider.baseUrl],
6878
7125
  ["Endpoint", `${endpointLabels[provider.endpoint]} (${provider.endpoint})`],
7126
+ ["Vendor", provider.vendor ? vendorLabels[provider.vendor] : `Follows the endpoint (${endpointLabels[provider.endpoint]})`],
6879
7127
  ["Icon", provider.iconUrl],
6880
7128
  ["API key", provider.apiKey]
6881
7129
  ]);
@@ -6937,6 +7185,13 @@ const add = command({
6937
7185
  details: endpointDetails,
6938
7186
  choices: endpointChoices
6939
7187
  }),
7188
+ vendor: select$1({
7189
+ summary: "Model vendor",
7190
+ placeholder: "vendor",
7191
+ details: vendorDetails,
7192
+ optional: true,
7193
+ choices: vendorChoices
7194
+ }),
6940
7195
  apiKey: secret({
6941
7196
  summary: "API key",
6942
7197
  parse: (raw) => parseWith(createProviderInput.shape.apiKey, raw)
@@ -6978,6 +7233,7 @@ const add = command({
6978
7233
  name: values.name,
6979
7234
  baseUrl: values.baseUrl,
6980
7235
  endpoint: values.endpoint,
7236
+ vendor: values.vendor === "follow" ? void 0 : values.vendor,
6981
7237
  apiKey: values.apiKey,
6982
7238
  iconUrl: values.iconUrl,
6983
7239
  ...fetched ? {
@@ -7024,6 +7280,14 @@ const edit = command({
7024
7280
  initial: (scope) => chosen(scope).endpoint,
7025
7281
  choices: endpointChoices
7026
7282
  }),
7283
+ vendor: select$1({
7284
+ summary: "Model vendor",
7285
+ placeholder: "vendor",
7286
+ details: vendorDetails,
7287
+ optional: true,
7288
+ initial: (scope) => chosen(scope).vendor ?? "follow",
7289
+ choices: vendorChoices
7290
+ }),
7027
7291
  apiKey: secret({
7028
7292
  summary: "API key",
7029
7293
  optional: true,
@@ -7042,7 +7306,7 @@ const edit = command({
7042
7306
  const ctx = await scope.services();
7043
7307
  if (Object.values(changes).every((value) => value === void 0)) {
7044
7308
  if (scope.session.interactive) return void 0;
7045
- throw new CliError("usage", "Nothing to change", "Pass --name, --base-url, --endpoint, --icon-url, --api-key-stdin or --api-key-env.");
7309
+ throw new CliError("usage", "Nothing to change", "Pass --name, --base-url, --endpoint, --vendor, --icon-url, --api-key-stdin or --api-key-env.");
7046
7310
  }
7047
7311
  if (changes.name !== void 0) await assertNameFree(scope, changes.name, provider.id);
7048
7312
  const current = ctx.providers.connection(provider.id);
@@ -7051,6 +7315,7 @@ const edit = command({
7051
7315
  name: changes.name ?? current.name,
7052
7316
  baseUrl: changes.baseUrl ?? current.baseUrl,
7053
7317
  endpoint: changes.endpoint ?? current.endpoint,
7318
+ vendor: changes.vendor === "follow" ? void 0 : changes.vendor ?? current.vendor,
7054
7319
  apiKey: changes.apiKey ?? current.apiKey,
7055
7320
  iconUrl: changes.iconUrl ?? current.iconUrl
7056
7321
  }));
@@ -7169,6 +7434,7 @@ const commands = group({
7169
7434
  ]
7170
7435
  }),
7171
7436
  model$1,
7437
+ override,
7172
7438
  ...applicationCommands,
7173
7439
  harness,
7174
7440
  plugin,
@@ -7233,7 +7499,7 @@ function appDirs(home, env, platform) {
7233
7499
  function loadConfig() {
7234
7500
  const home = homedir();
7235
7501
  return {
7236
- version: "0.1.0",
7502
+ version: "0.2.1",
7237
7503
  dirs: appDirs(home, process.env, process.platform),
7238
7504
  home,
7239
7505
  env: { ...process.env }
@@ -13452,7 +13718,7 @@ var HarnessService = class extends Service {
13452
13718
  }
13453
13719
  for (const provider of applied) {
13454
13720
  const { key } = provider.harnesses[harness.id];
13455
- const state = files ? files.reduce((worst, { file, entries }) => worseState(worst, entryState(file, provider, key, entries)), "applied") : "unreadable";
13721
+ const state = files ? files.reduce((worst, { file, entries }) => worseState(worst, entryState(file, this.effective(provider), key, entries)), "applied") : "unreadable";
13456
13722
  result[provider.id] = [...result[provider.id] ?? [], {
13457
13723
  harnessId: harness.id,
13458
13724
  key,
@@ -13471,7 +13737,7 @@ var HarnessService = class extends Service {
13471
13737
  }
13472
13738
  async applyTo(providerId, harness, replace) {
13473
13739
  const harnessId = harness.id;
13474
- const provider = this.provider(providerId);
13740
+ const provider = this.effective(this.provider(providerId));
13475
13741
  if (!await isDirectory(harness.homeDir(this.environment))) throw new AppError("precondition_failed", `未发现 ${harness.name}`);
13476
13742
  if (harness.unsupportedEndpoints?.includes(provider.endpoint)) throw new AppError("precondition_failed", `${harness.name} 不支持这个供应商的端点`);
13477
13743
  const files = await harness.configFiles(this.environment);
@@ -13545,7 +13811,8 @@ var HarnessService = class extends Service {
13545
13811
  });
13546
13812
  }
13547
13813
  /** Rewrite a provider in every harness it is applied to, after it changed. Failures are reported, not thrown. */
13548
- async syncProvider(provider) {
13814
+ async syncProvider(original) {
13815
+ const provider = this.effective(original);
13549
13816
  const failures = [];
13550
13817
  for (const [harnessId, application] of this.applied(provider)) try {
13551
13818
  await this.track(harnessId, async (harness) => {
@@ -13723,6 +13990,12 @@ var HarnessService = class extends Service {
13723
13990
  return harness.homeDir(this.environment);
13724
13991
  }
13725
13992
  }
13993
+ effective(provider) {
13994
+ return {
13995
+ ...provider,
13996
+ models: provider.models.map((model) => effectiveModel(model, this.ctx.store.data.modelOverrides, provider.modelOverrides))
13997
+ };
13998
+ }
13726
13999
  /** Registered harnesses in display order. Harnesses are independent of each other, so they are sorted by name. */
13727
14000
  harnesses() {
13728
14001
  return [...this.registrations.values()].map((registration) => registration.harness).sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
@@ -14273,7 +14546,7 @@ function push(map, key, entry) {
14273
14546
  }
14274
14547
  //#endregion
14275
14548
  //#region src/core/models-dev/service.ts
14276
- const maxAgeMs = 864e5;
14549
+ const maxAgeMs = 36e5;
14277
14550
  const maxBytes = 33554432;
14278
14551
  const cacheFile = object({
14279
14552
  /** Bumped whenever the reduced entry shape changes, so older caches are downloaded again. */
@@ -26260,23 +26533,83 @@ var ProviderService = class extends Service {
26260
26533
  list() {
26261
26534
  return this.ctx.store.data.providers.map((provider) => this.summary(provider));
26262
26535
  }
26536
+ /** Model ids saved across providers, without connection details or credentials. */
26537
+ modelIds() {
26538
+ return [...new Set(this.ctx.store.data.providers.flatMap((provider) => provider.models.map((model) => model.id)))].sort((a, b) => a.localeCompare(b));
26539
+ }
26263
26540
  /** The detail view of a provider, with its models. */
26264
26541
  get(providerId) {
26265
26542
  const provider = this.find(this.ctx.store.data.providers, providerId);
26266
26543
  return {
26267
26544
  ...this.summary(provider),
26268
26545
  models: provider.models,
26546
+ modelOverrides: provider.modelOverrides,
26547
+ globalModelOverrides: this.ctx.store.data.modelOverrides,
26548
+ inheritedModels: provider.models.map((model) => effectiveModel(model, this.ctx.store.data.modelOverrides)),
26549
+ effectiveModels: provider.models.map((model) => effectiveModel(model, this.ctx.store.data.modelOverrides, provider.modelOverrides)),
26269
26550
  listedModels: provider.listedModels
26270
26551
  };
26271
26552
  }
26272
- /** The connection fields for the editor, the only place the API key is returned. */
26553
+ modelOverrides() {
26554
+ return this.ctx.store.data.modelOverrides;
26555
+ }
26556
+ async setModelOverride(input) {
26557
+ const providers = await this.ctx.store.update((draft) => {
26558
+ Object.defineProperty(draft.modelOverrides, input.modelId, {
26559
+ value: input.override,
26560
+ enumerable: true,
26561
+ configurable: true,
26562
+ writable: true
26563
+ });
26564
+ return draft.providers.filter((provider) => provider.models.some((model) => model.id === input.modelId));
26565
+ });
26566
+ return this.syncOverrideProviders(providers);
26567
+ }
26568
+ async removeModelOverride(modelId) {
26569
+ const providers = await this.ctx.store.update((draft) => {
26570
+ delete draft.modelOverrides[modelId];
26571
+ return draft.providers.filter((provider) => provider.models.some((model) => model.id === modelId));
26572
+ });
26573
+ return this.syncOverrideProviders(providers);
26574
+ }
26575
+ /** Replace local overrides without touching the snapshot; {} restores inheritance. */
26576
+ setProviderModelOverride(input) {
26577
+ return this.save(input.providerId, (provider) => {
26578
+ const fields = Object.entries(input.override).filter(([, value]) => value !== void 0);
26579
+ if (!fields.length) {
26580
+ delete provider.modelOverrides[input.modelId];
26581
+ return;
26582
+ }
26583
+ if (!provider.models.some((model) => model.id === input.modelId)) throw new AppError("not_found", "模型不存在或已移除");
26584
+ Object.defineProperty(provider.modelOverrides, input.modelId, {
26585
+ value: Object.fromEntries(fields),
26586
+ enumerable: true,
26587
+ configurable: true,
26588
+ writable: true
26589
+ });
26590
+ });
26591
+ }
26592
+ async syncOverrideProviders(providers) {
26593
+ const failures = [];
26594
+ for (const provider of providers) for (const failure of await this.ctx.harnesses.syncProvider(provider)) failures.push({
26595
+ providerId: provider.id,
26596
+ providerName: provider.name,
26597
+ ...failure
26598
+ });
26599
+ return {
26600
+ affected: providers.length,
26601
+ failures
26602
+ };
26603
+ }
26604
+ /** The editable fields for the editor, the only place the API key is returned. */
26273
26605
  connection(providerId) {
26274
- const { name, baseUrl, apiKey, endpoint, iconUrl } = this.find(this.ctx.store.data.providers, providerId);
26606
+ const { name, baseUrl, apiKey, endpoint, vendor, iconUrl } = this.find(this.ctx.store.data.providers, providerId);
26275
26607
  return {
26276
26608
  name,
26277
26609
  baseUrl,
26278
26610
  apiKey,
26279
26611
  endpoint,
26612
+ vendor,
26280
26613
  iconUrl: iconUrl ?? ""
26281
26614
  };
26282
26615
  }
@@ -26400,6 +26733,7 @@ var ProviderService = class extends Service {
26400
26733
  name,
26401
26734
  ...connection,
26402
26735
  models,
26736
+ modelOverrides: {},
26403
26737
  harnesses: applications,
26404
26738
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
26405
26739
  };
@@ -26443,6 +26777,8 @@ var ProviderService = class extends Service {
26443
26777
  provider.baseUrl = input.baseUrl;
26444
26778
  provider.apiKey = input.apiKey;
26445
26779
  provider.endpoint = input.endpoint;
26780
+ if (input.vendor) provider.vendor = input.vendor;
26781
+ else delete provider.vendor;
26446
26782
  if (input.iconUrl) provider.iconUrl = input.iconUrl;
26447
26783
  else delete provider.iconUrl;
26448
26784
  });
@@ -26464,9 +26800,11 @@ var ProviderService = class extends Service {
26464
26800
  name: input.name,
26465
26801
  baseUrl: input.baseUrl,
26466
26802
  endpoint: input.endpoint,
26803
+ ...input.vendor ? { vendor: input.vendor } : {},
26467
26804
  apiKey: input.apiKey,
26468
26805
  ...input.iconUrl ? { iconUrl: input.iconUrl } : {},
26469
26806
  models,
26807
+ modelOverrides: {},
26470
26808
  ...listed ? { listedModels: listed.map((model) => model.id) } : {},
26471
26809
  harnesses: {},
26472
26810
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -26592,6 +26930,7 @@ var ProviderService = class extends Service {
26592
26930
  name: provider.name,
26593
26931
  baseUrl: provider.baseUrl,
26594
26932
  endpoint: provider.endpoint,
26933
+ vendor: provider.vendor,
26595
26934
  modelCount: provider.models.length,
26596
26935
  harnesses: this.ctx.harnesses.appliedTo(provider),
26597
26936
  createdAt: provider.createdAt
@@ -26606,15 +26945,17 @@ var ProviderService = class extends Service {
26606
26945
  //#endregion
26607
26946
  //#region src/core/store/store.ts
26608
26947
  const storeFile = object({
26609
- version: literal(3),
26610
- providers: array(storedProvider)
26948
+ version: literal(6),
26949
+ providers: array(storedProvider),
26950
+ modelOverrides: record$2(string().min(1).max(256), modelOverride)
26611
26951
  });
26612
26952
  const fileName = "store.json";
26613
26953
  /** Several writes in a row are read once, after the file has been quiet this long. */
26614
26954
  const reloadDelayMs = 100;
26615
26955
  const emptyStore = () => ({
26616
- version: 3,
26617
- providers: []
26956
+ version: 6,
26957
+ providers: [],
26958
+ modelOverrides: {}
26618
26959
  });
26619
26960
  /**
26620
26961
  * Upgrade an older store file in place, one version at a time. A version newer than this build is left alone,
@@ -26625,6 +26966,12 @@ function migrate(raw) {
26625
26966
  const data = raw;
26626
26967
  if (data.version === 1) data.version = 2;
26627
26968
  if (data.version === 2) data.version = 3;
26969
+ if (data.version === 3) Object.assign(data, {
26970
+ version: 4,
26971
+ modelOverrides: {}
26972
+ });
26973
+ if (data.version === 4) data.version = 5;
26974
+ if (data.version === 5) data.version = 6;
26628
26975
  return data;
26629
26976
  }
26630
26977
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ohmyswitch",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Provider-first config manager for AI coding harnesses",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -18,4 +18,4 @@
18
18
  "engines": {
19
19
  "node": ">=24.14.0"
20
20
  }
21
- }
21
+ }