@cratis/pi 7.1.5 → 7.2.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/README.md +44 -3
- package/package/corpus/agents/coordinator.md +1 -1
- package/package/corpus/agents/orchestrator.md +1 -1
- package/package/corpus/agents/planner.md +1 -1
- package/package/corpus/harnesses/pi/extensions/cratis-path-guidance/LoadedSkill.ts +9 -0
- package/package/corpus/harnesses/pi/extensions/cratis-path-guidance/SkillMatch.ts +10 -0
- package/package/corpus/harnesses/pi/extensions/cratis-path-guidance/SkillTrigger.ts +13 -0
- package/package/corpus/harnesses/pi/extensions/cratis-path-guidance/ToolName.ts +11 -0
- package/package/corpus/harnesses/pi/extensions/cratis-path-guidance/index.ts +166 -0
- package/package/corpus/harnesses/pi/extensions/cratis-path-guidance/skillReads.ts +62 -0
- package/package/corpus/harnesses/pi/extensions/cratis-path-guidance/skills.ts +72 -0
- package/package/corpus/harnesses/pi/extensions/cratis-path-guidance/standDown.ts +48 -0
- package/package/corpus/harnesses/pi/extensions/cratis-path-guidance/touchedPaths.ts +52 -0
- package/package/corpus/harnesses/pi/extensions/cratis-rules/index.ts +6 -237
- package/package/corpus/harnesses/pi/extensions/shared/AiConfiguration.ts +8 -0
- package/package/corpus/harnesses/pi/extensions/shared/ManagedRule.ts +13 -0
- package/package/corpus/harnesses/pi/extensions/shared/corpusRoot.ts +12 -0
- package/package/corpus/harnesses/pi/extensions/shared/frontmatter.ts +31 -0
- package/package/corpus/harnesses/pi/extensions/shared/globs.ts +62 -0
- package/package/corpus/harnesses/pi/extensions/shared/rules.ts +98 -0
- package/package/corpus/harnesses/pi/extensions/shared/skillFrontmatter.ts +9 -0
- package/package/corpus/harnesses/pi/extensions/shared/skillSelection.ts +67 -0
- package/package/corpus/prompts/ship-changes.prompt.md +19 -4
- package/package/corpus/rules/pull-requests.md +72 -10
- package/package/corpus/skills/cratis-application-react-specifications/SKILL.md +3 -0
- package/package/corpus/skills/cratis-application-slice-specifications/SKILL.md +3 -0
- package/package/corpus/skills/cratis-documentation-writing/SKILL.md +5 -3
- package/package/corpus/skills/cratis-engineering-docs-authoring/SKILL.md +2 -0
- package/package/corpus/skills/cratis-release-notes/SKILL.md +44 -13
- package/package/corpus/skills/cratis-release-notes/verification.json +4 -1
- package/package/corpus/skills/cratis-specifications-csharp/SKILL.md +2 -0
- package/package/corpus/skills/cratis-specifications-typescript/SKILL.md +3 -0
- package/package/corpus/skills/cratis-technical-examples/SKILL.md +2 -0
- package/package.json +2 -1
- package/src/index.ts +11 -0
package/README.md
CHANGED
|
@@ -9,8 +9,8 @@ pi install -l npm:@cratis/pi
|
|
|
9
9
|
|
|
10
10
|
The package reads the repository's `.cratis/ai.json`, resolves its profiles and
|
|
11
11
|
languages through the packaged profile catalog, and contributes only the matching
|
|
12
|
-
skills. It also loads packaged rules, prompts, agents, the
|
|
13
|
-
Cratis quality hooks. When no `.cratis/ai.json` exists, it exposes the complete
|
|
12
|
+
skills. It also loads packaged rules, path guidance, prompts, agents, the
|
|
13
|
+
subagent tool, and Cratis quality hooks. When no `.cratis/ai.json` exists, it exposes the complete
|
|
14
14
|
packaged skill set. It therefore gives Pi the complete single-harness Cratis
|
|
15
15
|
experience without requiring the Cratis CLI.
|
|
16
16
|
|
|
@@ -24,7 +24,48 @@ The managed CLI path remains the choice when one repository must configure and
|
|
|
24
24
|
synchronize several harnesses. It writes the resolved corpus to `.cratis/ai`,
|
|
25
25
|
creates every harness integration, and records hashes for safe update and
|
|
26
26
|
uninstall. That managed setup loads rules through its own `.pi/extensions/cratis-rules`
|
|
27
|
-
|
|
27
|
+
and `.pi/extensions/cratis-path-guidance` extensions and does not require this package. If both paths are present, the package
|
|
28
28
|
yields to the managed installation to avoid duplicate resources and hooks. The Pi
|
|
29
29
|
package manages only Pi; it neither configures other harnesses nor owns a local
|
|
30
30
|
managed corpus.
|
|
31
|
+
|
|
32
|
+
## Path guidance and subagents
|
|
33
|
+
|
|
34
|
+
The packaged `cratis-path-guidance` extension attaches a path-scoped rule to the
|
|
35
|
+
tool result the first time a matching file is touched, and after a successful
|
|
36
|
+
`write` or `edit` adds one advisory line naming every skill whose `SKILL.md`
|
|
37
|
+
`cratis-hint-paths` frontmatter matches the file. (The key is Cratis-specific
|
|
38
|
+
because Claude Code gives a plain `paths` key its own meaning.) A skill is hinted at
|
|
39
|
+
most once per session and not when it is already in context: read (a shell command
|
|
40
|
+
counts only when `cat`, `sed`, `head`, `tail`, `less`, `bat`, `rg` or `grep` opens
|
|
41
|
+
its `SKILL.md` or a file under `references/`), preloaded by pi-subagents, or
|
|
42
|
+
expanded by `/skill:name`. A pi-subagents header without the skill's text (its
|
|
43
|
+
loader cannot read a symlinked `.pi/skills`) does not count as preloaded. The
|
|
44
|
+
skills considered are the ones Pi loaded plus the skills the repository selected
|
|
45
|
+
(`.cratis/ai.json`), so a session whose Pi skill list holds only personal skills,
|
|
46
|
+
or none (for example `skills: false`), still gets hints; an unselected skill is
|
|
47
|
+
never hinted, and none is added if the selection cannot be resolved. Rules follow
|
|
48
|
+
the same language and documentation selection as the system prompt. Nothing is
|
|
49
|
+
blocked and the system prompt is untouched. The system prompt carries only the
|
|
50
|
+
universal rules, so path-scoped rules are not delivered twice. The extension works
|
|
51
|
+
in sessions without a UI. It stands down when a managed installation
|
|
52
|
+
(`.cratis/ai.manifest.json`) already delivers path guidance: through its own
|
|
53
|
+
`.pi/extensions/cratis-path-guidance`, or through any `.pi/extensions/cratis-rules`
|
|
54
|
+
that is not the current universal-only version, since every earlier version
|
|
55
|
+
delivers path-scoped rules itself. A `cratis-rules` that cannot be recognised
|
|
56
|
+
counts as one that delivers them. In such an older managed installation, a subagent
|
|
57
|
+
that loads only the allowlisted extensions below gets no path guidance until
|
|
58
|
+
`cratis ai update` installs the managed `cratis-path-guidance`.
|
|
59
|
+
|
|
60
|
+
The universal rules add about 26k tokens to every session. A pi-subagents agent
|
|
61
|
+
(`@tintinweb/pi-subagents`) with an `extensions:` allowlist loads only the
|
|
62
|
+
extensions it names, so it gets none of this package by default. Name the two
|
|
63
|
+
cheap extensions to give it path guidance and the write and store guards without
|
|
64
|
+
the universal rules:
|
|
65
|
+
|
|
66
|
+
```yaml
|
|
67
|
+
extensions: cratis-path-guidance, cratis-hooks
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The `subagent` tool of this package starts a full `pi` process and loads every
|
|
71
|
+
extension.
|
|
@@ -128,7 +128,7 @@ For implementation, the applicable changed-lane gates must pass. Mark unrelated
|
|
|
128
128
|
- [ ] `Documentation/verify-markdown.sh` passes when documentation is added or changed
|
|
129
129
|
- [ ] `code-reviewer` finds no blocking issues
|
|
130
130
|
- [ ] `security-reviewer` finds no vulnerabilities
|
|
131
|
-
- [ ] PR description follows the pull request template
|
|
131
|
+
- [ ] PR description follows the pull request template and the release-note contract in `pull-requests.md`; test and review notes are in a PR comment
|
|
132
132
|
|
|
133
133
|
---
|
|
134
134
|
|
|
@@ -152,7 +152,7 @@ For implementation, the applicable changed-lane gates must pass. Mark unrelated
|
|
|
152
152
|
- [ ] `code-reviewer` finds no blocking issues
|
|
153
153
|
- [ ] `security-reviewer` finds no vulnerabilities
|
|
154
154
|
- [ ] All documentation is complete and accurate (if required)
|
|
155
|
-
- [ ] PR description follows the pull request template
|
|
155
|
+
- [ ] PR description follows the pull request template and the release-note contract in `pull-requests.md`; test and review notes are in a PR comment
|
|
156
156
|
|
|
157
157
|
---
|
|
158
158
|
|
|
@@ -115,7 +115,7 @@ For an implemented application slice, require the applicable changed-lane gates
|
|
|
115
115
|
- [ ] `Documentation/verify-markdown.sh` passes when documentation is added or changed
|
|
116
116
|
- [ ] Code review by `code-reviewer` finds no blocking issues
|
|
117
117
|
- [ ] Security review by `security-reviewer` finds no vulnerabilities
|
|
118
|
-
- [ ] PR description follows the pull request template
|
|
118
|
+
- [ ] PR description follows the pull request template and the release-note contract in `pull-requests.md`; test and review notes are in a PR comment
|
|
119
119
|
|
|
120
120
|
---
|
|
121
121
|
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
/** The part of a Pi skill (`event.systemPromptOptions.skills`) this extension reads. */
|
|
5
|
+
export interface LoadedSkill {
|
|
6
|
+
name: string;
|
|
7
|
+
filePath: string;
|
|
8
|
+
baseDir?: string;
|
|
9
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import type { SkillTrigger } from './SkillTrigger.ts';
|
|
5
|
+
|
|
6
|
+
/** A skill whose trigger matched a path, with the glob that matched. */
|
|
7
|
+
export interface SkillMatch {
|
|
8
|
+
skill: SkillTrigger;
|
|
9
|
+
glob: string;
|
|
10
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
/** A skill available to the session together with the path globs its `SKILL.md` declares as triggers. */
|
|
5
|
+
export interface SkillTrigger {
|
|
6
|
+
name: string;
|
|
7
|
+
/** Absolute path of the skill's `SKILL.md`. */
|
|
8
|
+
filePath: string;
|
|
9
|
+
/** Directory holding `SKILL.md` and the skill's references. */
|
|
10
|
+
baseDir: string;
|
|
11
|
+
/** The `cratis-hint-paths` frontmatter of the skill. Empty when the skill declares no trigger. */
|
|
12
|
+
globs: string[];
|
|
13
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
/** The Pi tools whose results carry a file path this extension reacts to. */
|
|
5
|
+
export enum ToolName {
|
|
6
|
+
Read = 'read',
|
|
7
|
+
Write = 'write',
|
|
8
|
+
Edit = 'edit',
|
|
9
|
+
Bash = 'bash',
|
|
10
|
+
PowerShell = 'powershell',
|
|
11
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
7
|
+
import type { ManagedRule } from '../shared/ManagedRule.ts';
|
|
8
|
+
import { rulesForPath } from '../shared/rules.ts';
|
|
9
|
+
import type { LoadedSkill } from './LoadedSkill.ts';
|
|
10
|
+
import type { SkillMatch } from './SkillMatch.ts';
|
|
11
|
+
import type { SkillTrigger } from './SkillTrigger.ts';
|
|
12
|
+
import { skillsRead } from './skillReads.ts';
|
|
13
|
+
import { skillsForPath, skillTriggers } from './skills.ts';
|
|
14
|
+
import { standsDown } from './standDown.ts';
|
|
15
|
+
import { ToolName } from './ToolName.ts';
|
|
16
|
+
import { touchedPaths } from './touchedPaths.ts';
|
|
17
|
+
|
|
18
|
+
const extensionDirectory = dirname(fileURLToPath(import.meta.url));
|
|
19
|
+
const isPackagedExtension = extensionDirectory.includes(`${sep}package${sep}corpus${sep}`);
|
|
20
|
+
|
|
21
|
+
function repositoryRelative(cwd: string, path: string): string | undefined {
|
|
22
|
+
const relativePath = relative(cwd, resolve(cwd, path));
|
|
23
|
+
return !relativePath || relativePath.startsWith('..') || isAbsolute(relativePath) ? undefined : relativePath.split(sep).join('/');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function displayPath(cwd: string, path: string): string {
|
|
27
|
+
return repositoryRelative(cwd, path) ?? path;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** One line for everything a write matched, however many skills, so overlapping triggers cost one line and not several. */
|
|
31
|
+
function hintLine(cwd: string, files: string[], matches: SkillMatch[]): string {
|
|
32
|
+
const skills = matches.map(match => `\`${match.skill.name}\` (matched \`${match.glob}\`)`);
|
|
33
|
+
const named = skills.length === 1 ? `Skill ${skills[0]} covers` : `Skills ${skills.slice(0, -1).join(', ')} and ${skills[skills.length - 1]} cover`;
|
|
34
|
+
const documents = matches.map(match => displayPath(cwd, match.skill.filePath));
|
|
35
|
+
const read = documents.length === 1 ? documents[0] : `${documents.slice(0, -1).join(', ')} and ${documents[documents.length - 1]}`;
|
|
36
|
+
return `[cratis-path-guidance] ${named} ${files.join(', ')}; read ${read} before continuing.`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* pi-subagents writes `# Preloaded Skill: <name>` for every name in `skills:` and then the skill's text, or a
|
|
41
|
+
* placeholder when it could not load it: `(Skill "<name>" not found in ...)` or `(Skill "<name>" skipped: ...)`.
|
|
42
|
+
* It cannot load a skill from a symlinked skills root, which is how a managed installation exposes
|
|
43
|
+
* `.pi/skills` and `.agents/skills`. Only a header followed by real content puts the skill in context.
|
|
44
|
+
*/
|
|
45
|
+
const placeholderBody = /^\(Skill "[^"]*" (?:not found|skipped)\b/;
|
|
46
|
+
|
|
47
|
+
/** The skills pi-subagents preloaded into the system prompt (`skills: a, b`) whose full text is already in context. */
|
|
48
|
+
function preloadedSkillNames(systemPrompt: unknown): Set<string> {
|
|
49
|
+
const names = new Set<string>();
|
|
50
|
+
if (typeof systemPrompt !== 'string') return names;
|
|
51
|
+
for (const match of systemPrompt.matchAll(/^# Preloaded Skill: (\S+)[ \t]*\r?\n/gm)) {
|
|
52
|
+
const body = systemPrompt.slice(match.index + match[0].length).split(/^# Preloaded Skill: /m)[0].trim();
|
|
53
|
+
if (body.length > 0 && !placeholderBody.test(body)) names.add(match[1]);
|
|
54
|
+
}
|
|
55
|
+
return names;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The skills a `/skill:name` command expanded into the user message, which arrive without a `read` call. */
|
|
59
|
+
function expandedSkillNames(prompt: unknown): string[] {
|
|
60
|
+
return typeof prompt === 'string' ? [...prompt.matchAll(/<skill name="([^"]+)"/g)].map(match => match[1]) : [];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Delivers the corpus guidance that belongs to a file at the moment the file is touched, so it works in every
|
|
65
|
+
* Pi process, including a subagent, without the universal rules `cratis-rules` puts in every system prompt.
|
|
66
|
+
*
|
|
67
|
+
* Path-scoped rules are attached to the tool result the first time a matching file is touched in the session,
|
|
68
|
+
* exactly as they were when `cratis-rules` delivered them. On a successful `write` or `edit`, one advisory line
|
|
69
|
+
* names every skill whose `cratis-hint-paths` frontmatter matches the file and where its `SKILL.md` is. A skill
|
|
70
|
+
* is not hinted when it is already in context: read in the session, preloaded by pi-subagents
|
|
71
|
+
* (`# Preloaded Skill: <name>` followed by its text in the system prompt), or expanded by `/skill:<name>`. Hints are advisory only:
|
|
72
|
+
* nothing is blocked and the system prompt is never touched.
|
|
73
|
+
*
|
|
74
|
+
* Delivery happens on `tool_result`, so guidance arrives after the call that first touched the file.
|
|
75
|
+
* `ToolCallEventResult` carries only `block`/`reason`/`terminate`, so there is no supported way to add
|
|
76
|
+
* context before a tool runs. In practice a file is read before it is edited, and reads through both the read
|
|
77
|
+
* tool and bash are covered; a file created blind by `write` is the residual case, and it receives the
|
|
78
|
+
* guidance with that result.
|
|
79
|
+
*
|
|
80
|
+
* Delivered guidance lives in the conversation rather than the system prompt, so anything that rewrites or
|
|
81
|
+
* replaces the conversation can remove it. The delivery record is therefore reset whenever that happens, and the
|
|
82
|
+
* guidance is delivered again the next time one of its files is touched.
|
|
83
|
+
*/
|
|
84
|
+
export default function (pi: ExtensionAPI): void {
|
|
85
|
+
if (standsDown(isPackagedExtension, process.cwd())) return;
|
|
86
|
+
|
|
87
|
+
const deliveredRules = new Set<string>();
|
|
88
|
+
const hintedSkills = new Set<string>();
|
|
89
|
+
const readSkills = new Set<string>();
|
|
90
|
+
// Preloaded skills live in the system prompt, which compaction leaves alone, so this is replaced at each
|
|
91
|
+
// agent start rather than reset with the conversation.
|
|
92
|
+
let preloadedSkills = new Set<string>();
|
|
93
|
+
let loadedSkills: LoadedSkill[] | undefined;
|
|
94
|
+
let loadedKey: string | undefined;
|
|
95
|
+
let triggers: SkillTrigger[] | undefined;
|
|
96
|
+
|
|
97
|
+
const availableTriggers = (cwd: string): SkillTrigger[] => triggers ??= skillTriggers(loadedSkills, cwd);
|
|
98
|
+
|
|
99
|
+
// Compaction summarizes the conversation, which can drop an injected rule or hint while leaving the
|
|
100
|
+
// delivery record claiming it is present; a switch replaces the conversation outright.
|
|
101
|
+
const reset = () => {
|
|
102
|
+
deliveredRules.clear();
|
|
103
|
+
hintedSkills.clear();
|
|
104
|
+
readSkills.clear();
|
|
105
|
+
triggers = undefined;
|
|
106
|
+
};
|
|
107
|
+
pi.on('session_start', reset);
|
|
108
|
+
pi.on('session_compact', reset);
|
|
109
|
+
pi.on('session_before_switch', reset);
|
|
110
|
+
|
|
111
|
+
// Only observes which skills are in context for this session; the system prompt is never changed.
|
|
112
|
+
pi.on('before_agent_start', event => {
|
|
113
|
+
const observed = event as { systemPrompt?: unknown; prompt?: unknown; systemPromptOptions?: { skills?: LoadedSkill[] } };
|
|
114
|
+
preloadedSkills = preloadedSkillNames(observed.systemPrompt);
|
|
115
|
+
expandedSkillNames(observed.prompt).forEach(name => readSkills.add(name));
|
|
116
|
+
const skills = observed.systemPromptOptions?.skills;
|
|
117
|
+
const key = skills?.map(skill => `${skill.name}\t${skill.filePath}`).join('\n');
|
|
118
|
+
if (key !== loadedKey) triggers = undefined;
|
|
119
|
+
loadedSkills = skills;
|
|
120
|
+
loadedKey = key;
|
|
121
|
+
return undefined;
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
pi.on('tool_result', (event, context) => {
|
|
125
|
+
if (event.isError) return;
|
|
126
|
+
const cwd = context.cwd;
|
|
127
|
+
const toolName: string = event.toolName;
|
|
128
|
+
const input = event.input;
|
|
129
|
+
|
|
130
|
+
const reads = skillsRead(toolName, input, availableTriggers(cwd));
|
|
131
|
+
reads.forEach(skill => readSkills.add(skill.name));
|
|
132
|
+
|
|
133
|
+
const pendingRules: ManagedRule[] = [];
|
|
134
|
+
const matchedFiles: string[] = [];
|
|
135
|
+
const hintedFiles: string[] = [];
|
|
136
|
+
const pendingMatches: SkillMatch[] = [];
|
|
137
|
+
for (const path of touchedPaths(toolName, input, cwd)) {
|
|
138
|
+
const relativePath = repositoryRelative(cwd, path);
|
|
139
|
+
if (!relativePath) continue;
|
|
140
|
+
for (const rule of rulesForPath(cwd, relativePath)) {
|
|
141
|
+
if (deliveredRules.has(rule.name) || pendingRules.some(candidate => candidate.name === rule.name)) continue;
|
|
142
|
+
pendingRules.push(rule);
|
|
143
|
+
if (!matchedFiles.includes(relativePath)) matchedFiles.push(relativePath);
|
|
144
|
+
}
|
|
145
|
+
if (toolName !== ToolName.Write && toolName !== ToolName.Edit) continue;
|
|
146
|
+
for (const match of skillsForPath(availableTriggers(cwd), relativePath)) {
|
|
147
|
+
const name = match.skill.name;
|
|
148
|
+
if (hintedSkills.has(name) || readSkills.has(name) || preloadedSkills.has(name)) continue;
|
|
149
|
+
hintedSkills.add(name);
|
|
150
|
+
pendingMatches.push(match);
|
|
151
|
+
if (!hintedFiles.includes(relativePath)) hintedFiles.push(relativePath);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (pendingRules.length === 0 && pendingMatches.length === 0) return;
|
|
155
|
+
pendingRules.forEach(rule => deliveredRules.add(rule.name));
|
|
156
|
+
|
|
157
|
+
const existing = Array.isArray(event.content) ? event.content : [];
|
|
158
|
+
const text = [
|
|
159
|
+
pendingRules.length === 0
|
|
160
|
+
? undefined
|
|
161
|
+
: `\n\n[cratis-rules] Rules that apply to ${matchedFiles.join(', ')}:\n\n${pendingRules.map(rule => rule.content).join('\n\n')}`,
|
|
162
|
+
pendingMatches.length === 0 ? undefined : `\n\n${hintLine(cwd, hintedFiles, pendingMatches)}`,
|
|
163
|
+
].filter(part => part !== undefined).join('');
|
|
164
|
+
return { content: [...existing, { type: 'text', text }] };
|
|
165
|
+
});
|
|
166
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import type { SkillTrigger } from './SkillTrigger.ts';
|
|
5
|
+
import { ToolName } from './ToolName.ts';
|
|
6
|
+
import { commandOf, isShellTool } from './touchedPaths.ts';
|
|
7
|
+
|
|
8
|
+
/** Shell commands that put a file's content in front of the model. `ls`, `git diff` or `git add` do not. */
|
|
9
|
+
const readers = new Set(['cat', 'sed', 'head', 'tail', 'less', 'bat', 'rg', 'grep']);
|
|
10
|
+
|
|
11
|
+
/** `rtk` verbs that read: `rtk read`, `rtk cat`, and `rtk grep`/`rtk rg` on a file. */
|
|
12
|
+
const rtkReaders = new Set(['read', ...readers]);
|
|
13
|
+
|
|
14
|
+
function escapeRegExp(text: string): string {
|
|
15
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Whether a path names a file inside the skill's directory. */
|
|
19
|
+
function isInsideSkill(path: string, skill: SkillTrigger): boolean {
|
|
20
|
+
if (path.includes(`${skill.baseDir}/`)) return true;
|
|
21
|
+
return new RegExp(`(?:^|[/\\s'"=])skills/${escapeRegExp(skill.name)}/`).test(path.replaceAll('\\', '/'));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Whether text names the skill's `SKILL.md`, or a file under its `references/`. */
|
|
25
|
+
function namesSkillDocument(text: string, skill: SkillTrigger): boolean {
|
|
26
|
+
const normalized = text.replaceAll('\\', '/');
|
|
27
|
+
if (normalized.includes(`${skill.baseDir}/SKILL.md`) || normalized.includes(`${skill.baseDir}/references/`)) return true;
|
|
28
|
+
return new RegExp(`(?:^|[/\\s'"=])skills/${escapeRegExp(skill.name)}/(?:SKILL\\.md|references/)`).test(normalized);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The commands of a shell line that read a file. The line is split at `&&`, `||`, `|`, `;` and newlines, and a
|
|
33
|
+
* command counts when its verb (after an optional `rtk` or `rtk proxy`) is a reader. An `echo`, a commit message
|
|
34
|
+
* or `git diff` that merely mentions a path is not a read.
|
|
35
|
+
*/
|
|
36
|
+
function readerCommands(command: string): string[] {
|
|
37
|
+
return command.split(/\s*(?:&&|\|\||\||;(?=\s|$)|\n)\s*/).filter(segment => {
|
|
38
|
+
const words = segment.trim().split(/\s+/);
|
|
39
|
+
if (words[0] !== 'rtk') return readers.has(words[0]);
|
|
40
|
+
const verb = words[1] === 'proxy' ? words[2] : words[1];
|
|
41
|
+
return words[1] === 'proxy' ? readers.has(verb) : rtkReaders.has(verb);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The skills a successful tool call read: the `read` tool on any file under `skills/<name>/`, or a shell reader
|
|
47
|
+
* (`cat`, `sed`, `head`, `tail`, `less`, `bat`, `rg`, `grep`, `rtk read`) on that skill's `SKILL.md` or a file
|
|
48
|
+
* under its `references/`. A model that opened either already has the skill's guidance. Listing the directory,
|
|
49
|
+
* or a `git` command that names the path, gives it nothing and is not a read.
|
|
50
|
+
*/
|
|
51
|
+
export function skillsRead(toolName: string, input: unknown, skills: SkillTrigger[]): SkillTrigger[] {
|
|
52
|
+
if (toolName === ToolName.Read) {
|
|
53
|
+
const candidate = input as { path?: unknown; file_path?: unknown } | undefined;
|
|
54
|
+
const value = candidate?.path ?? candidate?.file_path;
|
|
55
|
+
return typeof value === 'string' ? skills.filter(skill => isInsideSkill(value, skill)) : [];
|
|
56
|
+
}
|
|
57
|
+
if (!isShellTool(toolName)) return [];
|
|
58
|
+
const command = commandOf(input);
|
|
59
|
+
if (command === undefined) return [];
|
|
60
|
+
const commands = readerCommands(command);
|
|
61
|
+
return skills.filter(skill => commands.some(segment => namesSkillDocument(segment, skill)));
|
|
62
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
import { corpusRoot } from '../shared/corpusRoot.ts';
|
|
7
|
+
import { frontmatter } from '../shared/frontmatter.ts';
|
|
8
|
+
import { globToRegExp } from '../shared/globs.ts';
|
|
9
|
+
import { skillTriggerKey } from '../shared/skillFrontmatter.ts';
|
|
10
|
+
import { selectedSkillNames } from '../shared/skillSelection.ts';
|
|
11
|
+
import type { LoadedSkill } from './LoadedSkill.ts';
|
|
12
|
+
import type { SkillMatch } from './SkillMatch.ts';
|
|
13
|
+
import type { SkillTrigger } from './SkillTrigger.ts';
|
|
14
|
+
|
|
15
|
+
function skillAt(root: string, name: string): LoadedSkill[] {
|
|
16
|
+
const filePath = join(root, name, 'SKILL.md');
|
|
17
|
+
return existsSync(filePath) ? [{ name, filePath, baseDir: join(root, name) }] : [];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The skills the repository selected, whether or not Pi loaded them into the session. A managed installation resolves
|
|
22
|
+
* them into `.cratis/ai/skills`. Without one, the packaged corpus holds every catalog skill, so the selection
|
|
23
|
+
* comes from `.cratis/ai.json` and the profile catalog; when that cannot be resolved nothing is hinted.
|
|
24
|
+
*/
|
|
25
|
+
function repositorySkills(cwd: string): LoadedSkill[] {
|
|
26
|
+
const managedRoot = join(cwd, '.cratis', 'ai', 'skills');
|
|
27
|
+
if (existsSync(managedRoot)) {
|
|
28
|
+
return readdirSync(managedRoot, { withFileTypes: true })
|
|
29
|
+
.filter(entry => entry.isDirectory())
|
|
30
|
+
.flatMap(entry => skillAt(managedRoot, entry.name));
|
|
31
|
+
}
|
|
32
|
+
const packagedRoot = join(corpusRoot, 'skills');
|
|
33
|
+
return (selectedSkillNames(cwd) ?? []).flatMap(name => skillAt(packagedRoot, name));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function triggerGlobs(filePath: string): string[] {
|
|
37
|
+
try {
|
|
38
|
+
return frontmatter(readFileSync(filePath, 'utf8')).get(skillTriggerKey) ?? [];
|
|
39
|
+
} catch {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The skills available to a session with their trigger globs: the skills Pi loaded for the session
|
|
46
|
+
* (`systemPromptOptions.skills`) together with the repository's selected skills, deduplicated by name with the
|
|
47
|
+
* loaded one winning. The union matters because Pi's list says nothing about whether the Cratis skills are in it:
|
|
48
|
+
* it can be empty (a pi-subagents agent with `skills: false`, the usual setup for cheap workers), or non-empty
|
|
49
|
+
* with only personal skills (an agent with `skills: true` whose `extensions:` allowlist leaves `@cratis/pi`, and
|
|
50
|
+
* so its skill paths, out). The selected skills' `SKILL.md` can still be read by path, which is what the hint asks
|
|
51
|
+
* for; a corpus skill the repository did not select is never added. Skills without a `cratis-hint-paths` trigger
|
|
52
|
+
* are left out.
|
|
53
|
+
*/
|
|
54
|
+
export function skillTriggers(loaded: LoadedSkill[] | undefined, cwd: string): SkillTrigger[] {
|
|
55
|
+
const loadedNames = new Set((loaded ?? []).map(skill => skill.name));
|
|
56
|
+
return [...(loaded ?? []), ...repositorySkills(cwd).filter(skill => !loadedNames.has(skill.name))]
|
|
57
|
+
.map(skill => ({
|
|
58
|
+
name: skill.name,
|
|
59
|
+
filePath: skill.filePath,
|
|
60
|
+
baseDir: skill.baseDir ?? dirname(skill.filePath),
|
|
61
|
+
globs: triggerGlobs(skill.filePath),
|
|
62
|
+
}))
|
|
63
|
+
.filter(skill => skill.globs.length > 0);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The skills whose trigger matches a repository-relative path, each with the first glob that matched. */
|
|
67
|
+
export function skillsForPath(triggers: SkillTrigger[], relativePath: string): SkillMatch[] {
|
|
68
|
+
return triggers.flatMap(skill => {
|
|
69
|
+
const glob = skill.globs.find(candidate => globToRegExp(candidate).test(relativePath));
|
|
70
|
+
return glob === undefined ? [] : [{ skill, glob }];
|
|
71
|
+
});
|
|
72
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Whether a managed `cratis-rules` delivers path-scoped rules itself, which is every generation but the current one:
|
|
9
|
+
*
|
|
10
|
+
* - `6b0bb54`, `5b048c6`: `before_agent_start` concatenates every rule into the system prompt;
|
|
11
|
+
* - `aca9c6b`, `59362cf`, `1937b06`, `eec744a`: universal rules in the system prompt, path-scoped rules on
|
|
12
|
+
* `tool_result`;
|
|
13
|
+
* - current: universal rules only, taken from `../shared/rules.ts`, with no `tool_result` handler.
|
|
14
|
+
*
|
|
15
|
+
* Only a file that is recognisably the current one, importing the shared rules and having no `tool_result`
|
|
16
|
+
* handler, is trusted not to deliver path rules; anything else, including a file that cannot be read, is assumed
|
|
17
|
+
* to. Standing down on a guess costs allowlisted subagents their path guidance until `cratis ai update`, which
|
|
18
|
+
* is cheaper than duplicating every path-scoped rule in every full session.
|
|
19
|
+
*/
|
|
20
|
+
function managedRulesDeliverPaths(cwd: string): boolean {
|
|
21
|
+
const path = join(cwd, '.pi', 'extensions', 'cratis-rules', 'index.ts');
|
|
22
|
+
if (!existsSync(path)) return false;
|
|
23
|
+
try {
|
|
24
|
+
const content = readFileSync(path, 'utf8');
|
|
25
|
+
return !content.includes("'../shared/rules.ts'") || content.includes('tool_result');
|
|
26
|
+
} catch {
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* A managed installation (`.cratis/ai.manifest.json`) loads its own extensions from `.pi/extensions`. The copy
|
|
33
|
+
* shipped in `@cratis/pi` stands down when that installation already delivers path guidance, so a rule or hint
|
|
34
|
+
* is never delivered twice, whichever versions are mixed:
|
|
35
|
+
*
|
|
36
|
+
* - the managed `cratis-path-guidance` exists: it delivers rules and hints;
|
|
37
|
+
* - an older managed `cratis-rules` exists, which delivers path-scoped rules itself, in the system prompt or on
|
|
38
|
+
* `tool_result`: the packaged copy would repeat every rule, so it yields until `cratis ai update` installs the
|
|
39
|
+
* managed copy;
|
|
40
|
+
* - a current managed `cratis-rules` that only injects universal rules, or no managed Pi extensions at all:
|
|
41
|
+
* nothing else delivers path guidance, so the packaged copy stays active.
|
|
42
|
+
*
|
|
43
|
+
* The managed copy never stands down.
|
|
44
|
+
*/
|
|
45
|
+
export function standsDown(packaged: boolean, cwd: string): boolean {
|
|
46
|
+
if (!packaged || !existsSync(join(cwd, '.cratis', 'ai.manifest.json'))) return false;
|
|
47
|
+
return existsSync(join(cwd, '.pi', 'extensions', 'cratis-path-guidance', 'index.ts')) || managedRulesDeliverPaths(cwd);
|
|
48
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import { statSync } from 'node:fs';
|
|
5
|
+
import { resolve } from 'node:path';
|
|
6
|
+
import { ToolName } from './ToolName.ts';
|
|
7
|
+
|
|
8
|
+
/** Upper bound on files considered from one bash command, so a wide command cannot deliver the corpus. */
|
|
9
|
+
const maxPathsPerCommand = 10;
|
|
10
|
+
|
|
11
|
+
export function isShellTool(toolName: string): boolean {
|
|
12
|
+
return toolName === ToolName.Bash || toolName === ToolName.PowerShell;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function commandOf(input: unknown): string | undefined {
|
|
16
|
+
const command = (input as { command?: unknown } | undefined)?.command;
|
|
17
|
+
return typeof command === 'string' ? command : undefined;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Extracts file paths a bash command refers to. `rtk.md` tells agents to run `rtk read`, `rtk grep`
|
|
22
|
+
* and `rtk find` from the terminal for bulk reads, so file access frequently arrives as a bash
|
|
23
|
+
* command rather than the read tool; without this, a session that follows that rule would never
|
|
24
|
+
* receive a path-scoped rule. A token counts only when it resolves to a file that exists inside the
|
|
25
|
+
* working directory, which keeps a filename mentioned inside a commit message from matching.
|
|
26
|
+
*/
|
|
27
|
+
function pathsFromCommand(command: string, cwd: string): string[] {
|
|
28
|
+
const found: string[] = [];
|
|
29
|
+
for (const raw of command.split(/[\s;|&()<>]+/)) {
|
|
30
|
+
if (found.length >= maxPathsPerCommand) break;
|
|
31
|
+
const token = raw.replace(/^['"]+|['"]+$/g, '').replace(/[,:]+$/, '');
|
|
32
|
+
if (!token || token.startsWith('-') || !/[./]/.test(token)) continue;
|
|
33
|
+
try {
|
|
34
|
+
if (statSync(resolve(cwd, token)).isFile()) found.push(token);
|
|
35
|
+
} catch {
|
|
36
|
+
/* not a path we can see; ignore */
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return found;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The file paths a tool call refers to, as the tool received them. */
|
|
43
|
+
export function touchedPaths(toolName: string, input: unknown, cwd: string): string[] {
|
|
44
|
+
if (isShellTool(toolName)) {
|
|
45
|
+
const command = commandOf(input);
|
|
46
|
+
return command === undefined ? [] : pathsFromCommand(command, cwd);
|
|
47
|
+
}
|
|
48
|
+
if (toolName !== ToolName.Read && toolName !== ToolName.Write && toolName !== ToolName.Edit) return [];
|
|
49
|
+
const candidate = (input as { path?: unknown; file_path?: unknown } | undefined);
|
|
50
|
+
const value = candidate?.path ?? candidate?.file_path;
|
|
51
|
+
return typeof value === 'string' && value.length > 0 ? [value] : [];
|
|
52
|
+
}
|