@omercnet/paseo-omp 5.4.0 → 5.5.0-next.429.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/OVERVIEW.md +7 -1
  2. package/README.md +2 -1
  3. package/client/ast-edit.tsx +53 -0
  4. package/client/composer-pill-settings.tsx +0 -5
  5. package/client/config-sidebar.tsx +15 -0
  6. package/client/generated-image.tsx +79 -0
  7. package/client/lsp-diagnostics.tsx +69 -0
  8. package/client/omp-config-surface.tsx +438 -108
  9. package/client/omp-config-views.ts +32 -5
  10. package/client/omp-extensions-section.tsx +145 -0
  11. package/client/omp-local-models-section.tsx +215 -0
  12. package/client/omp-plugin-manager.tsx +198 -3
  13. package/client/omp-routing-editor.tsx +123 -2
  14. package/client/omp-rule-test.tsx +140 -0
  15. package/client/omp-rules-section.tsx +353 -0
  16. package/client/omp-security-section.tsx +99 -0
  17. package/client/omp-security-state.ts +14 -0
  18. package/client/omp-skills-section.tsx +195 -0
  19. package/client/omp-tool-config-section.tsx +204 -0
  20. package/client/omp-tool-policy-state.ts +101 -0
  21. package/client/omp-tool-policy.tsx +435 -0
  22. package/client/omp-update-row.tsx +87 -0
  23. package/client/provider-diagnostics-state.ts +38 -1
  24. package/client/provider-image.tsx +1 -1
  25. package/client/rule-notice.tsx +33 -0
  26. package/client/sidebar-compat.ts +0 -109
  27. package/client/web.ts +34 -0
  28. package/index.client.tsx +79 -46
  29. package/index.server.ts +77 -3
  30. package/npm-shrinkwrap.json +2 -2
  31. package/package.json +4 -4
  32. package/server/generated-images.ts +57 -0
  33. package/server/omp-agents.ts +170 -0
  34. package/server/omp-extensions.ts +235 -0
  35. package/server/omp-list-setting.ts +98 -0
  36. package/server/omp-local-models.ts +202 -0
  37. package/server/omp-models-file.ts +178 -0
  38. package/server/omp-plugins.ts +182 -0
  39. package/server/omp-prompt-files.ts +41 -0
  40. package/server/omp-rule-firings.ts +211 -0
  41. package/server/omp-rule-switch.ts +38 -0
  42. package/server/omp-rule-test.ts +82 -0
  43. package/server/omp-rules.ts +452 -0
  44. package/server/omp-security.ts +169 -0
  45. package/server/omp-settings.ts +92 -16
  46. package/server/omp-skills.ts +179 -0
  47. package/server/omp-tool-config.ts +144 -0
  48. package/server/omp-update.ts +203 -0
  49. package/server/package-version.ts +1 -1
  50. package/server/provider/connection.ts +1 -1
  51. package/server/provider/image-cache.ts +1 -1
  52. package/server/provider/omp-rpc-environment.ts +1 -1
  53. package/server/provider/session-descriptors.ts +3 -0
  54. package/server/provider-diagnostics.ts +26 -4
  55. package/server/regular-file.ts +30 -0
  56. package/server/rule-notices.ts +112 -0
  57. package/server/turn-rows.ts +59 -0
  58. package/server/turn-screenshots.ts +140 -0
  59. package/shared/ast-edit.ts +124 -0
  60. package/shared/composer-pill-settings.ts +0 -2
  61. package/shared/generated-image.ts +68 -0
  62. package/shared/lsp-diagnostics.ts +141 -0
  63. package/shared/omp-agents.ts +26 -0
  64. package/shared/omp-extensions.ts +45 -0
  65. package/shared/omp-local-models.ts +44 -0
  66. package/shared/omp-models-file.ts +30 -0
  67. package/shared/omp-plugins.ts +90 -0
  68. package/shared/omp-prompt-files.ts +24 -0
  69. package/shared/omp-rules.ts +134 -0
  70. package/shared/omp-security.ts +50 -0
  71. package/shared/omp-settings.ts +211 -2
  72. package/shared/omp-skills.ts +80 -0
  73. package/shared/omp-tool-config.ts +283 -0
  74. package/shared/omp-update.ts +27 -0
  75. package/shared/provider-image.ts +10 -3
  76. package/shared/rule-notices.ts +20 -0
  77. package/client/hub-sidebar.tsx +0 -99
  78. package/client/sessions-popover.tsx +0 -78
  79. package/server/sessions.ts +0 -58
  80. package/shared/sessions.ts +0 -24
