Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 149 lines 4.74 KB
Raw
1 import type { KbSourceDocument, KbSourceMetadata, KbSourceReference } from './types';
2
3 const REQUIRED_KEYS = [
4 'type',
5 'title',
6 'description',
7 'category',
8 'visibility',
9 'timestamp',
10 'tags',
11 ] as const;
12
13 function unquote(value: string): string {
14 const trimmed = value.trim();
15 if (
16 (trimmed.startsWith('"') && trimmed.endsWith('"')) ||
17 (trimmed.startsWith("'") && trimmed.endsWith("'"))
18 ) {
19 return trimmed.slice(1, -1);
20 }
21 return trimmed;
22 }
23
24 export function parsePublicKbDocument(raw: string): KbSourceDocument {
25 if (!raw.startsWith('---\n')) {
26 throw new Error('Public KB source is missing YAML frontmatter');
27 }
28
29 const closing = raw.indexOf('\n---\n', 4);
30 if (closing < 0) throw new Error('Public KB frontmatter is not closed');
31
32 const values = new Map<string, string | string[]>();
33 let listKey: string | null = null;
34
35 for (const line of raw.slice(4, closing).split('\n')) {
36 const listItem = line.match(/^\s+-\s+(.+)$/);
37 if (listItem && listKey) {
38 const current = values.get(listKey);
39 if (!Array.isArray(current)) throw new Error(`${listKey} is not a list`);
40 current.push(unquote(listItem[1] ?? ''));
41 continue;
42 }
43
44 const field = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
45 if (!field) continue;
46 const [, key, rawValue] = field;
47 if (!key) continue;
48 if (values.has(key)) throw new Error(`Duplicate frontmatter key: ${key}`);
49 if (key === 'tags') {
50 values.set(key, []);
51 listKey = key;
52 } else {
53 values.set(key, unquote(rawValue ?? ''));
54 listKey = null;
55 }
56 }
57
58 const actualKeys = [...values.keys()].sort();
59 const expectedKeys = [...REQUIRED_KEYS].sort();
60 if (actualKeys.join('|') !== expectedKeys.join('|')) {
61 throw new Error(`Public KB frontmatter must contain exactly: ${REQUIRED_KEYS.join(', ')}`);
62 }
63
64 const stringValue = (key: string): string => {
65 const value = values.get(key);
66 if (typeof value !== 'string' || !value.trim()) {
67 throw new Error(`Frontmatter field ${key} must be a non-empty string`);
68 }
69 return value.trim();
70 };
71 const tags = values.get('tags');
72 if (!Array.isArray(tags) || tags.length === 0) {
73 throw new Error('Frontmatter field tags must be a non-empty list');
74 }
75
76 const metadata: KbSourceMetadata = {
77 type: stringValue('type'),
78 title: stringValue('title'),
79 description: stringValue('description'),
80 category: stringValue('category'),
81 visibility: stringValue('visibility'),
82 timestamp: stringValue('timestamp'),
83 tags,
84 };
85
86 return { metadata, body: raw.slice(closing + 5).trim() };
87 }
88
89 function normalizedHeading(value: string): string {
90 return value.trim().replace(/\s+/g, ' ').toLowerCase();
91 }
92
93 function guideSection(
94 document: KbSourceDocument,
95 sourceHeading: string | null
96 ): { heading: string | null; body: string } {
97 const lines = document.body.split('\n');
98 if (!sourceHeading) {
99 if (lines.some(line => /^##\s+/.test(line))) {
100 throw new Error('A source without a heading cannot contain level-two sections');
101 }
102 const firstContent = lines.findIndex(line => line.trim().length > 0);
103 if (firstContent >= 0 && /^#\s+/.test(lines[firstContent] ?? '')) {
104 lines.splice(firstContent, 1);
105 }
106 return { heading: null, body: lines.join('\n').trim() };
107 }
108
109 const target = normalizedHeading(sourceHeading);
110 const matches = lines
111 .map((line, index) => ({ index, match: line.match(/^##\s+(.+?)\s*$/) }))
112 .filter(item => item.match && normalizedHeading(item.match[1] ?? '') === target);
113
114 if (matches.length === 0) throw new Error(`Heading "${sourceHeading}" was not found`);
115 if (matches.length > 1) throw new Error(`Heading "${sourceHeading}" is duplicated`);
116
117 const match = matches[0];
118 const start = (match?.index ?? 0) + 1;
119 let end = lines.length;
120 for (let index = start; index < lines.length; index++) {
121 if (/^##\s+/.test(lines[index] ?? '')) {
122 end = index;
123 break;
124 }
125 }
126 return { heading: match?.match?.[1] ?? null, body: lines.slice(start, end).join('\n').trim() };
127 }
128
129 export function extractGuideBody(document: KbSourceDocument, sourceHeading: string | null): string {
130 return guideSection(document, sourceHeading).body;
131 }
132
133 export function extractGuideSections(
134 document: KbSourceDocument | ((sourcePath: string) => KbSourceDocument),
135 references: KbSourceReference[]
136 ): string {
137 const resolveDocument =
138 typeof document === 'function' ? document : (_sourcePath: string) => document;
139 const includeHeadings = references.length > 1;
140
141 return references
142 .map(reference => {
143 const section = guideSection(resolveDocument(reference.sourcePath), reference.sourceHeading);
144 return includeHeadings && section.heading
145 ? `## ${section.heading}\n\n${section.body}`
146 : section.body;
147 })
148 .join('\n\n');
149 }