@omercnet/paseo-omp 5.4.0-next.415.1 → 5.4.0-next.416.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}
@@ -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
@@ -32,6 +32,7 @@ import {
32
32
  resolveListOmpSkills,
33
33
  resolveSetOmpSkillEnabled,
34
34
  } from "./server/omp-skills";
35
+ import { resolveReadOmpToolConfig, resolveWriteOmpToolConfig } from "./server/omp-tool-config";
35
36
  import { resolveGetOmpUpdateStatus, resolveInstallOmpUpdate } from "./server/omp-update";
36
37
  import { OmpOperationalFailureCollector } from "./server/operational-failure-diagnostics";
37
38
  import { withOmpStore } from "./server/paths";
@@ -101,6 +102,7 @@ import { listOmpSecurity } from "./shared/omp-security";
101
102
  import { listOmpSettings, updateOmpSettings } from "./shared/omp-settings";
102
103
  import { deleteOmpManagedSkill, listOmpSkills, setOmpSkillEnabled } from "./shared/omp-skills";
103
104
  import { listOmpStores, type OmpStore } from "./shared/omp-store";
105
+ import { readOmpToolConfig, writeOmpToolConfig } from "./shared/omp-tool-config";
104
106
  import { getOmpUpdateStatus, installOmpUpdate } from "./shared/omp-update";
105
107
  import { getOmpProviderHealth } from "./shared/provider-diagnostics";
106
108
  import { getOmpImage } from "./shared/provider-image";
@@ -234,6 +236,8 @@ export default function contribute(server: PluginServerContext) {
234
236
  server.handle(mutateOmpPluginConfig, scoped(resolveMutateOmpPluginConfig));
235
237
  server.handle(listOmpSettings, scoped(resolveListOmpSettings));
236
238
  server.handle(updateOmpSettings, scoped(resolveUpdateOmpSettings));
239
+ server.handle(readOmpToolConfig, scoped(resolveReadOmpToolConfig));
240
+ server.handle(writeOmpToolConfig, scoped(resolveWriteOmpToolConfig));
237
241
  server.handle(listOmpLocalModels, scoped(resolveListOmpLocalModels));
238
242
  server.handle(downloadOmpLocalModel, scoped(resolveDownloadOmpLocalModel));
239
243
  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.416.1",
4
4
  "type": "module",
5
5
  "description": "Paseo integration for OMP, including its direct provider and workspace tooling.",
6
6
  "license": "MIT",
@@ -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.416.1"; // x-release-please-version
@@ -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
+ });