ohmyswitch 0.2.2 → 0.2.3

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 +430 -301
  2. package/package.json +1 -1
package/oms.mjs CHANGED
@@ -1759,6 +1759,290 @@ ${r ? styleText("cyan", S_BAR_END) : ""}
1759
1759
  }
1760
1760
  }).prompt();
1761
1761
  //#endregion
1762
+ //#region src/cli/framework/prompt.ts
1763
+ updateSettings({ withGuide: false });
1764
+ /**
1765
+ * Turn stdin into keypress events. Node does this once per stream, and the first call fixes how long a lone Esc
1766
+ * waits to be told apart from an escape sequence: 500ms unless given, which makes Esc lag. Call it before clack
1767
+ * does, so the wait is clack's 50ms whichever of a prompt or a spinner comes first.
1768
+ */
1769
+ function decodeKeys() {
1770
+ emitKeypressEvents(process.stdin, { escapeCodeTimeout: 50 });
1771
+ }
1772
+ const unchanged = {
1773
+ value: void 0,
1774
+ raws: []
1775
+ };
1776
+ const capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
1777
+ /** Whether Ctrl-C was pressed during the current prompt. */
1778
+ let interrupted = false;
1779
+ const watchInterrupt = (_text, key) => {
1780
+ if (key?.ctrl && key.name === "c") interrupted = true;
1781
+ };
1782
+ /**
1783
+ * Show a prompt and return its answer. clack reports Esc and Ctrl-C alike as a cancel; the keys are watched
1784
+ * alongside it so the cancel says which one it was: Esc backs out of one step, Ctrl-C ends the CLI.
1785
+ */
1786
+ async function prompted(show) {
1787
+ interrupted = false;
1788
+ decodeKeys();
1789
+ process.stdin.on("keypress", watchInterrupt);
1790
+ try {
1791
+ const result = await show();
1792
+ if (isCancel(result)) throw new Cancelled(interrupted);
1793
+ return result;
1794
+ } finally {
1795
+ process.stdin.off("keypress", watchInterrupt);
1796
+ }
1797
+ }
1798
+ /** Run `parse` for a prompt's validation, returning the problem as the prompt shows it. */
1799
+ function problemOf(parse) {
1800
+ try {
1801
+ parse();
1802
+ return;
1803
+ } catch (error) {
1804
+ if (error instanceof ParamError) return capitalize(error.message);
1805
+ throw error;
1806
+ }
1807
+ }
1808
+ const parseRaw = (param, raw) => param.parse ? param.parse(raw) : raw;
1809
+ const splitList = (raw) => raw.split(/[\s,]+/).map((item) => item.trim()).filter(Boolean);
1810
+ /**
1811
+ * Ask for one parameter. An optional parameter left empty stays unset; one with an initial value that is kept
1812
+ * also stays unset, since keeping it changes nothing.
1813
+ */
1814
+ async function ask(param, required, scope) {
1815
+ switch (param.kind) {
1816
+ case "text": {
1817
+ const suggested = await suggestionsOf(param, scope);
1818
+ if (suggested) {
1819
+ const answer = await askSuggestedOne(param, required, suggested);
1820
+ if (answer) return answer;
1821
+ }
1822
+ const initial = await param.initial?.(scope);
1823
+ const skips = (raw) => !required && raw === (initial ?? "");
1824
+ const value = await prompted(() => text({
1825
+ message: param.summary,
1826
+ placeholder: param.hint,
1827
+ initialValue: initial,
1828
+ validate: (value) => {
1829
+ const raw = value ?? "";
1830
+ if (skips(raw)) return void 0;
1831
+ return problemOf(() => parseRaw(param, raw));
1832
+ }
1833
+ })) ?? "";
1834
+ if (skips(value)) return unchanged;
1835
+ return {
1836
+ value: parseRaw(param, value),
1837
+ raws: [value]
1838
+ };
1839
+ }
1840
+ case "secret": {
1841
+ const raw = await prompted(() => password({
1842
+ message: required ? param.summary : `${param.summary} (leave empty to keep)`,
1843
+ validate: (value) => {
1844
+ const raw = value ?? "";
1845
+ if (raw === "" && !required) return void 0;
1846
+ return problemOf(() => parseRaw(param, raw));
1847
+ }
1848
+ }));
1849
+ if (!raw && !required) return unchanged;
1850
+ return {
1851
+ value: parseRaw(param, raw ?? ""),
1852
+ raws: [""]
1853
+ };
1854
+ }
1855
+ case "list": {
1856
+ const suggested = await suggestionsOf(param, scope);
1857
+ if (suggested) return askSuggested(param, required, suggested);
1858
+ const raw = await prompted(() => text({
1859
+ message: `${param.summary} (comma-separated)`,
1860
+ placeholder: param.hint,
1861
+ validate: (value) => problemOf(() => splitList(value ?? "").map((item) => parseRaw(param, item)))
1862
+ }));
1863
+ const items = splitList(raw ?? "");
1864
+ return {
1865
+ value: items.map((item) => parseRaw(param, item)),
1866
+ raws: items
1867
+ };
1868
+ }
1869
+ case "select": return param.multiple ? askMany(param, required, scope) : askOne(param, required, scope);
1870
+ case "flag": return {
1871
+ value: false,
1872
+ raws: []
1873
+ };
1874
+ }
1875
+ }
1876
+ /** Lists longer than this can be filtered by typing, like the GUI's model picker with its search box. */
1877
+ const filterableFrom = 12;
1878
+ /**
1879
+ * The options to show, or undefined when an optional parameter has none to offer, which leaves it unset. A
1880
+ * required one with nothing to choose cannot go on.
1881
+ */
1882
+ async function choicesOf(param, required, scope) {
1883
+ const choices = await param.choices?.(scope) ?? [];
1884
+ if (choices.some((choice) => !choice.disabled)) return choices;
1885
+ if (!required) return void 0;
1886
+ throw new CliError("precondition_failed", param.empty ?? `There is nothing to choose for "${param.summary}"`);
1887
+ }
1888
+ const optionOf = (choice, index) => ({
1889
+ value: index,
1890
+ label: choice.label,
1891
+ hint: choice.disabled ?? choice.hint,
1892
+ disabled: Boolean(choice.disabled)
1893
+ });
1894
+ async function askOne(param, required, scope) {
1895
+ const choices = await choicesOf(param, required, scope);
1896
+ if (!choices) return unchanged;
1897
+ const initial = await param.initial?.(scope);
1898
+ const initialIndex = choices.findIndex((choice) => choice.value === initial);
1899
+ const skip = -1;
1900
+ const options = choices.map(optionOf);
1901
+ if (!required && initialIndex < 0) options.push({
1902
+ value: skip,
1903
+ label: "Skip",
1904
+ hint: void 0,
1905
+ disabled: false
1906
+ });
1907
+ const initialValue = initialIndex >= 0 ? initialIndex : void 0;
1908
+ const index = await prompted(() => options.length > filterableFrom ? autocomplete({
1909
+ message: param.summary,
1910
+ options,
1911
+ initialValue,
1912
+ placeholder: "Type to filter"
1913
+ }) : select({
1914
+ message: param.summary,
1915
+ options,
1916
+ initialValue
1917
+ }));
1918
+ if (index === skip || index === initialIndex) return unchanged;
1919
+ const choice = choices[index];
1920
+ if (!choice.keys.length) return unchanged;
1921
+ return {
1922
+ value: choice.value,
1923
+ raws: [choice.keys[0] ?? choice.label]
1924
+ };
1925
+ }
1926
+ async function askMany(param, required, scope) {
1927
+ const choices = await choicesOf(param, required, scope);
1928
+ if (!choices) return unchanged;
1929
+ const initial = await param.initial?.(scope) ?? [];
1930
+ const chosen = await pickSeveral(param.summary, choices, (choice) => initial.includes(choice.value), required);
1931
+ return {
1932
+ value: chosen.map((choice) => choice.value),
1933
+ raws: chosen.map((choice) => choice.keys[0] ?? choice.label)
1934
+ };
1935
+ }
1936
+ /** Tick options in a list, filterable when long; returns them in list order, not the order they were ticked. */
1937
+ async function pickSeveral(message, choices, ticked, required) {
1938
+ const options = choices.map(optionOf);
1939
+ const initialValues = choices.flatMap((choice, index) => ticked(choice) ? [index] : []);
1940
+ for (;;) {
1941
+ const indexes = await prompted(() => options.length > filterableFrom ? autocompleteMultiselect({
1942
+ message,
1943
+ options,
1944
+ initialValues,
1945
+ required: false,
1946
+ placeholder: "Type to filter"
1947
+ }) : multiselect({
1948
+ message,
1949
+ options,
1950
+ initialValues,
1951
+ required: false
1952
+ }));
1953
+ if (required && !indexes.length) {
1954
+ log.warn("Select at least one (space toggles an option).");
1955
+ continue;
1956
+ }
1957
+ return indexes.toSorted((a, b) => a - b).map((index) => choices[index]);
1958
+ }
1959
+ }
1960
+ /**
1961
+ * What a list parameter offers to pick from, or undefined to type the values instead: when it offers nothing, or
1962
+ * getting the offer failed, which is shown so the user knows why.
1963
+ */
1964
+ async function suggestionsOf(param, scope) {
1965
+ if (!param.suggest) return void 0;
1966
+ try {
1967
+ const suggested = await param.suggest(scope);
1968
+ return suggested.choices.length ? suggested : void 0;
1969
+ } catch (error) {
1970
+ if (error instanceof Cancelled) throw error;
1971
+ const typed = param.kind === "list" ? "them" : "it";
1972
+ scope.session.out.warn(`${toCliError(error).message.replace(/\.$/, "")}. Type ${typed} instead.`);
1973
+ return;
1974
+ }
1975
+ }
1976
+ async function askSuggested(param, required, suggested) {
1977
+ const ticked = new Set(suggested.ticked ?? []);
1978
+ const chosen = await pickSeveral(param.summary, suggested.choices, (choice) => ticked.has(choice.value), required);
1979
+ if (suggested.all && chosen.length === suggested.choices.length) return {
1980
+ value: void 0,
1981
+ raws: [],
1982
+ flag: suggested.all
1983
+ };
1984
+ const raws = chosen.map((choice) => choice.value);
1985
+ return {
1986
+ value: raws.map((raw) => parseRaw(param, raw)),
1987
+ raws
1988
+ };
1989
+ }
1990
+ /** Pick one suggested value for a text parameter; undefined when the user chooses to type one instead. */
1991
+ async function askSuggestedOne(param, required, suggested) {
1992
+ const [skip, other] = [-1, -2];
1993
+ const options = suggested.choices.map(optionOf);
1994
+ if (suggested.open) options.push({
1995
+ value: other,
1996
+ label: "Another…",
1997
+ hint: void 0,
1998
+ disabled: false
1999
+ });
2000
+ if (!required) options.push({
2001
+ value: skip,
2002
+ label: "Skip",
2003
+ hint: void 0,
2004
+ disabled: false
2005
+ });
2006
+ const index = await prompted(() => options.length > filterableFrom ? autocomplete({
2007
+ message: param.summary,
2008
+ options,
2009
+ placeholder: "Type to filter"
2010
+ }) : select({
2011
+ message: param.summary,
2012
+ options
2013
+ }));
2014
+ if (index === other) return void 0;
2015
+ if (index === skip) return unchanged;
2016
+ const raw = suggested.choices[index].value;
2017
+ return {
2018
+ value: parseRaw(param, raw),
2019
+ raws: [raw]
2020
+ };
2021
+ }
2022
+ /** Ask a yes/no question, no by default. */
2023
+ async function confirm(message) {
2024
+ return prompted(() => confirm$1({
2025
+ message,
2026
+ initialValue: false
2027
+ }));
2028
+ }
2029
+ /** Pick one of a menu's entries; undefined when the user backs out with Esc. Ctrl-C throws Cancelled. */
2030
+ async function pickEntry(message, entries) {
2031
+ try {
2032
+ return entries[await prompted(() => select({
2033
+ message,
2034
+ options: entries.map((entry, index) => ({
2035
+ value: index,
2036
+ label: entry.label,
2037
+ hint: entry.hint
2038
+ }))
2039
+ }))]?.value;
2040
+ } catch (error) {
2041
+ if (error instanceof Cancelled && !error.interrupted) return void 0;
2042
+ throw error;
2043
+ }
2044
+ }
2045
+ //#endregion
1762
2046
  //#region src/cli/framework/progress.ts
