@businesskit/agent 1.0.5 → 1.0.8

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.
Files changed (83) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.cursor-plugin/plugin.json +1 -1
  4. package/.superconsole-plugin/plugin.json +61 -31
  5. package/AGENTS.md +33 -15
  6. package/README.md +101 -113
  7. package/bin/businesskit.js +47 -8
  8. package/commands/brief.md +12 -0
  9. package/commands/chase.md +12 -0
  10. package/commands/competitors.md +12 -0
  11. package/commands/create-page.md +43 -15
  12. package/commands/crm.md +13 -0
  13. package/commands/drafts.md +12 -0
  14. package/commands/followups.md +13 -0
  15. package/commands/inbox-rules.md +12 -0
  16. package/commands/inbox.md +13 -0
  17. package/commands/otp.md +12 -0
  18. package/commands/pipeline.md +13 -0
  19. package/commands/post.md +12 -0
  20. package/commands/reply.md +12 -0
  21. package/commands/repurpose.md +12 -0
  22. package/commands/social-analytics.md +12 -0
  23. package/commands/social-inbox.md +12 -0
  24. package/commands/social-reply.md +12 -0
  25. package/commands/social.md +12 -0
  26. package/commands/triage.md +12 -0
  27. package/commands/update-agent.md +33 -0
  28. package/commands/update-content.md +1 -0
  29. package/commands/update-page.md +3 -2
  30. package/commands/write-blog.md +4 -0
  31. package/commands/write-docs.md +6 -0
  32. package/commands/write-guide.md +5 -0
  33. package/commands/write-newsletter.md +4 -0
  34. package/dist/server.js +7513 -0
  35. package/mcp_config.json +6 -2
  36. package/package.json +25 -5
  37. package/plugin.json +1 -1
  38. package/scripts/release.js +200 -0
  39. package/scripts/setup.sh +70 -35
  40. package/scripts/setup.ts +58 -21
  41. package/scripts/update.sh +56 -0
  42. package/server.json +3 -3
  43. package/skills/README.md +3 -2
  44. package/skills/cms/SKILL.md +111 -0
  45. package/skills/cms/references/cms-hubs.md +84 -0
  46. package/skills/cms/references/html-blocks.md +177 -0
  47. package/skills/crm/SKILL.md +15 -29
  48. package/skills/docs/SKILL.md +65 -0
  49. package/skills/docs/references/how-to.md +155 -0
  50. package/skills/inbox/SKILL.md +32 -40
  51. package/skills/pages/SKILL.md +62 -17
  52. package/skills/pages/references/sections-catalog.json +377 -144
  53. package/skills/social/SKILL.md +83 -210
  54. package/skills/social/evals/evals.json +66 -0
  55. package/skills/social/evals/rubric.md +26 -0
  56. package/skills/social/examples/repurposing-blog-to-social.md +93 -0
  57. package/skills/social/examples/weekly-content-calendar.md +30 -0
  58. package/skills/social/linkedin/SKILL.md +107 -0
  59. package/skills/social/linkedin/evals/evals.json +106 -0
  60. package/skills/social/linkedin/evals/rubric.md +28 -0
  61. package/skills/social/linkedin/examples/gasp-weekly-sprint.md +24 -0
  62. package/skills/social/linkedin/examples/growth-posts-by-format.md +140 -0
  63. package/skills/social/linkedin/references/gasp-funnel-and-calibration.md +90 -0
  64. package/skills/social/linkedin/references/six-growth-formats.md +114 -0
  65. package/skills/social/references/platforms.md +76 -0
  66. package/skills/social/references/post-templates.md +105 -0
  67. package/skills/social/references/reverse-engineering.md +62 -0
  68. package/src/data/sections-catalog.json +950 -0
  69. package/src/db.ts +181 -0
  70. package/src/server.ts +119 -0
  71. package/src/tools/content.ts +326 -0
  72. package/src/tools/crm.ts +1416 -0
  73. package/src/tools/domains.ts +89 -0
  74. package/src/tools/inbox.ts +1400 -0
  75. package/src/tools/index.ts +138 -0
  76. package/src/tools/pages.ts +1217 -0
  77. package/src/tools/shop.ts +771 -0
  78. package/src/tools/social.ts +2131 -0
  79. package/src/tools/system.ts +96 -0
  80. package/src/tools/types.ts +17 -0
  81. package/src/worker-tick.ts +394 -0
  82. package/skills/docs-cms/SKILL.md +0 -53
  83. package/skills/docs-cms/references/how-to.md +0 -383
