Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions packages/ai-claude-compat/src/frontmatter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,61 @@ test('asStringArray: passes arrays, splits scalars, undefined when absent', () =
assert.equal(asStringArray(undefined), undefined);
assert.equal(asStringArray(''), undefined);
});

// ---- block scalars (issue #120) ----

test('parseFrontmatter: folded block scalar (>) joins lines with spaces, clip keeps one newline', () => {
const { data } = parseFrontmatter('---\ndescription: >\n line one\n line two\n---\nbody');
assert.equal(data.description, 'line one line two\n');
});

test('parseFrontmatter: folded strip (>-) drops the trailing newline', () => {
const { data } = parseFrontmatter('---\ndescription: >-\n line one\n line two\n---\nbody');
assert.equal(data.description, 'line one line two');
});

test('parseFrontmatter: literal block scalar (|) preserves interior newlines', () => {
const { data } = parseFrontmatter('---\nsteps: |\n first\n second\n---\nbody');
assert.equal(data.steps, 'first\nsecond\n');
});

test('parseFrontmatter: literal strip (|-) keeps interior newlines but strips the trailing one', () => {
const { data } = parseFrontmatter('---\nsteps: |-\n a\n b\n---\nbody');
assert.equal(data.steps, 'a\nb');
});

test('parseFrontmatter: a folded blank line becomes a paragraph break', () => {
const { data } = parseFrontmatter('---\ndesc: >-\n para one\n\n para two\n---\nb');
assert.equal(data.desc, 'para one\npara two');
});

test('parseFrontmatter: a block scalar ends at the next top-level key, which still parses', () => {
const { data } = parseFrontmatter(
'---\nname: s\ndescription: >-\n folded value\n continues\nallowed-tools: [Read]\n---\nbody',
);
assert.equal(data.name, 's');
assert.equal(data.description, 'folded value continues');
assert.deepEqual(data['allowed-tools'], ['Read']);
});

test('parseFrontmatter: `key: >text` on one line stays a plain scalar, not a block header', () => {
const { data } = parseFrontmatter('---\narrow: >text here\n---\nb');
assert.equal(data.arrow, '>text here');
});

test('parseFrontmatter: a folded block scalar strips CRLF carriage returns from every line', () => {
const { data } = parseFrontmatter(
'---\r\ndescription: >-\r\n line one\r\n line two\r\n---\r\nbody\r\n',
);
assert.equal(data.description, 'line one line two', 'no stray \\r in the folded value');
});

test('parseFrontmatter: a literal block scalar strips CRLF carriage returns from every line', () => {
const { data } = parseFrontmatter('---\r\nsteps: |-\r\n a\r\n b\r\n---\r\nbody\r\n');
assert.equal(data.steps, 'a\nb', 'interior newline preserved, no \\r');
});

test('parseFrontmatter: `>+` (keep) is unsupported — it stays a plain scalar, not a block header', () => {
const { data } = parseFrontmatter('---\ndesc: >+\n content\n---\nb');
assert.equal(data.desc, '>+', 'the header does not match; the value is the literal marker');
});
73 changes: 67 additions & 6 deletions packages/ai-claude-compat/src/frontmatter.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// Minimal YAML-frontmatter parser for `.claude/` extension files (SKILL.md, agents/*.md) and the
// memory format (issue #118). Handles only what those files use — scalar strings, flow arrays
// (`[a, b]`), block sequences (`- a` lines), and one level of nested map (indented `key: value`
// lines under a bare parent key) — so the lib stays dependency-free rather than pulling a full YAML
// engine. Anything outside that shape is ignored, not errored, so a malformed field never blocks
// discovery of the rest.
// (`[a, b]`), block sequences (`- a` lines), one level of nested map (indented `key: value` lines
// under a bare parent key), and block scalars (`key: |` / `key: >`, with `-` chomping — issue #120,
// where multi-line skill descriptions live) — so the lib stays dependency-free rather than pulling a
// full YAML engine. Anything outside that shape is ignored, not errored, so a malformed field never
// blocks discovery of the rest.

