@omercnet/paseo-omp 5.4.0-next.414.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.
@@ -47,6 +47,7 @@ import {
47
47
  type OmpDocumentationLink,
48
48
  } from "./omp-doc-links";
49
49
  import { OmpExtensionsSection } from "./omp-extensions-section";
50
+ import { OmpLocalModelsSection } from "./omp-local-models-section";
50
51
  import { OmpMcpsSection } from "./omp-mcps-section";
51
52
  import { normalizeOmpModels } from "./omp-model-picker-state";
52
53
  import { OmpPluginManagerSection } from "./omp-plugin-manager";
@@ -61,6 +62,7 @@ import { SECURITY_QUERY_KEY } from "./omp-security-state";
61
62
  import { OmpSkillsSection } from "./omp-skills-section";
62
63
  import { OmpStorePicker } from "./omp-store-picker";
63
64
  import { ompStoreKey } from "./omp-store-state";
65
+ import { OmpToolConfigSection } from "./omp-tool-config-section";
64
66
  import { ToolPolicyCard } from "./omp-tool-policy";
65
67
  import { OmpUpdateRow, UPDATE_QUERY_KEY } from "./omp-update-row";
66
68
  import {
@@ -1240,6 +1242,15 @@ function OmpConfigContent({
1240
1242
  ? drafts.modelRoles.value
1241
1243
  : undefined
1242
1244
  : catalog.sourceSettings.find((setting) => setting.path === "modelRoles")?.value;
1245
+ const savedModelRolesValue = catalog.sourceSettings.find(
1246
+ (setting) => setting.path === "modelRoles",
1247
+ )?.value;
1248
+ const savedModelRoles =
1249
+ savedModelRolesValue !== null &&
1250
+ typeof savedModelRolesValue === "object" &&
1251
+ !Array.isArray(savedModelRolesValue)
1252
+ ? (savedModelRolesValue as Readonly<Record<string, unknown>>)
1253
+ : {};
1243
1254
  const modelRoles =
1244
1255
  modelRolesValue !== null &&
1245
1256
  typeof modelRolesValue === "object" &&
@@ -1450,6 +1461,8 @@ function OmpConfigContent({
1450
1461
  agentsQuery.isFetching
1451
1462
  }
1452
1463
  onPress={() => {
1464
+ void queryClient.invalidateQueries({ queryKey: ["paseo-omp", "tool-config"] });
1465
+ void queryClient.invalidateQueries({ queryKey: ["paseo-omp", "local-models"] });
1453
1466
  void Promise.all([
1454
1467
  configQuery.refetch(),
1455
1468
  settingsQuery.refetch(),
@@ -1624,6 +1637,27 @@ function OmpConfigContent({
1624
1637
  </View>
1625
1638
  </View>
1626
1639
  ) : null}
1640
+ <OmpToolConfigSection
1641
+ key={`${ompStoreKey(store)}:${cwd ?? ""}`}
1642
+ styles={styles}
1643
+ theme={theme}
1644
+ store={store}
1645
+ cwd={cwd}
1646
+ />
1647
+ {cwd === undefined ? (
1648
+ <OmpLocalModelsSection
1649
+ styles={styles}
1650
+ store={store}
1651
+ modelRoles={savedModelRoles}
1652
+ settingsRevision={settingsQuery.data?.revision}
1653
+ rolesPending={drafts.modelRoles !== undefined}
1654
+ onRolesChanged={(catalog) => {
1655
+ if (catalog) queryClient.setQueryData(settingsQueryKey, catalog);
1656
+ void queryClient.invalidateQueries({ queryKey: SETTINGS_QUERY_KEY });
1657
+ void queryClient.invalidateQueries({ queryKey: ["paseo-omp", "config"] });
1658
+ }}
1659
+ />
1660
+ ) : null}
1627
1661
  </>
1628
1662
  ) : null}
1629
1663
  </ScrollView>
@@ -0,0 +1,215 @@
1
+ import { useRpc } from "@getpaseo/plugin/client";
2
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
3
+ import { useState } from "react";
4
+ import { Pressable, Text, View } from "react-native";
5
+ import {
6
+ downloadOmpLocalModel,
7
+ listOmpLocalModels,
8
+ type OmpLocalModel,
9
+ withLocalModelRole,
10
+ } from "../shared/omp-local-models";
11
+ import { type OmpSettingsCatalog, updateOmpSettings } from "../shared/omp-settings";
12
+ import type { OmpStore } from "../shared/omp-store";
13
+ import type { OmpConfigStyles } from "./omp-config-styles";
14
+ import { ompStoreKey } from "./omp-store-state";
15
+
16
+ const POLL_MS = 3_000;
17
+ const ACTION_GROUP = { flexDirection: "row", flexWrap: "wrap", gap: 8 } as const;
18
+
19
+ const ROLES = [
20
+ { role: "tiny", label: "titles" },
21
+ { role: "memory", label: "memory" },
22
+ ] as const;
23
+
24
+ function Choice({
25
+ styles,
26
+ label,
27
+ accessibilityLabel,
28
+ selected,
29
+ disabled,
30
+ onPress,
31
+ }: {
32
+ styles: OmpConfigStyles;
33
+ label: string;
34
+ accessibilityLabel: string;
35
+ selected?: boolean;
36
+ disabled?: boolean;
37
+ onPress(): void;
38
+ }) {
39
+ return (
40
+ <Pressable
41
+ accessibilityRole="button"
42
+ accessibilityLabel={accessibilityLabel}
43
+ accessibilityState={{ selected: selected === true }}
44
+ disabled={disabled}
45
+ onPress={onPress}
46
+ style={[styles.editorAction, selected ? styles.editorActionPrimary : null]}
47
+ >
48
+ <Text style={[styles.editorActionText, selected ? styles.editorActionTextPrimary : null]}>
49
+ {label}
50
+ </Text>
51
+ </Pressable>
52
+ );
53
+ }
54
+
55
+ function status(model: OmpLocalModel): string {
56
+ if (model.download === "running") return "Downloading...";
57
+ if (model.download === "failed") return `Download failed: ${model.error ?? "unknown error"}`;
58
+ return model.downloaded ? "Downloaded" : "Not downloaded";
59
+ }
60
+
61
+ /** OMP's own on-device models for titles and memory. Not Paseo's Voice and Dictation models. */
62
+ export function OmpLocalModelsSection({
63
+ styles,
64
+ store,
65
+ modelRoles,
66
+ settingsRevision,
67
+ rolesPending,
68
+ onRolesChanged,
69
+ }: {
70
+ styles: OmpConfigStyles;
71
+ store: OmpStore | undefined;
72
+ modelRoles: Readonly<Record<string, unknown>>;
73
+ settingsRevision: string | undefined;
74
+ /** Unapplied edits to modelRoles would be overwritten by a role assignment made here. */
75
+ rolesPending: boolean;
76
+ onRolesChanged(catalog: OmpSettingsCatalog | undefined): void;
77
+ }) {
78
+ const list = useRpc(listOmpLocalModels);
79
+ const download = useRpc(downloadOmpLocalModel);
80
+ const update = useRpc(updateOmpSettings);
81
+ const queryClient = useQueryClient();
82
+ const [confirming, setConfirming] = useState<string | null>(null);
83
+ const queryKey = ["paseo-omp", "local-models", ompStoreKey(store)];
84
+ const models = useQuery({
85
+ queryKey,
86
+ queryFn: () => list(store ? { store } : {}),
87
+ refetchInterval: (query) =>
88
+ query.state.data?.models.some((model) => model.download === "running") ? POLL_MS : false,
89
+ });
90
+ const start = useMutation({
91
+ mutationKey: ["paseo-omp", "local-model-download"],
92
+ mutationFn: (key: string) => download({ ...(store ? { store } : {}), key }),
93
+ onSettled: () => queryClient.invalidateQueries({ queryKey }),
94
+ });
95
+ const assign = useMutation({
96
+ mutationKey: ["paseo-omp", "settings", ompStoreKey(store)],
97
+ mutationFn: async (next: Record<string, unknown>) => {
98
+ if (!settingsRevision) throw new Error("OMP settings cannot be edited without a revision.");
99
+ const input = updateOmpSettings.input.parse({
100
+ ...(store ? { store } : {}),
101
+ revision: settingsRevision,
102
+ changes: [{ operation: "set", path: "modelRoles", value: next }],
103
+ });
104
+ return update(input);
105
+ },
106
+ onSuccess: (result) => onRolesChanged(result.catalog),
107
+ onError: () => onRolesChanged(undefined),
108
+ });
109
+
110
+ const busy = models.data?.models.some((model) => model.download === "running") === true;
111
+ const blocked = !settingsRevision || rolesPending || assign.isPending;
112
+ const failed = start.data && start.data.outcome !== "started";
113
+
114
+ function assignRole(role: string, selector: string | null) {
115
+ assign.mutate(withLocalModelRole(modelRoles, role, selector));
116
+ }
117
+
118
+ return (
119
+ <View style={styles.card}>
120
+ <View style={styles.cardHeader}>
121
+ <Text style={styles.cardTitle}>OMP local models</Text>
122
+ </View>
123
+ <View style={styles.setting}>
124
+ <Text style={styles.settingDescription}>
125
+ Small models OMP runs on this machine for session titles and memory. They belong to OMP
126
+ only and are separate from Paseo's own Voice and Dictation models. Role changes apply to
127
+ new sessions or after a reload. A local titles role never falls back to an online model:
128
+ if the local model fails, the session stays untitled. The first download can also install
129
+ OMP's inference runtime, so it may take longer and use more disk than the model size.
130
+ </Text>
131
+ {models.error || (models.data && !models.data.available) ? (
132
+ <Text style={styles.error}>OMP could not list its local models.</Text>
133
+ ) : null}
134
+ {start.error ? <Text style={styles.error}>Could not start the download.</Text> : null}
135
+ {failed ? (
136
+ <Text style={styles.error}>
137
+ {start.data?.outcome === "busy"
138
+ ? "Another download is still running."
139
+ : "OMP could not start that download."}
140
+ </Text>
141
+ ) : null}
142
+ {assign.error || (assign.data && (assign.data.conflict || assign.data.failed)) ? (
143
+ <Text style={styles.error}>
144
+ Could not change the role. Refresh the settings and try again.
145
+ </Text>
146
+ ) : null}
147
+ </View>
148
+ {models.data?.models.map((model) => (
149
+ <View key={model.key} style={styles.setting}>
150
+ <View style={styles.settingHeader}>
151
+ <Text style={styles.cardTitle}>{model.label}</Text>
152
+ <Text style={styles.source}>{status(model)}</Text>
153
+ </View>
154
+ <Text selectable style={styles.settingPath}>
155
+ {model.key}
156
+ </Text>
157
+ <Text style={styles.settingDescription}>{model.description}</Text>
158
+ {confirming === model.key ? (
159
+ <View style={styles.recordList}>
160
+ <Text style={styles.settingDescription}>
161
+ Download {model.label}
162
+ {model.sizeMb ? ` (about ${model.sizeMb} MB)` : ""} to this machine? OMP shows no
163
+ progress, so this can take several minutes.
164
+ </Text>
165
+ <View style={ACTION_GROUP}>
166
+ <Choice
167
+ styles={styles}
168
+ label="Download"
169
+ accessibilityLabel={`Confirm download of ${model.label}`}
170
+ selected
171
+ disabled={busy || start.isPending}
172
+ onPress={() => {
173
+ setConfirming(null);
174
+ start.mutate(model.key);
175
+ }}
176
+ />
177
+ <Choice
178
+ styles={styles}
179
+ label="Cancel"
180
+ accessibilityLabel={`Cancel download of ${model.label}`}
181
+ onPress={() => setConfirming(null)}
182
+ />
183
+ </View>
184
+ </View>
185
+ ) : (
186
+ <View style={ACTION_GROUP}>
187
+ <Choice
188
+ styles={styles}
189
+ label={model.downloaded ? "Download again" : "Download"}
190
+ accessibilityLabel={`Download ${model.label}`}
191
+ disabled={busy || start.isPending}
192
+ onPress={() => setConfirming(model.key)}
193
+ />
194
+ {ROLES.map(({ role, label }) => {
195
+ const selector = `local/${model.key}`;
196
+ const assigned = modelRoles[role] === selector;
197
+ return (
198
+ <Choice
199
+ key={role}
200
+ styles={styles}
201
+ label={assigned ? `Using for ${label}` : `Use for ${label}`}
202
+ accessibilityLabel={`${assigned ? "Stop using" : "Use"} ${model.label} for ${label}`}
203
+ selected={assigned}
204
+ disabled={blocked}
205
+ onPress={() => assignRole(role, assigned ? null : selector)}
206
+ />
207
+ );
208
+ })}
209
+ </View>
210
+ )}
211
+ </View>
212
+ ))}
213
+ </View>
214
+ );
215
+ }
@@ -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
@@ -10,6 +10,7 @@ import { OmpAccounts } from "./server/omp-accounts";
10
10
  import { resolveListOmpAgents } from "./server/omp-agents";
11
11
  import { resolveListOmpConfig } from "./server/omp-config";
12
12
  import { resolveListOmpExtensions, resolveSetOmpExtensionEnabled } from "./server/omp-extensions";
13
+ import { resolveDownloadOmpLocalModel, resolveListOmpLocalModels } from "./server/omp-local-models";
13
14
  import { OmpMcps } from "./server/omp-mcps";
14
15
  import { resolveListOmpModels } from "./server/omp-models";
15
16
  import { resolveGetOmpModelsFileStatus, resolveRefreshOmpModels } from "./server/omp-models-file";
@@ -31,6 +32,7 @@ import {
31
32
  resolveListOmpSkills,
32
33
  resolveSetOmpSkillEnabled,
33
34
  } from "./server/omp-skills";
35
+ import { resolveReadOmpToolConfig, resolveWriteOmpToolConfig } from "./server/omp-tool-config";
34
36
  import { resolveGetOmpUpdateStatus, resolveInstallOmpUpdate } from "./server/omp-update";
35
37
  import { OmpOperationalFailureCollector } from "./server/operational-failure-diagnostics";
36
38
  import { withOmpStore } from "./server/paths";
@@ -74,6 +76,7 @@ import {
74
76
  import { listOmpAgents } from "./shared/omp-agents";
75
77
  import { listOmpConfig } from "./shared/omp-config";
76
78
  import { listOmpExtensions, setOmpExtensionEnabled } from "./shared/omp-extensions";
79
+ import { downloadOmpLocalModel, listOmpLocalModels } from "./shared/omp-local-models";
77
80
  import {
78
81
  addOmpMcp,
79
82
  cancelOmpMcpAuth,
@@ -99,6 +102,7 @@ import { listOmpSecurity } from "./shared/omp-security";
99
102
  import { listOmpSettings, updateOmpSettings } from "./shared/omp-settings";
100
103
  import { deleteOmpManagedSkill, listOmpSkills, setOmpSkillEnabled } from "./shared/omp-skills";
101
104
  import { listOmpStores, type OmpStore } from "./shared/omp-store";
105
+ import { readOmpToolConfig, writeOmpToolConfig } from "./shared/omp-tool-config";
102
106
  import { getOmpUpdateStatus, installOmpUpdate } from "./shared/omp-update";
103
107
  import { getOmpProviderHealth } from "./shared/provider-diagnostics";
104
108
  import { getOmpImage } from "./shared/provider-image";
@@ -232,6 +236,10 @@ export default function contribute(server: PluginServerContext) {
232
236
  server.handle(mutateOmpPluginConfig, scoped(resolveMutateOmpPluginConfig));
233
237
  server.handle(listOmpSettings, scoped(resolveListOmpSettings));
234
238
  server.handle(updateOmpSettings, scoped(resolveUpdateOmpSettings));
239
+ server.handle(readOmpToolConfig, scoped(resolveReadOmpToolConfig));
240
+ server.handle(writeOmpToolConfig, scoped(resolveWriteOmpToolConfig));
241
+ server.handle(listOmpLocalModels, scoped(resolveListOmpLocalModels));
242
+ server.handle(downloadOmpLocalModel, scoped(resolveDownloadOmpLocalModel));
235
243
  server.handle(getOmpProviderHealth, scoped(resolveGetOmpProviderHealth));
236
244
  // Not `scoped`: the handler also needs the host context to read Paseo's Append system prompt.
237
245
  server.handle(getOmpPromptFiles, ({ store, cwd }, { paseo }) =>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omercnet/paseo-omp",
3
- "version": "5.4.0-next.414.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,202 @@
1
+ import { stat } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import type { RpcInput, RpcOutput } from "@getpaseo/plugin";
5
+ import { z } from "zod";
6
+ import {
7
+ type downloadOmpLocalModel,
8
+ type listOmpLocalModels,
9
+ OmpLocalModelKeySchema,
10
+ } from "../shared/omp-local-models";
11
+ import { resolveOmpExecutable } from "./omp-settings";
12
+ import { currentOmpEnvironment, ompAgentDir, ompCacheDir } from "./paths";
13
+ import {
14
+ type BoundedRun,
15
+ buildStatefulCommandEnv,
16
+ defaultSpawn,
17
+ runBounded,
18
+ } from "./provider-diagnostics";
19
+
20
+ const LIST_TIMEOUT_MS = 30_000;
21
+ const DOWNLOAD_TIMEOUT_MS = 30 * 60_000;
22
+ const KILL_GRACE_MS = 1_000;
23
+ const MAX_OUTPUT_BYTES = 1024 * 1024;
24
+
25
+ const ListedModelsSchema = z.object({
26
+ models: z.array(
27
+ z.object({
28
+ key: z.string(),
29
+ repo: z.string(),
30
+ label: z.string(),
31
+ description: z.string(),
32
+ }),
33
+ ),
34
+ });
35
+
36
+ const DownloadResultSchema = z.object({ results: z.array(z.object({ ok: z.boolean() })) });
37
+
38
+ export interface OmpLocalModelsDependencies {
39
+ resolveExecutable(): Promise<string | null>;
40
+ run(executable: string, args: readonly string[], timeoutMs: number): Promise<BoundedRun>;
41
+ /** True when OMP's cache folder already holds the model's repository. */
42
+ isCached(repo: string): Promise<boolean>;
43
+ }
44
+
45
+ /** Where a download from a network that needs a proxy or a private CA still works. */
46
+ const NETWORK_VARIABLES = [
47
+ "HTTPS_PROXY",
48
+ "HTTP_PROXY",
49
+ "NO_PROXY",
50
+ "https_proxy",
51
+ "http_proxy",
52
+ "no_proxy",
53
+ "SSL_CERT_FILE",
54
+ "NODE_EXTRA_CA_CERTS",
55
+ ];
56
+
57
+ function downloadEnvironment(): NodeJS.ProcessEnv {
58
+ const environment = currentOmpEnvironment();
59
+ const network = NETWORK_VARIABLES.flatMap((name) =>
60
+ environment[name] === undefined ? [] : [[name, environment[name]] as const],
61
+ );
62
+ return { ...buildStatefulCommandEnv(environment), ...Object.fromEntries(network) };
63
+ }
64
+
65
+ /** OMP keeps its tiny models under `cache/tiny-models` of its cache root (the agent folder, or the XDG cache folder's omp). */
66
+ export function tinyModelPath(repo: string): string {
67
+ return join(ompCacheDir(), "cache", "tiny-models", ...repo.split("/"));
68
+ }
69
+
70
+ const DEFAULT_DEPENDENCIES: OmpLocalModelsDependencies = {
71
+ resolveExecutable: resolveOmpExecutable,
72
+ run: (executable, args, timeoutMs) =>
73
+ runBounded(
74
+ defaultSpawn,
75
+ executable,
76
+ args,
77
+ downloadEnvironment(),
78
+ timeoutMs,
79
+ KILL_GRACE_MS,
80
+ MAX_OUTPUT_BYTES,
81
+ tmpdir(),
82
+ ),
83
+ async isCached(repo) {
84
+ try {
85
+ return (await stat(tinyModelPath(repo))).isDirectory();
86
+ } catch {
87
+ return false;
88
+ }
89
+ },
90
+ };
91
+
92
+ interface Job {
93
+ state: "running" | "failed";
94
+ error: string | null;
95
+ }
96
+
97
+ /** Download progress lives here because a download outlasts the request that started it. */
98
+ const jobs = new Map<string, Job>();
99
+
100
+ function jobKey(key: string): string {
101
+ return `${ompAgentDir()}\0${key}`;
102
+ }
103
+
104
+ function anyRunning(): boolean {
105
+ const prefix = `${ompAgentDir()}\0`;
106
+ return [...jobs].some(([key, job]) => key.startsWith(prefix) && job.state === "running");
107
+ }
108
+
109
+ function sizeFrom(description: string): number | null {
110
+ const match = /(\d+(?:\.\d+)?)\s*MB/u.exec(description);
111
+ return match?.[1] ? Math.round(Number(match[1])) : null;
112
+ }
113
+
114
+ async function listModels(executable: string, dependencies: OmpLocalModelsDependencies) {
115
+ const result = await dependencies.run(
116
+ executable,
117
+ ["tiny-models", "list", "--json"],
118
+ LIST_TIMEOUT_MS,
119
+ );
120
+ if (result.outcome !== "exited" || result.exitCode !== 0 || result.truncated) return null;
121
+ try {
122
+ const parsed = ListedModelsSchema.safeParse(JSON.parse(result.stdout));
123
+ return parsed.success ? parsed.data.models : null;
124
+ } catch {
125
+ return null;
126
+ }
127
+ }
128
+
129
+ export async function listOmpLocalModelsWithDependencies(
130
+ dependencies: OmpLocalModelsDependencies,
131
+ ): Promise<RpcOutput<typeof listOmpLocalModels>> {
132
+ const executable = await dependencies.resolveExecutable();
133
+ const listed = executable ? await listModels(executable, dependencies) : null;
134
+ if (!listed) return { available: false, models: [] };
135
+ const models = await Promise.all(
136
+ listed
137
+ .filter((model) => OmpLocalModelKeySchema.safeParse(model.key).success)
138
+ .map(async (model) => {
139
+ const job = jobs.get(jobKey(model.key));
140
+ return {
141
+ key: model.key,
142
+ label: model.label,
143
+ description: model.description,
144
+ sizeMb: sizeFrom(model.description),
145
+ downloaded: await dependencies.isCached(model.repo),
146
+ download: job?.state ?? ("idle" as const),
147
+ error: job?.error ?? null,
148
+ };
149
+ }),
150
+ );
151
+ return { available: true, models };
152
+ }
153
+
154
+ function finishDownload(name: string, result: BoundedRun): void {
155
+ const parsed = (() => {
156
+ try {
157
+ return DownloadResultSchema.safeParse(JSON.parse(result.stdout));
158
+ } catch {
159
+ return null;
160
+ }
161
+ })();
162
+ const ok =
163
+ result.outcome === "exited" &&
164
+ result.exitCode === 0 &&
165
+ parsed?.success === true &&
166
+ parsed.data.results.every((entry) => entry.ok);
167
+ if (ok) {
168
+ jobs.delete(name);
169
+ return;
170
+ }
171
+ jobs.set(name, {
172
+ state: "failed",
173
+ error: result.outcome === "timeout" ? "The download timed out." : "OMP could not download it.",
174
+ });
175
+ }
176
+
177
+ export async function downloadOmpLocalModelWithDependencies(
178
+ input: RpcInput<typeof downloadOmpLocalModel>,
179
+ dependencies: OmpLocalModelsDependencies,
180
+ ): Promise<RpcOutput<typeof downloadOmpLocalModel>> {
181
+ const executable = await dependencies.resolveExecutable();
182
+ if (!executable) return { outcome: "unavailable" };
183
+ const listed = await listModels(executable, dependencies);
184
+ if (!listed) return { outcome: "unavailable" };
185
+ if (!listed.some((model) => model.key === input.key)) return { outcome: "unknown-model" };
186
+ if (anyRunning()) return { outcome: "busy" };
187
+
188
+ const name = jobKey(input.key);
189
+ jobs.set(name, { state: "running", error: null });
190
+ void dependencies
191
+ .run(executable, ["tiny-models", "download", input.key, "--json"], DOWNLOAD_TIMEOUT_MS)
192
+ .then((result) => finishDownload(name, result));
193
+ return { outcome: "started" };
194
+ }
195
+
196
+ export function resolveListOmpLocalModels() {
197
+ return listOmpLocalModelsWithDependencies(DEFAULT_DEPENDENCIES);
198
+ }
199
+
200
+ export function resolveDownloadOmpLocalModel(input: RpcInput<typeof downloadOmpLocalModel>) {
201
+ return downloadOmpLocalModelWithDependencies(input, DEFAULT_DEPENDENCIES);
202
+ }
@@ -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.414.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,44 @@
1
+ import { defineRpc } from "@getpaseo/plugin";
2
+ import { z } from "zod";
3
+ import { OmpStoreSchema } from "./omp-store";
4
+
5
+ /** Model keys come from `omp tiny-models list`, for example `lfm2.5-230m` or `llama3.2:3b`. */
6
+ export const OmpLocalModelKeySchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u);
7
+
8
+ export const OmpLocalModelSchema = z.object({
9
+ key: OmpLocalModelKeySchema,
10
+ label: z.string(),
11
+ description: z.string(),
12
+ /** Approximate download size parsed from OMP's description, when it names one. */
13
+ sizeMb: z.number().nullable(),
14
+ /** Found in OMP's cache folder. OMP's list does not report this itself. */
15
+ downloaded: z.boolean(),
16
+ download: z.enum(["idle", "running", "failed"]),
17
+ error: z.string().nullable(),
18
+ });
19
+ export type OmpLocalModel = z.infer<typeof OmpLocalModelSchema>;
20
+
21
+ export const listOmpLocalModels = defineRpc({
22
+ name: "paseo-omp.list-local-models",
23
+ input: z.object({ store: OmpStoreSchema.optional() }).strict(),
24
+ output: z.object({
25
+ available: z.boolean(),
26
+ models: z.array(OmpLocalModelSchema),
27
+ }),
28
+ });
29
+
30
+ export const downloadOmpLocalModel = defineRpc({
31
+ name: "paseo-omp.download-local-model",
32
+ input: z.object({ store: OmpStoreSchema.optional(), key: OmpLocalModelKeySchema }).strict(),
33
+ output: z.object({ outcome: z.enum(["started", "busy", "unknown-model", "unavailable"]) }),
34
+ });
35
+
36
+ /** The roles record with `role` pointed at `selector`, or removed when `selector` is null. */
37
+ export function withLocalModelRole(
38
+ roles: Readonly<Record<string, unknown>>,
39
+ role: string,
40
+ selector: string | null,
41
+ ): Record<string, unknown> {
42
+ const { [role]: _replaced, ...rest } = roles;
43
+ return selector === null ? rest : { ...rest, [role]: selector };
44
+ }
@@ -1,4 +1,4 @@
1
- import { defineRpc } from "@getpaseo/plugin";
1
+ import { defineRpc, type RpcOutput } from "@getpaseo/plugin";
2
2
  import { z } from "zod";
3
3
  import { OmpWorkspaceCwdSchema } from "./hub";
4
4
  import { OmpStoreSchema } from "./omp-store";
@@ -642,3 +642,6 @@ export const updateOmpSettings = defineRpc({
642
642
  }),
643
643
  }),
644
644
  });
645
+
646
+ /** The settings catalog an update returns, which a cache can take in place of a refetch. */
647
+ export type OmpSettingsCatalog = RpcOutput<typeof updateOmpSettings>["catalog"];
@@ -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
+ });