@@ -0,0 +1,1217 @@
1
+ // src/tools/pages.ts
2
+ // Website Pages & Custom Section Components MCP Tools
3
+
4
+ import { execute, generateId, query } from '../db.js';
5
+ import type { ToolDefinition, ToolContext } from './types.js';
6
+ import { existsSync, readFileSync } from 'fs';
7
+ import { fileURLToPath } from 'url';
8
+ import { dirname, join } from 'path';
9
+
10
+ const __dirname = dirname(fileURLToPath(import.meta.url));
11
+ let sectionsCatalogCache: any = null;
12
+
13
+ function getSectionsCatalog(): any {
14
+ if (sectionsCatalogCache) return sectionsCatalogCache;
15
+ const candidates = [
16
+ join(__dirname, '..', 'skills', 'pages', 'references', 'sections-catalog.json'),
17
+ join(__dirname, '..', '..', 'skills', 'pages', 'references', 'sections-catalog.json'),
18
+ join(__dirname, '..', 'data', 'sections-catalog.json'),
19
+ ];
20
+ for (const p of candidates) {
21
+ if (existsSync(p)) {
22
+ try {
23
+ sectionsCatalogCache = JSON.parse(readFileSync(p, 'utf-8'));
24
+ return sectionsCatalogCache;
25
+ } catch (err) {
26
+ console.error(`[Pages] Failed parsing ${p}:`, err);
27
+ }
28
+ }
29
+ }
30
+ console.error('[Pages] Could not locate sections-catalog.json in:', candidates);
31
+ return { sections: [], themes: [] };
32
+ }
33
+
34
+ function parseAndNormalizeSections(
35
+ rawVal: unknown,
36
+ contentFallback = ''
37
+ ): { sectionsJson: string; sectionCount: number; sectionTypes: string[] } {
38
+ let parsedList: any[] = [];
39
+
40
+ if (Array.isArray(rawVal)) {
41
+ parsedList = [...rawVal];
42
+ } else if (typeof rawVal === 'string') {
43
+ try {
44
+ const parsed = JSON.parse(rawVal);
45
+ if (Array.isArray(parsed)) parsedList = parsed;
46
+ else if (parsed && typeof parsed === 'object') parsedList = [parsed];
47
+ } catch {}
48
+ } else if (rawVal && typeof rawVal === 'object') {
49
+ parsedList = [rawVal];
50
+ }
51
+
52
+ if (parsedList.length === 0 && contentFallback.trim()) {
53
+ parsedList.push({
54
+ id: generateId('sec'),
55
+ type: 'text',
56
+ enabled: true,
57
+ order: 0,
58
+ data: {
59
+ text: contentFallback.trim(),
60
+ },
61
+ });
62
+ }
63
+
64
+ const sectionTypes: string[] = [];
65
+ const normalized: any[] = [];
66
+
67
+ parsedList.forEach((item, idx) => {
68
+ if (item && typeof item === 'object' && !Array.isArray(item)) {
69
+ const obj = { ...item };
70
+ const id =
71
+ typeof obj.id === 'string' && obj.id.trim().length > 0 ? obj.id : generateId('sec');
72
+ const secType =
73
+ typeof obj.type === 'string' && obj.type.trim().length > 0 ? obj.type : 'text';
74
+ obj.id = id;
75
+ obj.type = secType;
76
+ if (obj.enabled === undefined) obj.enabled = true;
77
+ if (obj.order === undefined) obj.order = idx;
78
+ if (obj.data === undefined) obj.data = {};
79
+ sectionTypes.push(secType);
80
+ normalized.push(obj);
81
+ }
82
+ });
83
+
84
+ return {
85
+ sectionsJson: JSON.stringify(normalized),
86
+ sectionCount: normalized.length,
87
+ sectionTypes,
88
+ };
89
+ }
90
+
91
+ function parseFaqJson(rawVal: unknown): string {
92
+ if (Array.isArray(rawVal)) {
93
+ return JSON.stringify(rawVal);
94
+ }
95
+ if (typeof rawVal === 'string') {
96
+ try {
97
+ const parsed = JSON.parse(rawVal);
98
+ if (Array.isArray(parsed)) return JSON.stringify(parsed);
99
+ } catch {}
100
+ }
101
+ return '[]';
102
+ }
103
+
104
+ function extractOrNormalizeSchema(args: Record<string, any>, html: string): string {
105
+ if (args.schema !== undefined) {
106
+ if (Array.isArray(args.schema) && args.schema.length > 0) {
107
+ return JSON.stringify(args.schema);
108
+ }
109
+ if (typeof args.schema === 'string') {
110
+ try {
111
+ const parsed = JSON.parse(args.schema);
112
+ if (Array.isArray(parsed) && parsed.length > 0) {
113
+ return args.schema;
114
+ }
115
+ } catch {}
116
+ }
117
+ }
118
+
119
+ const fields: Array<{ name: string; label: string; type: string }> = [];
120
+ const seen = new Set<string>();
121
+ const regex = /data-field=(?:"([^"]+)"|'([^']+)')/g;
122
+ let match: RegExpExecArray | null;
123
+
124
+ while ((match = regex.exec(html)) !== null) {
125
+ const fieldName = (match[1] ?? match[2] ?? '').trim();
126
+ if (
127
+ fieldName &&
128
+ !seen.has(fieldName) &&
129
+ /^[a-zA-Z0-9_-]+$/.test(fieldName)
130
+ ) {
131
+ seen.add(fieldName);
132
+ const lower = fieldName.toLowerCase();
133
+ const fieldType =
134
+ lower.includes('desc') ||
135
+ lower.includes('subtitle') ||
136
+ lower.includes('text') ||
137
+ lower.includes('content')
138
+ ? 'textarea'
139
+ : 'text';
140
+
141
+ let label = '';
142
+ let prevIsLower = false;
143
+ for (const ch of fieldName) {
144
+ if (ch >= 'A' && ch <= 'Z' && prevIsLower) {
145
+ label += ' ';
146
+ }
147
+ if (label.length === 0) {
148
+ label += ch.toUpperCase();
149
+ } else if (ch === '_' || ch === '-') {
150
+ label += ' ';
151
+ } else {
152
+ label += ch;
153
+ }
154
+ prevIsLower = ch >= 'a' && ch <= 'z';
155
+ }
156
+
157
+ fields.push({ name: fieldName, label, type: fieldType });
158
+ }
159
+ }
160
+
161
+ if (!fields.some((f) => f.name === 'bgColor' || f.name === 'backgroundColor')) {
162
+ fields.push({ name: 'bgColor', label: 'Background Color', type: 'color' });
163
+ }
164
+ if (!fields.some((f) => f.name === 'textColor' || f.name === 'color')) {
165
+ fields.push({ name: 'textColor', label: 'Text Color', type: 'color' });
166
+ }
167
+
168
+ const btnUrlFields: Array<{ name: string; label: string; type: string }> = [];
169
+ for (const f of fields) {
170
+ const lower = f.name.toLowerCase();
171
+ if (
172
+ (lower.includes('btn') || lower.includes('button')) &&
173
+ !lower.endsWith('url') &&
174
+ !lower.endsWith('link')
175
+ ) {
176
+ const urlName = `${f.name}Url`;
177
+ if (!fields.some((x) => x.name === urlName)) {
178
+ btnUrlFields.push({
179
+ name: urlName,
180
+ label: `${f.label} Link (URL)`,
181
+ type: 'url',
182
+ });
183
+ }
184
+ }
185
+ }
186
+ fields.push(...btnUrlFields);
187
+
188
+ return JSON.stringify(fields);
189
+ }
190
+
191
+ function resolveCanonicalCategories(queryStr: string): string[] {
192
+ const q = queryStr.trim().toLowerCase();
193
+ switch (q) {
194
+ case 'hero':
195
+ case 'banner':
196
+ case 'intro':
197
+ case 'landing_hero':
198
+ return ['Hero'];
199
+ case 'navigation':
200
+ case 'nav':
201
+ case 'navbar':
202
+ case 'header':
203
+ case 'menu':
204
+ return ['Navigation'];
205
+ case 'features':
206
+ case 'feature':
207
+ case 'use_cases':
208
+ case 'use-cases':
209
+ case 'usecases':
210
+ case 'services':
211
+ case 'benefits':
212
+ return ['Features'];
213
+ case 'showcase':
214
+ case 'workspace':
215
+ case 'under_the_hood':
216
+ case 'split':
217
+ case 'demo':
218
+ case 'product':
219
+ return ['Showcase'];
220
+ case 'conversion':
221
+ case 'commercial':
222
+ case 'pricing':
223
+ case 'price':
224
+ case 'plans':
225
+ case 'cta':
226
+ case 'call to action':
227
+ case 'sales':
228
+ case 'buy':
229
+ return ['Conversion'];
230
+ case 'content':
231
+ case 'faq':
232
+ case 'faqs':
233
+ case 'questions':
234
+ case 'about':
235
+ case 'text':
236
+ case 'rich_text':
237
+ case 'copy':
238
+ case 'misc':
239
+ return ['Content'];
240
+ case 'social proof':
241
+ case 'social_proof':
242
+ case 'socialproof':
243
+ case 'testimonials':
244
+ case 'testimonial':
245
+ case 'reviews':
246
+ case 'review':
247
+ case 'ratings':
248
+ case 'trust':
249
+ return ['Social Proof'];
250
+ case 'footer':
251
+ case 'bottom':
252
+ return ['Footer'];
253
+ case 'education':
254
+ case 'curriculum':
255
+ case 'course':
256
+ case 'syllabus':
257
+ case 'modules':
258
+ return ['Education'];
259
+ default:
260
+ return [];
261
+ }
262
+ }
263
+
264
+ function mapFullSection(sec: any) {
265
+ return {
266
+ type: sec.type ?? null,
267
+ name: sec.name ?? null,
268
+ theme: sec.theme ?? null,
269
+ category: sec.category ?? null,
270
+ description: sec.description ?? null,
271
+ ai_summary: sec.ai_summary ?? null,
272
+ when_to_use: sec.when_to_use ?? null,
273
+ schema: sec.schema ?? null,
274
+ sample_data: sec.default_data ?? null,
275
+ reference_html: sec.reference_html ?? null,
276
+ reference_css: sec.reference_css ?? null,
277
+ };
278
+ }
279
+
280
+ export const pagesTools: ToolDefinition[] = [
281
+ {
282
+ name: 'page_create',
283
+ domain: 'pages',
284
+ description:
285
+ 'Create a complete website page or landing page with title, slug, and visual sections. Use native sections by default (sc_navbar, sc_hero, sc_use_cases, sc_workspace, sc_under_the_hood, sc_footer, hero_section, pricing, faq, text). For custom HTML/CSS blocks, use component_create first and pass { "type": "custom", "component_id": id }.',
286
+ inputSchema: {
287
+ type: 'object',
288
+ properties: {
289
+ title: { type: 'string', description: "Website page title (e.g. 'Home', 'About Us', 'Pricing', 'Services')" },
290
+ slug: { type: 'string', description: "URL slug for the page (e.g. 'home', 'about', 'pricing'), optional" },
291
+ excerpt: { type: 'string', description: 'Short summary or meta excerpt for the page, optional' },
292
+ sections: {
293
+ type: 'array',
294
+ description:
295
+ "List of visual section blocks. Common types & data schemas:\n- sc_navbar: { brandName, brandLogoUrl, links: [{label, url}], ctaText, ctaUrl, loginText, loginUrl, bgColor, isSticky }\n- sc_hero: { title, subtitle, primaryButtonText, primaryButtonUrl, secondaryButtonText, secondaryButtonUrl, noteText, githubRepo, bgColor }\n- sc_use_cases: { badgeText, title, subtitle, pillText, tabs: [{id, icon, title, eyebrow, subtitle, headline, body, code}], bgColor }\n- sc_workspace: { badgeText, title, subtitle, stats: [{value, label, description}], overviewTitle, overviewIcon, overviewSubtitle, tabs: [{id, title, subtitle, breadcrumb, code}], bgColor }\n- sc_under_the_hood: { badgeText, title, stats: [{value, label, description}], overviewTitle, overviewIcon, overviewSubtitle, tabs: [{id, title, subtitle, breadcrumb, code}], bgColor }\n- sc_footer: { brandName, brandLogoUrl, brandUrl, tagline, statusText, statusDotColor, columns: [{title, links: [{label, url}]}], copyright, githubUrl, twitterUrl, discordUrl, bgColor }\n- hero_section: { logoUrl, text1, text2, heading, text3, mediaUrl, text4, bgColor, highlightBoxColor }\n- pricing: { title, description, plans: [{offer, title, description, scarcity, price, sale_price, price_text, features: [{key, value}], cta_text, cta_url}], bgColor }\n- faq: { title, description, items: [{question, answer}], bgColor }\n- testimonials: { title, description, items: [{name, role, platform, url, quote, avatar_url, rating}], bgColor }\n- cta_section: { title, h3, description, richtext, buttonText, buttonUrl, bgColor }\n- text: { title, description, htmlContent, bgColor }\n- custom: { component_id: 'comp_...' } (must reference a component created via component_create)",
296
+ items: { type: 'object' },
297
+ },
298
+ content: { type: 'string', description: 'Fallback text or markdown if sections is not provided, optional' },
299
+ faq: {
300
+ type: 'array',
301
+ description: "Optional FAQ list [{ 'question': '...', 'answer': '...' }]",
302
+ items: { type: 'object' },
303
+ },
304
+ seo_title: { type: 'string', description: 'SEO page title, optional' },
305
+ seo_description: { type: 'string', description: 'SEO meta description, optional' },
306
+ seo_og_image: { type: 'string', description: 'OpenGraph image URL, optional' },
307
+ published: { type: 'boolean', description: 'Whether to publish immediately (defaults to false for draft)', default: false },
308
+ },
309
+ required: ['title'],
310
+ },
311
+ handler: async (args: Record<string, any>, ctx: ToolContext) => {
312
+ const profileId = ctx.profileId;
313
+ const title = String(args.title || '').trim();
314
+ if (!title) {
315
+ throw new Error('Title cannot be empty');
316
+ }
317
+
318
+ const defaultSlug = title
319
+ .toLowerCase()
320
+ .replace(/[^a-z0-9\s-]/g, '')
321
+ .trim()
322
+ .split(/\s+/)
323
+ .filter(Boolean)
324
+ .join('-');
325
+ const slug =
326
+ (typeof args.slug === 'string' && args.slug.trim()) ||
327
+ defaultSlug ||
328
+ `page-${Date.now()}`;
329
+
330
+ const contentMarkdown = String(
331
+ args.content ?? args.body ?? args.content_markdown ?? ''
332
+ );
333
+ const { sectionsJson, sectionCount, sectionTypes } = parseAndNormalizeSections(
334
+ args.sections,
335
+ contentMarkdown
336
+ );
337
+ const faqJson = parseFaqJson(args.faq);
338
+ const published = Boolean(args.published);
339
+ const now = Math.floor(Date.now() / 1000);
340
+ const pageId = generateId('page');
341
+
342
+ try {
343
+ await execute(
344
+ `INSERT INTO pages
345
+ (id, profile_id, user_id, updated_by, slug, title, excerpt, sections, faq,
346
+ published, nav_active, menu_active, footer_active,
347
+ seo_title, seo_description, seo_og_image, created_at, updated_at)
348
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 1, ?, ?, ?, ?, ?)`,
349
+ [
350
+ pageId,
351
+ profileId,
352
+ 'agent',
353
+ 'agent',
354
+ slug,
355
+ title,
356
+ args.excerpt ?? null,
357
+ sectionsJson,
358
+ faqJson,
359
+ published ? 1 : 0,
360
+ args.seo_title ?? null,
361
+ args.seo_description ?? null,
362
+ args.seo_og_image ?? null,
363
+ now,
364
+ now,
365
+ ]
366
+ );
367
+ } catch (err: any) {
368
+ if (String(err?.message || err).includes('no column named updated_by')) {
369
+ try {
370
+ await execute('ALTER TABLE pages ADD COLUMN updated_by TEXT', []);
371
+ } catch {}
372
+ await execute(
373
+ `INSERT INTO pages
374
+ (id, profile_id, user_id, slug, title, excerpt, sections, faq,
375
+ published, nav_active, menu_active, footer_active,
376
+ seo_title, seo_description, seo_og_image, created_at, updated_at)
377
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 1, ?, ?, ?, ?, ?)`,
378
+ [
379
+ pageId,
380
+ profileId,
381
+ 'agent',
382
+ slug,
383
+ title,
384
+ args.excerpt ?? null,
385
+ sectionsJson,
386
+ faqJson,
387
+ published ? 1 : 0,
388
+ args.seo_title ?? null,
389
+ args.seo_description ?? null,
390
+ args.seo_og_image ?? null,
391
+ now,
392
+ now,
393
+ ]
394
+ );
395
+ } else {
396
+ throw err;
397
+ }
398
+ }
399
+
400
+ return {
401
+ success: true,
402
+ page: {
403
+ id: pageId,
404
+ title,
405
+ slug,
406
+ published,
407
+ section_count: sectionCount,
408
+ section_types: sectionTypes,
409
+ url: `/dashboard/pages/${pageId}`,
410
+ },
411
+ message: `Website page '${title}' created successfully with ${sectionCount} section(s) (slug: /${slug})`,
412
+ };
413
+ },
414
+ },
415
+ {
416
+ name: 'page_get',
417
+ domain: 'pages',
418
+ description: 'Fetch a website page and all its visual sections, faq, and metadata by page ID or slug.',
419
+ inputSchema: {
420
+ type: 'object',
421
+ properties: {
422
+ page_id_or_slug: { type: 'string', description: "Page ID or slug (e.g. 'about', 'pricing', 'page_xyz')" },
423
+ },
424
+ required: ['page_id_or_slug'],
425
+ },
426
+ handler: async (args: Record<string, any>, ctx: ToolContext) => {
427
+ const profileId = ctx.profileId;
428
+ const target = String(args.page_id_or_slug ?? args.id ?? args.slug ?? '').trim();
429
+ if (!target) {
430
+ throw new Error('Missing required parameter: page_id_or_slug');
431
+ }
432
+
433
+ const rows = await query(
434
+ `SELECT id, profile_id, slug, title, excerpt, sections, faq, published,
435
+ nav_active, menu_active, footer_active, seo_title, seo_description,
436
+ seo_og_image, created_at, updated_at
437
+ FROM pages
438
+ WHERE profile_id = ? AND (id = ? OR slug = ?)
439
+ LIMIT 1`,
440
+ [profileId, target, target]
441
+ );
442
+
443
+ if (rows.length === 0) {
444
+ throw new Error(`Page with id or slug '${target}' not found`);
445
+ }
446
+
447
+ const p = rows[0];
448
+ let sections: any[] = [];
449
+ let faq: any[] = [];
450
+ try {
451
+ const parsed = JSON.parse(p.sections || '[]');
452
+ if (Array.isArray(parsed)) sections = parsed;
453
+ } catch {}
454
+ try {
455
+ const parsed = JSON.parse(p.faq || '[]');
456
+ if (Array.isArray(parsed)) faq = parsed;
457
+ } catch {}
458
+
459
+ return {
460
+ success: true,
461
+ page: {
462
+ id: p.id,
463
+ profile_id: p.profile_id,
464
+ slug: p.slug,
465
+ title: p.title,
466
+ excerpt: p.excerpt ?? null,
467
+ sections,
468
+ faq,
469
+ section_count: sections.length,
470
+ published: Number(p.published || 0) !== 0,
471
+ nav_active: Number(p.nav_active ?? 1) !== 0,
472
+ menu_active: Number(p.menu_active ?? 1) !== 0,
473
+ footer_active: Number(p.footer_active ?? 1) !== 0,
474
+ seo_title: p.seo_title ?? null,
475
+ seo_description: p.seo_description ?? null,
476
+ seo_og_image: p.seo_og_image ?? null,
477
+ created_at: p.created_at,
478
+ updated_at: p.updated_at,
479
+ url: `/dashboard/pages/${p.id}`,
480
+ },
481
+ };
482
+ },
483
+ },
484
+ {
485
+ name: 'page_update',
486
+ domain: 'pages',
487
+ description:
488
+ "Update an existing website page's visual sections, title, slug, excerpt, FAQ, SEO metadata, or published status.",
489
+ inputSchema: {
490
+ type: 'object',
491
+ properties: {
492
+ page_id_or_slug: { type: 'string', description: "Page ID or slug (e.g. 'about', 'pricing', 'page_xyz')" },
493
+ title: { type: 'string', description: 'New website page title, optional' },
494
+ slug: { type: 'string', description: 'New URL slug, optional' },
495
+ excerpt: { type: 'string', description: 'New excerpt or summary, optional' },
496
+ sections: {
497
+ type: 'array',
498
+ description: 'Updated list of section blocks (see page_create for section schemas)',
499
+ items: { type: 'object' },
500
+ },
501
+ faq: { type: 'array', description: 'Updated FAQ items, optional', items: { type: 'object' } },
502
+ published: { type: 'boolean', description: 'Publish (true) or draft (false) status, optional' },
503
+ seo_title: { type: 'string', description: 'Updated SEO title, optional' },
504
+ seo_description: { type: 'string', description: 'Updated SEO description, optional' },
505
+ seo_og_image: { type: 'string', description: 'Updated OpenGraph image URL, optional' },
506
+ },
507
+ required: ['page_id_or_slug'],
508
+ },
509
+ handler: async (args: Record<string, any>, ctx: ToolContext) => {
510
+ const profileId = ctx.profileId;
511
+ const target = String(args.page_id_or_slug ?? args.id ?? args.slug ?? '').trim();
512
+ if (!target) {
513
+ throw new Error('Missing required parameter: page_id_or_slug');
514
+ }
515
+
516
+ const pages = await query<{ id: string; slug: string; title: string }>(
517
+ 'SELECT id, slug, title FROM pages WHERE profile_id = ? AND (id = ? OR slug = ?) LIMIT 1',
518
+ [profileId, target, target]
519
+ );
520
+
521
+ if (pages.length === 0) {
522
+ throw new Error(`Page with id or slug '${target}' not found`);
523
+ }
524
+
525
+ const pageId = pages[0].id;
526
+ let finalTitle = pages[0].title;
527
+ let finalSlug = pages[0].slug;
528
+ const updates: string[] = [];
529
+ const params: any[] = [];
530
+
531
+ if (typeof args.title === 'string' && args.title.trim()) {
532
+ finalTitle = args.title.trim();
533
+ updates.push('title = ?');
534
+ params.push(finalTitle);
535
+ }
536
+ if (typeof args.slug === 'string' && args.slug.trim()) {
537
+ finalSlug = args.slug.trim();
538
+ updates.push('slug = ?');
539
+ params.push(finalSlug);
540
+ }
541
+ if (typeof args.excerpt === 'string') {
542
+ updates.push('excerpt = ?');
543
+ params.push(args.excerpt);
544
+ }
545
+
546
+ let sectionCount: number | null = null;
547
+ let sectionTypes: string[] | null = null;
548
+ if (
549
+ args.sections !== undefined ||
550
+ args.content !== undefined ||
551
+ args.body !== undefined ||
552
+ args.content_markdown !== undefined
553
+ ) {
554
+ const contentFb = String(
555
+ args.content ?? args.body ?? args.content_markdown ?? ''
556
+ );
557
+ const normalized = parseAndNormalizeSections(args.sections, contentFb);
558
+ updates.push('sections = ?');
559
+ params.push(normalized.sectionsJson);
560
+ sectionCount = normalized.sectionCount;
561
+ sectionTypes = normalized.sectionTypes;
562
+ }
563
+
564
+ if (args.faq !== undefined) {
565
+ updates.push('faq = ?');
566
+ params.push(parseFaqJson(args.faq));
567
+ }
568
+ if (typeof args.published === 'boolean') {
569
+ updates.push('published = ?');
570
+ params.push(args.published ? 1 : 0);
571
+ }
572
+ if (typeof args.seo_title === 'string') {
573
+ updates.push('seo_title = ?');
574
+ params.push(args.seo_title);
575
+ }
576
+ if (typeof args.seo_description === 'string') {
577
+ updates.push('seo_description = ?');
578
+ params.push(args.seo_description);
579
+ }
580
+ if (typeof args.seo_og_image === 'string') {
581
+ updates.push('seo_og_image = ?');
582
+ params.push(args.seo_og_image);
583
+ }
584
+
585
+ const now = Math.floor(Date.now() / 1000);
586
+ const baseParams = [...params];
587
+ const baseUpdates = [...updates];
588
+ updates.push('updated_at = ?', 'updated_by = ?');
589
+ params.push(now, 'agent', profileId, pageId);
590
+
591
+ try {
592
+ await execute(
593
+ `UPDATE pages SET ${updates.join(', ')} WHERE profile_id = ? AND id = ?`,
594
+ params
595
+ );
596
+ } catch (err: any) {
597
+ if (String(err?.message || err).includes('no column named updated_by')) {
598
+ baseUpdates.push('updated_at = ?');
599
+ baseParams.push(now, profileId, pageId);
600
+ await execute(
601
+ `UPDATE pages SET ${baseUpdates.join(', ')} WHERE profile_id = ? AND id = ?`,
602
+ baseParams
603
+ );
604
+ } else {
605
+ throw err;
606
+ }
607
+ }
608
+
609
+ return {
610
+ success: true,
611
+ page: {
612
+ id: pageId,
613
+ title: finalTitle,
614
+ slug: finalSlug,
615
+ section_count: sectionCount,
616
+ section_types: sectionTypes,
617
+ url: `/dashboard/pages/${pageId}`,
618
+ },
619
+ message: `Website page '${finalTitle}' updated successfully`,
620
+ };
621
+ },
622
+ },
623
+ {
624
+ name: 'page_publish',
625
+ domain: 'pages',
626
+ description: 'Toggle published or draft status for a website page by ID or slug.',
627
+ inputSchema: {
628
+ type: 'object',
629
+ properties: {
630
+ page_id_or_slug: { type: 'string', description: "Page ID or slug (e.g. 'about', 'page_xyz')" },
631
+ published: {
632
+ type: 'boolean',
633
+ description: 'True to publish, false to unpublish/draft (defaults to true)',
634
+ default: true,
635
+ },
636
+ },
637
+ required: ['page_id_or_slug'],
638
+ },
639
+ handler: async (args: Record<string, any>, ctx: ToolContext) => {
640
+ const profileId = ctx.profileId;
641
+ const target = String(args.page_id_or_slug ?? args.id ?? args.slug ?? '').trim();
642
+ if (!target) {
643
+ throw new Error('Missing required parameter: page_id_or_slug');
644
+ }
645
+
646
+ const rawPub = args.published !== undefined ? args.published : args.publish;
647
+ const publishState = typeof rawPub === 'boolean' ? rawPub : true;
648
+ const now = Math.floor(Date.now() / 1000);
649
+
650
+ let res;
651
+ try {
652
+ res = await execute(
653
+ `UPDATE pages
654
+ SET published = ?, updated_at = ?, updated_by = ?
655
+ WHERE profile_id = ? AND (id = ? OR slug = ?)`,
656
+ [publishState ? 1 : 0, now, 'agent', profileId, target, target]
657
+ );
658
+ } catch (err: any) {
659
+ if (String(err?.message || err).includes('no column named updated_by')) {
660
+ res = await execute(
661
+ `UPDATE pages
662
+ SET published = ?, updated_at = ?
663
+ WHERE profile_id = ? AND (id = ? OR slug = ?)`,
664
+ [publishState ? 1 : 0, now, profileId, target, target]
665
+ );
666
+ } else {
667
+ throw err;
668
+ }
669
+ }
670
+
671
+ if (res.rowsAffected === 0) {
672
+ throw new Error(`Page with id or slug '${target}' not found`);
673
+ }
674
+
675
+ return {
676
+ success: true,
677
+ target,
678
+ published: publishState,
679
+ message: `Page '${target}' is now ${publishState ? 'published' : 'draft'}`,
680
+ };
681
+ },
682
+ },
683
+ {
684
+ name: 'page_list',
685
+ domain: 'pages',
686
+ description: 'List all website pages, URLs, slugs, and publication statuses for the profile.',
687
+ inputSchema: {
688
+ type: 'object',
689
+ properties: {
690
+ published_only: { type: 'boolean', description: 'Filter to only show published pages, optional' },
691
+ },
692
+ },
693
+ handler: async (args: Record<string, any>, ctx: ToolContext) => {
694
+ const profileId = ctx.profileId;
695
+ let sql = 'SELECT id, title, slug, excerpt, published, sections, updated_at FROM pages WHERE profile_id = ?';
696
+ if (args.published_only) {
697
+ sql += ' AND published = 1';
698
+ }
699
+ sql += ' ORDER BY updated_at DESC LIMIT 50';
700
+
701
+ const rows = await query(sql, [profileId]);
702
+ return {
703
+ total: rows.length,
704
+ pages: rows.map((r: any) => {
705
+ let sectionCount = 0;
706
+ try {
707
+ const parsed = JSON.parse(r.sections || '[]');
708
+ if (Array.isArray(parsed)) sectionCount = parsed.length;
709
+ } catch {}
710
+ return {
711
+ id: r.id,
712
+ title: r.title,
713
+ slug: r.slug,
714
+ excerpt: r.excerpt ?? null,
715
+ published: Number(r.published || 0) !== 0,
716
+ section_count: sectionCount,
717
+ updated_at: r.updated_at,
718
+ };
719
+ }),
720
+ };
721
+ },
722
+ },
723
+ {
724
+ name: 'component_create',
725
+ domain: 'pages',
726
+ description:
727
+ 'Create a bespoke custom HTML/CSS/JS section component saved in user_components. To make it editable in the Visual Builder, every text element must have `contenteditable="true"` and `data-field="fieldName"`, and buttons/images should have `data-element-type="button|image|link"`. Include `schema` with field types (\'text\', \'textarea\', \'url\', \'color\', \'image\') for full editing in the Section Editor slideover.',
728
+ inputSchema: {
729
+ type: 'object',
730
+ properties: {
731
+ name: { type: 'string', description: "Component name (e.g. 'ROI Profit Calculator', 'Interactive Timeline', 'Hero Banner')" },
732
+ html: {
733
+ type: 'string',
734
+ description:
735
+ 'Complete HTML markup. MUST include `contenteditable="true"` and `data-field="..."` on text elements, and `data-element-type="..."` on interactive elements so they can be edited inline in the Visual Builder.',
736
+ },
737
+ css: { type: 'string', description: 'Scoped CSS styles for the component (e.g. `.comp-name { ... }`), optional' },
738
+ js: { type: 'string', description: 'Client-side JavaScript interaction logic, optional' },
739
+ ts: { type: 'string', description: 'TypeScript / TSX component source if maintaining a Qwik or React component definition, optional' },
740
+ schema: {
741
+ type: 'array',
742
+ description:
743
+ "Form fields for the Section Editor slideover. REQUIRED for full field editing. Array of objects: [{ name: 'title', label: 'Headline', type: 'text' }, { name: 'primaryBtnUrl', label: 'Button URL', type: 'url' }, { name: 'bgColor', label: 'Background Color', type: 'color' }, { name: 'textColor', label: 'Text Color', type: 'color' }]. Supported types: 'text', 'textarea', 'color', 'url', 'image', 'select'.",
744
+ items: {
745
+ type: 'object',
746
+ properties: {
747
+ name: { type: 'string' },
748
+ label: { type: 'string' },
749
+ type: { type: 'string', enum: ['text', 'textarea', 'color', 'url', 'image', 'select', 'boolean'] },
750
+ options: { type: 'array', items: { type: 'string' } },
751
+ },
752
+ required: ['name', 'label', 'type'],
753
+ },
754
+ },
755
+ collection: { type: 'string', description: "Category or collection name (e.g. 'Hero', 'Marketing', 'Widgets', 'Custom'), default 'Custom'" },
756
+ },
757
+ required: ['name', 'html'],
758
+ },
759
+ handler: async (args: Record<string, any>, ctx: ToolContext) => {
760
+ const profileId = ctx.profileId;
761
+ const name = String(args.name || '').trim();
762
+ if (!name) throw new Error('Parameter name cannot be empty');
763
+
764
+ const html = String(args.html || '').trim();
765
+ if (!html) throw new Error('Parameter html cannot be empty');
766
+
767
+ const css = typeof args.css === 'string' ? args.css : '';
768
+ const js = typeof args.js === 'string' ? args.js : '';
769
+ const ts = typeof args.ts === 'string' ? args.ts : '';
770
+ const rawCollection = typeof args.collection === 'string' ? args.collection.trim() : '';
771
+ const rawType = typeof args.type === 'string' ? args.type.trim() : '';
772
+
773
+ let collection = 'Custom';
774
+ let compType = 'custom';
775
+
776
+ if (rawCollection) {
777
+ const colMap: Record<string, string> = {
778
+ hero: 'Hero',
779
+ navigation: 'Navigation',
780
+ nav: 'Navigation',
781
+ header: 'Navigation',
782
+ content: 'Content',
783
+ conversion: 'Conversion',
784
+ pricing: 'Conversion',
785
+ commercial: 'Conversion',
786
+ 'social proof': 'Social Proof',
787
+ social_proof: 'Social Proof',
788
+ testimonials: 'Social Proof',
789
+ showcase: 'Showcase',
790
+ footer: 'Footer',
791
+ education: 'Education',
792
+ curriculum: 'Education',
793
+ };
794
+ collection = colMap[rawCollection.toLowerCase()] ?? rawCollection;
795
+ compType = rawType || collection.toLowerCase();
796
+ } else {
797
+ const nameLower = name.toLowerCase();
798
+ const typeLower = rawType.toLowerCase();
799
+ if (nameLower.includes('hero') || typeLower.includes('hero')) {
800
+ collection = 'Hero';
801
+ compType = 'hero';
802
+ } else if (nameLower.includes('nav') || nameLower.includes('header') || typeLower.includes('nav')) {
803
+ collection = 'Navigation';
804
+ compType = 'sc_navbar';
805
+ } else if (nameLower.includes('footer') || typeLower.includes('footer')) {
806
+ collection = 'Footer';
807
+ compType = 'sc_footer';
808
+ } else if (nameLower.includes('price') || nameLower.includes('pricing') || typeLower.includes('pricing')) {
809
+ collection = 'Conversion';
810
+ compType = 'pricing';
811
+ } else if (nameLower.includes('testimonial') || nameLower.includes('review')) {
812
+ collection = 'Social Proof';
813
+ compType = 'testimonials';
814
+ } else if (nameLower.includes('faq') || nameLower.includes('question')) {
815
+ collection = 'Content';
816
+ compType = 'faq';
817
+ } else if (nameLower.includes('showcase') || nameLower.includes('feature')) {
818
+ collection = 'Showcase';
819
+ compType = 'features';
820
+ }
821
+ }
822
+
823
+ const isGlobal = args.is_global === true || Number(args.is_global) === 1 ? 1 : 0;
824
+ const compId = generateId('comp');
825
+ const now = Math.floor(Date.now() / 1000);
826
+ const schemaJson = extractOrNormalizeSchema(args, html);
827
+
828
+ try {
829
+ await execute(
830
+ `INSERT INTO user_components
831
+ (id, profile_id, name, thumbnail_url, html, css, js, ts, schema, source, type, collection, is_primary, is_global, created_at)
832
+ VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?, 'agent', ?, ?, 0, ?, ?)`,
833
+ [compId, profileId, name, html, css, js, ts, schemaJson, compType, collection, isGlobal, now]
834
+ );
835
+ } catch (err: any) {
836
+ const msg = String(err?.message || err);
837
+ if (msg.includes('no column named is_global')) {
838
+ try {
839
+ await execute('ALTER TABLE user_components ADD COLUMN is_global INTEGER DEFAULT 0', []);
840
+ } catch {}
841
+ await execute(
842
+ `INSERT INTO user_components
843
+ (id, profile_id, name, thumbnail_url, html, css, js, ts, schema, source, type, collection, is_primary, is_global, created_at)
844
+ VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?, 'agent', ?, ?, 0, ?, ?)`,
845
+ [compId, profileId, name, html, css, js, ts, schemaJson, compType, collection, isGlobal, now]
846
+ );
847
+ } else if (msg.includes('no column named ts')) {
848
+ try {
849
+ await execute('ALTER TABLE user_components ADD COLUMN ts TEXT', []);
850
+ } catch {}
851
+ await execute(
852
+ `INSERT INTO user_components
853
+ (id, profile_id, name, thumbnail_url, html, css, js, schema, source, type, collection, is_primary, created_at)
854
+ VALUES (?, ?, ?, NULL, ?, ?, ?, ?, 'agent', ?, ?, 0, ?)`,
855
+ [compId, profileId, name, html, css, js, schemaJson, compType, collection, now]
856
+ );
857
+ } else {
858
+ throw err;
859
+ }
860
+ }
861
+
862
+ return {
863
+ success: true,
864
+ component: {
865
+ id: compId,
866
+ name,
867
+ collection,
868
+ is_global: isGlobal,
869
+ section_reference: {
870
+ type: 'custom',
871
+ component_id: compId,
872
+ },
873
+ },
874
+ message: `Custom component '${name}' created successfully with ID '${compId}'. Add to a page with {'type': 'custom', 'component_id': '${compId}'}.`,
875
+ };
876
+ },
877
+ },
878
+ {
879
+ name: 'component_list',
880
+ domain: 'pages',
881
+ description: 'List all custom components stored in user_components for the profile.',
882
+ inputSchema: {
883
+ type: 'object',
884
+ properties: {
885
+ collection: { type: 'string', description: 'Optional collection filter, optional' },
886
+ },
887
+ },
888
+ handler: async (args: Record<string, any>, ctx: ToolContext) => {
889
+ const profileId = ctx.profileId;
890
+ const collectionFilter = typeof args.collection === 'string' ? args.collection.trim() : '';
891
+
892
+ let rows: any[] = [];
893
+ try {
894
+ const sql = collectionFilter
895
+ ? 'SELECT id, name, collection, type, source, COALESCE(is_global, 0) AS is_global, created_at FROM user_components WHERE profile_id = ? AND collection = ? ORDER BY created_at DESC LIMIT 50'
896
+ : 'SELECT id, name, collection, type, source, COALESCE(is_global, 0) AS is_global, created_at FROM user_components WHERE profile_id = ? ORDER BY created_at DESC LIMIT 50';
897
+ rows = await query(sql, collectionFilter ? [profileId, collectionFilter] : [profileId]);
898
+ } catch {
899
+ const fbSql = collectionFilter
900
+ ? 'SELECT id, name, collection, type, source, 0 AS is_global, created_at FROM user_components WHERE profile_id = ? AND collection = ? ORDER BY created_at DESC LIMIT 50'
901
+ : 'SELECT id, name, collection, type, source, 0 AS is_global, created_at FROM user_components WHERE profile_id = ? ORDER BY created_at DESC LIMIT 50';
902
+ rows = await query(fbSql, collectionFilter ? [profileId, collectionFilter] : [profileId]);
903
+ }
904
+
905
+ return {
906
+ total: rows.length,
907
+ components: rows.map((r: any) => ({
908
+ id: r.id,
909
+ name: r.name,
910
+ collection: r.collection || 'Custom',
911
+ type: r.type || 'custom',
912
+ source: r.source || 'manual',
913
+ is_global: Number(r.is_global || 0),
914
+ created_at: r.created_at,
915
+ })),
916
+ };
917
+ },
918
+ },
919
+ {
920
+ name: 'component_get',
921
+ domain: 'pages',
922
+ description: 'Fetch a custom component by its ID with full HTML, CSS, and JS source.',
923
+ inputSchema: {
924
+ type: 'object',
925
+ properties: {
926
+ component_id: { type: 'string', description: "Component ID (e.g. 'comp_xyz')" },
927
+ },
928
+ required: ['component_id'],
929
+ },
930
+ handler: async (args: Record<string, any>, ctx: ToolContext) => {
931
+ const profileId = ctx.profileId;
932
+ const componentId = String(args.component_id ?? args.id ?? '').trim();
933
+ if (!componentId) {
934
+ throw new Error('Missing required parameter: component_id');
935
+ }
936
+
937
+ let rows: any[] = [];
938
+ try {
939
+ rows = await query(
940
+ 'SELECT id, name, html, css, js, schema, collection, type, source, COALESCE(is_global, 0) AS is_global, created_at FROM user_components WHERE profile_id = ? AND id = ? LIMIT 1',
941
+ [profileId, componentId]
942
+ );
943
+ } catch {
944
+ rows = await query(
945
+ 'SELECT id, name, html, css, js, schema, collection, type, source, 0 AS is_global, created_at FROM user_components WHERE profile_id = ? AND id = ? LIMIT 1',
946
+ [profileId, componentId]
947
+ );
948
+ }
949
+
950
+ if (rows.length === 0) {
951
+ throw new Error(`Custom component with ID '${componentId}' not found`);
952
+ }
953
+
954
+ const c = rows[0];
955
+ return {
956
+ component: {
957
+ id: c.id,
958
+ name: c.name,
959
+ html: c.html || '',
960
+ css: c.css || '',
961
+ js: c.js || '',
962
+ schema: c.schema || '[]',
963
+ collection: c.collection || 'Custom',
964
+ type: c.type || 'custom',
965
+ source: c.source || 'manual',
966
+ is_global: Number(c.is_global || 0),
967
+ created_at: c.created_at,
968
+ },
969
+ };
970
+ },
971
+ },
972
+ {
973
+ name: 'page_get_section_schema',
974
+ domain: 'pages',
975
+ description:
976
+ "Inspect JSON schema, data fields, and reference HTML/CSS blueprints for native sections. MANDATORY before designing a custom component: inspect blueprints from the MATCHING native category ('category: \"Content\"' for FAQs/text, 'category: \"Conversion\"' for pricing/CTA, 'category: \"Hero\"' for hero headers, 'category: \"Features\"' for feature tabs/grids, 'category: \"Showcase\"' for split previews, 'category: \"Social Proof\"' for testimonials). Also supports specific 'section_types' or 'theme'.",
977
+ inputSchema: {
978
+ type: 'object',
979
+ properties: {
980
+ category: {
981
+ type: 'string',
982
+ description:
983
+ "PRIMARY FILTER: Section category to inspect blueprints for ('Hero', 'Features', 'Conversion', 'Content', 'Social Proof', 'Showcase', 'Navigation', 'Footer', or 'list' to see all categories). Returns all native sections in that category.",
984
+ },
985
+ section_type: {
986
+ type: 'string',
987
+ description: "Specific section type (e.g. 'sc_hero', 'pricing', 'faq'), comma-separated types, or theme discovery ('themes').",
988
+ },
989
+ section_types: {
990
+ type: 'array',
991
+ items: { type: 'string' },
992
+ description: "Array of specific section types to inspect simultaneously (e.g. ['sc_hero', 'hero_section']).",
993
+ },
994
+ theme: {
995
+ type: 'string',
996
+ description: "Theme name filter (e.g. 'superconsole', 'classic', 'nike', 'tesla', or 'list' to discover all themes).",
997
+ },
998
+ limit: {
999
+ type: 'number',
1000
+ description: 'Max number of sections to return (e.g. 5). Defaults to returning all matching sections.',
1001
+ },
1002
+ },
1003
+ },
1004
+ handler: async (args: Record<string, any>, _ctx: ToolContext) => {
1005
+ const catalog = getSectionsCatalog();
1006
+ const sections: any[] = Array.isArray(catalog.sections) ? catalog.sections : [];
1007
+ const themesList: any[] = Array.isArray(catalog.themes) ? catalog.themes : [];
1008
+
1009
+ const requestedTypes: string[] = [];
1010
+ const arrInput = args.section_types ?? args.types;
1011
+ if (Array.isArray(arrInput)) {
1012
+ for (const v of arrInput) {
1013
+ if (typeof v === 'string') {
1014
+ const t = v.trim().toLowerCase();
1015
+ if (t && !requestedTypes.includes(t)) requestedTypes.push(t);
1016
+ }
1017
+ }
1018
+ } else if (typeof args.section_type === 'string') {
1019
+ for (const part of args.section_type.split(',')) {
1020
+ const t = part.trim().toLowerCase();
1021
+ if (t && !requestedTypes.includes(t)) requestedTypes.push(t);
1022
+ }
1023
+ }
1024
+
1025
+ const themeFilter = String(args.theme ?? '').trim().toLowerCase();
1026
+ const categoryFilter = String(args.category ?? '').trim().toLowerCase();
1027
+ const limit = typeof args.limit === 'number' && args.limit >= 0 ? Math.floor(args.limit) : undefined;
1028
+
1029
+ // 0. Themes Catalog Discovery
1030
+ if (requestedTypes.includes('themes') || themeFilter === 'list' || themeFilter === 'all') {
1031
+ return {
1032
+ available_themes: themesList,
1033
+ usage:
1034
+ "To fetch all section blocks tailored to a specific theme, call page_get_section_schema with theme (e.g. 'superconsole', 'classic', 'nike', 'tesla').",
1035
+ };
1036
+ }
1037
+
1038
+ // 1. Explicit Category Filter (PRIMARY)
1039
+ if (categoryFilter) {
1040
+ if (categoryFilter === 'list' || categoryFilter === 'all') {
1041
+ return {
1042
+ categories: [
1043
+ { name: 'Hero', description: 'Hero banners, main headlines, intro sections', sections: ['sc_hero', 'hero_section'] },
1044
+ { name: 'Navigation', description: 'Top navigation header with brand and links', sections: ['sc_navbar'] },
1045
+ { name: 'Features', description: 'Feature highlights, interactive tabs, capability grids', sections: ['sc_use_cases'] },
1046
+ { name: 'Showcase', description: 'Split product previews, architecture, live terminals', sections: ['sc_workspace', 'sc_under_the_hood'] },
1047
+ { name: 'Conversion', description: 'Pricing tiers, subscription plans, CTA banners', sections: ['pricing', 'cta_section'] },
1048
+ { name: 'Content', description: 'FAQ accordions, about company, rich text articles', sections: ['faq', 'about_section', 'text'] },
1049
+ { name: 'Social Proof', description: 'Customer testimonials, reviews, trust badges', sections: ['testimonials'] },
1050
+ { name: 'Footer', description: 'Site footer, copyright, legal links, status indicator', sections: ['sc_footer'] },
1051
+ { name: 'Education', description: 'Curriculum, course modules, lesson plans', sections: ['curriculum'] },
1052
+ ],
1053
+ guidance:
1054
+ "MANDATORY: When designing any custom component, first inspect the matching category via page_get_section_schema(category: '<Category>') to learn layout, typography, CSS variables, and data-fields.",
1055
+ };
1056
+ }
1057
+
1058
+ const matchedCategories = resolveCanonicalCategories(categoryFilter);
1059
+ let matches = sections
1060
+ .filter((sec) => {
1061
+ const secCat = String(sec.category ?? '');
1062
+ if (matchedCategories.length > 0) {
1063
+ return matchedCategories.some((c) => c.toLowerCase() === secCat.toLowerCase());
1064
+ }
1065
+ return (
1066
+ secCat.toLowerCase().includes(categoryFilter) ||
1067
+ String(sec.type ?? '').toLowerCase() === categoryFilter
1068
+ );
1069
+ })
1070
+ .map(mapFullSection);
1071
+
1072
+ if (limit !== undefined) matches = matches.slice(0, limit);
1073
+
1074
+ return {
1075
+ category: matchedCategories[0] ?? categoryFilter,
1076
+ filter: `category: ${categoryFilter}`,
1077
+ count: matches.length,
1078
+ sections: matches,
1079
+ guidance:
1080
+ 'MANDATORY: Learn layout structure, typography scale, responsive breakpoints, and CSS variables from these matching category blueprints before building custom components.',
1081
+ };
1082
+ }
1083
+
1084
+ // 2. Multiple Specific Section Types Requested
1085
+ if (requestedTypes.length > 1) {
1086
+ let matches: any[] = [];
1087
+ for (const req of requestedTypes) {
1088
+ const found = sections.find((sec) => {
1089
+ const matchesType = String(sec.type ?? '').toLowerCase() === req;
1090
+ const matchesAlias =
1091
+ Array.isArray(sec.aliases) &&
1092
+ sec.aliases.some((a: any) => String(a).toLowerCase() === req);
1093
+ return matchesType || matchesAlias;
1094
+ });
1095
+ if (found) matches.push(mapFullSection(found));
1096
+ }
1097
+
1098
+ if (limit !== undefined) matches = matches.slice(0, limit);
1099
+
1100
+ return {
1101
+ requested_types: requestedTypes,
1102
+ count: matches.length,
1103
+ sections: matches,
1104
+ guidance: 'Compare the reference blueprints to craft your bespoke custom component.',
1105
+ };
1106
+ }
1107
+
1108
+ // 3. Single Specific Section Type Requested
1109
+ if (requestedTypes.length === 1) {
1110
+ const singleType = requestedTypes[0];
1111
+ if (singleType !== 'list' && singleType !== 'all') {
1112
+ const canonicalCats = resolveCanonicalCategories(singleType);
1113
+ const isCategoryWord = [
1114
+ 'hero',
1115
+ 'content',
1116
+ 'features',
1117
+ 'showcase',
1118
+ 'conversion',
1119
+ 'commercial',
1120
+ 'social proof',
1121
+ 'social_proof',
1122
+ 'footer',
1123
+ 'navigation',
1124
+ 'education',
1125
+ ].includes(singleType);
1126
+
1127
+ if (isCategoryWord && canonicalCats.length > 0) {
1128
+ let categoryMatches = sections
1129
+ .filter((sec) =>
1130
+ canonicalCats.some(
1131
+ (c) => c.toLowerCase() === String(sec.category ?? '').toLowerCase()
1132
+ )
1133
+ )
1134
+ .map(mapFullSection);
1135
+
1136
+ if (categoryMatches.length > 0) {
1137
+ if (limit !== undefined) categoryMatches = categoryMatches.slice(0, limit);
1138
+ return {
1139
+ query: singleType,
1140
+ category: canonicalCats[0],
1141
+ category_matches: categoryMatches.length,
1142
+ sections: categoryMatches,
1143
+ guidance: "Compare reference blueprints and 'when_to_use' to choose or craft the best section.",
1144
+ };
1145
+ }
1146
+ }
1147
+
1148
+ const exactMatch = sections.find((sec) => {
1149
+ const matchesType = String(sec.type ?? '').toLowerCase() === singleType;
1150
+ const matchesAlias =
1151
+ Array.isArray(sec.aliases) &&
1152
+ sec.aliases.some((a: any) => String(a).toLowerCase() === singleType);
1153
+ return matchesType || matchesAlias;
1154
+ });
1155
+
1156
+ if (exactMatch) {
1157
+ const secCat = exactMatch.category || 'Custom';
1158
+ return {
1159
+ ...mapFullSection(exactMatch),
1160
+ rules: exactMatch.rules ?? null,
1161
+ category_guidance: `To inspect all native blueprints in the '${secCat}' category, call page_get_section_schema(category: '${secCat}')`,
1162
+ };
1163
+ }
1164
+
1165
+ let subMatches = sections
1166
+ .filter((sec) => String(sec.category ?? '').toLowerCase().includes(singleType))
1167
+ .map(mapFullSection);
1168
+ if (subMatches.length > 0) {
1169
+ if (limit !== undefined) subMatches = subMatches.slice(0, limit);
1170
+ return {
1171
+ query: singleType,
1172
+ category_matches: subMatches.length,
1173
+ sections: subMatches,
1174
+ guidance: "Compare reference blueprints and 'when_to_use' to choose or craft the best section.",
1175
+ };
1176
+ }
1177
+ }
1178
+ }
1179
+
1180
+ // 4. Explicit Theme Filter
1181
+ if (themeFilter) {
1182
+ let matches = sections
1183
+ .filter((sec) => String(sec.theme ?? '').toLowerCase() === themeFilter)
1184
+ .map(mapFullSection);
1185
+ if (limit !== undefined) matches = matches.slice(0, limit);
1186
+
1187
+ return {
1188
+ filter: `theme: ${themeFilter}`,
1189
+ count: matches.length,
1190
+ sections: matches,
1191
+ guidance: 'Assemble landing page using sections from this theme to ensure unified visual aesthetics.',
1192
+ };
1193
+ }
1194
+
1195
+ // 5. Default: Lightweight catalog list
1196
+ const effectiveLimit = limit ?? 12;
1197
+ const list = sections.slice(0, effectiveLimit).map((sec) => ({
1198
+ type: sec.type ?? null,
1199
+ name: sec.name ?? null,
1200
+ theme: sec.theme ?? null,
1201
+ category: sec.category ?? null,
1202
+ description: sec.description ?? null,
1203
+ ai_summary: sec.ai_summary ?? null,
1204
+ when_to_use: sec.when_to_use ?? null,
1205
+ }));
1206
+
1207
+ return {
1208
+ catalog_summary: 'BusinessKit native visual sections catalog (single source of truth from pagex).',
1209
+ returned_sections: list.length,
1210
+ total_available: sections.length,
1211
+ available_sections: list,
1212
+ usage:
1213
+ "To inspect the exact code blueprint, schema, and HTML/CSS for specific sections, call page_get_section_schema with section_type (e.g. 'sc_hero'), section_types (e.g. ['sc_hero', 'hero_section']), or category (e.g. 'hero').",
1214
+ };
1215
+ },
1216
+ },
1217
+ ];