@omercnet/paseo-omp 5.4.0-next.415.1 → 5.4.0-next.417.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.
@@ -62,6 +62,7 @@ import { SECURITY_QUERY_KEY } from "./omp-security-state";
62
62
  import { OmpSkillsSection } from "./omp-skills-section";
63
63
  import { OmpStorePicker } from "./omp-store-picker";
64
64
  import { ompStoreKey } from "./omp-store-state";
65
+ import { OmpToolConfigSection } from "./omp-tool-config-section";
65
66
  import { ToolPolicyCard } from "./omp-tool-policy";
66
67
  import { OmpUpdateRow, UPDATE_QUERY_KEY } from "./omp-update-row";
67
68
  import {
@@ -1460,6 +1461,8 @@ function OmpConfigContent({
1460
1461
  agentsQuery.isFetching
1461
1462
  }
1462
1463
  onPress={() => {
1464
+ void queryClient.invalidateQueries({ queryKey: ["paseo-omp", "tool-config"] });
1465
+ void queryClient.invalidateQueries({ queryKey: ["paseo-omp", "local-models"] });
1463
1466
  void Promise.all([
1464
1467
  configQuery.refetch(),
1465
1468
  settingsQuery.refetch(),
@@ -1634,6 +1637,13 @@ function OmpConfigContent({
1634
1637
  </View>
1635
1638
  </View>
1636
1639
  ) : null}
1640
+ <OmpToolConfigSection
1641
+ key={`${ompStoreKey(store)}:${cwd ?? ""}`}
1642
+ styles={styles}
1643
+ theme={theme}
1644
+ store={store}
1645
+ cwd={cwd}
1646
+ />
1637
1647
  {cwd === undefined ? (
1638
1648
  <OmpLocalModelsSection
1639
1649
  styles={styles}
@@ -1,10 +1,16 @@
1
1
  import { type PluginSurfaceProps, useRpc } from "@getpaseo/plugin/client";
2
- import { copyText, Icon } from "@getpaseo/plugin/client/ui";
3
- import { useQuery } from "@tanstack/react-query";
2
+ import { copyText, Icon, useToast } from "@getpaseo/plugin/client/ui";
3
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
4
4
  import { useState } from "react";
5
- import { Pressable, Text, View } from "react-native";
6
- import { listOmpRules, type OmpRule, type OmpRuleKind } from "../shared/omp-rules";
5
+ import { Pressable, Switch, Text, View } from "react-native";
6
+ import {
7
+ listOmpRules,
8
+ type OmpRule,
9
+ type OmpRuleKind,
10
+ setOmpRuleEnabled,
11
+ } from "../shared/omp-rules";
7
12
  import type { OmpStore } from "../shared/omp-store";
13
+ import { describe } from "./omp-accounts-section";
8
14
  import type { OmpConfigStyles } from "./omp-config-styles";
9
15
  import { ompStoreKey } from "./omp-store-state";
10
16
 
@@ -17,6 +23,8 @@ const COPY_LABELS: Record<CopyState, string> = {
17
23
  failed: "Copy failed",
18
24
  };
19
25
 
26
+ const RULES_KEY = ["paseo-omp", "rules"] as const;
27
+
20
28
  const GROUPS: readonly { kind: OmpRuleKind; title: string; empty: string }[] = [
21
29
  { kind: "watch", title: "Watch", empty: "No watch rules" },
22
30
  { kind: "always", title: "Always applied", empty: "No always-applied rules" },
@@ -50,7 +58,20 @@ function Detail({
50
58
  );
51
59
  }
52
60
 
53
- function RuleRow({ styles, rule }: { styles: OmpConfigStyles; rule: OmpRule }) {
61
+ interface RuleSwitch {
62
+ busy: boolean;
63
+ toggle: (name: string, enabled: boolean) => void;
64
+ }
65
+
66
+ function RuleRow({
67
+ styles,
68
+ rule,
69
+ rules,
70
+ }: {
71
+ styles: OmpConfigStyles;
72
+ rule: OmpRule;
73
+ rules: RuleSwitch;
74
+ }) {
54
75
  const [copyState, setCopyState] = useState<CopyState>("idle");
55
76
  async function copyPath() {
56
77
  try {
@@ -75,6 +96,12 @@ function RuleRow({ styles, rule }: { styles: OmpConfigStyles; rule: OmpRule }) {
75
96
  {rule.name}
76
97
  </Text>
77
98
  <Text style={styles.source}>{sourceLabel(rule)}</Text>
99
+ <Switch
100
+ accessibilityLabel={`Rule ${rule.name} is on`}
101
+ disabled={rules.busy}
102
+ value
103
+ onValueChange={() => rules.toggle(rule.name, false)}
104
+ />
78
105
  </View>
79
106
  {rule.description ? <Text style={styles.settingDescription}>{rule.description}</Text> : null}
80
107
  {details.map(([label, values]) =>
@@ -102,10 +129,12 @@ function BuiltinRules({
102
129
  theme,
103
130
  styles,
104
131
  rules,
132
+ rulesSwitch,
105
133
  }: {
106
134
  theme: Theme;
107
135
  styles: OmpConfigStyles;
108
136
  rules: OmpRule[];
137
+ rulesSwitch: RuleSwitch;
109
138
  }) {
110
139
  const [expanded, setExpanded] = useState(false);
111
140
  if (rules.length === 0) return null;
@@ -126,7 +155,9 @@ function BuiltinRules({
126
155
  <Text style={styles.rowValue}>Built-in rules ({rules.length})</Text>
127
156
  </Pressable>
128
157
  {expanded
129
- ? rules.map((rule) => <RuleRow key={rule.name} styles={styles} rule={rule} />)
158
+ ? rules.map((rule) => (
159
+ <RuleRow key={rule.name} styles={styles} rule={rule} rules={rulesSwitch} />
160
+ ))
130
161
  : null}
131
162
  </>
132
163
  );
@@ -144,10 +175,27 @@ export function OmpRulesSection({
144
175
  store?: OmpStore;
145
176
  }) {
146
177
  const loadRules = useRpc(listOmpRules);
178
+ const setEnabled = useRpc(setOmpRuleEnabled);
179
+ const toast = useToast();
180
+ const queryClient = useQueryClient();
147
181
  const rules = useQuery({
148
- queryKey: ["paseo-omp", "rules", ompStoreKey(store), cwd ?? "global"],
182
+ queryKey: [...RULES_KEY, ompStoreKey(store), cwd ?? "global"],
149
183
  queryFn: () => loadRules({ store, ...(cwd ? { cwd } : {}) }),
150
184
  });
185
+ const toggle = useMutation({
186
+ mutationKey: [...RULES_KEY, "toggle"],
187
+ mutationFn: (change: { name: string; enabled: boolean }) =>
188
+ setEnabled({ store, ...(cwd ? { cwd } : {}), ...change }),
189
+ onSuccess: async (result) => {
190
+ if (result.status === "error") toast.error(result.message);
191
+ await queryClient.invalidateQueries({ queryKey: RULES_KEY });
192
+ },
193
+ onError: (error) => toast.error(describe(error)),
194
+ });
195
+ const rulesSwitch: RuleSwitch = {
196
+ busy: toggle.isPending,
197
+ toggle: (name, enabled) => toggle.mutate({ name, enabled }),
198
+ };
151
199
  const list = rules.data;
152
200
  return (
153
201
  <>
@@ -186,9 +234,14 @@ export function OmpRulesSection({
186
234
  <Text style={styles.cardTitle}>{group.title}</Text>
187
235
  {members.length === 0 ? <Text style={styles.muted}>{group.empty}</Text> : null}
188
236
  {own.map((rule) => (
189
- <RuleRow key={rule.name} styles={styles} rule={rule} />
237
+ <RuleRow key={rule.name} styles={styles} rule={rule} rules={rulesSwitch} />
190
238
  ))}
191
- <BuiltinRules theme={theme} styles={styles} rules={builtin} />
239
+ <BuiltinRules
240
+ theme={theme}
241
+ styles={styles}
242
+ rules={builtin}
243
+ rulesSwitch={rulesSwitch}
244
+ />
192
245
  {group.kind === "watch" && !list.builtinRules ? (
193
246
  <Text style={styles.muted}>Built-in rules are off (ttsr.builtinRules)</Text>
194
247
  ) : null}
@@ -203,10 +256,16 @@ export function OmpRulesSection({
203
256
  <>
204
257
  <Text style={styles.muted}>Listed in ttsr.disabledRules, so OMP skips them</Text>
205
258
  {list.disabled.map((name) => (
206
- <View key={name} style={styles.setting}>
259
+ <View key={name} style={[styles.setting, styles.settingHeader]}>
207
260
  <Text selectable style={styles.settingValue}>
208
261
  {name}
209
262
  </Text>
263
+ <Switch
264
+ accessibilityLabel={`Rule ${name} is off`}
265
+ disabled={rulesSwitch.busy}
266
+ value={false}
267
+ onValueChange={() => rulesSwitch.toggle(name, true)}
268
+ />
210
269
  </View>
211
270
  ))}
212
271
  </>
@@ -0,0 +1,204 @@
1
+ import { type PluginSurfaceProps, useRpc } from "@getpaseo/plugin/client";
2
+ import { TextInput } from "@getpaseo/plugin/client/ui";
3
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
4
+ import { useState } from "react";
5
+ import { Pressable, Text, View } from "react-native";
6
+ import type { OmpStore } from "../shared/omp-store";
7
+ import {
8
+ type OmpToolConfigKind,
9
+ readOmpToolConfig,
10
+ writeOmpToolConfig,
11
+ } from "../shared/omp-tool-config";
12
+ import type { OmpConfigStyles } from "./omp-config-styles";
13
+ import { ompStoreKey } from "./omp-store-state";
14
+
15
+ type Theme = PluginSurfaceProps["theme"];
16
+
17
+ const KINDS: readonly { kind: OmpToolConfigKind; label: string; example: string }[] = [
18
+ {
19
+ kind: "lsp",
20
+ label: "Language servers (lsp.json)",
21
+ example: '{\n "servers": {\n "pylsp": { "disabled": true }\n }\n}',
22
+ },
23
+ {
24
+ kind: "dap",
25
+ label: "Debug adapters (dap.json)",
26
+ example:
27
+ '{\n "adapters": {\n "my-adapter": { "command": "my-dap-server", "fileTypes": [".xyz"] }\n }\n}',
28
+ },
29
+ ];
30
+
31
+ function Choice({
32
+ styles,
33
+ label,
34
+ selected,
35
+ disabled,
36
+ onPress,
37
+ }: {
38
+ styles: OmpConfigStyles;
39
+ label: string;
40
+ selected?: boolean;
41
+ disabled?: boolean;
42
+ onPress(): void;
43
+ }) {
44
+ return (
45
+ <Pressable
46
+ accessibilityRole="button"
47
+ accessibilityState={{ selected: selected === true }}
48
+ disabled={disabled}
49
+ onPress={onPress}
50
+ style={[styles.editorAction, selected ? styles.editorActionPrimary : null]}
51
+ >
52
+ <Text style={[styles.editorActionText, selected ? styles.editorActionTextPrimary : null]}>
53
+ {label}
54
+ </Text>
55
+ </Pressable>
56
+ );
57
+ }
58
+
59
+ export function OmpToolConfigSection({
60
+ styles,
61
+ theme,
62
+ store,
63
+ cwd,
64
+ }: {
65
+ styles: OmpConfigStyles;
66
+ theme: Theme;
67
+ store: OmpStore | undefined;
68
+ cwd: string | undefined;
69
+ }) {
70
+ const read = useRpc(readOmpToolConfig);
71
+ const write = useRpc(writeOmpToolConfig);
72
+ const queryClient = useQueryClient();
73
+ const [kind, setKind] = useState<OmpToolConfigKind>("lsp");
74
+ /** A draft keeps the revision it started from, so a refetch cannot hide an outside edit. */
75
+ const [drafts, setDrafts] = useState<Record<string, { text: string; revision: string }>>({});
76
+ const scope = `${ompStoreKey(store)}:${cwd ?? "user"}:${kind}`;
77
+ const queryKey = ["paseo-omp", "tool-config", ompStoreKey(store), cwd ?? "user", kind];
78
+ const target = { ...(store ? { store } : {}), ...(cwd ? { cwd } : {}), kind };
79
+ const file = useQuery({ queryKey, queryFn: () => read(target) });
80
+ const save = useMutation({
81
+ mutationKey: ["paseo-omp", "tool-config-save"],
82
+ mutationFn: (input: { revision: string; text: string }) => write({ ...target, ...input }),
83
+ onSuccess: async (result, input) => {
84
+ if (result.outcome !== "saved") return;
85
+ await queryClient.invalidateQueries({ queryKey });
86
+ setDrafts((current) => {
87
+ if (current[scope]?.text !== input.text) return current;
88
+ const { [scope]: _saved, ...rest } = current;
89
+ return rest;
90
+ });
91
+ },
92
+ });
93
+
94
+ const loaded = file.data;
95
+ const draft = drafts[scope];
96
+ const text = draft?.text ?? loaded?.text ?? "";
97
+ const dirty = draft !== undefined && loaded !== undefined && draft.text !== loaded.text;
98
+ const result = save.data;
99
+ const example = KINDS.find((entry) => entry.kind === kind)?.example ?? "";
100
+
101
+ return (
102
+ <View style={styles.card}>
103
+ <View style={styles.cardHeader}>
104
+ <Text style={styles.cardTitle}>Language server and debugger config</Text>
105
+ </View>
106
+ <View style={styles.setting}>
107
+ <View style={styles.editorActions}>
108
+ {KINDS.map((entry) => (
109
+ <Choice
110
+ key={entry.kind}
111
+ styles={styles}
112
+ label={entry.label}
113
+ selected={entry.kind === kind}
114
+ onPress={() => {
115
+ save.reset();
116
+ setKind(entry.kind);
117
+ }}
118
+ />
119
+ ))}
120
+ </View>
121
+ <Text style={styles.settingDescription}>
122
+ {cwd ? "Project file" : "User file"} for new sessions only. OMP keeps running agents on
123
+ their current servers, and reports server status only inside a session. OMP ignores an
124
+ invalid definition and only logs a warning, so Save checks the file first. Save cannot
125
+ tell which servers are built in, so a new server still needs command, fileTypes and
126
+ rootMarkers.
127
+ </Text>
128
+ {loaded ? (
129
+ <Text selectable style={styles.settingPath}>
130
+ {loaded.path}
131
+ {loaded.exists ? "" : " (not created yet)"}
132
+ </Text>
133
+ ) : null}
134
+ {loaded && loaded.otherFiles.length > 0 ? (
135
+ <Text style={styles.settingDescription}>
136
+ OMP also merges {loaded.otherFiles.join(", ")} from the same folder. This editor does
137
+ not change those files.
138
+ </Text>
139
+ ) : null}
140
+ {file.error ? (
141
+ <Text style={styles.error}>Could not read the file. Check its permissions.</Text>
142
+ ) : null}
143
+ <TextInput
144
+ accessibilityLabel={`Edit ${kind}.json`}
145
+ multiline
146
+ editable={loaded !== undefined && !save.isPending}
147
+ placeholder={example}
148
+ placeholderTextColor={theme.colors.foregroundMuted}
149
+ value={text}
150
+ onChangeText={(next) => {
151
+ save.reset();
152
+ setDrafts((current) => ({
153
+ ...current,
154
+ [scope]: { text: next, revision: current[scope]?.revision ?? loaded?.revision ?? "" },
155
+ }));
156
+ }}
157
+ style={[styles.scalarInput, { minHeight: 200, maxWidth: undefined }]}
158
+ />
159
+ {result?.outcome === "invalid"
160
+ ? result.errors.map((error) => (
161
+ <Text key={error} style={styles.error}>
162
+ {error}
163
+ </Text>
164
+ ))
165
+ : null}
166
+ {result?.outcome === "conflict" ? (
167
+ <Text style={styles.error}>
168
+ The file changed on disk. Revert to load the current version.
169
+ </Text>
170
+ ) : null}
171
+ {save.error ? <Text style={styles.error}>Could not save the file.</Text> : null}
172
+ {result?.outcome === "saved" ? (
173
+ <Text style={styles.muted}>Saved. New sessions will use it.</Text>
174
+ ) : null}
175
+ {result?.outcome === "saved"
176
+ ? result.warnings.map((warning) => (
177
+ <Text key={warning} style={styles.error}>
178
+ {warning}
179
+ </Text>
180
+ ))
181
+ : null}
182
+ <View style={styles.editorActions}>
183
+ <Choice
184
+ styles={styles}
185
+ label="Revert"
186
+ disabled={!dirty || save.isPending}
187
+ onPress={() => {
188
+ save.reset();
189
+ setDrafts(({ [scope]: _discarded, ...rest }) => rest);
190
+ void file.refetch();
191
+ }}
192
+ />
193
+ <Choice
194
+ styles={styles}
195
+ label={save.isPending ? "Saving..." : "Save"}
196
+ selected
197
+ disabled={!loaded || !dirty || save.isPending}
198
+ onPress={() => save.mutate({ revision: draft?.revision ?? "", text })}
199
+ />
200
+ </View>
201
+ </View>
202
+ </View>
203
+ );
204
+ }
package/index.server.ts CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  resolveMutateOmpPluginConfig,
25
25
  } from "./server/omp-plugins";
26
26
  import { readHostAppendPrompt, readOmpPromptFiles } from "./server/omp-prompt-files";
27
+ import { resolveSetOmpRuleEnabled } from "./server/omp-rule-switch";
27
28
  import { resolveListOmpRules } from "./server/omp-rules";
28
29
  import { resolveListOmpSecurity } from "./server/omp-security";
29
30
  import { resolveListOmpSettings, resolveUpdateOmpSettings } from "./server/omp-settings";
@@ -32,6 +33,7 @@ import {
32
33
  resolveListOmpSkills,
33
34
  resolveSetOmpSkillEnabled,
34
35
  } from "./server/omp-skills";
36
+ import { resolveReadOmpToolConfig, resolveWriteOmpToolConfig } from "./server/omp-tool-config";
35
37
  import { resolveGetOmpUpdateStatus, resolveInstallOmpUpdate } from "./server/omp-update";
36
38
  import { OmpOperationalFailureCollector } from "./server/operational-failure-diagnostics";
37
39
  import { withOmpStore } from "./server/paths";
@@ -96,11 +98,12 @@ import {
96
98
  mutateOmpPluginConfig,
97
99
  } from "./shared/omp-plugins";
98
100
  import { getOmpPromptFiles } from "./shared/omp-prompt-files";
99
- import { listOmpRules } from "./shared/omp-rules";
101
+ import { listOmpRules, setOmpRuleEnabled } from "./shared/omp-rules";
100
102
  import { listOmpSecurity } from "./shared/omp-security";
101
103
  import { listOmpSettings, updateOmpSettings } from "./shared/omp-settings";
102
104
  import { deleteOmpManagedSkill, listOmpSkills, setOmpSkillEnabled } from "./shared/omp-skills";
103
105
  import { listOmpStores, type OmpStore } from "./shared/omp-store";
106
+ import { readOmpToolConfig, writeOmpToolConfig } from "./shared/omp-tool-config";
104
107
  import { getOmpUpdateStatus, installOmpUpdate } from "./shared/omp-update";
105
108
  import { getOmpProviderHealth } from "./shared/provider-diagnostics";
106
109
  import { getOmpImage } from "./shared/provider-image";
@@ -223,6 +226,7 @@ export default function contribute(server: PluginServerContext) {
223
226
  server.handle(browseOmpMarketplace, scoped(resolveBrowseOmpMarketplace));
224
227
  server.handle(mutateOmpMarketplace, scoped(resolveMutateOmpMarketplace));
225
228
  server.handle(listOmpRules, scoped(resolveListOmpRules));
229
+ server.handle(setOmpRuleEnabled, scoped(resolveSetOmpRuleEnabled));
226
230
  server.handle(listOmpExtensions, scoped(resolveListOmpExtensions));
227
231
  server.handle(setOmpExtensionEnabled, scoped(resolveSetOmpExtensionEnabled));
228
232
  server.handle(listOmpSecurity, scoped(resolveListOmpSecurity));
@@ -234,6 +238,8 @@ export default function contribute(server: PluginServerContext) {
234
238
  server.handle(mutateOmpPluginConfig, scoped(resolveMutateOmpPluginConfig));
235
239
  server.handle(listOmpSettings, scoped(resolveListOmpSettings));
236
240
  server.handle(updateOmpSettings, scoped(resolveUpdateOmpSettings));
241
+ server.handle(readOmpToolConfig, scoped(resolveReadOmpToolConfig));
242
+ server.handle(writeOmpToolConfig, scoped(resolveWriteOmpToolConfig));
237
243
  server.handle(listOmpLocalModels, scoped(resolveListOmpLocalModels));
238
244
  server.handle(downloadOmpLocalModel, scoped(resolveDownloadOmpLocalModel));
239
245
  server.handle(getOmpProviderHealth, scoped(resolveGetOmpProviderHealth));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omercnet/paseo-omp",
3
- "version": "5.4.0-next.415.1",
3
+ "version": "5.4.0-next.417.1",
4
4
  "type": "module",
5
5
  "description": "Paseo integration for OMP, including its direct provider and workspace tooling.",
6
6
  "license": "MIT",
@@ -9,7 +9,7 @@ import {
9
9
  } from "./omp-settings";
10
10
  import { OmpPublicError } from "./provider/security";
11
11
 
12
- export type OmpListName = "skills.ignoredSkills" | "disabledExtensions";
12
+ export type OmpListName = "skills.ignoredSkills" | "disabledExtensions" | "ttsr.disabledRules";
13
13
 
14
14
  export class OmpListError extends OmpPublicError {}
15
15
 
@@ -0,0 +1,38 @@
1
+ import type { RpcInput } from "@getpaseo/plugin";
2
+ import type { setOmpRuleEnabled } from "../shared/omp-rules";
3
+ import {
4
+ type OmpListDependencies,
5
+ ompListDependencies,
6
+ requireOmpExecutable,
7
+ writeListEntry,
8
+ } from "./omp-list-setting";
9
+ import { inOmpScope } from "./omp-rules";
10
+ import { runSettingsMutation } from "./omp-settings";
11
+ import { OmpPublicError } from "./provider/security";
12
+
13
+ /** Off adds the rule to `ttsr.disabledRules`; on removes it. A workspace saves the whole project list. */
14
+ export async function setOmpRuleEnabledWithDependencies(
15
+ input: RpcInput<typeof setOmpRuleEnabled>,
16
+ dependencies: OmpListDependencies,
17
+ ): Promise<{ status: "ok" } | { status: "error"; message: string }> {
18
+ try {
19
+ const executable = await requireOmpExecutable(dependencies);
20
+ const change = {
21
+ cwd: input.cwd,
22
+ list: "ttsr.disabledRules" as const,
23
+ entry: input.name,
24
+ enabled: input.enabled,
25
+ };
26
+ await inOmpScope(input.cwd, dependencies, (runIn) =>
27
+ runSettingsMutation(() => writeListEntry(change, dependencies, executable, runIn)),
28
+ );
29
+ return { status: "ok" };
30
+ } catch (error) {
31
+ if (error instanceof OmpPublicError) return { status: "error", message: error.message };
32
+ throw error;
33
+ }
34
+ }
35
+
36
+ export function resolveSetOmpRuleEnabled(input: RpcInput<typeof setOmpRuleEnabled>) {
37
+ return setOmpRuleEnabledWithDependencies(input, ompListDependencies);
38
+ }
@@ -0,0 +1,144 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { isAbsolute, join } from "node:path";
4
+ import type { RpcInput, RpcOutput } from "@getpaseo/plugin";
5
+ import {
6
+ MAX_TOOL_CONFIG_BYTES,
7
+ type OmpToolConfigKind,
8
+ type readOmpToolConfig,
9
+ validateOmpToolConfig,
10
+ warnOmpToolConfig,
11
+ type writeOmpToolConfig,
12
+ } from "../shared/omp-tool-config";
13
+ import { SerialMutationQueue } from "./mutation-queue";
14
+ import { ompAgentDir } from "./paths";
15
+ import { OmpPublicError } from "./provider/security";
16
+
17
+ export class OmpToolConfigError extends OmpPublicError {}
18
+
19
+ type ReadInput = RpcInput<typeof readOmpToolConfig>;
20
+ type WriteInput = RpcInput<typeof writeOmpToolConfig>;
21
+
22
+ function variantsOf(kind: OmpToolConfigKind): string[] {
23
+ return [`.${kind}.json`, `${kind}.yaml`, `.${kind}.yaml`, `${kind}.yml`, `.${kind}.yml`];
24
+ }
25
+
26
+ function locate({ cwd, kind }: Pick<ReadInput, "cwd" | "kind">) {
27
+ if (cwd !== undefined && (!isAbsolute(cwd) || cwd.includes("\0"))) {
28
+ throw new OmpToolConfigError("The workspace path is invalid.");
29
+ }
30
+ const directory = cwd === undefined ? ompAgentDir() : join(cwd, ".omp");
31
+ return { directory, path: join(directory, `${kind}.json`) };
32
+ }
33
+
34
+ /** A cloned project could point .omp anywhere, so a project folder that is a symlink is refused. */
35
+ async function refuseLinkedProjectFolder(directory: string, cwd: string | undefined) {
36
+ if (cwd === undefined) return;
37
+ try {
38
+ if ((await lstat(directory)).isSymbolicLink()) {
39
+ throw new OmpToolConfigError("A symlinked .omp folder cannot be edited here.");
40
+ }
41
+ } catch (error) {
42
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
43
+ }
44
+ }
45
+
46
+ function revisionOf(text: string | null): string {
47
+ return text === null ? "" : createHash("sha256").update(text).digest("hex");
48
+ }
49
+
50
+ /** The file's text, or null when it does not exist. A symlink or an oversized file is refused. */
51
+ async function readExisting(path: string): Promise<string | null> {
52
+ let size: number;
53
+ try {
54
+ const metadata = await lstat(path);
55
+ if (metadata.isSymbolicLink()) {
56
+ throw new OmpToolConfigError("A symlinked OMP configuration file cannot be edited here.");
57
+ }
58
+ if (!metadata.isFile()) throw new OmpToolConfigError("The OMP configuration is not a file.");
59
+ size = metadata.size;
60
+ } catch (error) {
61
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
62
+ throw error;
63
+ }
64
+ if (size > MAX_TOOL_CONFIG_BYTES) {
65
+ throw new OmpToolConfigError("The OMP configuration file is too large to edit here.");
66
+ }
67
+ return readFile(path, "utf8");
68
+ }
69
+
70
+ async function existingVariants(directory: string, kind: OmpToolConfigKind): Promise<string[]> {
71
+ const found: string[] = [];
72
+ for (const name of variantsOf(kind)) {
73
+ try {
74
+ await lstat(join(directory, name));
75
+ found.push(name);
76
+ } catch (error) {
77
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
78
+ }
79
+ }
80
+ return found;
81
+ }
82
+
83
+ export async function resolveReadOmpToolConfig(
84
+ input: ReadInput,
85
+ ): Promise<RpcOutput<typeof readOmpToolConfig>> {
86
+ const { directory, path } = locate(input);
87
+ await refuseLinkedProjectFolder(directory, input.cwd);
88
+ const text = await readExisting(path);
89
+ return {
90
+ path,
91
+ exists: text !== null,
92
+ text: text ?? "",
93
+ revision: revisionOf(text),
94
+ otherFiles: await existingVariants(directory, input.kind),
95
+ };
96
+ }
97
+
98
+ async function writeToolConfig(input: WriteInput): Promise<RpcOutput<typeof writeOmpToolConfig>> {
99
+ const text = input.text.endsWith("\n") ? input.text : `${input.text}\n`;
100
+ const errors = validateOmpToolConfig(input.kind, input.text);
101
+ if (Buffer.byteLength(text) > MAX_TOOL_CONFIG_BYTES) {
102
+ errors.push("The file is larger than 256 KiB, which this editor will not open again.");
103
+ }
104
+ if (errors.length > 0)
105
+ return { outcome: "invalid", errors, warnings: [], revision: input.revision };
106
+
107
+ const { directory, path } = locate(input);
108
+ await refuseLinkedProjectFolder(directory, input.cwd);
109
+ const snapshot = await readExisting(path);
110
+ if (revisionOf(snapshot) !== input.revision) {
111
+ return { outcome: "conflict", errors: [], warnings: [], revision: revisionOf(snapshot) };
112
+ }
113
+
114
+ await mkdir(directory, { recursive: true });
115
+ const temporaryPath = `${path}.${randomUUID()}.tmp`;
116
+ try {
117
+ await writeFile(temporaryPath, text, { encoding: "utf8", mode: 0o600 });
118
+ if ((await readExisting(path)) !== snapshot) {
119
+ return {
120
+ outcome: "conflict",
121
+ errors: [],
122
+ warnings: [],
123
+ revision: revisionOf(await readExisting(path)),
124
+ };
125
+ }
126
+ await rename(temporaryPath, path);
127
+ return {
128
+ outcome: "saved",
129
+ errors: [],
130
+ warnings: warnOmpToolConfig(input.kind, text),
131
+ revision: revisionOf(text),
132
+ };
133
+ } finally {
134
+ await unlink(temporaryPath).catch(() => {});
135
+ }
136
+ }
137
+
138
+ const writeQueue = new SerialMutationQueue();
139
+
140
+ export function resolveWriteOmpToolConfig(
141
+ input: WriteInput,
142
+ ): Promise<RpcOutput<typeof writeOmpToolConfig>> {
143
+ return writeQueue.run(() => writeToolConfig(input));
144
+ }
@@ -1,2 +1,2 @@
1
1
  /** Release Please keeps this bundle-safe constant aligned with package.json. */
2
- export const PASEO_OMP_PACKAGE_VERSION = "5.4.0-next.415.1"; // x-release-please-version
2
+ export const PASEO_OMP_PACKAGE_VERSION = "5.4.0-next.417.1"; // x-release-please-version
@@ -47,3 +47,20 @@ export const listOmpRules = defineRpc({
47
47
  .strict(),
48
48
  output: OmpRulesListSchema,
49
49
  });
50
+
51
+ /** Off adds `name` to `ttsr.disabledRules`; on removes it. A workspace writes its own `.omp/config.yml`. */
52
+ export const setOmpRuleEnabled = defineRpc({
53
+ name: "paseo-omp.set-rule-enabled",
54
+ input: z
55
+ .object({
56
+ store: OmpStoreSchema.optional(),
57
+ cwd: OmpWorkspaceCwdSchema.optional(),
58
+ name: z.string().trim().min(1).max(256),
59
+ enabled: z.boolean(),
60
+ })
61
+ .strict(),
62
+ output: z.discriminatedUnion("status", [
63
+ z.object({ status: z.literal("ok") }),
64
+ z.object({ status: z.literal("error"), message: z.string() }),
65
+ ]),
66
+ });
@@ -0,0 +1,283 @@
1
+ import { defineRpc } from "@getpaseo/plugin";
2
+ import { z } from "zod";
3
+ import { OmpWorkspaceCwdSchema } from "./hub";
4
+ import { OmpStoreSchema } from "./omp-store";
5
+
6
+ /** OMP reads `lsp.json` for language servers and `dap.json` for debug adapters, from the user and the project. */
7
+ export const OmpToolConfigKindSchema = z.enum(["lsp", "dap"]);
8
+ export type OmpToolConfigKind = z.infer<typeof OmpToolConfigKindSchema>;
9
+
10
+ export const MAX_TOOL_CONFIG_BYTES = 256 * 1024;
11
+
12
+ const stringList = z.array(z.string());
13
+ const object = z.record(z.string(), z.unknown());
14
+
15
+ const LspServerSchema = z
16
+ .looseObject({
17
+ command: z.string().min(1).optional(),
18
+ args: stringList.optional(),
19
+ fileTypes: stringList.optional(),
20
+ languageId: z.string().optional(),
21
+ rootMarkers: stringList.optional(),
22
+ initOptions: object.optional(),
23
+ settings: object.optional(),
24
+ disabled: z.boolean().optional(),
25
+ warmupTimeoutMs: z.number().optional(),
26
+ isLinter: z.boolean().optional(),
27
+ capabilities: z.record(z.string(), z.boolean()).optional(),
28
+ workspaceReadyTimings: z.record(z.string(), z.number()).optional(),
29
+ })
30
+ .refine(
31
+ (server) => !("resolvedCommand" in server) && !("createClient" in server),
32
+ "resolvedCommand and createClient are owned by OMP and cannot be configured",
33
+ );
34
+
35
+ const DapAdapterSchema = z
36
+ .looseObject({
37
+ command: z.string().min(1).optional(),
38
+ args: stringList.optional(),
39
+ languages: stringList.optional(),
40
+ fileTypes: stringList.optional(),
41
+ rootMarkers: stringList.optional(),
42
+ launchDefaults: object.optional(),
43
+ attachDefaults: object.optional(),
44
+ connectMode: z.enum(["stdio", "socket", "tcp"]).optional(),
45
+ acceptsDirectoryProgram: z.boolean().optional(),
46
+ })
47
+ .refine(
48
+ (adapter) => !("skipAttachRequest" in adapter),
49
+ "skipAttachRequest belongs inside attachDefaults, where OMP reads it",
50
+ );
51
+
52
+ const LspFileSchema = z.looseObject({ idleTimeoutMs: z.number().optional() });
53
+
54
+ function describe(issue: z.core.$ZodIssue, prefix: string): string {
55
+ const path = [prefix, ...issue.path.map(String)].filter(Boolean).join(".");
56
+ return path ? `${path}: ${issue.message}` : issue.message;
57
+ }
58
+
59
+ function isObject(value: unknown): value is Record<string, unknown> {
60
+ return value !== null && typeof value === "object" && !Array.isArray(value);
61
+ }
62
+
63
+ /** OMP accepts a wrapper key or a flat map of entries. For lsp.json, mixing them silently drops the flat ones. */
64
+ function entriesOf(
65
+ document: Record<string, unknown>,
66
+ wrapper: "servers" | "adapters",
67
+ ignoredKeys: readonly string[],
68
+ rejectMixed: boolean,
69
+ ): { entries: Record<string, unknown>; errors: string[] } {
70
+ const wrapped = document[wrapper];
71
+ if (wrapped === undefined) {
72
+ const flat = Object.entries(document).filter(([key]) => !ignoredKeys.includes(key));
73
+ return { entries: Object.fromEntries(flat), errors: [] };
74
+ }
75
+ if (!isObject(wrapped)) return { entries: {}, errors: [`${wrapper} must be an object`] };
76
+ const stray = Object.keys(document).filter(
77
+ (key) => key !== wrapper && !ignoredKeys.includes(key),
78
+ );
79
+ const errors =
80
+ rejectMixed && stray.length > 0
81
+ ? [`Do not mix ${wrapper} with entries at the top level (${stray.join(", ")})`]
82
+ : [];
83
+ return { entries: wrapped, errors };
84
+ }
85
+
86
+ /** Problems that make OMP ignore a definition, found before the file is written. Empty means valid. */
87
+ export function validateOmpToolConfig(kind: OmpToolConfigKind, text: string): string[] {
88
+ let document: unknown;
89
+ try {
90
+ document = JSON.parse(text);
91
+ } catch (error) {
92
+ return [`Not valid JSON: ${error instanceof Error ? error.message : "parse error"}`];
93
+ }
94
+ if (!isObject(document)) return ["The file must hold a JSON object"];
95
+
96
+ const wrapper = kind === "lsp" ? "servers" : "adapters";
97
+ const ignoredKeys = kind === "lsp" ? ["idleTimeoutMs"] : [];
98
+ const errors: string[] = [];
99
+ if (kind === "lsp") {
100
+ const top = LspFileSchema.safeParse(document);
101
+ if (!top.success) errors.push(...top.error.issues.map((issue) => describe(issue, "")));
102
+ }
103
+ const { entries, errors: shapeErrors } = entriesOf(
104
+ document,
105
+ wrapper,
106
+ ignoredKeys,
107
+ kind === "lsp",
108
+ );
109
+ errors.push(...shapeErrors);
110
+ const schema = kind === "lsp" ? LspServerSchema : DapAdapterSchema;
111
+ for (const [name, entry] of Object.entries(entries)) {
112
+ const parsed = schema.safeParse(entry);
113
+ if (!parsed.success) {
114
+ errors.push(...parsed.error.issues.map((issue) => describe(issue, name)));
115
+ }
116
+ }
117
+ return errors;
118
+ }
119
+
120
+ /** The debug adapters OMP ships. An override of one inherits its command. */
121
+ const BUILT_IN_DAP_ADAPTERS: ReadonlySet<string> = new Set([
122
+ "gdb",
123
+ "lldb-dap",
124
+ "codelldb",
125
+ "debugpy",
126
+ "dlv",
127
+ "js-debug-adapter",
128
+ "netcoredbg",
129
+ "kotlin-debug-adapter",
130
+ "rdbg",
131
+ "php-debug-adapter",
132
+ "bash-debug-adapter",
133
+ "dart-debug-adapter",
134
+ "flutter-debug-adapter",
135
+ "elixir-ls-debugger",
136
+ ]);
137
+
138
+ /** The servers OMP ships. Any other name is a new definition, which OMP drops unless it is complete. */
139
+ const BUILT_IN_LSP_SERVERS: ReadonlySet<string> = new Set([
140
+ "rust-analyzer",
141
+ "clangd",
142
+ "zls",
143
+ "gopls",
144
+ "typescript-language-server",
145
+ "typescript-native",
146
+ "denols",
147
+ "biome",
148
+ "eslint",
149
+ "vscode-html-language-server",
150
+ "vscode-css-language-server",
151
+ "vscode-json-language-server",
152
+ "tailwindcss",
153
+ "svelte",
154
+ "vue-language-server",
155
+ "astro",
156
+ "pyright",
157
+ "basedpyright",
158
+ "pylsp",
159
+ "ty",
160
+ "ruff",
161
+ "jdtls",
162
+ "kotlin-lsp",
163
+ "metals",
164
+ "hls",
165
+ "ocamllsp",
166
+ "elixirls",
167
+ "expert",
168
+ "erlangls",
169
+ "gleam",
170
+ "solargraph",
171
+ "ruby-lsp",
172
+ "rubocop",
173
+ "bashls",
174
+ "lua-language-server",
175
+ "intelephense",
176
+ "phpactor",
177
+ "omnisharp",
178
+ "yamlls",
179
+ "terraformls",
180
+ "dockerls",
181
+ "helm-ls",
182
+ "nixd",
183
+ "nil",
184
+ "ols",
185
+ "dartls",
186
+ "marksman",
187
+ "texlab",
188
+ "graphql",
189
+ "prismals",
190
+ "vimls",
191
+ "emmet-language-server",
192
+ "sourcekit-lsp",
193
+ "swiftlint",
194
+ "tlaplus",
195
+ ]);
196
+
197
+ /**
198
+ * Definitions that pass validation but that OMP drops: a server that is not built in needs a
199
+ * command, file types and root markers (or extensionToLanguage, which supplies both).
200
+ */
201
+ function hasText(value: unknown): boolean {
202
+ return Array.isArray(value) && value.some((item) => typeof item === "string" && item.length > 0);
203
+ }
204
+
205
+ export function warnOmpToolConfig(kind: OmpToolConfigKind, text: string): string[] {
206
+ let document: unknown;
207
+ try {
208
+ document = JSON.parse(text);
209
+ } catch {
210
+ return [];
211
+ }
212
+ if (!isObject(document)) return [];
213
+ const lsp = kind === "lsp";
214
+ const { entries } = entriesOf(
215
+ document,
216
+ lsp ? "servers" : "adapters",
217
+ lsp ? ["idleTimeoutMs"] : [],
218
+ false,
219
+ );
220
+ const builtIn = lsp ? BUILT_IN_LSP_SERVERS : BUILT_IN_DAP_ADAPTERS;
221
+ const ignored =
222
+ !lsp && isObject(document.adapters)
223
+ ? Object.keys(document).filter((key) => key !== "adapters")
224
+ : [];
225
+ const ignoredWarning =
226
+ ignored.length > 0
227
+ ? [`OMP ignores ${ignored.join(", ")} because adapters is present; move them inside adapters`]
228
+ : [];
229
+ return [
230
+ ...ignoredWarning,
231
+ ...Object.entries(entries).flatMap(([name, entry]) => {
232
+ if (builtIn.has(name) || !isObject(entry)) return [];
233
+ const extensions = isObject(entry.extensionToLanguage)
234
+ ? Object.keys(entry.extensionToLanguage).filter((extension) => extension.length > 0)
235
+ : [];
236
+ const missing = [
237
+ typeof entry.command === "string" && entry.command ? null : "command",
238
+ !lsp || extensions.length > 0 || hasText(entry.fileTypes) ? null : "fileTypes",
239
+ !lsp || extensions.length > 0 || hasText(entry.rootMarkers) ? null : "rootMarkers",
240
+ ].filter((field) => field !== null);
241
+ return missing.length === 0
242
+ ? []
243
+ : [
244
+ `${name} is not a built-in ${lsp ? "server" : "adapter"}, so OMP ignores it without ${missing.join(", ")}`,
245
+ ];
246
+ }),
247
+ ];
248
+ }
249
+
250
+ const ToolConfigTargetSchema = z.object({
251
+ store: OmpStoreSchema.optional(),
252
+ /** A workspace folder selects its project file; without one the user file is used. */
253
+ cwd: OmpWorkspaceCwdSchema.optional(),
254
+ kind: OmpToolConfigKindSchema,
255
+ });
256
+
257
+ export const readOmpToolConfig = defineRpc({
258
+ name: "paseo-omp.read-tool-config",
259
+ input: ToolConfigTargetSchema.strict(),
260
+ output: z.object({
261
+ path: z.string(),
262
+ exists: z.boolean(),
263
+ text: z.string(),
264
+ revision: z.string(),
265
+ /** Sibling variants OMP also merges, such as lsp.yaml, which this editor does not change. */
266
+ otherFiles: z.array(z.string()),
267
+ }),
268
+ });
269
+
270
+ export const writeOmpToolConfig = defineRpc({
271
+ name: "paseo-omp.write-tool-config",
272
+ input: ToolConfigTargetSchema.extend({
273
+ revision: z.string(),
274
+ text: z.string().max(MAX_TOOL_CONFIG_BYTES),
275
+ }).strict(),
276
+ output: z.object({
277
+ outcome: z.enum(["saved", "conflict", "invalid"]),
278
+ errors: z.array(z.string()),
279
+ /** Saved anyway, but OMP will not use these definitions. */
280
+ warnings: z.array(z.string()),
281
+ revision: z.string(),
282
+ }),
283
+ });