1763
2047
  /**
1764
2048
  * Run a slow task with a spinner on stderr, whose message each stage replaces. Nothing is shown until the first
@@ -1773,6 +2057,7 @@ async function withProgress(enabled, task) {
1773
2057
  spinner$1.message(message);
1774
2058
  return;
1775
2059
  }
2060
+ decodeKeys();
1776
2061
  spinner$1 = spinner({
1777
2062
  output: process.stderr,
1778
2063
  onCancel: () => process.exit(exitCodes.cancelled)
@@ -1833,7 +2118,7 @@ function match(param, choices, raw) {
1833
2118
  if (found.length > 1) throw new ParamError(`"${raw}" matches more than one ${noun}`);
1834
2119
  const [choice] = found;
1835
2120
  if (!choice) {
1836
- const accepted = choices.filter((item) => !item.disabled).map((item) => item.keys[0] ?? item.label);
2121
+ const accepted = choices.flatMap((item) => item.disabled || !item.keys[0] ? [] : [item.keys[0]]);
1837
2122
  throw new ParamError(`no ${noun} "${raw}"${accepted.length && accepted.length <= 12 ? `; expected one of ${accepted.join(", ")}` : ""}`, "not_found");
1838
2123
  }
1839
2124
  if (choice.disabled) throw new ParamError(`${choice.label}: ${choice.disabled}`, "precondition_failed");
@@ -2392,14 +2677,14 @@ function warnProblems(out, problems) {
2392
2677
  }
2393
2678
  //#endregion
2394
2679
  //#region src/cli/commands/apply.ts
2395
- const chosen$2 = (scope) => scope.values.provider;
2680
+ const chosen$3 = (scope) => scope.values.provider;
2396
2681
  /** Why a provider cannot be applied to a harness now, if it cannot. */
