ceulen 0.7.0 → 0.9.0
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/CHANGELOG.md +83 -0
- package/extensions/lib/registry.test.ts +67 -0
- package/extensions/lib/registry.ts +24 -7
- package/extensions/modules/a2a/configPanel.ts +435 -0
- package/extensions/modules/a2a/index.ts +1117 -0
- package/extensions/modules/a2a/lib/activity.ts +173 -0
- package/extensions/modules/a2a/lib/client.ts +1061 -0
- package/extensions/modules/a2a/lib/config.ts +920 -0
- package/extensions/modules/a2a/lib/discovery.ts +158 -0
- package/extensions/modules/a2a/lib/gateway.ts +889 -0
- package/extensions/modules/a2a/lib/mdns.ts +233 -0
- package/extensions/modules/a2a/lib/outcome.ts +48 -0
- package/extensions/modules/a2a/lib/persistence.ts +123 -0
- package/extensions/modules/a2a/lib/protocol.ts +506 -0
- package/extensions/modules/a2a/lib/registry.ts +146 -0
- package/extensions/modules/a2a/lib/retry.ts +86 -0
- package/extensions/modules/a2a/lib/security.ts +394 -0
- package/extensions/modules/a2a/lib/server.ts +1436 -0
- package/extensions/modules/a2a/test/activity.test.ts +138 -0
- package/extensions/modules/a2a/test/bridge.test.ts +101 -0
- package/extensions/modules/a2a/test/broadcast-parse.test.ts +31 -0
- package/extensions/modules/a2a/test/chai.ts +101 -0
- package/extensions/modules/a2a/test/client.test.ts +856 -0
- package/extensions/modules/a2a/test/completion-guard.test.ts +73 -0
- package/extensions/modules/a2a/test/config.test.ts +1396 -0
- package/extensions/modules/a2a/test/configPanel.test.ts +393 -0
- package/extensions/modules/a2a/test/discovery.test.ts +144 -0
- package/extensions/modules/a2a/test/extension.test.ts +135 -0
- package/extensions/modules/a2a/test/gateway.test.ts +1449 -0
- package/extensions/modules/a2a/test/helpers.ts +39 -0
- package/extensions/modules/a2a/test/mdns.test.ts +131 -0
- package/extensions/modules/a2a/test/outcome.test.ts +61 -0
- package/extensions/modules/a2a/test/persistence.test.ts +92 -0
- package/extensions/modules/a2a/test/protocol.test.ts +217 -0
- package/extensions/modules/a2a/test/registry.test.ts +114 -0
- package/extensions/modules/a2a/test/retry.test.ts +136 -0
- package/extensions/modules/a2a/test/security.test.ts +281 -0
- package/extensions/modules/a2a/test/server.test.ts +1966 -0
- package/extensions/modules/a2a/test/tmp.ts +59 -0
- package/extensions/modules/a2a/test/vendor.test.ts +57 -0
- package/extensions/modules/a2a/types/bonjour-service.d.ts +22 -0
- package/extensions/modules/a2a/vendor/VENDORED.md +18 -0
- package/extensions/modules/a2a/vendor/package.json +1 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/LICENSE +23 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.d.ts +14 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.js +57 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.d.ts +4 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.js +3 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.d.ts +13 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.js +50 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.d.ts +41 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.js +209 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.d.ts +9 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.js +42 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.d.ts +14 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.js +119 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.d.ts +14 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.js +142 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.d.ts +7 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.js +53 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.d.ts +58 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.js +130 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.d.ts +1 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.js +13 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.d.ts +1 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.js +17 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.d.ts +4 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.js +22 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.d.ts +3 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.js +6 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/classes.js +23 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/index.js +1761 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/opcodes.js +50 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/optioncodes.js +59 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/rcodes.js +50 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/types.js +103 -0
- package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/es6.js +73 -0
- package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/index.js +46 -0
- package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/index.cjs +250 -0
- package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/index.js +205 -0
- package/extensions/modules/a2a/vendor/vendored_deps/thunky/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/thunky/index.js +55 -0
- package/extensions/modules/advisor/index.ts +20 -2
- package/extensions/modules/advisor/lib/watcher.ts +3 -1
- package/extensions/modules/advisor/test/module.test.ts +64 -1
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/index.ts +2 -0
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/munin/configPanel.ts +5 -2
- package/extensions/modules/munin/test/configPanel.test.ts +27 -2
- package/extensions/modules/router/configPanel.ts +24 -10
- package/extensions/modules/router/lib/client.ts +6 -4
- package/extensions/modules/router/test/unit.test.ts +83 -2
- package/extensions/modules/rules/index.ts +120 -0
- package/extensions/modules/rules/lib/rules.ts +348 -0
- package/extensions/modules/rules/test/lib.test.ts +263 -0
- package/extensions/modules/rules/test/module.test.ts +222 -0
- package/extensions/modules/subagent/index.ts +19 -6
- package/extensions/modules/subagent/lib/routing.ts +11 -6
- package/extensions/modules/subagent/lib/security.ts +12 -1
- package/extensions/modules/subagent/test/routing.test.ts +174 -0
- package/extensions/modules/todo/configPanel.ts +55 -0
- package/extensions/modules/todo/index.ts +511 -0
- package/extensions/modules/todo/lib/render.ts +271 -0
- package/extensions/modules/todo/lib/settings.ts +73 -0
- package/extensions/modules/todo/test/todo.test.ts +528 -0
- package/extensions/modules/usage/index.ts +11 -0
- package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
- package/extensions/modules/web/configPanel.ts +38 -13
- package/extensions/modules/web/lib/settings.ts +11 -2
- package/extensions/modules/web/test/configPanel.test.ts +67 -1
- package/extensions/modules/zai/configPanel.ts +5 -2
- package/extensions/modules/zai/lib/signing.ts +4 -1
- package/extensions/modules/zai/test/configPanel.test.ts +23 -0
- package/extensions/modules/zai/test/signing.test.ts +19 -0
- package/package.json +2 -2
- package/skills/a2a/SKILL.md +63 -0
|
@@ -105,6 +105,85 @@ describe("config", () => {
|
|
|
105
105
|
});
|
|
106
106
|
});
|
|
107
107
|
|
|
108
|
+
// ── /config Router save: re-register from the EFFECTIVE settings ─────────
|
|
109
|
+
// With a trusted project endpoint P shadowing global G, saving any /config
|
|
110
|
+
// change must leave the provider on P (registering the raw saved copy would
|
|
111
|
+
// clobber it with G); the disclosure must report the effective values.
|
|
112
|
+
describe("saveRouterConfig re-registers from effective settings", () => {
|
|
113
|
+
const repoPath = () => join(process.cwd(), ".pi", "settings.json");
|
|
114
|
+
|
|
115
|
+
async function withRepoSettings(router: unknown, fn: () => Promise<void>): Promise<void> {
|
|
116
|
+
const prev = existsSync(repoPath()) ? readFileSync(repoPath(), "utf8") : null;
|
|
117
|
+
mkdirSync(join(process.cwd(), ".pi"), { recursive: true });
|
|
118
|
+
writeFileSync(repoPath(), JSON.stringify({ router }));
|
|
119
|
+
try {
|
|
120
|
+
await fn();
|
|
121
|
+
} finally {
|
|
122
|
+
if (prev === null) unlinkSync(repoPath());
|
|
123
|
+
else writeFileSync(repoPath(), prev);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function makeSaveHarness(trusted: boolean) {
|
|
128
|
+
const registered: string[] = [];
|
|
129
|
+
const notes: { text: string; level: string }[] = [];
|
|
130
|
+
const pi = {
|
|
131
|
+
registerProvider: (_n: string, config: { baseUrl: string }) => { registered.push(config.baseUrl); },
|
|
132
|
+
};
|
|
133
|
+
const ctx = {
|
|
134
|
+
ui: { notify: (text: string, level: string) => { notes.push({ text, level }); } },
|
|
135
|
+
model: undefined,
|
|
136
|
+
modelRegistry: { refresh: async () => ({}), find: () => undefined },
|
|
137
|
+
isProjectTrusted: () => trusted,
|
|
138
|
+
};
|
|
139
|
+
return { pi, ctx, registered, notes };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
it("trusted project endpoint wins over the saved copy", async () => {
|
|
143
|
+
try { unlinkSync(settingsPath()); } catch { /* ignore */ }
|
|
144
|
+
writeSettings({ baseUrl: "http://global" });
|
|
145
|
+
const { saveRouterConfig } = await import("../configPanel.js");
|
|
146
|
+
const h = makeSaveHarness(true);
|
|
147
|
+
await withRepoSettings({ baseUrl: "http://trusted-repo" }, async () => {
|
|
148
|
+
// The panel baseline/working copy is the effective (project) value…
|
|
149
|
+
const before = { baseUrl: "http://trusted-repo", enableReasoning: true };
|
|
150
|
+
await saveRouterConfig(h.pi as never, before, { ...before, enableReasoning: false }, h.ctx as never);
|
|
151
|
+
});
|
|
152
|
+
assert.deepEqual(h.registered, ["http://trusted-repo"], "provider re-registered with the project endpoint, not the saved global one");
|
|
153
|
+
assert.equal(h.notes.at(-1)!.level, "info", "no phantom override when saved and effective agree");
|
|
154
|
+
assert.match(h.notes.at(-1)!.text, /http:\/\/trusted-repo/);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it("untrusted project endpoint is ignored — the saved value is registered", async () => {
|
|
158
|
+
try { unlinkSync(settingsPath()); } catch { /* ignore */ }
|
|
159
|
+
writeSettings({ baseUrl: "http://global" });
|
|
160
|
+
const { saveRouterConfig } = await import("../configPanel.js");
|
|
161
|
+
const h = makeSaveHarness(false);
|
|
162
|
+
await withRepoSettings({ baseUrl: "http://trusted-repo" }, async () => {
|
|
163
|
+
const before = { baseUrl: "http://global", enableReasoning: true };
|
|
164
|
+
await saveRouterConfig(h.pi as never, before, { ...before, enableReasoning: false }, h.ctx as never);
|
|
165
|
+
});
|
|
166
|
+
assert.deepEqual(h.registered, ["http://global"], "untrusted repo scope never owns the endpoint");
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("env ROUTER_BASE_URL shadows the save: disclosed + provider follows env", async () => {
|
|
170
|
+
try { unlinkSync(settingsPath()); } catch { /* ignore */ }
|
|
171
|
+
writeSettings({ baseUrl: "http://global" });
|
|
172
|
+
process.env.ROUTER_BASE_URL = "http://from-env/";
|
|
173
|
+
try {
|
|
174
|
+
const { saveRouterConfig } = await import("../configPanel.js");
|
|
175
|
+
const h = makeSaveHarness(false);
|
|
176
|
+
const before = { baseUrl: "", enableReasoning: true };
|
|
177
|
+
await saveRouterConfig(h.pi as never, before, { ...before, baseUrl: "http://panel-typed" }, h.ctx as never);
|
|
178
|
+
assert.deepEqual(h.registered, ["http://from-env"], "catalog refresh + requests hit the effective env endpoint");
|
|
179
|
+
assert.equal(h.notes.at(-1)!.level, "warning");
|
|
180
|
+
assert.match(h.notes.at(-1)!.text, /ROUTER_BASE_URL/);
|
|
181
|
+
} finally {
|
|
182
|
+
delete process.env.ROUTER_BASE_URL;
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
108
187
|
it("legacy NINE_ROUTER_BASE_URL still works", async () => {
|
|
109
188
|
try { unlinkSync(settingsPath()); } catch { /* ignore */ }
|
|
110
189
|
process.env.NINE_ROUTER_BASE_URL = "http://legacy-env";
|
|
@@ -398,13 +477,15 @@ describe("client", () => {
|
|
|
398
477
|
}
|
|
399
478
|
});
|
|
400
479
|
|
|
401
|
-
it("combo/ backends map onto the CC enum (
|
|
480
|
+
it("combo/ backends map onto the CC enum (nothing invalid is ever sent)", async () => {
|
|
402
481
|
const { mapModel } = await import("../lib/client.js");
|
|
403
482
|
const tlm = (id: string) => mapModel({ id }, true).thinkingLevelMap ?? {};
|
|
404
483
|
// The deepseek family map would send off→"none" — the yardmaster combo
|
|
405
484
|
// backend 400s on it (live-probed 2026-10-03). cc-enum must win.
|
|
406
485
|
const m = tlm("combo/deepseek-v4.1-flash");
|
|
407
|
-
|
|
486
|
+
// The literal "off" 422s upstream too (reasoning_effort: unknown variant
|
|
487
|
+
// 'off', live 2026-10-04) — off must OMIT the parameter, not send "off".
|
|
488
|
+
assert.equal(m.off, null);
|
|
408
489
|
assert.equal(m.low, "low");
|
|
409
490
|
assert.equal(m.medium, "medium");
|
|
410
491
|
assert.equal(m.max, "max");
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// rules module — sticky RULES.md + on-demand rulebook.
|
|
2
|
+
//
|
|
3
|
+
// Ported CONTRACT (not code) from OMP's sticky RULES.md + rulebook split
|
|
4
|
+
// (omp/docs/context-files.md "Sticky rules vs normal context",
|
|
5
|
+
// omp/docs/rulebook-matching-pipeline.md §5 bucket split,
|
|
6
|
+
// omp/packages/coding-agent/src/capability/rule.ts). The file format is
|
|
7
|
+
// documented at the top of ./lib/rules.ts.
|
|
8
|
+
//
|
|
9
|
+
// Surfaces:
|
|
10
|
+
// - ONE `before_agent_start` handler: append-only composition exactly like the
|
|
11
|
+
// fff module (returns `{ systemPrompt: \`${event.systemPrompt}\n\n${block}\` }`
|
|
12
|
+
// or undefined when no RULES.md exists anywhere — zero footprint by default).
|
|
13
|
+
// - ONE tool `rule_get` (name) serving a rulebook rule's body on demand.
|
|
14
|
+
// - `/rules` status + `/rules reload` (drops the mtime cache).
|
|
15
|
+
//
|
|
16
|
+
// Registered in a guarded()`-deduped bundle: no attempt is made to own the
|
|
17
|
+
// rules — dropping the module (or never wiring it) restores vanilla pi.
|
|
18
|
+
|
|
19
|
+
import type {
|
|
20
|
+
BeforeAgentStartEventResult,
|
|
21
|
+
ExtensionAPI,
|
|
22
|
+
ExtensionContext,
|
|
23
|
+
} from "@earendil-works/pi-coding-agent";
|
|
24
|
+
import { Type } from "typebox";
|
|
25
|
+
import { readDisabledTools } from "../../lib/tools";
|
|
26
|
+
import { clearRuleCache, loadRules, type RuleModel } from "./lib/rules";
|
|
27
|
+
|
|
28
|
+
/** Cap on a single rule body returned by rule_get (chars). */
|
|
29
|
+
const RULE_GET_MAX_CHARS = 20000;
|
|
30
|
+
|
|
31
|
+
function statusLines(model: RuleModel, cwd: string): string {
|
|
32
|
+
if (model.files.length === 0) {
|
|
33
|
+
return [
|
|
34
|
+
"Rule sources: none",
|
|
35
|
+
" No .pi/RULES.md found from cwd to the filesystem root, and no user-level ~/.pi/agent/RULES.md.",
|
|
36
|
+
" Create one to add sticky rules (append-only to the system prompt) or rulebook rules.",
|
|
37
|
+
].join("\n");
|
|
38
|
+
}
|
|
39
|
+
const names = (rules: { name: string }[]) => rules.map((rule) => rule.name).join(", ") || "(none)";
|
|
40
|
+
return [
|
|
41
|
+
`Rule sources (${model.files.length}):`,
|
|
42
|
+
...model.files.map((file, index) => ` ${index + 1}. ${file}`),
|
|
43
|
+
`Sticky rules (${model.sticky.length}): ${names(model.sticky)}`,
|
|
44
|
+
`Rulebook rules (${model.rulebook.length}): ${names(model.rulebook)}`,
|
|
45
|
+
" Bodies are served on demand by rule_get — never listed here.",
|
|
46
|
+
`Prompt block: ${model.blockChars} chars${model.block ? "" : " (no block emitted)"}`,
|
|
47
|
+
` Sources are resolved nearest-first from ${cwd}; project files override user rules on duplicate names.`,
|
|
48
|
+
].join("\n");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export default function rulesExtension(pi: ExtensionAPI): void {
|
|
52
|
+
const disabledTools = readDisabledTools();
|
|
53
|
+
|
|
54
|
+
pi.on("before_agent_start", async (event, ctx): Promise<BeforeAgentStartEventResult | undefined> => {
|
|
55
|
+
let model: RuleModel;
|
|
56
|
+
try {
|
|
57
|
+
model = loadRules(ctx?.cwd ?? process.cwd());
|
|
58
|
+
} catch {
|
|
59
|
+
return undefined; // never break a turn over rule discovery
|
|
60
|
+
}
|
|
61
|
+
if (!model.block) return undefined;
|
|
62
|
+
return { systemPrompt: `${event.systemPrompt}\n\n${model.block}` };
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
pi.registerTool({
|
|
66
|
+
name: "rule_get",
|
|
67
|
+
label: "rule_get",
|
|
68
|
+
description:
|
|
69
|
+
"Read the full body of a project rule listed in the <user-rules> rulebook (sticky rules are already in the system prompt).",
|
|
70
|
+
promptSnippet: "Read a rulebook rule's body by name",
|
|
71
|
+
parameters: Type.Object({
|
|
72
|
+
name: Type.String({ description: "Rule name (the `## <name>` heading) from the rulebook listing." }),
|
|
73
|
+
}),
|
|
74
|
+
defaultActive: !disabledTools.has("rule_get"),
|
|
75
|
+
async execute(_id: string, params: { name: string }, _signal, _onUpdate, ctx) {
|
|
76
|
+
const model = loadRules(ctx?.cwd ?? process.cwd());
|
|
77
|
+
const wanted = (params.name ?? "").trim();
|
|
78
|
+
const rule = model.rules.find((item) => item.name === wanted);
|
|
79
|
+
if (!rule) {
|
|
80
|
+
const available = model.rules.map((item) => item.name);
|
|
81
|
+
return {
|
|
82
|
+
content: [{
|
|
83
|
+
type: "text" as const,
|
|
84
|
+
text: available.length === 0
|
|
85
|
+
? `Rule "${wanted}" not found: no RULES.md exists in this workspace (searched .pi/RULES.md from cwd to the filesystem root, plus ~/.pi/agent/RULES.md).`
|
|
86
|
+
: `Rule "${wanted}" not found. Available rules: ${available.join(", ")}`,
|
|
87
|
+
}],
|
|
88
|
+
details: { found: false, available },
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
const body = rule.sticky
|
|
92
|
+
? `[sticky rule "${rule.name}" — already appended to the system prompt]\n\n${rule.body}`
|
|
93
|
+
: rule.body;
|
|
94
|
+
const clipped = body.length > RULE_GET_MAX_CHARS
|
|
95
|
+
? `${body.slice(0, RULE_GET_MAX_CHARS)}\n\n[rule body truncated at ${RULE_GET_MAX_CHARS} chars]`
|
|
96
|
+
: body;
|
|
97
|
+
return {
|
|
98
|
+
content: [{ type: "text" as const, text: `${clipped}\n\n(rule "${rule.name}" from ${rule.source})` }],
|
|
99
|
+
details: { found: true, name: rule.name, source: rule.source, sticky: rule.sticky, truncated: clipped !== body },
|
|
100
|
+
};
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
pi.registerCommand("rules", {
|
|
105
|
+
description: "Rule sources status, or /rules reload to drop the rule-file cache.",
|
|
106
|
+
handler: async (args: string, ctx: ExtensionContext) => {
|
|
107
|
+
const arg = (args ?? "").trim().toLowerCase();
|
|
108
|
+
if (arg === "reload") {
|
|
109
|
+
clearRuleCache();
|
|
110
|
+
ctx.ui.notify(`[rules] cache dropped — re-reading ${loadRules(ctx.cwd).files.length} source(s)`, "info");
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (arg !== "") {
|
|
114
|
+
ctx.ui.notify(`[rules] unknown argument "${arg}" — use /rules or /rules reload`, "error");
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
ctx.ui.notify(statusLines(loadRules(ctx.cwd), ctx.cwd), "info");
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
}
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
// rules — RULES.md discovery, parsing, @import expansion, prompt composition.
|
|
2
|
+
//
|
|
3
|
+
// FORMAT (one rule per `## <name>` section; ported CONTRACT from OMP's
|
|
4
|
+
// sticky RULES.md + rulebook split):
|
|
5
|
+
//
|
|
6
|
+
// ## never-push
|
|
7
|
+
// Never commit or push unless the user explicitly asks.
|
|
8
|
+
//
|
|
9
|
+
// ## api-style
|
|
10
|
+
// description: How to write HTTP handlers in this repo.
|
|
11
|
+
// Always use the shared `json()` helper and return a typed error shape.
|
|
12
|
+
//
|
|
13
|
+
// - A section whose body STARTS with a `description:` line is a RULEBOOK rule:
|
|
14
|
+
// the prompt lists only `name — description`; the body is served on demand by
|
|
15
|
+
// the `rule_get` tool.
|
|
16
|
+
// - A section with no `description:` line is a STICKY rule: its body is always
|
|
17
|
+
// appended to the system prompt, under STICKY_CHAR_CAP (lowest-precedence
|
|
18
|
+
// rules dropped first, with a loud marker).
|
|
19
|
+
// - Content BEFORE the first `##` heading (i.e. a heading-less RULES.md) is one
|
|
20
|
+
// sticky rule named `RULES` — OMP's plain-prose RULES.md still works.
|
|
21
|
+
// - `# title` and `### x` are NOT rule headings; `##` inside a ``` fence is text.
|
|
22
|
+
// - `@path` tokens (at line start or after whitespace, outside fences) expand
|
|
23
|
+
// inline: relative to the RULES.md's own directory, `~/` from home, absolute
|
|
24
|
+
// as-is. Cycles and repeats stay literal; missing targets get a marker.
|
|
25
|
+
//
|
|
26
|
+
// SOURCES / PRECEDENCE: nearest-first walk from cwd to the filesystem root for
|
|
27
|
+
// `<dir>/.pi/RULES.md`, then the user-level `<agentDir>/RULES.md`. Duplicate
|
|
28
|
+
// rule names resolve first-wins, so a project rule overrides a user rule and a
|
|
29
|
+
// nearer project file overrides a farther one.
|
|
30
|
+
//
|
|
31
|
+
// DELIBERATE DEVIATIONS from OMP (documented, not accidental):
|
|
32
|
+
// 1. Only `##` headings split rules — no frontmatter (`description:` line
|
|
33
|
+
// instead) and no `alwaysApply`/TTSR condition fields. Sticky is the
|
|
34
|
+
// absence of a description, which keeps one parseable format.
|
|
35
|
+
// 2. A heading-less file is ONE sticky rule named `RULES` (OMP's plain-prose
|
|
36
|
+
// RULES.md); a `# Title` preamble before the first `##` is dropped.
|
|
37
|
+
// 3. `@token` inside a FENCED block stays literal (OMP parity), but a span
|
|
38
|
+
// opening with a backtick is left literal only because a backtick is not
|
|
39
|
+
// whitespace — no code-span parser is worth its weight here.
|
|
40
|
+
|
|
41
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
42
|
+
import os from "node:os";
|
|
43
|
+
import path from "node:path";
|
|
44
|
+
|
|
45
|
+
export const STICKY_CHAR_CAP = 4000;
|
|
46
|
+
export const MAX_IMPORT_DEPTH = 5;
|
|
47
|
+
export const RULES_FILE = "RULES.md";
|
|
48
|
+
const PROJECT_DIR = ".pi";
|
|
49
|
+
|
|
50
|
+
const HEADING = /^##\s+(.+?)\s*$/;
|
|
51
|
+
const DESCRIPTION = /^description:\s*(.*)$/i;
|
|
52
|
+
const FENCE = /^\s*(?:```|~~~)/;
|
|
53
|
+
// A token only counts as an import when `@` starts a line or follows whitespace
|
|
54
|
+
// (so `user@example.com` and `git@github.com:o/r.git` are never imports).
|
|
55
|
+
const IMPORT = /(^|[ \t])@([^\s]+)/g;
|
|
56
|
+
const TRAILING_PUNCTUATION = /[.,;:!?)\]}"']+$/;
|
|
57
|
+
|
|
58
|
+
export interface LoadedRule {
|
|
59
|
+
/** The rule's slug/heading (or `RULES` for pre-heading prose). */
|
|
60
|
+
name: string;
|
|
61
|
+
/** Present = rulebook rule (body on demand); absent = sticky rule. */
|
|
62
|
+
description?: string;
|
|
63
|
+
/** Body, with `@` imports already expanded. */
|
|
64
|
+
body: string;
|
|
65
|
+
/** Absolute path of the RULES.md that defined it. */
|
|
66
|
+
source: string;
|
|
67
|
+
sticky: boolean;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface RuleModel {
|
|
71
|
+
/** Discovered RULES.md files, highest precedence first. */
|
|
72
|
+
files: string[];
|
|
73
|
+
/** Deduped rules in precedence order. */
|
|
74
|
+
rules: LoadedRule[];
|
|
75
|
+
sticky: LoadedRule[];
|
|
76
|
+
rulebook: LoadedRule[];
|
|
77
|
+
/** The composed prompt block, or undefined when nothing was found. */
|
|
78
|
+
block?: string;
|
|
79
|
+
/** Length of `block` (the char count /rules reports). */
|
|
80
|
+
blockChars: number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
// Parsing
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
interface Section {
|
|
88
|
+
name: string | null;
|
|
89
|
+
lines: string[];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function splitSections(text: string): Section[] {
|
|
93
|
+
const sections: Section[] = [{ name: null, lines: [] }];
|
|
94
|
+
let fenced = false;
|
|
95
|
+
for (const line of text.replace(/^\uFEFF/, "").split(/\r?\n/)) {
|
|
96
|
+
if (FENCE.test(line)) fenced = !fenced;
|
|
97
|
+
const heading = fenced ? null : HEADING.exec(line);
|
|
98
|
+
if (heading) sections.push({ name: heading[1].trim(), lines: [] });
|
|
99
|
+
else sections.at(-1)!.lines.push(line);
|
|
100
|
+
}
|
|
101
|
+
return sections;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function makeRule(name: string, rawLines: string[], source: string): LoadedRule | null {
|
|
105
|
+
const lines = rawLines.slice();
|
|
106
|
+
while (lines.length > 0 && lines[0].trim() === "") lines.shift();
|
|
107
|
+
while (lines.length > 0 && lines.at(-1)!.trim() === "") lines.pop();
|
|
108
|
+
|
|
109
|
+
let description: string | undefined;
|
|
110
|
+
const match = lines.length > 0 ? DESCRIPTION.exec(lines[0].trim()) : null;
|
|
111
|
+
if (match && match[1].trim() !== "") {
|
|
112
|
+
description = match[1].trim();
|
|
113
|
+
lines.shift();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const body = lines.join("\n").trim();
|
|
117
|
+
return { name, description, body, source, sticky: description === undefined };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Parse one RULES.md into rules. A heading-less file (plain prose) is ONE sticky
|
|
121
|
+
* rule named `RULES`; in a sectioned file the pre-heading preamble is document
|
|
122
|
+
* title, not a rule, so it is dropped. */
|
|
123
|
+
export function parseRulesFile(text: string, source: string): LoadedRule[] {
|
|
124
|
+
const out: LoadedRule[] = [];
|
|
125
|
+
const sections = splitSections(text);
|
|
126
|
+
const sectioned = sections.some((section) => section.name !== null);
|
|
127
|
+
for (const section of sections) {
|
|
128
|
+
if (section.name === null && sectioned) continue;
|
|
129
|
+
const rule = makeRule(section.name ?? "RULES", section.lines, source);
|
|
130
|
+
if (rule && (rule.body !== "" || rule.description !== undefined)) out.push(rule);
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// ---------------------------------------------------------------------------
|
|
136
|
+
// Discovery
|
|
137
|
+
// ---------------------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
/** The user-level agent dir (pi relocates it with PI_CODING_AGENT_DIR). */
|
|
140
|
+
export function defaultUserRulesDir(): string {
|
|
141
|
+
return process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** `<dir>/.pi/RULES.md` from cwd up to the filesystem root, then the user file. */
|
|
145
|
+
export function discoverRuleFiles(cwd: string, userDir = defaultUserRulesDir()): string[] {
|
|
146
|
+
const files: string[] = [];
|
|
147
|
+
let dir = path.resolve(cwd);
|
|
148
|
+
for (;;) {
|
|
149
|
+
const candidate = path.join(dir, PROJECT_DIR, RULES_FILE);
|
|
150
|
+
if (existsSync(candidate)) files.push(candidate);
|
|
151
|
+
const parent = path.dirname(dir);
|
|
152
|
+
if (parent === dir) break;
|
|
153
|
+
dir = parent;
|
|
154
|
+
}
|
|
155
|
+
const user = path.join(userDir, RULES_FILE);
|
|
156
|
+
if (existsSync(user)) files.push(user);
|
|
157
|
+
return files;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ---------------------------------------------------------------------------
|
|
161
|
+
// @import expansion
|
|
162
|
+
// ---------------------------------------------------------------------------
|
|
163
|
+
|
|
164
|
+
function resolveImport(token: string, baseDir: string): string {
|
|
165
|
+
const raw = token.startsWith("~/") ? path.join(os.homedir(), token.slice(2)) : token;
|
|
166
|
+
return path.resolve(baseDir, raw);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
interface ImportState {
|
|
170
|
+
/** Resolved paths already pulled into this expansion tree (cycle guard). */
|
|
171
|
+
seen: Set<string>;
|
|
172
|
+
/** Every file actually read — feeds the cache signature. */
|
|
173
|
+
read: Set<string>;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function expandImports(text: string, baseDir: string, state: ImportState, depth: number): string {
|
|
177
|
+
let fenced = false;
|
|
178
|
+
return text
|
|
179
|
+
.split("\n")
|
|
180
|
+
.map((line) => {
|
|
181
|
+
if (FENCE.test(line)) {
|
|
182
|
+
fenced = !fenced;
|
|
183
|
+
return line;
|
|
184
|
+
}
|
|
185
|
+
if (fenced) return line;
|
|
186
|
+
return line.replace(IMPORT, (whole: string, lead: string, token: string) => {
|
|
187
|
+
const cleaned = token.replace(TRAILING_PUNCTUATION, "");
|
|
188
|
+
if (cleaned === "") return whole;
|
|
189
|
+
|
|
190
|
+
const resolved = resolveImport(cleaned, baseDir);
|
|
191
|
+
// ponytail: repeats/cycles stay literal (OMP parity) — only a MISSING
|
|
192
|
+
// target gets a marker, so a real typo is loud and a repeat is silent.
|
|
193
|
+
if (state.seen.has(resolved)) return whole;
|
|
194
|
+
|
|
195
|
+
let content: string;
|
|
196
|
+
try {
|
|
197
|
+
content = readFileSync(resolved, "utf8");
|
|
198
|
+
} catch {
|
|
199
|
+
return `${lead}[missing import: @${cleaned}]`;
|
|
200
|
+
}
|
|
201
|
+
if (depth >= MAX_IMPORT_DEPTH) {
|
|
202
|
+
return `${lead}[import depth limit reached: @${cleaned}]`;
|
|
203
|
+
}
|
|
204
|
+
state.seen.add(resolved);
|
|
205
|
+
state.read.add(resolved);
|
|
206
|
+
const nested = expandImports(content.trim(), path.dirname(resolved), state, depth + 1);
|
|
207
|
+
return `${lead}${nested}`;
|
|
208
|
+
});
|
|
209
|
+
})
|
|
210
|
+
.join("\n");
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function expandFile(raw: string, source: string, state: ImportState): string {
|
|
214
|
+
state.seen.add(source);
|
|
215
|
+
state.read.add(source);
|
|
216
|
+
return expandImports(raw.trim(), path.dirname(source), state, 0);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---------------------------------------------------------------------------
|
|
220
|
+
// Model build
|
|
221
|
+
// ---------------------------------------------------------------------------
|
|
222
|
+
|
|
223
|
+
/** Parse one RULES.md from disk with imports expanded (used by the loader). */
|
|
224
|
+
export function readRulesFile(source: string, state: ImportState = { seen: new Set(), read: new Set() }): LoadedRule[] {
|
|
225
|
+
let raw: string;
|
|
226
|
+
try {
|
|
227
|
+
raw = readFileSync(source, "utf8");
|
|
228
|
+
} catch {
|
|
229
|
+
return [];
|
|
230
|
+
}
|
|
231
|
+
return parseRulesFile(expandFile(raw, source, state), source);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function buildModel(files: string[], cwd: string): { model: RuleModel; imported: string[] } {
|
|
235
|
+
const state: ImportState = { seen: new Set(), read: new Set() };
|
|
236
|
+
const rules: LoadedRule[] = [];
|
|
237
|
+
const claimed = new Set<string>();
|
|
238
|
+
|
|
239
|
+
for (const file of files) {
|
|
240
|
+
for (const rule of readRulesFile(file, state)) {
|
|
241
|
+
// Name-based dedup, first-wins (precedence order = discovery order).
|
|
242
|
+
if (claimed.has(rule.name)) continue;
|
|
243
|
+
claimed.add(rule.name);
|
|
244
|
+
rules.push(rule);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const model: RuleModel = {
|
|
249
|
+
files,
|
|
250
|
+
rules,
|
|
251
|
+
sticky: rules.filter((rule) => rule.sticky),
|
|
252
|
+
rulebook: rules.filter((rule) => !rule.sticky),
|
|
253
|
+
blockChars: 0,
|
|
254
|
+
};
|
|
255
|
+
model.block = composeRulesBlock(model, cwd);
|
|
256
|
+
model.blockChars = model.block?.length ?? 0;
|
|
257
|
+
return { model, imported: [...state.read] };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// ---------------------------------------------------------------------------
|
|
261
|
+
// mtime cache (ponytail's config precedent: one stat per call, re-parse only on
|
|
262
|
+
// change — so edits apply without /reload)
|
|
263
|
+
// ---------------------------------------------------------------------------
|
|
264
|
+
|
|
265
|
+
let cache: { key: string; tracked: Set<string>; sig: string; model: RuleModel } | null = null;
|
|
266
|
+
|
|
267
|
+
function signature(files: Iterable<string>): string {
|
|
268
|
+
const parts: string[] = [];
|
|
269
|
+
for (const file of files) {
|
|
270
|
+
try {
|
|
271
|
+
const stat = statSync(file);
|
|
272
|
+
parts.push(`${file}:${stat.mtimeMs}:${stat.size}`);
|
|
273
|
+
} catch {
|
|
274
|
+
parts.push(`${file}:missing`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return parts.join("|");
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Drop the mtime cache (`/rules reload`, tests). */
|
|
281
|
+
export function clearRuleCache(): void {
|
|
282
|
+
cache = null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export function loadRules(cwd = process.cwd(), userDir = defaultUserRulesDir()): RuleModel {
|
|
286
|
+
const key = `${path.resolve(cwd)}\u0000${userDir}`;
|
|
287
|
+
const files = discoverRuleFiles(cwd, userDir);
|
|
288
|
+
// Track RULES.md files AND previously imported files, so editing an imported
|
|
289
|
+
// doc invalidates the cache too.
|
|
290
|
+
const tracked = new Set([...files, ...(cache?.tracked ?? [])]);
|
|
291
|
+
const sig = signature(tracked);
|
|
292
|
+
if (cache && cache.key === key && cache.sig === sig) return cache.model;
|
|
293
|
+
|
|
294
|
+
const { model, imported } = buildModel(files, cwd);
|
|
295
|
+
const nextTracked = new Set([...tracked, ...imported]);
|
|
296
|
+
cache = { key, tracked: nextTracked, sig: signature(nextTracked), model };
|
|
297
|
+
return model;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// ---------------------------------------------------------------------------
|
|
301
|
+
// Prompt composition
|
|
302
|
+
// ---------------------------------------------------------------------------
|
|
303
|
+
|
|
304
|
+
export function displayPath(file: string, cwd: string): string {
|
|
305
|
+
const rel = path.relative(cwd, file);
|
|
306
|
+
return rel === "" || rel.startsWith("..") || path.isAbsolute(rel) ? file : rel;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function renderSticky(rules: LoadedRule[], cwd: string, cap = STICKY_CHAR_CAP): string {
|
|
310
|
+
const parts: string[] = [];
|
|
311
|
+
let used = 0;
|
|
312
|
+
let dropped = 0;
|
|
313
|
+
|
|
314
|
+
for (const rule of rules) {
|
|
315
|
+
const part = `### ${rule.name} (${displayPath(rule.source, cwd)})\n${rule.body}\n`;
|
|
316
|
+
if (used + part.length > cap) {
|
|
317
|
+
if (used === 0) {
|
|
318
|
+
// First rule alone blows the cap — truncate it rather than dump it all.
|
|
319
|
+
parts.push(part.slice(0, Math.max(0, cap - 80)) + "\n[rule body truncated at the sticky cap]\n");
|
|
320
|
+
used = cap;
|
|
321
|
+
}
|
|
322
|
+
dropped++;
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
parts.push(part);
|
|
326
|
+
used += part.length;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const marker = dropped > 0
|
|
330
|
+
? `⚠ STICKY RULES TRUNCATED — ${dropped} rule(s) omitted: the always-appended block exceeded ${cap} chars. Trim RULES.md, or move detail into rulebook rules (add a \`description:\` line so the body is served on demand by rule_get).`
|
|
331
|
+
: "";
|
|
332
|
+
return [parts.join("\n"), marker].filter((text) => text !== "").join("\n").trim();
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** The `<user-rules>` block, or undefined when no RULES.md exists anywhere. */
|
|
336
|
+
export function composeRulesBlock(model: RuleModel, cwd: string): string | undefined {
|
|
337
|
+
if (model.rules.length === 0) return undefined;
|
|
338
|
+
|
|
339
|
+
const sections: string[] = [];
|
|
340
|
+
if (model.sticky.length > 0) {
|
|
341
|
+
sections.push(`Sticky rules — ALWAYS in effect for this session:\n\n${renderSticky(model.sticky, cwd)}`);
|
|
342
|
+
}
|
|
343
|
+
if (model.rulebook.length > 0) {
|
|
344
|
+
const lines = model.rulebook.map((rule) => `- ${rule.name}: ${rule.description}`).join("\n");
|
|
345
|
+
sections.push(`Rulebook — read the full body with rule_get("<name>") before applying one:\n${lines}`);
|
|
346
|
+
}
|
|
347
|
+
return `<user-rules>\n${sections.join("\n\n")}\n</user-rules>`;
|
|
348
|
+
}
|