export type FrontmatterValue = string | string[] | Record<string, string>;
export type Frontmatter = { data: Record<string, FrontmatterValue>; body: string };
Expand All @@ -18,15 +19,24 @@ export function parseFrontmatter(content: string): Frontmatter {

function parseBlock(raw: string): Record<string, FrontmatterValue> {
const data: Record<string, FrontmatterValue> = {};
const lines = raw.split('\n');
// Split on CRLF or LF so a Windows-authored / CRLF-checked-out SKILL.md doesn't leave a trailing
// `\r` on every line — it would fail the key-line match outright and, for block scalars (whose
// value skips the usual `.trim()`), embed `\r` inside the parsed text.
const lines = raw.split(/\r?\n/);
for (let i = 0; i < lines.length; i++) {
const line = lines[i] ?? '';
if (line.trim() === '' || line.trimStart().startsWith('#')) continue;
const m = /^([A-Za-z0-9_-]+):[ \t]*(.*)$/.exec(line);
if (!m) continue;
const key = m[1] ?? '';
const rest = (m[2] ?? '').trim();
if (rest === '') {
if (BLOCK_SCALAR.test(rest)) {
// `key: |` / `key: >` head an indented block; the value spans the following more-indented
// lines. Multi-line skill descriptions (issue #120) are the reason this exists.
const { value, next } = parseBlockScalar(lines, i, rest);
data[key] = value;
i = next - 1;
} else if (rest === '') {
// A bare `key:` heads either a nested map (indented `subkey: value` lines) or a block
// sequence (`- item` lines). An indented `key:` line wins — it's a map, not a sequence item.
if (/^[ \t]+[A-Za-z0-9_-]+:/.test(lines[i + 1] ?? '')) {
Expand Down Expand Up @@ -55,6 +65,57 @@ function parseBlock(raw: string): Record<string, FrontmatterValue> {
return data;
}

// A block-scalar header is a lone `|` or `>` (literal / folded) with an optional `-` (strip)
// chomping indicator. `key: >text` is a plain scalar, not a block — the header must stand alone.
// `+` (keep) is intentionally unsupported: `>+` fails this match and falls through to the plain
// scalar path rather than being silently treated as clip (its behavior can't be produced here, since
// trailing blank lines are always popped below).
const BLOCK_SCALAR = /^([|>])(-?)$/;

// Consume the indented lines following a `key: |` / `key: >` header into a single string. `folded`
// (`>`) joins lines with spaces and blank lines with newlines; literal (`|`) keeps every newline.
// The block ends at the first non-blank line that dedents to the header's column (the next key) or
// below the block's own indent. Default chomping keeps one trailing newline; `-` strips it.
function parseBlockScalar(
lines: string[],
keyIndex: number,
header: string,
): { value: string; next: number } {
const folded = header[0] === '>';
const strip = header[1] === '-';
const collected: string[] = [];
let baseIndent = -1;
let i = keyIndex + 1;
for (; i < lines.length; i++) {
const line = lines[i] ?? '';
if (line.trim() === '') {
collected.push('');
continue;
}
const indent = line.length - line.trimStart().length;
if (indent === 0) break;
if (baseIndent === -1) baseIndent = indent;
if (indent < baseIndent) break;
collected.push(line.slice(baseIndent));
}
// Trailing blank lines are the separator before the next key, not part of the value.
while (collected.length > 0 && collected[collected.length - 1] === '') collected.pop();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
const assembled = assembleBlockScalar(collected, folded);
const value = strip || assembled === '' ? assembled : `${assembled}\n`;
return { value, next: i };
}

function assembleBlockScalar(lines: string[], folded: boolean): string {
if (!folded) return lines.join('\n');
let out = '';
for (const line of lines) {
if (line === '') out += '\n';
else if (out === '' || out.endsWith('\n')) out += line;
else out += ` ${line}`;
}
return out;
}

function stripQuotes(s: string): string {
if (s.length >= 2) {
const first = s[0];
Expand Down
7 changes: 7 additions & 0 deletions packages/ai-claude-compat/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,13 @@ export {
globToRegExp,
grepTool,
} from './search-tools.ts';
export {
SKILL_INVOCATION_CONTRACT,
type SkillToolInput,
type SkillToolOutput,
skillIndexBlock,
skillTool,
} from './skill-tool.ts';
export { loadSkills, type SkillDefinition } from './skills-loader.ts';
export {
callWithStepTimeout,
Expand Down
124 changes: 124 additions & 0 deletions packages/ai-claude-compat/src/skill-tool.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import type { SkillToolInput, SkillToolOutput } from './skill-tool.ts';
import { SKILL_INVOCATION_CONTRACT, skillIndexBlock, skillTool } from './skill-tool.ts';
import type { SkillDefinition } from './skills-loader.ts';

function skill(partial: Partial<SkillDefinition> & { name: string }): SkillDefinition {
return {
name: partial.name,
description: partial.description ?? `desc for ${partial.name}`,
body: partial.body ?? `body for ${partial.name}`,
path: partial.path ?? `/repo/.claude/skills/${partial.name}/SKILL.md`,
extra: partial.extra ?? {},
};
}

function runExec(t: { execute?: unknown }, input: SkillToolInput): SkillToolOutput {
const exec = t.execute;
if (typeof exec !== 'function') throw new Error('tool has no execute');
return (
exec as (i: SkillToolInput, o: { toolCallId: string; messages: never[] }) => SkillToolOutput
)(input, { toolCallId: 'c', messages: [] });
}

function textOf(
t: { toModelOutput?: unknown },
input: SkillToolInput,
output: SkillToolOutput,
): string {
const fn = t.toModelOutput;
if (typeof fn !== 'function') throw new Error('tool has no toModelOutput');
const part = (
fn as (o: { toolCallId: string; input: SkillToolInput; output: SkillToolOutput }) => {
type: string;
value: string;
}
)({ toolCallId: 'c', input, output });
assert.equal(part.type, 'text');
return part.value;
}

test('skillIndexBlock: contract preamble + one line per invocable skill; disabled excluded (issue #120)', () => {
const block = skillIndexBlock([
skill({ name: 'repo-recon', description: 'map a repo before editing' }),
skill({
name: 'secret',
description: 'hidden',
extra: { 'disable-model-invocation': 'true' },
}),
]);
assert.ok(block.startsWith(SKILL_INVOCATION_CONTRACT), 'the invocation contract is the preamble');
assert.match(block, /<skills>\nrepo-recon: map a repo before editing\n<\/skills>/);
assert.equal(block.includes('secret'), false, 'disable-model-invocation excludes from the index');
});

test('skillIndexBlock: collapses a multi-line description to a single index line (issue #120)', () => {
const block = skillIndexBlock([skill({ name: 'x', description: 'line one\nline two' })]);
assert.match(block, /x: line one line two/);
assert.equal(
block.split('\n').filter((l) => l.startsWith('x:')).length,
1,
'exactly one line for the skill',
);
});

test('skillIndexBlock: empty or all-disabled input renders nothing (issue #120)', () => {
assert.equal(skillIndexBlock([]), '');
assert.equal(
skillIndexBlock([skill({ name: 'z', extra: { 'disable-model-invocation': 'true' } })]),
'',
);
});

test('skillTool: a valid name returns the skill body and path, rendered as plain text (issue #120)', () => {
const t = skillTool([
skill({
name: 'triage',
body: 'read logs bottom-up',
path: '/r/.claude/skills/triage/SKILL.md',
}),
]);
const out = runExec(t, { skill: 'triage' });
assert.equal(out.ok, true);
if (!out.ok) return;
assert.equal(out.body, 'read logs bottom-up');
assert.equal(out.path, '/r/.claude/skills/triage/SKILL.md');
const text = textOf(t, { skill: 'triage' }, out);
assert.match(text, /^Skill: triage/);
assert.match(text, /read logs bottom-up/);
assert.ok(text.includes('/r/.claude/skills/triage/SKILL.md'), 'result carries the path');
assert.match(text, /read them on demand with the Read tool/);
});

test('skillTool: an unknown name returns an error naming the available skills — never throws (issue #120)', () => {
const t = skillTool([skill({ name: 'a' }), skill({ name: 'b' })]);
const out = runExec(t, { skill: 'nope' });
assert.equal(out.ok, false);
if (out.ok) return;
assert.match(out.error, /Unknown skill "nope"/);
assert.match(out.error, /Available skills: a, b/);
assert.equal(
textOf(t, { skill: 'nope' }, out),
out.error,
'the error text is what the model sees',
);
});

test('skillTool: a disabled skill is not in the matchable set (issue #120)', () => {
const t = skillTool([skill({ name: 'secret', extra: { 'disable-model-invocation': 'true' } })]);
const out = runExec(t, { skill: 'secret' });
assert.equal(out.ok, false);
if (out.ok) return;
assert.match(out.error, /Available skills: \(none available\)/);
});

test('skillTool: args are echoed into the result and its rendering (issue #120)', () => {
const t = skillTool([skill({ name: 'triage', body: 'B' })]);
const input = { skill: 'triage', args: 'job=e2e' };
const out = runExec(t, input);
assert.equal(out.ok, true);
if (!out.ok) return;
assert.equal(out.args, 'job=e2e');
assert.match(textOf(t, input, out), /Arguments: job=e2e/);
});
94 changes: 94 additions & 0 deletions packages/ai-claude-compat/src/skill-tool.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Model-facing surface for skills (issue #120). Two builders turn discovered `SkillDefinition`s
// (skills-loader.ts) into progressive disclosure:
//
// - `skillIndexBlock` renders the always-visible tier — one `<name>: <description>` line per skill
// plus the invocation contract — for the system prompt. Bodies never appear here.
// - `skillTool` is the AI-SDK tool a subagent calls to pull a skill's body into context on demand
// (the second tier); the body then directs on-demand reads of sibling `references/*` (the third).
//
// Both exclude skills whose `disable-model-invocation` frontmatter is `true`. Neither mounts anything
// itself — the caller passes the `skills` array, deciding what a given role may see (target-repo
// skills are untrusted and Worker-only; that wiring is a separate aitm-side issue).

import { type Tool, tool } from 'ai';
import { z } from 'zod';
import { asString } from './frontmatter.ts';
import type { SkillDefinition } from './skills-loader.ts';

// Rendered as the index block's preamble: the blocking contract the model must follow.
export const SKILL_INVOCATION_CONTRACT =
"Skills extend you with task-specific procedures. Each line below is `<name>: <description>`. When a skill's description matches the task at hand, you MUST call the `Skill` tool with that exact name and follow the instructions it returns before producing your answer — this is blocking, not optional. Never claim to have applied a skill without calling the tool, and only invoke names that appear in this list.";

const skillInputSchema = z.object({
skill: z.string().min(1).describe('The exact name of a skill from the skills index.'),
args: z
.string()
.optional()
.describe('Free-form input for the skill; echoed back in the result for its instructions.'),
});
export type SkillToolInput = z.infer<typeof skillInputSchema>;
export type SkillToolOutput =
| { ok: true; name: string; path: string; body: string; args?: string }
| { ok: false; error: string };

// A skill is model-invocable unless it opts out with `disable-model-invocation: true`.
function isModelInvocable(skill: SkillDefinition): boolean {
return asString(skill.extra['disable-model-invocation']).trim() !== 'true';
}

const oneLine = (s: string): string => s.replace(/[\r\n]+/g, ' ').trim();

// The always-visible index tier: the invocation contract plus one line per model-invocable skill.
// Returns '' when nothing is invocable, so a caller can drop the block entirely.
export function skillIndexBlock(skills: readonly SkillDefinition[]): string {
const invocable = skills.filter(isModelInvocable);
if (invocable.length === 0) return '';
const lines = invocable.map((s) => `${s.name}: ${oneLine(s.description)}`);
return [SKILL_INVOCATION_CONTRACT, '<skills>', ...lines, '</skills>'].join('\n');
}

// The `Skill` tool: exact-name lookup over the model-invocable set. A hit returns the skill's body
// and absolute path; a miss returns an error result naming the available skills (never throws).
export function skillTool(
skills: readonly SkillDefinition[],
): Tool<SkillToolInput, SkillToolOutput> {
const invocable = skills.filter(isModelInvocable);
const byName = new Map(invocable.map((s) => [s.name, s]));
const available = invocable.map((s) => s.name);
return tool({
description:
'Load a skill by name to pull its full instructions into context, then follow them before answering. Only names present in the skills index are valid. `args` is optional free-form text passed through to the skill.',
inputSchema: skillInputSchema,
execute: (input: SkillToolInput): SkillToolOutput => {
const skill = byName.get(input.skill);
if (skill === undefined) {
const names = available.length > 0 ? available.join(', ') : '(none available)';
return { ok: false, error: `Unknown skill "${input.skill}". Available skills: ${names}.` };
}
return {
ok: true,
name: skill.name,
path: skill.path,
body: skill.body,
...(input.args !== undefined ? { args: input.args } : {}),
};
},
toModelOutput: ({ output }) => ({ type: 'text', value: renderSkillResult(output) }),
});
}

// Plain-text rendering so the body reads as instructions, not a JSON-escaped blob (issue #127).
function renderSkillResult(output: SkillToolOutput): string {
if (!output.ok) return output.error;
const header =
output.args !== undefined && output.args !== ''
? `Skill: ${output.name}\nArguments: ${output.args}`
: `Skill: ${output.name}`;
return [
header,
'',
output.body,
'',
`Files this skill references (e.g. references/*.md) live next to ${output.path}; read them on demand with the Read tool.`,
].join('\n');
}
Loading
Loading