@omercnet/paseo-omp 5.4.0-next.395.1 → 5.4.0-next.396.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.
package/OVERVIEW.md CHANGED
@@ -12,6 +12,7 @@ OMP adds an agent provider for the OMP coding agent, plus an OMP sidebar and wor
12
12
  - Manage OMP's own plugins, and view quota history, memory, hub processes and a support report.
13
13
  - List the logins in OMP's own credential store, add or sign one out, spend a banked reset, and steer how OMP balances agents across them, from the **Accounts** tab.
14
14
  - List the MCP servers OMP connects to, add, test, enable, disable or remove them, and authorize a remote server through your browser, from the **MCPs** tab.
15
+ - See which OMP rules apply (watch, always applied, rulebook, turned off) and the file each comes from, from the read-only **Rules** tab.
15
16
  - An **MCP** composer control runs OMP's MCP management in the current session, with authorization prompts shown in the chat.
16
17
  - While OMP subagents run, a row under each `task` card in the conversation lets you steer one with a message or stop it after confirmation. It needs OMP 18.4.9 or newer.
17
18
  - When an OMP rule fires during a turn of an agent on Paseo's bundled `omp` provider, a notice under that turn names the rule and the text it matched. The plugin reads this, best effort, from the end of the agent's OMP session file, which that provider does not report.
@@ -43,6 +43,7 @@ import { OmpMcpsSection } from "./omp-mcps-section";
43
43
  import { normalizeOmpModels } from "./omp-model-picker-state";
44
44
  import { OmpPluginManagerSection } from "./omp-plugin-manager";
45
45
  import { type OmpModelCatalogState, StructuredRoutingEditor } from "./omp-routing-editor";
46
+ import { OmpRulesSection } from "./omp-rules-section";
46
47
  import { OmpStorePicker } from "./omp-store-picker";
47
48
  import { ompStoreKey } from "./omp-store-state";