2397
2682
  function blocker(harness, provider) {
2398
2683
  if (!harness.detected) return "not found on this machine";
2399
2684
  if (harness.unsupportedEndpoints.includes(provider.endpoint)) return `does not support ${endpointLabels[provider.endpoint]}`;
2400
2685
  }
2401
2686
  async function applyChoices(scope) {
2402
- const provider = chosen$2(scope);
2687
+ const provider = chosen$3(scope);
2403
2688
  return [...(await harnessIndex(scope)).values()].map((harness) => ({
2404
2689
  value: harness,
2405
2690
  keys: harnessKeys(harness),
@@ -2486,7 +2771,7 @@ const apply = command({
2486
2771
  failed: (result) => result.failures.length > 0
2487
2772
  });
2488
2773
  async function appliedChoices(scope) {
2489
- const provider = chosen$2(scope);
2774
+ const provider = chosen$3(scope);
2490
2775
  return [...(await harnessIndex(scope)).values()].map((harness) => ({
2491
2776
  value: harness,
2492
2777
  keys: harnessKeys(harness),
@@ -2605,7 +2890,7 @@ const harness = group({
2605
2890
  });
2606
2891
  //#endregion
2607
2892
  //#region src/cli/commands/model.ts
2608
- const chosen$1 = (scope) => scope.values.provider;
2893
+ const chosen$2 = (scope) => scope.values.provider;
2609
2894
  /** What a model can do beyond plain text, in a few words. */
2610
2895
  function features(model) {
2611
2896
  const notes = [];
@@ -2631,7 +2916,7 @@ function modelTable(out, models, marks) {
2631
2916
  }
2632
2917
  /** The provider's models as it lists them now, fetched once per run and recorded as reviewed, like the GUI's picker. */
2633
2918
  function fetched(scope) {
2634
- const provider = chosen$1(scope);
2919
+ const provider = chosen$2(scope);
2635
2920
  return scope.memo(`fetched:${provider.id}`, async () => {
2636
2921
  const ctx = await scope.services();
2637
2922
  try {
@@ -2714,7 +2999,7 @@ const pick$1 = command({
2714
2999
  complete: false,
2715
3000
  choices: listedChoices,
2716
3001
  async initial(scope) {
2717
- const saved = (await scope.services()).providers.get(chosen$1(scope).id).models.map((model) => model.id);
3002
+ const saved = (await scope.services()).providers.get(chosen$2(scope).id).models.map((model) => model.id);
2718
3003
  return saved.length ? saved : (await fetched(scope)).models.map((model) => model.id);
2719
3004
  }
2720
3005
  })
@@ -2748,7 +3033,7 @@ const add$1 = command({
2748
3033
  empty: noListedModels,
2749
3034
  async choices(scope) {
2750
3035
  const ctx = await scope.services();
2751
- const saved = new Set(ctx.providers.get(chosen$1(scope).id).models.map((model) => model.id));
3036
+ const saved = new Set(ctx.providers.get(chosen$2(scope).id).models.map((model) => model.id));
2752
3037
  return (await fetched(scope)).models.map((model) => ({
2753
3038
  ...modelChoice(model),
2754
3039
  hint: saved.has(model.id) ? "saved" : modelChoice(model).hint
@@ -2801,7 +3086,7 @@ const remove$2 = command({
2801
3086
  placeholder: "model",
2802
3087
  details: "By id",
2803
3088
  async choices(scope) {
2804
- return (await scope.services()).providers.get(chosen$1(scope).id).models.map(modelChoice);
3089
+ return (await scope.services()).providers.get(chosen$2(scope).id).models.map(modelChoice);
2805
3090
  }
2806
3091
  })
2807
3092
  },
@@ -2847,7 +3132,7 @@ const sync = command({
2847
3132
  });
2848
3133
  /** How the provider's list changed since it was last reviewed, fetched once per run. */
2849
3134
  function changes(scope) {
2850
- const provider = chosen$1(scope);
3135
+ const provider = chosen$2(scope);
2851
3136
  return scope.memo(`changes:${provider.id}`, async () => {
2852
3137
  const ctx = await scope.services();
2853
3138
  try {
@@ -8752,25 +9037,25 @@ const createProviderInput = connectionInput.extend({
8752
9037
  const updateProviderInput = connectionInput.extend(providerIdInput.shape);
8753
9038
  object({ providerIds: array(uuid()).max(1e3).refine((ids) => new Set(ids).size === ids.length, { error: "供应商顺序中有重复项" }) });
8754
9039
  providerIdInput.extend({ models: array(modelInfo).max(2e3).transform((models) => [...new Map(models.map((model) => [model.id, model])).values()]) });
8755
- const modelId$1 = string().min(1).max(256);
8756
- object({
8757
- modelId: modelId$1,
9040
+ const modelId$2 = string().min(1).max(256);
9041
+ const modelOverrideInput = object({
9042
+ modelId: modelId$2,
8758
9043
  override: modelOverride.refine((value) => Object.values(value).some((field) => field !== void 0), { error: "请至少填写一项覆盖信息" })
8759
9044
  });
8760
- object({ modelId: modelId$1 });
9045
+ object({ modelId: modelId$2 });
8761
9046
  /** Replace one model's provider overrides. An empty object restores inheritance for every field. */
8762
9047
  const providerModelOverrideInput = providerIdInput.extend({
8763
- modelId: modelId$1,
9048
+ modelId: modelId$2,
8764
9049
  override: providerModelOverride.strict()
8765
9050
  });
8766
9051
  providerIdInput.extend({
8767
9052
  listed: array(modelInfo).max(2e3),
8768
- selected: array(modelId$1).max(2e3).transform((ids) => [...new Set(ids)])
9053
+ selected: array(modelId$2).max(2e3).transform((ids) => [...new Set(ids)])
8769
9054
  });
8770
9055
  providerIdInput.extend({
8771
9056
  add: array(modelInfo).max(2e3),
8772
- remove: array(modelId$1).max(2e3),
8773
- listed: array(modelId$1).max(2e3).transform((ids) => [...new Set(ids)])
9057
+ remove: array(modelId$2).max(2e3),
9058
+ listed: array(modelId$2).max(2e3).transform((ids) => [...new Set(ids)])
8774
9059
  });
8775
9060
  object({ candidates: array(object({ sources: array(object({
8776
9061
  harnessId,
@@ -8778,29 +9063,68 @@ object({ candidates: array(object({ sources: array(object({
8778
9063
  })).min(1).max(16) })).min(1, { error: "请选择要导入的供应商" }).max(200) });
8779
9064
  //#endregion
8780
9065
  //#region src/cli/commands/override.ts
8781
- const provider$1 = () => select$1({
8782
- summary: "Override only this provider (default: global)",
9066
+ const chosen$1 = (scope) => scope.values.provider;
9067
+ const provider$1 = (disabled) => select$1({
9068
+ summary: "Provider",
8783
9069
  optional: true,
8784
- ask: false,
9070
+ target: true,
8785
9071
  placeholder: "provider",
8786
- details: "Its name or id",
8787
- empty: noProviders,
8788
- choices: providerChoices
8789
- });
8790
- const id = () => text$1({
8791
- summary: "Model id (exact match)",
8792
- positional: true,
8793
- placeholder: "model",
8794
- parse: (raw) => {
8795
- if (!raw.trim() || raw.length > 256) throw new ParamError("Model id must contain 1 to 256 characters.");
8796
- return raw;
9072
+ details: "Its name or id; without it, the override is global and applies to every provider's model",
9073
+ async choices(scope) {
9074
+ const providers = await providerChoices(scope, disabled);
9075
+ if (!providers.length) return [];
9076
+ return [{
9077
+ value: void 0,
9078
+ keys: [],
9079
+ label: "All providers",
9080
+ hint: "global"
9081
+ }, ...providers];
8797
9082
  }
8798
9083
  });
8799
- const tokens = (summary) => text$1({
9084
+ /** The overrides in the chosen scope: the provider's own, or the global ones. */
9085
+ async function overridesOf(scope) {
9086
+ const ctx = await scope.services();
9087
+ const provider = chosen$1(scope);
9088
+ return provider ? ctx.providers.get(provider.id).modelOverrides : ctx.providers.modelOverrides();
9089
+ }
9090
+ /** One model's override in the chosen scope, empty when it has none. */
9091
+ async function currentOverride(scope, model) {
9092
+ const overrides = await overridesOf(scope);
9093
+ return Object.hasOwn(overrides, model) ? overrides[model] : {};
9094
+ }
9095
+ const describeOverride = (override) => [
9096
+ override.name,
9097
+ override.contextWindow && `${formatTokens(override.contextWindow)} context`,
9098
+ override.maxOutput && `${formatTokens(override.maxOutput)} output`
9099
+ ].filter(Boolean).join(", ");
9100
+ /**
9101
+ * Models an override can be set for: the provider's saved models, or for a global one, every model a provider
9102
+ * saves and every model that already has a global override.
9103
+ */
9104
+ async function settableModels(scope) {
9105
+ const ctx = await scope.services();
9106
+ const provider = chosen$1(scope);
9107
+ const overrides = await overridesOf(scope);
9108
+ const models = provider ? ctx.providers.get(provider.id).models : ctx.providers.baseModels();
9109
+ const ids = new Set(models.map((model) => model.id));
9110
+ const others = provider ? [] : Object.keys(overrides).filter((id) => !ids.has(id));
9111
+ return [...models, ...others.map((id) => ({ id }))].map((model) => ({
9112
+ ...modelChoice(model),
9113
+ hint: Object.hasOwn(overrides, model.id) ? "overridden" : modelChoice(model).hint
9114
+ }));
9115
+ }
9116
+ const modelId$1 = (raw) => {
9117
+ if (!raw.trim() || raw.length > 256) throw new ParamError("Model id must contain 1 to 256 characters.");
9118
+ return raw;
9119
+ };
9120
+ /** An override field: unset leaves it as it is; an empty value, as null, clears it. */
9121
+ const tokens = (summary, field) => text$1({
8800
9122
  summary,
8801
9123
  optional: true,
8802
- ask: false,
9124
+ details: "An empty value clears it",
9125
+ initial: async (scope) => (await currentOverride(scope, scope.values.model))[field]?.toString(),
8803
9126
  parse: (raw) => {
9127
+ if (!raw.trim()) return null;
8804
9128
  if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw)) || Number(raw) < 1) throw new ParamError("Must be a positive integer.");
8805
9129
  return Number(raw);
8806
9130
  }
@@ -8813,17 +9137,19 @@ const override = group({
8813
9137
  name: "list",
8814
9138
  summary: "List global or provider model overrides",
8815
9139
  params: { provider: provider$1() },
8816
- async run({ provider }, scope) {
8817
- const ctx = await scope.services();
8818
- return provider ? ctx.providers.get(provider.id).modelOverrides : ctx.providers.modelOverrides();
8819
- },
8820
- render(result, out) {
9140
+ run: (_values, scope) => overridesOf(scope),
9141
+ render(result, out, { provider }) {
9142
+ const rows = Object.entries(result);
9143
+ if (!rows.length) {
9144
+ out.hint(provider ? `"${provider.name}" has no model overrides.` : "No global model overrides.");
9145
+ return;
9146
+ }
8821
9147
  out.table([
8822
9148
  "MODEL",
8823
9149
  "NAME",
8824
9150
  "CONTEXT",
8825
9151
  "OUTPUT"
8826
- ], Object.entries(result).map(([model, value]) => [
9152
+ ], rows.map(([model, value]) => [
8827
9153
  model,
8828
9154
  value.name ?? "-",
8829
9155
  value.contextWindow?.toString() ?? "-",
@@ -8833,39 +9159,61 @@ const override = group({
8833
9159
  }),
8834
9160
  command({
8835
9161
  name: "set",
8836
- summary: "Replace the entire override for a model",
9162
+ summary: "Set fields of a model's override, keeping the others",
8837
9163
  params: {
8838
- provider: provider$1(),
8839
- model: id(),
9164
+ provider: provider$1((provider) => provider.modelCount ? void 0 : "has no models"),
9165
+ model: text$1({
9166
+ summary: "Model",
9167
+ positional: true,
9168
+ placeholder: "model",
9169
+ details: "Its id, exactly; for a provider override, one of its saved models",
9170
+ parse: modelId$1,
9171
+ complete: settableModels,
9172
+ suggest: async (scope) => ({
9173
+ choices: await settableModels(scope),
9174
+ open: !chosen$1(scope)
9175
+ })
9176
+ }),
8840
9177
  name: text$1({
8841
9178
  summary: "Display name",
8842
9179
  optional: true,
8843
- ask: false,
9180
+ details: "An empty value clears it",
9181
+ initial: async (scope) => (await currentOverride(scope, scope.values.model)).name,
8844
9182
  parse: (raw) => {
8845
- if (!raw.trim() || raw.length > 256) throw new ParamError("Name must contain 1 to 256 characters.");
8846
- return raw.trim();
9183
+ if (raw.length > 256) throw new ParamError("Name must contain at most 256 characters.");
9184
+ return raw.trim() || null;
8847
9185
  }
8848
9186
  }),
8849
- context: tokens("Maximum context in tokens"),
8850
- output: tokens("Maximum output in tokens")
9187
+ context: tokens("Maximum context in tokens", "contextWindow"),
9188
+ output: tokens("Maximum output in tokens", "maxOutput")
8851
9189
  },
8852
9190
  async run({ provider, model, name, context, output }, scope) {
8853
- const override = {
8854
- ...name !== void 0 && { name },
8855
- ...context !== void 0 && { contextWindow: context },
8856
- ...output !== void 0 && { maxOutput: output }
9191
+ const changes = {
9192
+ name,
9193
+ contextWindow: context,
9194
+ maxOutput: output
8857
9195
  };
8858
- if (!Object.keys(override).length) throw new CliError("usage", "Specify at least one override field, or use \"override remove\" to restore inheritance.");
9196
+ if (Object.values(changes).every((value) => value === void 0)) {
9197
+ if (scope.session.interactive) return void 0;
9198
+ throw new CliError("usage", "Nothing to change", "Pass --name, --context or --output.");
9199
+ }
8859
9200
  const ctx = await scope.services();
8860
- if (!provider) return ctx.providers.setModelOverride({
9201
+ 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.");
9202
+ const next = { ...await currentOverride(scope, model) };
9203
+ for (const [field, value] of Object.entries(changes)) if (value === null) delete next[field];
9204
+ else if (value !== void 0) next[field] = value;
9205
+ if (!Object.keys(next).length) {
9206
+ const scoped = provider ? ` --provider ${shellQuote(provider.name)}` : "";
9207
+ throw new CliError("usage", "Every field of the override would be cleared", `Remove it with "oms override remove ${shellQuote(model)}${scoped}".`);
9208
+ }
9209
+ if (!provider) return ctx.providers.setModelOverride(modelOverrideInput.parse({
8861
9210
  modelId: model,
8862
- override
8863
- });
8864
- 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.");
9211
+ override: next
9212
+ }));
8865
9213
  const saved = await ctx.providers.setProviderModelOverride(providerModelOverrideInput.parse({
8866
9214
  providerId: provider.id,
8867
9215
  modelId: model,
8868
- override
9216
+ override: next
8869
9217
  }));
8870
9218
  return {
8871
9219
  affected: 1,
@@ -8877,10 +9225,14 @@ const override = group({
8877
9225
  };
8878
9226
  },
8879
9227
  render(result, out) {
8880
- out.success(`Saved override for ${result.affected} providers.`);
9228
+ if (!result) {
9229
+ out.hint("Nothing changed.");
9230
+ return;
9231
+ }
9232
+ out.success(`Saved override for ${plural(result.affected, "provider")}.`);
8881
9233
  for (const failure of result.failures) out.warn(`${failure.providerName} / ${failure.harnessId}: ${failure.message}`);
8882
9234
  },
8883
- failed: (result) => result.failures.length > 0
9235
+ failed: (result) => Boolean(result?.failures.length)
8884
9236
  }),
8885
9237
  command({
8886
9238
  name: "remove",
@@ -8888,7 +9240,21 @@ const override = group({
8888
9240
  summary: "Remove an override and restore inheritance",
8889
9241
  params: {
8890
9242
  provider: provider$1(),
8891
- model: id()
9243
+ model: select$1({
9244
+ summary: "Model",
9245
+ positional: true,
9246
+ placeholder: "model",
9247
+ details: "Its id",
9248
+ empty: "There is no override to remove.",
9249
+ async choices(scope) {
9250
+ return Object.entries(await overridesOf(scope)).map(([id, override]) => ({
9251
+ value: id,
9252
+ keys: [id],
9253
+ label: id,
9254
+ hint: describeOverride(override) || void 0
9255
+ }));
9256
+ }
9257
+ })
8892
9258
  },
8893
9259
  confirm: ({ provider, model }) => `Remove the ${provider ? `provider "${provider.name}"` : "global"} override for "${model}"?`,
8894
9260
  async run({ provider, model }, scope) {
@@ -8909,7 +9275,7 @@ const override = group({
8909
9275
  };
8910
9276
  },
8911
9277
  render(result, out) {
8912
- out.success(`Removed override for ${result.affected} providers.`);
9278
+ out.success(`Removed override for ${plural(result.affected, "provider")}.`);
8913
9279
  for (const failure of result.failures) out.warn(`${failure.providerName} / ${failure.harnessId}: ${failure.message}`);
8914
9280
  },
8915
9281
  failed: (result) => result.failures.length > 0
@@ -9513,7 +9879,7 @@ function appDirs(home, env, platform) {
9513
9879
  function loadConfig() {
9514
9880
  const home = homedir();
9515
9881
  return {
9516
- version: "0.2.2",
9882
+ version: "0.2.3",
9517
9883
  dirs: appDirs(home, process.env, process.platform),
9518
9884
  home,
9519
9885
  env: { ...process.env }
@@ -9631,243 +9997,6 @@ function commandHelp(command, path) {
9631
9997
  }
9632
9998
  const describe$1 = (summary, details) => details ? `${summary}. ${details}` : summary;
9633
9999
  //#endregion
9634
- //#region src/cli/framework/prompt.ts
9635
- updateSettings({ withGuide: false });
9636
- const unchanged = {
9637
- value: void 0,
9638
- raws: []
9639
- };
9640
- const capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
9641
- /** Whether Ctrl-C was pressed during the current prompt. */
9642
- let interrupted = false;
9643
- const watchInterrupt = (_text, key) => {
9644
- if (key?.ctrl && key.name === "c") interrupted = true;
9645
- };
9646
- /**
9647
- * Show a prompt and return its answer. clack reports Esc and Ctrl-C alike as a cancel; the keys are watched
9648
- * alongside it so the cancel says which one it was: Esc backs out of one step, Ctrl-C ends the CLI.
9649
- */
9650
- async function prompted(show) {
9651
- interrupted = false;
9652
- emitKeypressEvents(process.stdin);
9653
- process.stdin.on("keypress", watchInterrupt);
9654
- try {
9655
- const result = await show();
9656
- if (isCancel(result)) throw new Cancelled(interrupted);
9657
- return result;
9658
- } finally {
9659
- process.stdin.off("keypress", watchInterrupt);
9660
- }
9661
- }
9662
- /** Run `parse` for a prompt's validation, returning the problem as the prompt shows it. */
9663
- function problemOf(parse) {
9664
- try {
9665
- parse();
9666
- return;
9667
- } catch (error) {
9668
- if (error instanceof ParamError) return capitalize(error.message);
9669
- throw error;
9670
- }
9671
- }
9672
- const parseRaw = (param, raw) => param.parse ? param.parse(raw) : raw;
9673
- const splitList = (raw) => raw.split(/[\s,]+/).map((item) => item.trim()).filter(Boolean);
9674
- /**
9675
- * Ask for one parameter. An optional parameter left empty stays unset; one with an initial value that is kept
9676
- * also stays unset, since keeping it changes nothing.
9677
- */
9678
- async function ask(param, required, scope) {
9679
- switch (param.kind) {
9680
- case "text": {
9681
- const initial = await param.initial?.(scope);
9682
- const skips = (raw) => !required && raw === (initial ?? "");
9683
- const value = await prompted(() => text({
9684
- message: param.summary,
9685
- placeholder: param.hint,
9686
- initialValue: initial,
9687
- validate: (value) => {
9688
- const raw = value ?? "";
9689
- if (skips(raw)) return void 0;
9690
- return problemOf(() => parseRaw(param, raw));
9691
- }
9692
- })) ?? "";
9693
- if (skips(value)) return unchanged;
9694
- return {
9695
- value: parseRaw(param, value),
9696
- raws: [value]
9697
- };
9698
- }
9699
- case "secret": {
9700
- const raw = await prompted(() => password({
9701
- message: required ? param.summary : `${param.summary} (leave empty to keep)`,
9702
- validate: (value) => {
9703
- const raw = value ?? "";
9704
- if (raw === "" && !required) return void 0;
9705
- return problemOf(() => parseRaw(param, raw));
9706
- }
9707
- }));
9708
- if (!raw && !required) return unchanged;
9709
- return {
9710
- value: parseRaw(param, raw ?? ""),
9711
- raws: [""]
9712
- };
9713
- }
9714
- case "list": {
9715
- const suggested = await suggestionsOf(param, scope);
9716
- if (suggested) return askSuggested(param, required, suggested);
9717
- const raw = await prompted(() => text({
9718
- message: `${param.summary} (comma-separated)`,
9719
- placeholder: param.hint,
9720
- validate: (value) => problemOf(() => splitList(value ?? "").map((item) => parseRaw(param, item)))
9721
- }));
9722
- const items = splitList(raw ?? "");
9723
- return {
9724
- value: items.map((item) => parseRaw(param, item)),
9725
- raws: items
9726
- };
9727
- }
9728
- case "select": return param.multiple ? askMany(param, required, scope) : askOne(param, required, scope);
9729
- case "flag": return {
9730
- value: false,
9731
- raws: []
9732
- };
9733
- }
9734
- }
9735
- /** Lists longer than this can be filtered by typing, like the GUI's model picker with its search box. */
9736
- const filterableFrom = 12;
9737
- /**
9738
- * The options to show, or undefined when an optional parameter has none to offer, which leaves it unset. A
9739
- * required one with nothing to choose cannot go on.
9740
- */
9741
- async function choicesOf(param, required, scope) {
9742
- const choices = await param.choices?.(scope) ?? [];
9743
- if (choices.some((choice) => !choice.disabled)) return choices;
9744
- if (!required) return void 0;
9745
- throw new CliError("precondition_failed", param.empty ?? `There is nothing to choose for "${param.summary}"`);
9746
- }
9747
- const optionOf = (choice, index) => ({
9748
- value: index,
9749
- label: choice.label,
9750
- hint: choice.disabled ?? choice.hint,
9751
- disabled: Boolean(choice.disabled)
9752
- });
9753
- async function askOne(param, required, scope) {
9754
- const choices = await choicesOf(param, required, scope);
9755
- if (!choices) return unchanged;
9756
- const initial = await param.initial?.(scope);
9757
- const initialIndex = choices.findIndex((choice) => choice.value === initial);
9758
- const skip = -1;
9759
- const options = choices.map(optionOf);
9760
- if (!required && initialIndex < 0) options.push({
9761
- value: skip,
9762
- label: "Skip",
9763
- hint: void 0,
9764
- disabled: false
9765
- });
9766
- const initialValue = initialIndex >= 0 ? initialIndex : void 0;
9767
- const index = await prompted(() => options.length > filterableFrom ? autocomplete({
9768
- message: param.summary,
9769
- options,
9770
- initialValue,
9771
- placeholder: "Type to filter"
9772
- }) : select({
9773
- message: param.summary,
9774
- options,
9775
- initialValue
9776
- }));
9777
- if (index === skip || index === initialIndex) return unchanged;
9778
- const choice = choices[index];
9779
- return {
9780
- value: choice.value,
9781
- raws: [choice.keys[0] ?? choice.label]
9782
- };
9783
- }
9784
- async function askMany(param, required, scope) {
9785
- const choices = await choicesOf(param, required, scope);
9786
- if (!choices) return unchanged;
9787
- const initial = await param.initial?.(scope) ?? [];
9788
- const chosen = await pickSeveral(param.summary, choices, (choice) => initial.includes(choice.value), required);
9789
- return {
9790
- value: chosen.map((choice) => choice.value),
9791
- raws: chosen.map((choice) => choice.keys[0] ?? choice.label)
9792
- };
9793
- }
9794
- /** Tick options in a list, filterable when long; returns them in list order, not the order they were ticked. */
9795
- async function pickSeveral(message, choices, ticked, required) {
9796
- const options = choices.map(optionOf);
9797
- const initialValues = choices.flatMap((choice, index) => ticked(choice) ? [index] : []);
9798
- for (;;) {
9799
- const indexes = await prompted(() => options.length > filterableFrom ? autocompleteMultiselect({
9800
- message,
9801
- options,
9802
- initialValues,
9803
- required: false,
9804
- placeholder: "Type to filter"
9805
- }) : multiselect({
9806
- message,
9807
- options,
9808
- initialValues,
9809
- required: false
9810
- }));
9811
- if (required && !indexes.length) {
9812
- log.warn("Select at least one (space toggles an option).");
9813
- continue;
9814
- }
9815
- return indexes.toSorted((a, b) => a - b).map((index) => choices[index]);
9816
- }
9817
- }
9818
- /**
9819
- * What a list parameter offers to pick from, or undefined to type the values instead: when it offers nothing, or
9820
- * getting the offer failed, which is shown so the user knows why.
9821
- */
9822
- async function suggestionsOf(param, scope) {
9823
- if (!param.suggest) return void 0;
9824
- try {
9825
- const suggested = await param.suggest(scope);
9826
- return suggested.choices.length ? suggested : void 0;
9827
- } catch (error) {
9828
- if (error instanceof Cancelled) throw error;
9829
- scope.session.out.warn(`${toCliError(error).message.replace(/\.$/, "")}. Type them instead.`);
9830
- return;
9831
- }
9832
- }
9833
- async function askSuggested(param, required, suggested) {
9834
- const ticked = new Set(suggested.ticked ?? []);
9835
- const chosen = await pickSeveral(param.summary, suggested.choices, (choice) => ticked.has(choice.value), required);
9836
- if (suggested.all && chosen.length === suggested.choices.length) return {
9837
- value: void 0,
9838
- raws: [],
9839
- flag: suggested.all
9840
- };
9841
- const raws = chosen.map((choice) => choice.value);
9842
- return {
9843
- value: raws.map((raw) => parseRaw(param, raw)),
9844
- raws
9845
- };
9846
- }
9847
- /** Ask a yes/no question, no by default. */
9848
- async function confirm(message) {
9849
- return prompted(() => confirm$1({
9850
- message,
9851
- initialValue: false
9852
- }));
9853
- }
9854
- /** Pick one of a menu's entries; undefined when the user backs out with Esc. Ctrl-C throws Cancelled. */
9855
- async function pickEntry(message, entries) {
9856
- try {
9857
- return entries[await prompted(() => select({
9858
- message,
9859
- options: entries.map((entry, index) => ({
9860
- value: index,
9861
- label: entry.label,
9862
- hint: entry.hint
9863
- }))
9864
- }))]?.value;
9865
- } catch (error) {
9866
- if (error instanceof Cancelled && !error.interrupted) return void 0;
9867
- throw error;
9868
- }
9869
- }
9870
- //#endregion
9871
10000
  //#region src/cli/framework/run.ts
9872
10001
  /** Run one command line and return the exit status. */
9873
10002
  async function runCli(root, argv, options) {
@@ -9988,7 +10117,7 @@ async function execute(command, path, invocation, session) {
9988
10117
  const confirmedFlags = /* @__PURE__ */ new Set();
9989
10118
  let prompted = false;
9990
10119
  const scope = createScope(session, values);
9991
- const explicitOptional = params.some(([key, param]) => param.optional && param.kind !== "flag" && isGiven(raw.get(key)));
10120
+ const explicitOptional = params.some(([key, param]) => param.optional && !param.target && param.kind !== "flag" && isGiven(raw.get(key)));
9992
10121
  for (const [key, param] of params) {
9993
10122
  const label = paramLabel(key, param);
9994
10123
  const given = raw.get(key);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ohmyswitch",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "Provider-first config manager for AI coding harnesses",
5
5
  "license": "MIT",
6
6
  "repository": {