Skip to content

Commit d848d95

Browse files
feat(blocks): share prompt text and config between resources
A system prompt can include a Markdown block with a line that says only "@include <name>", and any mapping can include a YAML block with a "$include" key, where the file's own keys win. Blocks are looked up in resources/<org>/templates/ first, then in templates/ at the repository root, so an org can replace or extend a shared block. The loader expands them, so validate, push, PR checks and drift hashes all see the finished resource. Liquid inside a block is passed through untouched. Pull never writes a file that uses blocks. It used to rewrite a file whenever the dashboard matched it, was ahead of it, or under --force and --resolve=theirs, and each of those would replace a marker with a copy of the block. It now leaves the file as written and saves the dashboard version beside it when the two differ. validate warns about YAML merge keys and Liquid include/render/layout tags, which the engine and Vapi drop silently. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
1 parent bc80d57 commit d848d95

10 files changed

Lines changed: 1575 additions & 6 deletions

‎src/blocks.ts‎

Lines changed: 350 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,350 @@
1+
// Blocks: text and config shared between resource files.
2+
//
3+
// A prompt block is a Markdown file under templates/blocks/. A system prompt
4+
// pulls it in with a line that holds only "@include <name>". A config block
5+
// is a YAML file under templates/config/. Any mapping in a resource pulls it
6+
// in with a "$include" key, and the mapping's own keys win over the block's.
7+
//
8+
// Both kinds are looked up in resources/<org>/templates/ first, then in
9+
// templates/ at the repository root, so an org can replace a shared block.
10+
// A block inside the org folder that includes its own name gets the shared
11+
// one, which lets it extend the shared block rather than copy it.
12+
//
13+
// Expansion happens when a resource file is loaded, so validate, push, PR
14+
// checks, drift hashes and the audit all see the expanded resource. Nothing
15+
// inside a block is interpreted: Liquid variables reach Vapi as written.
16+
// The marker is deliberately not Liquid, because Vapi renders "include" and
17+
// "render" tags as nothing on a live call.
18+
//
19+
// Config-free, like resource-parse.ts, so every org can be read in one run.
20+
21+
import { createHash } from "node:crypto";
22+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
23+
import { dirname, join, relative, resolve } from "node:path";
24+
import { isDeepStrictEqual } from "node:util";
25+
import { parse as parseYaml } from "yaml";
26+
27+
export const TEMPLATES_FOLDER = "templates";
28+
export const INCLUDE_KEY = "$include";
29+
30+
const INCLUDE_LINE = /^[ \t]*@include[ \t]+(\S+)[ \t]*\r?$/;
31+
const INCLUDE_LINE_ANYWHERE = /^[ \t]*@include[ \t]+\S+[ \t]*\r?$/m;
32+
const BLOCK_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*(\/[A-Za-z0-9][A-Za-z0-9_-]*)*$/;
33+
34+
interface BlockKind {
35+
label: string;
36+
folder: string;
37+
extensions: string[];
38+
}
39+
40+
const PROMPT: BlockKind = {
41+
label: "prompt block",
42+
folder: "blocks",
43+
extensions: [".md"],
44+
};
45+
const CONFIG: BlockKind = {
46+
label: "config block",
47+
folder: "config",
48+
extensions: [".yml", ".yaml"],
49+
};
50+
51+
// The two folders a block is looked up in, in order.
52+
export interface BlockLayers {
53+
org: string;
54+
shared: string;
55+
}
56+
57+
// <root>/resources/<org> → <root>/resources/<org>/templates and <root>/templates.
58+
export function blockLayers(resourcesDir: string): BlockLayers {
59+
return {
60+
org: join(resourcesDir, TEMPLATES_FOLDER),
61+
shared: resolve(resourcesDir, "..", "..", TEMPLATES_FOLDER),
62+
};
63+
}
64+
65+
// Block file → hash of its content, for every block a resource resolved to,
66+
// nested ones included. Keys are paths inside a templates folder
67+
// ("blocks/red-flags.md"), the same whichever layer supplied the file.
68+
export type BlockUsage = Record<string, string>;
69+
70+
interface BlockFile {
71+
key: string;
72+
path: string;
73+
content: string;
74+
}
75+
76+
interface Expansion {
77+
layers: BlockLayers;
78+
usage: Map<string, string>;
79+
// Block files being expanded right now, outermost first.
80+
stack: BlockFile[];
81+
}
82+
83+
type Mapping = Record<string, unknown>;
84+
85+
function isMapping(value: unknown): value is Mapping {
86+
return typeof value === "object" && value !== null && !Array.isArray(value);
87+
}
88+
89+
function isSystemMessage(
90+
value: Mapping,
91+
): value is Mapping & { content: string } {
92+
return value.role === "system" && typeof value.content === "string";
93+
}
94+
95+
function blockFind(
96+
kind: BlockKind,
97+
name: string,
98+
expansion: Expansion,
99+
): BlockFile {
100+
if (!BLOCK_NAME.test(name))
101+
throw new Error(
102+
`Invalid ${kind.label} name "${name}": use the file name without its extension, for example "red-flags" or "safety/red-flags"`,
103+
);
104+
const { layers, stack } = expansion;
105+
const from = stack[stack.length - 1]?.path;
106+
const root = dirname(layers.shared);
107+
const searched: string[] = [];
108+
for (const layer of [layers.org, layers.shared]) {
109+
for (const extension of kind.extensions) {
110+
const path = join(layer, kind.folder, `${name}${extension}`);
111+
// An org block that includes its own name extends the shared one.
112+
if (layer === layers.org && path === from) continue;
113+
searched.push(relative(root, path));
114+
if (!existsSync(path)) continue;
115+
const block = {
116+
key: `${kind.folder}/${name}${extension}`,
117+
path,
118+
content: readFileSync(path, "utf8"),
119+
};
120+
if (stack.some((open) => open.path === path))
121+
throw new Error(
122+
`Blocks include each other in a loop: ${[...stack, block].map((open) => relative(root, open.path)).join(" → ")}`,
123+
);
124+
// An org block that extends the shared one uses both files.
125+
const hash = createHash("sha256").update(block.content);
126+
const outer = expansion.usage.get(block.key);
127+
if (outer !== undefined) hash.update(outer);
128+
expansion.usage.set(block.key, hash.digest("hex").slice(0, 16));
129+
return block;
130+
}
131+
}
132+
throw new Error(
133+
`Unknown ${kind.label} "${name}". Looked for:\n${searched.map((path) => ` - ${path}`).join("\n")}`,
134+
);
135+
}
136+
137+
function blockExpand<T>(
138+
block: BlockFile,
139+
expansion: Expansion,
140+
expand: () => T,
141+
): T {
142+
expansion.stack.push(block);
143+
try {
144+
return expand();
145+
} finally {
146+
expansion.stack.pop();
147+
}
148+
}
149+
150+
function textExpand(text: string, expansion: Expansion): string {
151+
if (!INCLUDE_LINE_ANYWHERE.test(text)) return text;
152+
return text
153+
.split("\n")
154+
.map((line) => {
155+
const name = line.match(INCLUDE_LINE)?.[1];
156+
if (name === undefined) return line;
157+
const block = blockFind(PROMPT, name, expansion);
158+
// The block's own text only: no byte-order mark, no blank lines around it.
159+
const body = block.content
160+
.replace(/^\uFEFF/, "")
161+
.replace(/^(?:[ \t]*\r?\n)+/, "")
162+
.trimEnd();
163+
return blockExpand(block, expansion, () => textExpand(body, expansion));
164+
})
165+
.join("\n");
166+
}
167+
168+
// Two blocks included side by side: mappings combine, and anything else set
169+
// by both must be identical, so the result never depends on their order.
170+
function blocksCombine(
171+
left: Mapping,
172+
right: Mapping,
173+
names: string,
174+
path: string[],
175+
): Mapping {
176+
const combined: Mapping = { ...left };
177+
for (const [key, value] of Object.entries(right)) {
178+
const existing = combined[key];
179+
if (!(key in combined)) combined[key] = value;
180+
else if (isMapping(existing) && isMapping(value))
181+
combined[key] = blocksCombine(existing, value, names, [...path, key]);
182+
else if (!isDeepStrictEqual(existing, value))
183+
throw new Error(
184+
`Config blocks ${names} both set "${[...path, key].join(".")}" to different values. Set it in one block, or in the file that includes them.`,
185+
);
186+
}
187+
return combined;
188+
}
189+
190+
// The including mapping over its blocks: mappings merge key by key, and any
191+
// other value the file sets (a list included) replaces the block's whole.
192+
function fileOverBlock(block: Mapping, file: Mapping): Mapping {
193+
const merged: Mapping = { ...block };
194+
for (const [key, value] of Object.entries(file)) {
195+
const inherited = merged[key];
196+
merged[key] =
197+
isMapping(inherited) && isMapping(value)
198+
? fileOverBlock(inherited, value)
199+
: value;
200+
}
201+
return merged;
202+
}
203+
204+
function includeNames(value: unknown): string[] {
205+
const names: unknown[] = Array.isArray(value) ? value : [value];
206+
if (
207+
names.length === 0 ||
208+
names.some((name) => typeof name !== "string" || name === "")
209+
)
210+
throw new Error(
211+
`"${INCLUDE_KEY}" takes a config block name or a list of names, got ${JSON.stringify(value)}`,
212+
);
213+
if (new Set(names).size !== names.length)
214+
throw new Error(`"${INCLUDE_KEY}" lists the same config block twice`);
215+
return names as string[];
216+
}
217+
218+
function configExpand(value: unknown, expansion: Expansion): unknown {
219+
if (Array.isArray(value))
220+
return value.map((item) => configExpand(item, expansion));
221+
if (!isMapping(value)) return value;
222+
const own: Mapping = {};
223+
for (const [key, child] of Object.entries(value))
224+
if (key !== INCLUDE_KEY) own[key] = configExpand(child, expansion);
225+
if (!(INCLUDE_KEY in value)) return own;
226+
if ("<<" in value)
227+
throw new Error(
228+
`A mapping uses both "${INCLUDE_KEY}" and a YAML merge key ("<<"). The engine does not process merge keys; keep "${INCLUDE_KEY}" only.`,
229+
);
230+
const names = includeNames(value[INCLUDE_KEY]);
231+
const included = names.map((name) => {
232+
const block = blockFind(CONFIG, name, expansion);
233+
const parsed: unknown = parseYaml(block.content);
234+
if (parsed === null || parsed === undefined)
235+
throw new Error(`Config block "${name}" is empty`);
236+
return blockExpand(block, expansion, () => configExpand(parsed, expansion));
237+
});
238+
// On its own, "$include" stands for the block's value, whatever its shape.
239+
if (Object.keys(own).length === 0 && included.length === 1)
240+
return included[0];
241+
const quoted = names.map((name) => `"${name}"`).join(" and ");
242+
let combined: Mapping = {};
243+
for (const [index, block] of included.entries()) {
244+
if (!isMapping(block))
245+
throw new Error(
246+
`Config block "${names[index]}" is not a mapping, so it can only be included on its own: no other keys beside "${INCLUDE_KEY}", and no other block in the list.`,
247+
);
248+
combined = blocksCombine(combined, block, quoted, []);
249+
}
250+
return fileOverBlock(combined, own);
251+
}
252+
253+
function promptsExpand(value: unknown, expansion: Expansion): unknown {
254+
if (Array.isArray(value))
255+
return value.map((item) => promptsExpand(item, expansion));
256+
if (!isMapping(value)) return value;
257+
const output: Mapping = {};
258+
for (const [key, child] of Object.entries(value))
259+
output[key] = promptsExpand(child, expansion);
260+
if (isSystemMessage(output))
261+
output.content = textExpand(output.content, expansion);
262+
return output;
263+
}
264+
265+
// Whether a parsed resource file uses a block anywhere. Pull asks this of the
266+
// file as written, before it decides whether it may rewrite that file.
267+
export function blocksUsedIn(value: unknown): boolean {
268+
if (Array.isArray(value)) return value.some(blocksUsedIn);
269+
if (!isMapping(value)) return false;
270+
if (INCLUDE_KEY in value) return true;
271+
if (isSystemMessage(value) && INCLUDE_LINE_ANYWHERE.test(value.content))
272+
return true;
273+
return Object.values(value).some(blocksUsedIn);
274+
}
275+
276+
// Expand every block a parsed resource uses. A resource that uses none is
277+
// returned as it came in.
278+
export function blocksExpand<T>(
279+
data: T,
280+
layers: BlockLayers,
281+
): { data: T; usage: BlockUsage } {
282+
if (!blocksUsedIn(data)) return { data, usage: {} };
283+
const expansion: Expansion = { layers, usage: new Map(), stack: [] };
284+
const expanded = promptsExpand(configExpand(data, expansion), expansion);
285+
const usage: BlockUsage = {};
286+
for (const key of [...expansion.usage.keys()].sort())
287+
usage[key] = expansion.usage.get(key)!;
288+
return { data: expanded as T, usage };
289+
}
290+
291+
// ─────────────────────────────────────────────────────────────────────────────
292+
// Sync record
293+
//
294+
// resources/<org>/.vapi-blocks.json records, for each resource that uses
295+
// blocks, the block content it was last pushed with. Push writes it and it is
296+
// committed. A resource whose blocks no longer match its entry still runs the
297+
// old block text on the platform: that is what "npm run sync-blocks" lists
298+
// and what promotion adds to its plan. The file text of such a resource has
299+
// not changed, so nothing else in git shows that it needs a push.
300+
// ─────────────────────────────────────────────────────────────────────────────
301+
302+
export const BLOCKS_RECORD_FILE = ".vapi-blocks.json";
303+
304+
// "<type folder>/<resource id>" → the blocks it was pushed with.
305+
export type BlocksRecord = Record<string, BlockUsage>;
306+
307+
export function blocksRecordRead(resourcesDir: string): BlocksRecord {
308+
const path = join(resourcesDir, BLOCKS_RECORD_FILE);
309+
if (!existsSync(path)) return {};
310+
const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
311+
if (!isMapping(parsed)) throw new Error(`${path} must hold a JSON object`);
312+
return parsed as BlocksRecord;
313+
}
314+
315+
// The block files that differ between what a resource uses now and what it
316+
// was last pushed with; empty when it is in sync.
317+
export function blocksChanged(
318+
usage: BlockUsage,
319+
recorded: BlockUsage | undefined,
320+
): string[] {
321+
const keys = new Set([...Object.keys(usage), ...Object.keys(recorded ?? {})]);
322+
return [...keys].filter((key) => usage[key] !== recorded?.[key]).sort();
323+
}
324+
325+
// Record what the pushed resources were pushed with, and drop entries for
326+
// resources that no longer exist or no longer use blocks. Entries for
327+
// resources this push did not touch are kept: they may still be out of date.
328+
export function blocksRecordUpdate(
329+
resourcesDir: string,
330+
current: Map<string, BlockUsage>,
331+
pushed: Iterable<string>,
332+
): void {
333+
const before = blocksRecordRead(resourcesDir);
334+
const after: BlocksRecord = { ...before };
335+
for (const key of pushed) {
336+
const usage = current.get(key);
337+
if (usage) after[key] = usage;
338+
}
339+
for (const key of Object.keys(after)) {
340+
const usage = current.get(key);
341+
if (!usage || Object.keys(usage).length === 0) delete after[key];
342+
}
343+
if (isDeepStrictEqual(before, after)) return;
344+
const sorted: BlocksRecord = {};
345+
for (const key of Object.keys(after).sort()) sorted[key] = after[key]!;
346+
writeFileSync(
347+
join(resourcesDir, BLOCKS_RECORD_FILE),
348+
`${JSON.stringify(sorted, null, 2)}\n`,
349+
);
350+
}

0 commit comments

Comments
 (0)