48
49
  import {
@@ -1166,6 +1167,9 @@ function OmpConfigContent({
1166
1167
  {view === "plugins" ? (
1167
1168
  <OmpPluginManagerSection theme={theme} compact={layout.compact} cwd={cwd} store={store} />
1168
1169
  ) : null}
1170
+ {view === "rules" ? (
1171
+ <OmpRulesSection theme={theme} styles={styles} cwd={cwd} store={store} />
1172
+ ) : null}
1169
1173
  {view === "composer" && !cwd && onComposerPillSettingsChange ? (
1170
1174
  <ComposerPillSettingsSection theme={theme} onChange={onComposerPillSettingsChange} />
1171
1175
  ) : null}
@@ -4,6 +4,7 @@ export type OmpConfigSurfaceView =
4
4
  | "mcps"
5
5
  | "plugin"
6
6
  | "plugins"
7
+ | "rules"
7
8
  | "composer"
8
9
  | "configuration"
9
10
  | "diagnostics"
@@ -15,6 +16,7 @@ const SURFACE_VIEWS: readonly { id: OmpConfigSurfaceView; label: string }[] = [
15
16
  { id: "mcps", label: "MCPs" },
16
17
  { id: "plugin", label: "Plugin" },
17
18
  { id: "plugins", label: "OMP plugins" },
19
+ { id: "rules", label: "Rules" },
18
20
  { id: "composer", label: "Composer" },
19
21
  { id: "configuration", label: "Configuration" },
20
22
  { id: "diagnostics", label: "Diagnostics" },
@@ -0,0 +1,219 @@
1
+ import { type PluginSurfaceProps, useRpc } from "@getpaseo/plugin/client";
2
+ import { copyText, Icon } from "@getpaseo/plugin/client/ui";
3
+ import { useQuery } from "@tanstack/react-query";
4
+ import { useState } from "react";
5
+ import { Pressable, Text, View } from "react-native";
6
+ import { listOmpRules, type OmpRule, type OmpRuleKind } from "../shared/omp-rules";
7
+ import type { OmpStore } from "../shared/omp-store";
8
+ import type { OmpConfigStyles } from "./omp-config-styles";
9
+ import { ompStoreKey } from "./omp-store-state";
10
+
11
+ type Theme = PluginSurfaceProps["theme"];
12
+ type CopyState = "idle" | "copied" | "failed";
13
+
14
+ const COPY_LABELS: Record<CopyState, string> = {
15
+ idle: "Copy path",
16
+ copied: "Copied",
17
+ failed: "Copy failed",
18
+ };
19
+
20
+ const GROUPS: readonly { kind: OmpRuleKind; title: string; empty: string }[] = [
21
+ { kind: "watch", title: "Watch", empty: "No watch rules" },
22
+ { kind: "always", title: "Always applied", empty: "No always-applied rules" },
23
+ { kind: "rulebook", title: "Rulebook", empty: "No rulebook rules" },
24
+ ];
25
+
26
+ function sourceLabel(rule: OmpRule): string {
27
+ if (rule.source === "project") return "Project";
28
+ if (rule.source === "user") return "User";
29
+ if (rule.source === "builtin") return "Built-in";
30
+ if (rule.provider === "omp-plugins") return "From an OMP plugin";
31
+ return `Imported from ${rule.provider}`;
32
+ }
33
+
34
+ function Detail({
35
+ styles,
36
+ label,
37
+ value,
38
+ }: {
39
+ styles: OmpConfigStyles;
40
+ label: string;
41
+ value: string;
42
+ }) {
43
+ return (
44
+ <View style={styles.recordRow}>
45
+ <Text style={styles.recordKey}>{label}</Text>
46
+ <Text selectable style={styles.recordValue}>
47
+ {value}
48
+ </Text>
49
+ </View>
50
+ );
51
+ }
52
+
53
+ function RuleRow({ styles, rule }: { styles: OmpConfigStyles; rule: OmpRule }) {
54
+ const [copyState, setCopyState] = useState<CopyState>("idle");
55
+ async function copyPath() {
56
+ try {
57
+ await copyText(rule.path);
58
+ setCopyState("copied");
59
+ } catch {
60
+ setCopyState("failed");
61
+ }
62
+ }
63
+ const details: [string, string[]][] = [
64
+ ["Text matches", rule.condition],
65
+ ["Code matches", rule.astCondition],
66
+ ["Asks the judge", rule.question ? [rule.question] : []],
67
+ ["Watches", rule.scope],
68
+ ["Files", rule.globs],
69
+ ["Agents", rule.agents],
70
+ ];
71
+ return (
72
+ <View style={styles.setting}>
73
+ <View style={styles.settingHeader}>
74
+ <Text selectable style={styles.settingValue}>
75
+ {rule.name}
76
+ </Text>
77
+ <Text style={styles.source}>{sourceLabel(rule)}</Text>
78
+ </View>
79
+ {rule.description ? <Text style={styles.settingDescription}>{rule.description}</Text> : null}
80
+ {details.map(([label, values]) =>
81
+ values.length > 0 ? (
82
+ <Detail key={label} styles={styles} label={label} value={values.join(", ")} />
83
+ ) : null,
84
+ )}
85
+ <View style={styles.settingHeader}>
86
+ <Text selectable style={styles.settingPath}>
87
+ {rule.path}
88
+ </Text>
89
+ <Pressable
90
+ accessibilityRole="button"
91
+ accessibilityLabel={`Copy the path of rule ${rule.name}`}
92
+ onPress={copyPath}
93
+ >
94
+ <Text style={styles.resetAction}>{COPY_LABELS[copyState]}</Text>
95
+ </Pressable>
96
+ </View>
97
+ </View>
98
+ );
99
+ }
100
+
101
+ function BuiltinRules({
102
+ theme,
103
+ styles,
104
+ rules,
105
+ }: {
106
+ theme: Theme;
107
+ styles: OmpConfigStyles;
108
+ rules: OmpRule[];
109
+ }) {
110
+ const [expanded, setExpanded] = useState(false);
111
+ if (rules.length === 0) return null;
112
+ return (
113
+ <>
114
+ <Pressable
115
+ accessibilityRole="button"
116
+ accessibilityState={{ expanded }}
117
+ accessibilityLabel={`${expanded ? "Hide" : "Show"} ${rules.length} built-in rules`}
118
+ onPress={() => setExpanded(!expanded)}
119
+ style={[styles.setting, styles.sectionHeaderRow]}
120
+ >
121
+ <Icon
122
+ name={expanded ? "ChevronDown" : "ChevronRight"}
123
+ size={14}
124
+ color={theme.colors.foregroundMuted}
125
+ />
126
+ <Text style={styles.rowValue}>Built-in rules ({rules.length})</Text>
127
+ </Pressable>
128
+ {expanded
129
+ ? rules.map((rule) => <RuleRow key={rule.name} styles={styles} rule={rule} />)
130
+ : null}
131
+ </>
132
+ );
133
+ }
134
+
135
+ export function OmpRulesSection({
136
+ theme,
137
+ styles,
138
+ cwd,
139
+ store,
140
+ }: {
141
+ theme: Theme;
142
+ styles: OmpConfigStyles;
143
+ cwd?: string;
144
+ store?: OmpStore;
145
+ }) {
146
+ const loadRules = useRpc(listOmpRules);
147
+ const rules = useQuery({
148
+ queryKey: ["paseo-omp", "rules", ompStoreKey(store), cwd ?? "global"],
149
+ queryFn: () => loadRules({ store, ...(cwd ? { cwd } : {}) }),
150
+ });
151
+ const list = rules.data;
152
+ return (
153
+ <>
154
+ <View style={styles.sectionHeader}>
155
+ <Text style={styles.sectionTitle}>Rules</Text>
156
+ <Text style={styles.muted}>
157
+ Watch rules step in when the agent writes something they match. Always-applied rules are
158
+ part of every prompt. Rulebook rules are listed by name and read when relevant. Changes
159
+ apply to new sessions, or after an agent reload.
160
+ </Text>
161
+ <Text style={styles.muted}>
162
+ Rules imported from other tools, such as Cursor or Windsurf, appear here only when they
163
+ are watch rules.
164
+ </Text>
165
+ <Text style={styles.muted}>Rule settings (ttsr.*) are in the Configuration tab.</Text>
166
+ </View>
167
+ {rules.isLoading ? <Text style={styles.muted}>Loading rules...</Text> : null}
168
+ {rules.error ? (
169
+ <Text accessibilityRole="alert" style={styles.error}>
170
+ Could not list OMP's rules.
171
+ </Text>
172
+ ) : null}
173
+ {list?.status === "error" ? (
174
+ <Text accessibilityRole="alert" style={styles.error}>
175
+ {list.message}
176
+ </Text>
177
+ ) : null}
178
+ {list?.status === "ready" ? (
179
+ <>
180
+ {GROUPS.map((group) => {
181
+ const members = list.rules.filter((rule) => rule.kind === group.kind);
182
+ const own = members.filter((rule) => rule.source !== "builtin");
183
+ const builtin = members.filter((rule) => rule.source === "builtin");
184
+ return (
185
+ <View key={group.kind} style={styles.card}>
186
+ <Text style={styles.cardTitle}>{group.title}</Text>
187
+ {members.length === 0 ? <Text style={styles.muted}>{group.empty}</Text> : null}
188
+ {own.map((rule) => (
189
+ <RuleRow key={rule.name} styles={styles} rule={rule} />
190
+ ))}
191
+ <BuiltinRules theme={theme} styles={styles} rules={builtin} />
192
+ {group.kind === "watch" && !list.builtinRules ? (
193
+ <Text style={styles.muted}>Built-in rules are off (ttsr.builtinRules)</Text>
194
+ ) : null}
195
+ </View>
196
+ );
197
+ })}
198
+ <View style={styles.card}>
199
+ <Text style={styles.cardTitle}>Turned off</Text>
200
+ {list.disabled.length === 0 ? (
201
+ <Text style={styles.muted}>No rules turned off</Text>
202
+ ) : (
203
+ <>
204
+ <Text style={styles.muted}>Listed in ttsr.disabledRules, so OMP skips them</Text>
205
+ {list.disabled.map((name) => (
206
+ <View key={name} style={styles.setting}>
207
+ <Text selectable style={styles.settingValue}>
208
+ {name}
209
+ </Text>
210
+ </View>
211
+ ))}
212
+ </>
213
+ )}
214
+ </View>
215
+ </>
216
+ ) : null}
217
+ </>
218
+ );
219
+ }
package/index.server.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  resolveMutateOmpPlugin,
16
16
  resolveMutateOmpPluginConfig,
17
17
  } from "./server/omp-plugins";
18
+ import { resolveListOmpRules } from "./server/omp-rules";
18
19
  import { resolveListOmpSettings, resolveUpdateOmpSettings } from "./server/omp-settings";
19
20
  import { OmpOperationalFailureCollector } from "./server/operational-failure-diagnostics";
20
21
  import { withOmpStore } from "./server/paths";
@@ -68,6 +69,7 @@ import {
68
69
  mutateOmpPlugin,
69
70
  mutateOmpPluginConfig,
70
71
  } from "./shared/omp-plugins";
72
+ import { listOmpRules } from "./shared/omp-rules";
71
73
  import { listOmpSettings, updateOmpSettings } from "./shared/omp-settings";
72
74
  import { listOmpStores, type OmpStore } from "./shared/omp-store";
73
75
  import { getOmpProviderHealth } from "./shared/provider-diagnostics";
@@ -186,6 +188,7 @@ export default function contribute(server: PluginServerContext) {
186
188
  server.handle(listOmpConfig, scoped(resolveListOmpConfig));
187
189
  server.handle(listOmpModels, scoped(resolveListOmpModels));
188
190
  server.handle(listOmpPlugins, scoped(resolveListOmpPlugins));
191
+ server.handle(listOmpRules, scoped(resolveListOmpRules));
189
192
  server.handle(inspectOmpPluginConfig, scoped(resolveInspectOmpPluginConfig));
190
193
  server.handle(mutateOmpPlugin, scoped(resolveMutateOmpPlugin));
191
194
  server.handle(mutateOmpPluginConfig, scoped(resolveMutateOmpPluginConfig));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omercnet/paseo-omp",
3
- "version": "5.4.0-next.395.1",
3
+ "version": "5.4.0-next.396.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,438 @@
1
+ import { constants } from "node:fs";
2
+ import { type FileHandle, lstat, mkdtemp, open, readdir, rm, stat } from "node:fs/promises";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { basename, dirname, extname, isAbsolute, join, resolve, sep } from "node:path";
5
+ import type { RpcInput } from "@getpaseo/plugin";
6
+ import { parse as parseYaml } from "yaml";
7
+ import { z } from "zod";
8
+ import type { listOmpRules, OmpRule, OmpRulesList } from "../shared/omp-rules";
9
+ import { resolveOmpExecutable } from "./omp-settings";
10
+ import { currentOmpEnvironment, ompAgentDir } from "./paths";
11
+ import { OmpPublicError } from "./provider/security";
12
+ import {
13
+ type BoundedRun,
14
+ buildStatefulCommandEnv,
15
+ defaultSpawn,
16
+ runBounded,
17
+ } from "./provider-diagnostics";
18
+
19
+ const COMMAND_TIMEOUT_MS = 30_000;
20
+ const KILL_GRACE_MS = 1_000;
21
+ const MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
22
+ const MAX_RULES = 500;
23
+ const MAX_RULE_FILES = 200;
24
+ const MAX_RULE_FILE_BYTES = 256 * 1024;
25
+ const MAX_TEXT_CHARS = 2_000;
26
+ const MAX_LIST_ENTRIES = 50;
27
+
28
+ export class OmpRulesError extends OmpPublicError {}
29
+
30
+ export interface OmpRulesDependencies {
31
+ resolveExecutable(): Promise<string | null>;
32
+ run(executable: string, args: readonly string[], cwd: string): Promise<BoundedRun>;
33
+ makeScratchDir(prefix: string): Promise<string>;
34
+ removeDir(path: string): Promise<void>;
35
+ }
36
+
37
+ function clip(text: string): string {
38
+ return text.slice(0, MAX_TEXT_CHARS);
39
+ }
40
+
41
+ function clipList(list: readonly string[]): string[] {
42
+ return list.slice(0, MAX_LIST_ENTRIES).map(clip);
43
+ }
44
+
45
+ const TextList = z
46
+ .array(z.string())
47
+ .nullish()
48
+ .transform((list) => clipList(list ?? []));
49
+ const OptionalText = z
50
+ .string()
51
+ .nullish()
52
+ .transform((text) => (text ? clip(text) : null));
53
+
54
+ /** One entry of `omp ttsr list --json`. */
55
+ const WatchRuleSchema = z.object({
56
+ name: z.string().min(1).max(256),
57
+ path: z.string().min(1).max(4_096),
58
+ provider: z.string().min(1).max(64),
59
+ condition: TextList,
60
+ astCondition: TextList,
61
+ question: OptionalText,
62
+ scope: TextList,
63
+ globs: TextList,
64
+ agents: TextList,
65
+ description: OptionalText,
66
+ });
67
+ type WatchRule = z.infer<typeof WatchRuleSchema>;
68
+
69
+ /** An entry that does not fit is left out, so one odd rule never hides the rest. */
70
+ export function parseWatchRules(raw: unknown): WatchRule[] {
71
+ if (!Array.isArray(raw))
72
+ throw new OmpRulesError("omp ttsr list gave output the plugin can't read");
73
+ return raw.slice(0, MAX_RULES).flatMap((entry) => {
74
+ const parsed = WatchRuleSchema.safeParse(entry);
75
+ return parsed.success ? [parsed.data] : [];
76
+ });
77
+ }
78
+
79
+ const DisabledRulesSchema = z.object({ value: z.array(z.string()) });
80
+ const BuiltinRulesSchema = z.object({ value: z.boolean() });
81
+
82
+ function isWithin(parent: string, child: string): boolean {
83
+ return child.startsWith(parent.endsWith(sep) ? parent : parent + sep);
84
+ }
85
+
86
+ function watchSource(rule: WatchRule, cwd: string | undefined): OmpRule["source"] {
87
+ if (rule.provider === "builtin-defaults") return "builtin";
88
+ if (rule.provider !== "native") return "imported";
89
+ return cwd && isWithin(cwd, rule.path) ? "project" : "user";
90
+ }
91
+
92
+ function toWatchRule(rule: WatchRule, cwd: string | undefined): OmpRule {
93
+ return {
94
+ name: rule.name,
95
+ kind: "watch",
96
+ source: watchSource(rule, cwd),
97
+ provider: rule.provider,
98
+ description: rule.description,
99
+ condition: rule.condition,
100
+ astCondition: rule.astCondition,
101
+ question: rule.question,
102
+ scope: rule.scope,
103
+ globs: rule.globs,
104
+ agents: rule.agents,
105
+ path: rule.path,
106
+ };
107
+ }
108
+
109
+ async function runJson(
110
+ dependencies: OmpRulesDependencies,
111
+ executable: string,
112
+ args: readonly string[],
113
+ cwd: string,
114
+ ): Promise<unknown> {
115
+ const label = `omp ${args.join(" ")}`;
116
+ const run = await dependencies.run(executable, args, cwd);
117
+ if (run.outcome === "timeout") throw new OmpRulesError(`${label} timed out`);
118
+ if (run.outcome !== "exited" || run.exitCode !== 0 || run.truncated) {
119
+ throw new OmpRulesError(`${label} failed`);
120
+ }
121
+ try {
122
+ return JSON.parse(run.stdout);
123
+ } catch {
124
+ throw new OmpRulesError(`${label} gave output the plugin can't read`);
125
+ }
126
+ }
127
+
128
+ async function readSetting<T>(
129
+ dependencies: OmpRulesDependencies,
130
+ executable: string,
131
+ path: string,
132
+ schema: z.ZodType<{ value: T }>,
133
+ cwd: string,
134
+ ): Promise<T> {
135
+ const parsed = schema.safeParse(
136
+ await runJson(dependencies, executable, ["config", "get", path, "--json"], cwd),
137
+ );
138
+ if (!parsed.success) throw new OmpRulesError(`OMP's ${path} setting could not be read`);
139
+ return parsed.data.value;
140
+ }
141
+
142
+ /** Reads a regular file without following a symlink, or returns null. */
143
+ async function readRuleFile(path: string): Promise<string | null> {
144
+ let handle: FileHandle | undefined;
145
+ try {
146
+ // O_NOFOLLOW does not exist on Windows, so reject a symlink before opening it too.
147
+ if (!(await lstat(path)).isFile()) return null;
148
+ handle = await open(
149
+ path,
150
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
151
+ );
152
+ const info = await handle.stat();
153
+ if (!info.isFile()) return null;
154
+ const buffer = Buffer.alloc(MAX_RULE_FILE_BYTES + 1);
155
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
156
+ if (bytesRead > MAX_RULE_FILE_BYTES) return null;
157
+ return buffer.toString("utf8", 0, bytesRead);
158
+ } catch {
159
+ return null;
160
+ } finally {
161
+ await handle?.close();
162
+ }
163
+ }
164
+
165
+ async function isNonEmptyDirectory(path: string): Promise<boolean> {
166
+ try {
167
+ if (!(await lstat(path)).isDirectory()) return false;
168
+ return (await readdir(path)).length > 0;
169
+ } catch {
170
+ return false;
171
+ }
172
+ }
173
+
174
+ async function isRealDirectory(path: string): Promise<boolean> {
175
+ return lstat(path).then(
176
+ (info) => info.isDirectory(),
177
+ () => false,
178
+ );
179
+ }
180
+
181
+ async function ruleFilesIn(directory: string): Promise<string[]> {
182
+ try {
183
+ const entries = await readdir(directory, { withFileTypes: true });
184
+ return entries
185
+ .filter((entry) => entry.isFile() && [".md", ".mdc"].includes(extname(entry.name)))
186
+ .map((entry) => entry.name)
187
+ .sort()
188
+ .slice(0, MAX_RULE_FILES)
189
+ .map((name) => join(directory, name));
190
+ } catch {
191
+ return [];
192
+ }
193
+ }
194
+
195
+ /** OMP never treats home or a temporary root as a project. */
196
+ const DISCOVERY_CEILINGS = new Set([
197
+ homedir(),
198
+ tmpdir(),
199
+ ...(process.platform === "win32" ? [] : ["/tmp", "/var/tmp"]),
200
+ ]);
201
+
202
+ function ancestors(cwd: string): string[] {
203
+ const dirs: string[] = [];
204
+ for (let current = resolve(cwd); ; current = dirname(current)) {
205
+ dirs.push(current);
206
+ if (dirname(current) === current) return dirs;
207
+ }
208
+ }
209
+
210
+ /** The `.omp/` OMP takes the project `RULES.md` from: the nearest non-empty one up to the repo root. */
211
+ async function nearestProjectConfigDir(cwd: string): Promise<string | null> {
212
+ const dirs = ancestors(cwd);
213
+ let repoRoot: string | undefined;
214
+ for (const dir of dirs) {
215
+ const isRepoRoot = await lstat(join(dir, ".git")).then(
216
+ () => true,
217
+ () => false,
218
+ );
219
+ if (isRepoRoot) {
220
+ repoRoot = dir;
221
+ break;
222
+ }
223
+ }
224
+ for (const dir of dirs) {
225
+ if (DISCOVERY_CEILINGS.has(dir)) return null;
226
+ if (await isNonEmptyDirectory(join(dir, ".omp"))) return join(dir, ".omp");
227
+ if (dir === repoRoot) return null;
228
+ }
229
+ return null;
230
+ }
231
+
232
+ interface RuleFile {
233
+ name: string;
234
+ path: string;
235
+ source: "project" | "user";
236
+ /** `RULES.md` always applies, whatever its frontmatter says. */
237
+ sticky: boolean;
238
+ }
239
+
240
+ /** OMP's own rule files, in its first-wins order. A global listing never reads project files. */
241
+ async function ruleFiles(cwd: string | undefined): Promise<RuleFile[]> {
242
+ const agentDir = ompAgentDir(currentOmpEnvironment());
243
+ const files: RuleFile[] = [];
244
+ const add = (paths: string[], source: RuleFile["source"]) => {
245
+ for (const path of paths) {
246
+ const base = path.slice(path.lastIndexOf(sep) + 1);
247
+ files.push({ name: base.replace(/\.(md|mdc)$/u, ""), path, source, sticky: false });
248
+ }
249
+ };
250
+ // A cloned project could point `.omp` or `.omp/rules` anywhere, so neither may be a symlink.
251
+ const projectRules = cwd ? join(cwd, ".omp", "rules") : undefined;
252
+ if (
253
+ cwd &&
254
+ projectRules &&
255
+ resolve(cwd) !== homedir() &&
256
+ (await isRealDirectory(join(cwd, ".omp"))) &&
257
+ (await isRealDirectory(projectRules))
258
+ )
259
+ add(await ruleFilesIn(projectRules), "project");
260
+ add(await ruleFilesIn(join(agentDir, "rules")), "user");
261
+ files.push({ name: "RULES", path: join(agentDir, "RULES.md"), source: "user", sticky: true });
262
+ const projectConfig = cwd ? await nearestProjectConfigDir(cwd) : null;
263
+ if (projectConfig) {
264
+ files.push({
265
+ name: "RULES@project",
266
+ path: join(projectConfig, "RULES.md"),
267
+ source: "project",
268
+ sticky: true,
269
+ });
270
+ }
271
+ return files;
272
+ }
273
+
274
+ const FrontmatterSchema = z.record(z.string(), z.unknown());
275
+ type Frontmatter = z.infer<typeof FrontmatterSchema>;
276
+
277
+ function frontmatter(text: string): Frontmatter {
278
+ const normalized = text.replace(/\r\n/gu, "\n");
279
+ if (!normalized.startsWith("---")) return {};
280
+ const end = normalized.indexOf("\n---", 3);
281
+ if (end === -1) return {};
282
+ try {
283
+ const parsed = FrontmatterSchema.safeParse(parseYaml(normalized.slice(3, end)));
284
+ return parsed.success ? parsed.data : {};
285
+ } catch {
286
+ return {};
287
+ }
288
+ }
289
+
290
+ function stringList(value: unknown, separator?: string): string[] {
291
+ if (typeof value === "string") {
292
+ const items = separator ? value.split(separator) : [value];
293
+ return clipList(items.map((item) => item.trim()).filter(Boolean));
294
+ }
295
+ if (!Array.isArray(value)) return [];
296
+ return clipList(value.filter((item): item is string => typeof item === "string"));
297
+ }
298
+
299
+ function classify(file: RuleFile, meta: Frontmatter): OmpRule | null {
300
+ const description = typeof meta.description === "string" ? clip(meta.description) : null;
301
+ let kind: OmpRule["kind"];
302
+ if (file.sticky || meta.alwaysApply === true) kind = "always";
303
+ else if (description) kind = "rulebook";
304
+ else return null;
305
+ return {
306
+ name: file.name,
307
+ kind,
308
+ source: file.source,
309
+ provider: "native",
310
+ description,
311
+ condition: [],
312
+ astCondition: [],
313
+ question: null,
314
+ scope: [],
315
+ globs: stringList(meta.globs),
316
+ agents: stringList(meta.agents, ","),
317
+ path: file.path,
318
+ };
319
+ }
320
+
321
+ /** Always-apply and rulebook rules: OMP's `ttsr list` reports only watch rules. */
322
+ export async function readPromptRules(
323
+ cwd: string | undefined,
324
+ hidden: ReadonlySet<string>,
325
+ ): Promise<OmpRule[]> {
326
+ const seen = new Set<string>();
327
+ const rules: OmpRule[] = [];
328
+ for (const file of await ruleFiles(cwd)) {
329
+ if (seen.has(file.name)) continue;
330
+ const text = await readRuleFile(file.path);
331
+ // OMP drops an empty RULES.md and an `enabled: false` file before the first-wins check.
332
+ if (text === null || (file.sticky && text.trim() === "")) continue;
333
+ const meta = frontmatter(text);
334
+ if (meta.enabled === false) continue;
335
+ seen.add(file.name);
336
+ const rule = classify(file, meta);
337
+ if (rule && !hidden.has(rule.name)) rules.push(rule);
338
+ }
339
+ return rules;
340
+ }
341
+
342
+ async function listRulesIn(
343
+ runIn: string,
344
+ cwd: string | undefined,
345
+ dependencies: OmpRulesDependencies,
346
+ ): Promise<OmpRulesList> {
347
+ const executable = await dependencies.resolveExecutable();
348
+ if (!executable) throw new OmpRulesError("The omp command was not found on this host");
349
+ // Every command finishes before the caller may remove its working directory.
350
+ const [watchResult, disabledResult, builtinResult] = await Promise.allSettled([
351
+ runJson(dependencies, executable, ["ttsr", "list", "--json"], runIn).then(parseWatchRules),
352
+ readSetting(dependencies, executable, "ttsr.disabledRules", DisabledRulesSchema, runIn),
353
+ readSetting(dependencies, executable, "ttsr.builtinRules", BuiltinRulesSchema, runIn),
354
+ ]);
355
+ for (const result of [watchResult, disabledResult, builtinResult]) {
356
+ if (result.status === "rejected") throw result.reason;
357
+ }
358
+ const watch = (watchResult as PromiseFulfilledResult<WatchRule[]>).value;
359
+ const disabled = (disabledResult as PromiseFulfilledResult<string[]>).value;
360
+ const builtinRules = (builtinResult as PromiseFulfilledResult<boolean>).value;
361
+ // OMP trims each name and matches the whole list; only the displayed names are clipped.
362
+ const allDisabled = [...new Set(disabled.map((name) => name.trim()).filter(Boolean))];
363
+ const disabledNames = clipList(allDisabled);
364
+ const hidden = new Set([...watch.map((rule) => rule.name), ...allDisabled]);
365
+ return {
366
+ status: "ready",
367
+ rules: [
368
+ ...watch.map((rule) => toWatchRule(rule, cwd)),
369
+ ...(await readPromptRules(cwd, hidden)),
370
+ ],
371
+ disabled: disabledNames,
372
+ builtinRules,
373
+ };
374
+ }
375
+
376
+ async function listRules(
377
+ cwd: string | undefined,
378
+ dependencies: OmpRulesDependencies,
379
+ ): Promise<OmpRulesList> {
380
+ if (cwd !== undefined) {
381
+ const isDirectory =
382
+ isAbsolute(cwd) &&
383
+ !cwd.includes("\0") &&
384
+ (await stat(cwd).then(
385
+ (info) => info.isDirectory(),
386
+ () => false,
387
+ ));
388
+ if (!isDirectory) throw new OmpRulesError("The workspace path is invalid");
389
+ return listRulesIn(cwd, cwd, dependencies);
390
+ }
391
+ // An empty directory keeps every project's rules out of the global listing.
392
+ const prefix = join(tmpdir(), "paseo-omp-rules-");
393
+ const scratch = await dependencies.makeScratchDir(prefix);
394
+ try {
395
+ return await listRulesIn(scratch, undefined, dependencies);
396
+ } finally {
397
+ // Only ever delete the directory this call created directly under the system temp directory.
398
+ const ours =
399
+ scratch === resolve(scratch) &&
400
+ dirname(scratch) === tmpdir() &&
401
+ basename(scratch).startsWith("paseo-omp-rules-") &&
402
+ basename(scratch) !== "paseo-omp-rules-";
403
+ if (ours) await dependencies.removeDir(scratch).catch(() => undefined);
404
+ }
405
+ }
406
+
407
+ export async function listOmpRulesWithDependencies(
408
+ input: RpcInput<typeof listOmpRules>,
409
+ dependencies: OmpRulesDependencies,
410
+ ): Promise<OmpRulesList> {
411
+ try {
412
+ return await listRules(input.cwd, dependencies);
413
+ } catch (error) {
414
+ if (error instanceof OmpRulesError) return { status: "error", message: error.message };
415
+ throw error;
416
+ }
417
+ }
418
+
419
+ const DEFAULT_DEPENDENCIES: OmpRulesDependencies = {
420
+ resolveExecutable: resolveOmpExecutable,
421
+ run: (executable, args, cwd) =>
422
+ runBounded(
423
+ defaultSpawn,
424
+ executable,
425
+ args,
426
+ buildStatefulCommandEnv(currentOmpEnvironment()),
427
+ COMMAND_TIMEOUT_MS,
428
+ KILL_GRACE_MS,
429
+ MAX_OUTPUT_BYTES,
430
+ cwd,
431
+ ),
432
+ makeScratchDir: (prefix) => mkdtemp(prefix),
433
+ removeDir: (path) => rm(path, { recursive: true, force: true }),
434
+ };
435
+
436
+ export function resolveListOmpRules(input: RpcInput<typeof listOmpRules>): Promise<OmpRulesList> {
437
+ return listOmpRulesWithDependencies(input, DEFAULT_DEPENDENCIES);
438
+ }
@@ -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.395.1"; // x-release-please-version
2
+ export const PASEO_OMP_PACKAGE_VERSION = "5.4.0-next.396.1"; // x-release-please-version
@@ -0,0 +1,49 @@
1
+ import { defineRpc } from "@getpaseo/plugin";
2
+ import { z } from "zod";
3
+ import { OmpWorkspaceCwdSchema } from "./hub";
4
+ import { OmpStoreSchema } from "./omp-store";
5
+
6
+ /** A watch rule fires on what the agent writes; always-apply and rulebook rules sit in the prompt. */
7
+ export const OmpRuleKindSchema = z.enum(["watch", "always", "rulebook"]);
8
+ export type OmpRuleKind = z.infer<typeof OmpRuleKindSchema>;
9
+
10
+ /** `imported` is a rule OMP reads from another tool's files (Cursor, Windsurf, Cline, ...). */
11
+ export const OmpRuleSourceSchema = z.enum(["project", "user", "builtin", "imported"]);
12
+
13
+ export const OmpRuleSchema = z.object({
14
+ name: z.string(),
15
+ kind: OmpRuleKindSchema,
16
+ source: OmpRuleSourceSchema,
17
+ /** OMP's provider id, such as `native`, `builtin-defaults`, or `cursor`. */
18
+ provider: z.string(),
19
+ description: z.string().nullable(),
20
+ condition: z.array(z.string()),
21
+ astCondition: z.array(z.string()),
22
+ question: z.string().nullable(),
23
+ scope: z.array(z.string()),
24
+ globs: z.array(z.string()),
25
+ agents: z.array(z.string()),
26
+ path: z.string(),
27
+ });
28
+ export type OmpRule = z.infer<typeof OmpRuleSchema>;
29
+
30
+ export const OmpRulesListSchema = z.discriminatedUnion("status", [
31
+ z.object({
32
+ status: z.literal("ready"),
33
+ rules: z.array(OmpRuleSchema),
34
+ /** `ttsr.disabledRules`: OMP hides these, so only their names are known. */
35
+ disabled: z.array(z.string()),
36
+ /** `ttsr.builtinRules`: false hides every built-in rule. */
37
+ builtinRules: z.boolean(),
38
+ }),
39
+ z.object({ status: z.literal("error"), message: z.string() }),
40
+ ]);
41
+ export type OmpRulesList = z.infer<typeof OmpRulesListSchema>;
42
+
43
+ export const listOmpRules = defineRpc({
44
+ name: "paseo-omp.list-rules",
45
+ input: z
46
+ .object({ store: OmpStoreSchema.optional(), cwd: OmpWorkspaceCwdSchema.optional() })
47
+ .strict(),
48
+ output: OmpRulesListSchema,
49
+ });