@@ -7,11 +7,14 @@ import { parseDocument, parse as parseYaml } from "yaml";
7
7
  import {
8
8
  isOmpStructuredSettingPath,
9
9
  type listOmpSettings,
10
+ OMP_SETTING_DESCRIPTIONS,
10
11
  OMP_SETTINGS_CATALOG_VERSION,
11
12
  type OmpSetting,
12
13
  type OmpSettingType,
13
14
  OmpSettingTypeSchema,
15
+ OmpToolPoliciesSchema,
14
16
  parseOmpStructuredSettingValue,
17
+ structuredSettingType,
15
18
  type updateOmpSettings,
16
19
  } from "../shared/omp-settings";
17
20
  import { SerialMutationQueue } from "./mutation-queue";
@@ -63,7 +66,7 @@ export interface OmpSettingsDependencies {
63
66
  validateProjectConfig(executable: string, path: string): Promise<BoundedRun>;
64
67
  }
65
68
 
66
- async function readProjectConfigText(path: string): Promise<string> {
69
+ export async function readProjectConfigText(path: string): Promise<string> {
67
70
  try {
68
71
  return await readFile(path, "utf8");
69
72
  } catch (error) {
@@ -82,12 +85,16 @@ function runSucceeded(result: BoundedRun): boolean {
82
85
  );
83
86
  }
84
87
 
85
- async function writeProjectChanges(
88
+ export type ProjectChange =
89
+ | { operation: "set"; path: string; value: unknown }
90
+ | { operation: "reset"; path: string };
91
+
92
+ export async function writeProjectChanges(
86
93
  cwd: string,
87
94
  expectedText: string,
88
- changes: RpcInput<typeof updateOmpSettings>["changes"],
95
+ changes: readonly ProjectChange[],
89
96
  executable: string,
90
- dependencies: OmpSettingsDependencies,
97
+ dependencies: Pick<OmpSettingsDependencies, "validateProjectConfig">,
91
98
  ): Promise<"applied" | "conflict"> {
92
99
  const path = join(cwd, ".omp", "config.yml");
93
100
  try {
@@ -106,8 +113,9 @@ async function writeProjectChanges(
106
113
  if (document.errors.length > 0) throw new Error("Workspace OMP configuration is invalid YAML.");
107
114
  for (const change of changes) {
108
115
  const segments = change.path.split(".");
109
- if (change.operation === "reset") document.deleteIn(segments);
110
- else document.setIn(segments, change.value);
116
+ if (change.operation === "reset") {
117
+ if (document.hasIn(segments)) document.deleteIn(segments);
118
+ } else document.setIn(segments, change.value);
111
119
  }
112
120
 
113
121
  await mkdir(dirname(path), { recursive: true });
@@ -191,7 +199,9 @@ export function parseOmpSettingsList(raw: unknown): ParsedOmpSettings {
191
199
  settings.push({
192
200
  path,
193
201
  type: parsedType.data,
194
- description: typeof entry.description === "string" ? entry.description : "",
202
+ description:
203
+ OMP_SETTING_DESCRIPTIONS[path] ??
204
+ (typeof entry.description === "string" ? entry.description : ""),
195
205
  ...(redacted
196
206
  ? { redacted: true, ...(configured === undefined ? {} : { configured }) }
197
207
  : { value: entry.value }),
@@ -238,12 +248,57 @@ async function validateOmpProjectConfig(executable: string, path: string): Promi
238
248
  );
239
249
  }
240
250
 
241
- const DEFAULT_DEPENDENCIES: OmpSettingsDependencies = {
251
+ export const ompSettingsDependencies: OmpSettingsDependencies = {
242
252
  resolveExecutable: resolveOmpExecutable,
243
253
  runConfig: runOmpConfig,
244
254
  validateProjectConfig: validateOmpProjectConfig,
245
255
  };
246
256
 
257
+ /**
258
+ * Project `tools.approval` entries merge with the user's instead of replacing them, so a project
259
+ * editor must know which entries are inherited.
260
+ */
261
+ async function withUserToolPolicies(
262
+ executable: string,
263
+ dependencies: OmpSettingsDependencies,
264
+ settings: OmpSetting[],
265
+ ): Promise<OmpSetting[]> {
266
+ const result = await dependencies.runConfig(executable, ["list", "--json"], tmpdir());
267
+ if (!runSucceeded(result)) return settings;
268
+ let listed: unknown;
269
+ try {
270
+ listed = JSON.parse(result.stdout);
271
+ } catch {
272
+ return settings;
273
+ }
274
+ const userValue =
275
+ parseOmpSettingsList(listed).settings.find((setting) => setting.path === "tools.approval")
276
+ ?.value ?? {};
277
+ return settings.map((setting) =>
278
+ setting.path === "tools.approval" ? { ...setting, userValue } : setting,
279
+ );
280
+ }
281
+
282
+ /** Keeps a project `tools.approval` record to what differs from the user's, so inherited rules stay inherited. */
283
+ function projectChanges(
284
+ changes: RpcInput<typeof updateOmpSettings>["changes"],
285
+ byPath: ReadonlyMap<string, OmpSetting>,
286
+ ): ProjectChange[] {
287
+ return changes.map((change) => {
288
+ if (change.operation !== "set" || change.path !== "tools.approval") return change;
289
+ const inherited =
290
+ OmpToolPoliciesSchema.safeParse(byPath.get(change.path)?.userValue).data ?? {};
291
+ const own = Object.fromEntries(
292
+ Object.entries(OmpToolPoliciesSchema.parse(change.value)).filter(
293
+ ([tool, approval]) => inherited[tool] !== approval,
294
+ ),
295
+ );
296
+ return Object.keys(own).length === 0
297
+ ? { operation: "reset", path: change.path }
298
+ : { operation: "set", path: change.path, value: own };
299
+ });
300
+ }
301
+
247
302
  async function loadCatalog(
248
303
  executable: string | null | undefined,
249
304
  dependencies: OmpSettingsDependencies,
@@ -293,7 +348,13 @@ async function loadCatalog(
293
348
  revision,
294
349
  droppedCount: catalog.droppedCount,
295
350
  ...(projectPath ? { path: projectPath } : path ? { path } : {}),
296
- settings: cwd ? await markWorkspaceOverrides(cwd, catalog.settings) : catalog.settings,
351
+ settings: cwd
352
+ ? await withUserToolPolicies(
353
+ resolved,
354
+ dependencies,
355
+ await markWorkspaceOverrides(cwd, catalog.settings),
356
+ )
357
+ : catalog.settings,
297
358
  };
298
359
  } catch {
299
360
  return {
@@ -308,8 +369,7 @@ async function loadCatalog(
308
369
 
309
370
  function serializeSettingValue(setting: OmpSetting, value: unknown): string | null {
310
371
  if (isOmpStructuredSettingPath(setting.path)) {
311
- const expectedType = setting.path === "cycleOrder" ? "array" : "record";
312
- if (setting.type !== expectedType) return null;
372
+ if (setting.type !== structuredSettingType(setting.path)) return null;
313
373
  const parsed = parseOmpStructuredSettingValue(setting.path, value);
314
374
  return parsed === undefined ? null : JSON.stringify(parsed);
315
375
  }
@@ -325,7 +385,7 @@ function isEditableSetting(setting: OmpSetting): boolean {
325
385
  if (setting.redacted) return false;
326
386
  if (["boolean", "number", "string", "enum"].includes(setting.type)) return true;
327
387
  if (!isOmpStructuredSettingPath(setting.path)) return false;
328
- return setting.type === (setting.path === "cycleOrder" ? "array" : "record");
388
+ return setting.type === structuredSettingType(setting.path);
329
389
  }
330
390
 
331
391
  export async function listOmpSettingsWithDependencies(
@@ -347,7 +407,7 @@ export async function listOmpSettingsWithDependencies(
347
407
  export async function resolveListOmpSettings(
348
408
  input: RpcInput<typeof listOmpSettings>,
349
409
  ): Promise<CatalogResult> {
350
- return listOmpSettingsWithDependencies(input, DEFAULT_DEPENDENCIES);
410
+ return listOmpSettingsWithDependencies(input, ompSettingsDependencies);
351
411
  }
352
412
 
353
413
  export async function updateOmpSettingsWithDependencies(
@@ -407,6 +467,17 @@ export async function updateOmpSettingsWithDependencies(
407
467
  catalog: current,
408
468
  };
409
469
  }
470
+ if (change.path === "tools.approval" && setting.userValue === undefined) {
471
+ return {
472
+ conflict: false,
473
+ appliedPaths: [],
474
+ failed: {
475
+ path: change.path,
476
+ message: "Could not read the user-level tool approvals. Try again.",
477
+ },
478
+ catalog: current,
479
+ };
480
+ }
410
481
  }
411
482
 
412
483
  const projectPath = join(input.cwd, ".omp", "config.yml");
@@ -420,7 +491,7 @@ export async function updateOmpSettingsWithDependencies(
420
491
  const outcome = await writeProjectChanges(
421
492
  input.cwd,
422
493
  afterValidation,
423
- input.changes,
494
+ projectChanges(input.changes, byPath),
424
495
  executable,
425
496
  dependencies,
426
497
  );
@@ -500,10 +571,15 @@ export async function updateOmpSettingsWithDependencies(
500
571
 
501
572
  const settingsMutationQueue = new SerialMutationQueue();
502
573
 
574
+ /** Settings and skill edits share this queue so they never write one config file at once. */
575
+ export function runSettingsMutation<T>(operation: () => Promise<T>): Promise<T> {
576
+ return settingsMutationQueue.run(operation);
577
+ }
578
+
503
579
  export function resolveUpdateOmpSettings(
504
580
  input: RpcInput<typeof updateOmpSettings>,
505
581
  ): Promise<OmpSettingsUpdateResult> {
506
- return settingsMutationQueue.run(() =>
507
- updateOmpSettingsWithDependencies(input, DEFAULT_DEPENDENCIES),
582
+ return runSettingsMutation(() =>
583
+ updateOmpSettingsWithDependencies(input, ompSettingsDependencies),
508
584
  );
509
585
  }
@@ -0,0 +1,179 @@
1
+ import { lstat, realpath } from "node:fs/promises";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ import type { RpcInput } from "@getpaseo/plugin";
4
+ import { z } from "zod";
5
+ import type {
6
+ deleteOmpManagedSkill,
7
+ listOmpSkills,
8
+ OmpSkill,
9
+ OmpSkillOff,
10
+ OmpSkillsList,
11
+ setOmpSkillEnabled,
12
+ } from "../shared/omp-skills";
13
+ import { SKILL_ENTRY_PREFIX } from "../shared/omp-skills";
14
+ import {
15
+ type OmpListDependencies,
16
+ ompListDependencies,
17
+ readList,
18
+ requireOmpExecutable,
19
+ writeListEntry,
20
+ } from "./omp-list-setting";
21
+ import { inOmpScope, runJson } from "./omp-rules";
22
+ import { runSettingsMutation } from "./omp-settings";
23
+ import { ompAgentDir } from "./paths";
24
+ import { OmpPublicError } from "./provider/security";
25
+
26
+ const MAX_SKILLS = 500;
27
+ const MAX_OFF_ENTRIES = 200;
28
+ const MAX_TEXT_CHARS = 2_000;
29
+ const MANAGED_SOURCE = "omp-managed";
30
+
31
+ export class OmpSkillsError extends OmpPublicError {}
32
+
33
+ /** One entry of `omp skill list --json`. */
34
+ const SkillEntrySchema = z.object({
35
+ name: z.string().min(1).max(256),
36
+ description: z
37
+ .string()
38
+ .nullish()
39
+ .transform((text) => (text ?? "").slice(0, MAX_TEXT_CHARS)),
40
+ baseDir: z.string().min(1).max(4_096),
41
+ source: z.string().min(1).max(128),
42
+ });
43
+ const SkillListSchema = z.object({ skills: z.array(z.unknown()) });
44
+
45
+ /** A source reads `<provider>:<level>`, such as `native:project` or `omp-managed:user`. */
46
+ function toSkill(entry: z.infer<typeof SkillEntrySchema>): OmpSkill {
47
+ const split = entry.source.lastIndexOf(":");
48
+ const provider = split < 0 ? entry.source : entry.source.slice(0, split);
49
+ const scope = split < 0 ? "" : entry.source.slice(split + 1);
50
+ return {
51
+ name: entry.name,
52
+ description: entry.description,
53
+ source: provider,
54
+ level: scope === "project" || scope === "user" ? scope : "other",
55
+ path: entry.baseDir,
56
+ managed: provider === MANAGED_SOURCE,
57
+ };
58
+ }
59
+
60
+ async function listSkills(
61
+ dependencies: OmpListDependencies,
62
+ executable: string,
63
+ runIn: string,
64
+ ): Promise<OmpSkill[]> {
65
+ const raw = await runJson(dependencies, executable, ["skill", "list", "--json"], runIn);
66
+ const parsed = SkillListSchema.safeParse(raw);
67
+ if (!parsed.success) throw new OmpSkillsError("omp skill list gave output the plugin can't read");
68
+ return parsed.data.skills.slice(0, MAX_SKILLS).flatMap((entry) => {
69
+ const skill = SkillEntrySchema.safeParse(entry);
70
+ return skill.success ? [toSkill(skill.data)] : [];
71
+ });
72
+ }
73
+
74
+ /** OMP trims each entry. Only `skill:` entries of `disabledExtensions` concern skills. */
75
+ function offEntries(ignored: readonly string[], extensions: readonly string[]): OmpSkillOff[] {
76
+ const entries: OmpSkillOff[] = [
77
+ ...ignored.map((entry) => ({ list: "skills.ignoredSkills" as const, entry: entry.trim() })),
78
+ ...extensions
79
+ .map((entry) => entry.trim())
80
+ .filter(
81
+ (entry) => entry.startsWith(SKILL_ENTRY_PREFIX) && entry.length > SKILL_ENTRY_PREFIX.length,
82
+ )
83
+ .map((entry) => ({ list: "disabledExtensions" as const, entry })),
84
+ ];
85
+ const seen = new Set<string>();
86
+ return entries
87
+ .filter(({ list, entry }) => {
88
+ const key = `${list}\0${entry}`;
89
+ if (entry === "" || seen.has(key)) return false;
90
+ seen.add(key);
91
+ return true;
92
+ })
93
+ .slice(0, MAX_OFF_ENTRIES)
94
+ .map(({ list, entry }) => ({ list, entry: entry.slice(0, MAX_TEXT_CHARS) }));
95
+ }
96
+
97
+ export async function listOmpSkillsWithDependencies(
98
+ input: RpcInput<typeof listOmpSkills>,
99
+ dependencies: OmpListDependencies,
100
+ ): Promise<OmpSkillsList> {
101
+ try {
102
+ const executable = await requireOmpExecutable(dependencies);
103
+ return await inOmpScope(input.cwd, dependencies, async (runIn) => {
104
+ const [skills, ignored, extensions] = await Promise.all([
105
+ listSkills(dependencies, executable, runIn),
106
+ readList(dependencies, executable, "skills.ignoredSkills", runIn),
107
+ readList(dependencies, executable, "disabledExtensions", runIn),
108
+ ]);
109
+ return { status: "ready" as const, skills, off: offEntries(ignored, extensions) };
110
+ });
111
+ } catch (error) {
112
+ if (error instanceof OmpPublicError) return { status: "error", message: error.message };
113
+ throw error;
114
+ }
115
+ }
116
+
117
+ export async function setOmpSkillEnabledWithDependencies(
118
+ input: RpcInput<typeof setOmpSkillEnabled>,
119
+ dependencies: OmpListDependencies,
120
+ ): Promise<{ status: "ok" } | { status: "error"; message: string }> {
121
+ try {
122
+ if (input.list === "disabledExtensions" && !input.entry.startsWith(SKILL_ENTRY_PREFIX)) {
123
+ throw new OmpSkillsError("That entry is not a skill");
124
+ }
125
+ const executable = await requireOmpExecutable(dependencies);
126
+ await inOmpScope(input.cwd, dependencies, (runIn) =>
127
+ runSettingsMutation(() => writeListEntry(input, dependencies, executable, runIn)),
128
+ );
129
+ return { status: "ok" };
130
+ } catch (error) {
131
+ if (error instanceof OmpPublicError) return { status: "error", message: error.message };
132
+ throw error;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Deletes one agent-learned skill folder. The path must be a managed skill OMP lists right now
138
+ * and a real directory directly inside `<agent dir>/managed-skills`, so a client can never name
139
+ * anything else.
140
+ */
141
+ export async function deleteOmpManagedSkillWithDependencies(
142
+ input: RpcInput<typeof deleteOmpManagedSkill>,
143
+ dependencies: OmpListDependencies,
144
+ ): Promise<{ status: "ok" } | { status: "error"; message: string }> {
145
+ try {
146
+ const executable = await requireOmpExecutable(dependencies);
147
+ const skills = await inOmpScope(undefined, dependencies, (runIn) =>
148
+ listSkills(dependencies, executable, runIn),
149
+ );
150
+ const skill = skills.find((candidate) => candidate.managed && candidate.path === input.path);
151
+ if (!skill) throw new OmpSkillsError("That is not a skill the agent learned");
152
+ const root = join(await realpath(ompAgentDir()), "managed-skills");
153
+ const folder = await lstat(skill.path).catch(() => null);
154
+ const inside =
155
+ folder?.isDirectory() === true &&
156
+ skill.path === resolve(skill.path) &&
157
+ basename(skill.path) !== "" &&
158
+ (await realpath(dirname(skill.path))) === root;
159
+ if (!inside)
160
+ throw new OmpSkillsError("That skill folder is not in OMP's managed skills folder");
161
+ await dependencies.removeDir(skill.path);
162
+ return { status: "ok" };
163
+ } catch (error) {
164
+ if (error instanceof OmpPublicError) return { status: "error", message: error.message };
165
+ throw error;
166
+ }
167
+ }
168
+
169
+ export function resolveListOmpSkills(input: RpcInput<typeof listOmpSkills>) {
170
+ return listOmpSkillsWithDependencies(input, ompListDependencies);
171
+ }
172
+
173
+ export function resolveSetOmpSkillEnabled(input: RpcInput<typeof setOmpSkillEnabled>) {
174
+ return setOmpSkillEnabledWithDependencies(input, ompListDependencies);
175
+ }
176
+
177
+ export function resolveDeleteOmpManagedSkill(input: RpcInput<typeof deleteOmpManagedSkill>) {
178
+ return deleteOmpManagedSkillWithDependencies(input, ompListDependencies);
179
+ }
@@ -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
+ }