@businesskit/agent 1.0.5 → 1.0.7
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/.superconsole-plugin/plugin.json +61 -31
- package/AGENTS.md +20 -9
- package/README.md +101 -113
- package/bin/businesskit.js +41 -8
- package/commands/brief.md +12 -0
- package/commands/chase.md +12 -0
- package/commands/create-page.md +43 -15
- package/commands/crm.md +13 -0
- package/commands/followups.md +13 -0
- package/commands/pipeline.md +13 -0
- package/commands/update-agent.md +33 -0
- package/commands/update-content.md +1 -0
- package/commands/update-page.md +3 -2
- package/commands/write-blog.md +4 -0
- package/commands/write-docs.md +6 -0
- package/commands/write-guide.md +5 -0
- package/commands/write-newsletter.md +4 -0
- package/dist/server.js +4099 -0
- package/mcp_config.json +6 -2
- package/package.json +23 -5
- package/scripts/setup.sh +70 -35
- package/scripts/setup.ts +58 -21
- package/scripts/update.sh +56 -0
- package/server.json +3 -3
- package/skills/README.md +3 -2
- package/skills/cms/SKILL.md +111 -0
- package/skills/cms/references/cms-hubs.md +84 -0
- package/skills/cms/references/html-blocks.md +177 -0
- package/skills/crm/SKILL.md +15 -29
- package/skills/docs/SKILL.md +65 -0
- package/skills/docs/references/how-to.md +155 -0
- package/skills/pages/SKILL.md +62 -17
- package/skills/pages/references/sections-catalog.json +377 -144
- package/skills/social/SKILL.md +83 -210
- package/skills/social/evals/evals.json +66 -0
- package/skills/social/evals/rubric.md +26 -0
- package/skills/social/examples/repurposing-blog-to-social.md +93 -0
- package/skills/social/examples/weekly-content-calendar.md +30 -0
- package/skills/social/linkedin/SKILL.md +107 -0
- package/skills/social/linkedin/evals/evals.json +106 -0
- package/skills/social/linkedin/evals/rubric.md +28 -0
- package/skills/social/linkedin/examples/gasp-weekly-sprint.md +24 -0
- package/skills/social/linkedin/examples/growth-posts-by-format.md +140 -0
- package/skills/social/linkedin/references/gasp-funnel-and-calibration.md +90 -0
- package/skills/social/linkedin/references/six-growth-formats.md +114 -0
- package/skills/social/references/platforms.md +76 -0
- package/skills/social/references/post-templates.md +105 -0
- package/skills/social/references/reverse-engineering.md +62 -0
- package/src/data/sections-catalog.json +950 -0
- package/src/db.ts +170 -0
- package/src/server.ts +75 -0
- package/src/tools/content.ts +326 -0
- package/src/tools/crm.ts +1416 -0
- package/src/tools/domains.ts +89 -0
- package/src/tools/inbox.ts +270 -0
- package/src/tools/index.ts +116 -0
- package/src/tools/pages.ts +1217 -0
- package/src/tools/shop.ts +771 -0
- package/src/tools/system.ts +94 -0
- package/src/tools/types.ts +17 -0
- package/skills/docs-cms/SKILL.md +0 -53
- package/skills/docs-cms/references/how-to.md +0 -383
package/dist/server.js
ADDED
|
@@ -0,0 +1,4099 @@
|
|
|
1
|
+
// src/server.ts
|
|
2
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
import {
|
|
5
|
+
CallToolRequestSchema,
|
|
6
|
+
ListToolsRequestSchema
|
|
7
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
8
|
+
|
|
9
|
+
// src/db.ts
|
|
10
|
+
import { createClient } from "@libsql/client";
|
|
11
|
+
import dotenv from "dotenv";
|
|
12
|
+
import { randomUUID } from "crypto";
|
|
13
|
+
dotenv.config();
|
|
14
|
+
var clientInstance = null;
|
|
15
|
+
var currentProfileId = process.env.PROFILE_ID || process.env.BK_PROFILE_ID || "";
|
|
16
|
+
var profileResolved = false;
|
|
17
|
+
function cleanVal(v) {
|
|
18
|
+
if (!v) return "";
|
|
19
|
+
const trimmed = v.trim();
|
|
20
|
+
if (trimmed.includes("your-db") || trimmed.includes("your-database") || trimmed.includes("your-token") || trimmed.includes("your-turso-auth-token")) {
|
|
21
|
+
return "";
|
|
22
|
+
}
|
|
23
|
+
return trimmed;
|
|
24
|
+
}
|
|
25
|
+
function getTursoConfig() {
|
|
26
|
+
const url = cleanVal(process.env.TURSO_DATABASE_URL) || cleanVal(process.env.TURSO_URL) || cleanVal(process.env.BK_TURSO_URL) || cleanVal(process.env.DATABASE_URL);
|
|
27
|
+
const writeToken = cleanVal(process.env.TURSO_AUTH_TOKEN) || cleanVal(process.env.TURSO_TOKEN) || cleanVal(process.env.BK_TURSO_TOKEN) || cleanVal(process.env.AUTH_TOKEN);
|
|
28
|
+
const roToken = cleanVal(process.env.TURSO_READ_ONLY_TOKEN) || cleanVal(process.env.TURSO_RO_TOKEN);
|
|
29
|
+
const isReadOnly = Boolean(
|
|
30
|
+
!writeToken && roToken || process.env.READ_ONLY === "true" || process.env.TURSO_READONLY === "true"
|
|
31
|
+
);
|
|
32
|
+
const token = writeToken || roToken;
|
|
33
|
+
if (!url || !token) {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
let normalizedUrl = url;
|
|
37
|
+
if (normalizedUrl.startsWith("turso://")) {
|
|
38
|
+
normalizedUrl = "https://" + normalizedUrl.slice(8);
|
|
39
|
+
}
|
|
40
|
+
return { url: normalizedUrl, token, readOnly: isReadOnly };
|
|
41
|
+
}
|
|
42
|
+
function isDbConfigured() {
|
|
43
|
+
return getTursoConfig() !== null;
|
|
44
|
+
}
|
|
45
|
+
function isDbReadOnly() {
|
|
46
|
+
const cfg = getTursoConfig();
|
|
47
|
+
return cfg ? cfg.readOnly : false;
|
|
48
|
+
}
|
|
49
|
+
function getDbClient() {
|
|
50
|
+
if (clientInstance) {
|
|
51
|
+
return clientInstance;
|
|
52
|
+
}
|
|
53
|
+
const config = getTursoConfig();
|
|
54
|
+
if (!config) {
|
|
55
|
+
throw new Error(
|
|
56
|
+
"Turso database credentials not configured. Please define TURSO_DATABASE_URL and TURSO_AUTH_TOKEN in your .env file or environment variables."
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
clientInstance = createClient({
|
|
60
|
+
url: config.url,
|
|
61
|
+
authToken: config.token
|
|
62
|
+
});
|
|
63
|
+
return clientInstance;
|
|
64
|
+
}
|
|
65
|
+
async function getActiveProfileId() {
|
|
66
|
+
if (currentProfileId) {
|
|
67
|
+
return currentProfileId;
|
|
68
|
+
}
|
|
69
|
+
if (profileResolved || !isDbConfigured()) {
|
|
70
|
+
currentProfileId = "default";
|
|
71
|
+
return currentProfileId;
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
profileResolved = true;
|
|
75
|
+
const client = getDbClient();
|
|
76
|
+
const result = await client.execute("SELECT id FROM profiles LIMIT 1");
|
|
77
|
+
if (result.rows.length > 0 && result.rows[0].id) {
|
|
78
|
+
currentProfileId = String(result.rows[0].id);
|
|
79
|
+
return currentProfileId;
|
|
80
|
+
}
|
|
81
|
+
const shopResult = await client.execute("SELECT profile_id FROM shop_items LIMIT 1");
|
|
82
|
+
if (shopResult.rows.length > 0 && shopResult.rows[0].profile_id) {
|
|
83
|
+
currentProfileId = String(shopResult.rows[0].profile_id);
|
|
84
|
+
return currentProfileId;
|
|
85
|
+
}
|
|
86
|
+
} catch (err) {
|
|
87
|
+
console.error('[DB] Profile lookup error (defaulting to "default"):', err?.message || err);
|
|
88
|
+
}
|
|
89
|
+
currentProfileId = "default";
|
|
90
|
+
return currentProfileId;
|
|
91
|
+
}
|
|
92
|
+
function setActiveProfileId(id) {
|
|
93
|
+
currentProfileId = id.trim();
|
|
94
|
+
profileResolved = true;
|
|
95
|
+
}
|
|
96
|
+
async function query(sql, args = []) {
|
|
97
|
+
const client = getDbClient();
|
|
98
|
+
const res = await client.execute({ sql, args });
|
|
99
|
+
return res.rows;
|
|
100
|
+
}
|
|
101
|
+
async function execute(sql, args = []) {
|
|
102
|
+
if (isDbReadOnly()) {
|
|
103
|
+
throw new Error(
|
|
104
|
+
"Database is connected in read-only mode (read-only token). Write operations (INSERT, UPDATE, DELETE) are not permitted."
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
const client = getDbClient();
|
|
108
|
+
const res = await client.execute({ sql, args });
|
|
109
|
+
return {
|
|
110
|
+
rowsAffected: res.rowsAffected,
|
|
111
|
+
lastInsertRowid: res.lastInsertRowid
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function generateId(prefix) {
|
|
115
|
+
const cleanPrefix = prefix.endsWith("_") ? prefix : `${prefix}_`;
|
|
116
|
+
return `${cleanPrefix}${randomUUID().replace(/-/g, "").slice(0, 12)}`;
|
|
117
|
+
}
|
|
118
|
+
function generateSku() {
|
|
119
|
+
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
120
|
+
let sku = "";
|
|
121
|
+
for (let i = 0; i < 10; i++) {
|
|
122
|
+
sku += chars.charAt(Math.floor(Math.random() * chars.length));
|
|
123
|
+
}
|
|
124
|
+
return sku;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// src/tools/shop.ts
|
|
128
|
+
var shopTools = [
|
|
129
|
+
{
|
|
130
|
+
name: "inventory_receive_purchase_invoice",
|
|
131
|
+
domain: "shop",
|
|
132
|
+
description: "Receive inventory items from a vendor purchase invoice, vendor bill, or restock shipment. Records a formal Goods Receipt / Purchase document (doc_type='goods_receipt'), auto-creates missing products in shop_items with clean 10-char alphanumeric SKUs (e.g. '7PKFJ7I5ND'), updates item cost prices, selling prices / markup % (shop_items.price), MRP (default_mrp), taxes, packaging, and logs stock ledger movements with movement_type 'purchase'.",
|
|
133
|
+
inputSchema: {
|
|
134
|
+
type: "object",
|
|
135
|
+
properties: {
|
|
136
|
+
vendor_name: {
|
|
137
|
+
type: "string",
|
|
138
|
+
description: "Supplier / Vendor company name (e.g. 'Sun Pharma Healthcare', 'Apple Inc.')"
|
|
139
|
+
},
|
|
140
|
+
invoice_number: {
|
|
141
|
+
type: "string",
|
|
142
|
+
description: "Vendor's invoice or bill number (e.g. 'INV-MED-44021', 'INV-APL-2026-089')"
|
|
143
|
+
},
|
|
144
|
+
invoice_date: {
|
|
145
|
+
type: "string",
|
|
146
|
+
description: "Invoice date (e.g. '2026-09-11' or ISO date), optional."
|
|
147
|
+
},
|
|
148
|
+
location: {
|
|
149
|
+
type: "string",
|
|
150
|
+
description: "Warehouse / store name, optional (defaults to Main Warehouse)."
|
|
151
|
+
},
|
|
152
|
+
media_id: {
|
|
153
|
+
type: "string",
|
|
154
|
+
description: "Associated media/attachment ID from uploaded invoice document, optional."
|
|
155
|
+
},
|
|
156
|
+
default_markup_pct: {
|
|
157
|
+
type: "number",
|
|
158
|
+
description: "Default markup % applied to cost_price to compute selling price for shop_items.price (e.g. 20 for cost + 20%), optional."
|
|
159
|
+
},
|
|
160
|
+
grand_total: {
|
|
161
|
+
type: "number",
|
|
162
|
+
description: "Total final invoice payable amount (after discounts and taxes, e.g. 5091.84), optional."
|
|
163
|
+
},
|
|
164
|
+
subtotal: {
|
|
165
|
+
type: "number",
|
|
166
|
+
description: "Pre-tax/discount subtotal, optional."
|
|
167
|
+
},
|
|
168
|
+
payment_status: {
|
|
169
|
+
type: "string",
|
|
170
|
+
enum: ["paid", "due", "partial", "confirmed"],
|
|
171
|
+
description: "Payment status of the invoice, optional (defaults to 'confirmed' or 'paid' if paid)."
|
|
172
|
+
},
|
|
173
|
+
payment_method: {
|
|
174
|
+
type: "string",
|
|
175
|
+
description: "Payment method (e.g. 'cash', 'bank_transfer', 'upi', 'credit'), optional."
|
|
176
|
+
},
|
|
177
|
+
payment_terms: {
|
|
178
|
+
type: "string",
|
|
179
|
+
description: "Payment terms (e.g. 'Net 30', 'Net 15', 'Immediate', 'Due on Receipt'), optional."
|
|
180
|
+
},
|
|
181
|
+
line_items: {
|
|
182
|
+
type: "array",
|
|
183
|
+
items: {
|
|
184
|
+
type: "object",
|
|
185
|
+
properties: {
|
|
186
|
+
item: {
|
|
187
|
+
type: "string",
|
|
188
|
+
description: "Item SKU, ID, or product name (e.g. 'URISPAS TAB', 'Apple Mac Mini', '7PKFJ7I5ND')"
|
|
189
|
+
},
|
|
190
|
+
sku: {
|
|
191
|
+
type: "string",
|
|
192
|
+
description: "Explicit product SKU code if provided on bill, optional."
|
|
193
|
+
},
|
|
194
|
+
quantity: {
|
|
195
|
+
type: "number",
|
|
196
|
+
description: "Billed quantity received (e.g. 50, 10)"
|
|
197
|
+
},
|
|
198
|
+
free_qty: {
|
|
199
|
+
type: "number",
|
|
200
|
+
description: "Free scheme quantity (e.g. 5 for 'buy 50 get 5 free'), optional."
|
|
201
|
+
},
|
|
202
|
+
unit_cost: {
|
|
203
|
+
type: "number",
|
|
204
|
+
description: "Unit cost price before discount/tax (optional if cost_price given)."
|
|
205
|
+
},
|
|
206
|
+
cost_price: {
|
|
207
|
+
type: "number",
|
|
208
|
+
description: "Net unit purchase cost price after line discounts."
|
|
209
|
+
},
|
|
210
|
+
selling_price: {
|
|
211
|
+
type: "number",
|
|
212
|
+
description: "Selling price to update on shop_items.price (optional)."
|
|
213
|
+
},
|
|
214
|
+
price: {
|
|
215
|
+
type: "number",
|
|
216
|
+
description: "Alias for selling_price (optional)."
|
|
217
|
+
},
|
|
218
|
+
markup_pct: {
|
|
219
|
+
type: "number",
|
|
220
|
+
description: "Markup percentage on cost_price (optional)."
|
|
221
|
+
},
|
|
222
|
+
mrp: {
|
|
223
|
+
type: "number",
|
|
224
|
+
description: "Maximum Retail Price (default_mrp), optional."
|
|
225
|
+
},
|
|
226
|
+
tax_pct: {
|
|
227
|
+
type: "number",
|
|
228
|
+
description: "GST / Tax percentage (e.g. 12 for 12% GST), optional."
|
|
229
|
+
},
|
|
230
|
+
batch_number: {
|
|
231
|
+
type: "string",
|
|
232
|
+
description: "Batch / Lot number (e.g. 'B2401', optional."
|
|
233
|
+
},
|
|
234
|
+
expiry_date: {
|
|
235
|
+
type: "string",
|
|
236
|
+
description: "Expiry date string (e.g. '2026-12', '12/26'), optional."
|
|
237
|
+
}
|
|
238
|
+
},
|
|
239
|
+
required: ["item", "quantity"]
|
|
240
|
+
},
|
|
241
|
+
description: "List of items received on the purchase invoice"
|
|
242
|
+
},
|
|
243
|
+
notes: { type: "string", description: "Optional notes or comments." }
|
|
244
|
+
},
|
|
245
|
+
required: ["vendor_name", "line_items"]
|
|
246
|
+
},
|
|
247
|
+
handler: async (args, ctx) => {
|
|
248
|
+
const { vendor_name, line_items, invoice_number, location, default_markup_pct } = args;
|
|
249
|
+
const profileId = ctx.profileId;
|
|
250
|
+
let vendorId;
|
|
251
|
+
const existingVendors = await query(
|
|
252
|
+
"SELECT id FROM shop_vendors WHERE profile_id = ? AND (LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1",
|
|
253
|
+
[profileId, vendor_name.trim(), `%${vendor_name.trim()}%`]
|
|
254
|
+
);
|
|
255
|
+
if (existingVendors.length > 0) {
|
|
256
|
+
vendorId = existingVendors[0].id;
|
|
257
|
+
} else {
|
|
258
|
+
vendorId = generateId("vend");
|
|
259
|
+
await execute(
|
|
260
|
+
"INSERT INTO shop_vendors (id, profile_id, name, payment_terms, is_active) VALUES (?, ?, ?, ?, 1)",
|
|
261
|
+
[vendorId, profileId, vendor_name.trim(), args.payment_terms || "Net 30"]
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
let warehouseId;
|
|
265
|
+
const locName = location || "Main Warehouse";
|
|
266
|
+
const existingWarehouses = await query(
|
|
267
|
+
"SELECT id FROM shop_warehouses WHERE profile_id = ? AND (LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1",
|
|
268
|
+
[profileId, locName, `%${locName}%`]
|
|
269
|
+
);
|
|
270
|
+
if (existingWarehouses.length > 0) {
|
|
271
|
+
warehouseId = existingWarehouses[0].id;
|
|
272
|
+
} else {
|
|
273
|
+
warehouseId = generateId("wh");
|
|
274
|
+
await execute(
|
|
275
|
+
"INSERT INTO shop_warehouses (id, profile_id, name, warehouse_type, is_default, is_active) VALUES (?, ?, ?, ?, 1, 1)",
|
|
276
|
+
[warehouseId, profileId, locName, "general"]
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
const countRes = await query(
|
|
280
|
+
"SELECT COUNT(*) as cnt FROM shop_documents WHERE profile_id = ? AND doc_type = 'goods_receipt'",
|
|
281
|
+
[profileId]
|
|
282
|
+
);
|
|
283
|
+
const seq = Number(countRes[0]?.cnt || 0) + 1;
|
|
284
|
+
const docNumber = `GR-${String(seq).padStart(4, "0")}`;
|
|
285
|
+
const docId = generateId("doc");
|
|
286
|
+
let totalCost = 0;
|
|
287
|
+
let totalQty = 0;
|
|
288
|
+
const processedItems = [];
|
|
289
|
+
for (const line of line_items) {
|
|
290
|
+
const itemRef = String(line.item || "").trim();
|
|
291
|
+
const billedQty = Number(line.quantity || 0);
|
|
292
|
+
const freeQty = Number(line.free_qty || 0);
|
|
293
|
+
const totalLineQty = billedQty + freeQty;
|
|
294
|
+
const costPrice = Number(line.cost_price || line.unit_cost || 0);
|
|
295
|
+
const mrp = line.mrp ? Number(line.mrp) : void 0;
|
|
296
|
+
let sellingPrice = line.selling_price || line.price ? Number(line.selling_price || line.price) : void 0;
|
|
297
|
+
if (!sellingPrice && default_markup_pct && costPrice > 0) {
|
|
298
|
+
sellingPrice = Math.round(costPrice * (1 + Number(default_markup_pct) / 100) * 100) / 100;
|
|
299
|
+
}
|
|
300
|
+
let itemId;
|
|
301
|
+
let itemSku;
|
|
302
|
+
let itemName = itemRef;
|
|
303
|
+
const itemsFound = await query(
|
|
304
|
+
"SELECT id, name, sku FROM shop_items WHERE profile_id = ? AND (sku = ? OR id = ? OR LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1",
|
|
305
|
+
[profileId, itemRef, itemRef, itemRef, `%${itemRef}%`]
|
|
306
|
+
);
|
|
307
|
+
if (itemsFound.length > 0) {
|
|
308
|
+
itemId = itemsFound[0].id;
|
|
309
|
+
itemName = itemsFound[0].name;
|
|
310
|
+
itemSku = itemsFound[0].sku || generateSku();
|
|
311
|
+
const updates = [];
|
|
312
|
+
const updateParams = [];
|
|
313
|
+
if (costPrice > 0) {
|
|
314
|
+
updates.push("cost_price = ?");
|
|
315
|
+
updateParams.push(costPrice);
|
|
316
|
+
}
|
|
317
|
+
if (sellingPrice && sellingPrice > 0) {
|
|
318
|
+
updates.push("price = ?");
|
|
319
|
+
updateParams.push(sellingPrice);
|
|
320
|
+
}
|
|
321
|
+
if (mrp && mrp > 0) {
|
|
322
|
+
updates.push("default_mrp = ?");
|
|
323
|
+
updateParams.push(mrp);
|
|
324
|
+
}
|
|
325
|
+
if (updates.length > 0) {
|
|
326
|
+
updates.push("updated_at = strftime('%s','now')");
|
|
327
|
+
updateParams.push(itemId, profileId);
|
|
328
|
+
await execute(
|
|
329
|
+
`UPDATE shop_items SET ${updates.join(", ")} WHERE id = ? AND profile_id = ?`,
|
|
330
|
+
updateParams
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
} else {
|
|
334
|
+
itemId = generateId("item");
|
|
335
|
+
itemSku = (line.sku || (itemRef.length <= 16 && !itemRef.includes(" ") ? itemRef : generateSku())).toUpperCase();
|
|
336
|
+
const slug = `item-${itemName.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
|
|
337
|
+
await execute(
|
|
338
|
+
`INSERT INTO shop_items (id, profile_id, name, sku, slug, cost_price, price, default_mrp, is_active, created_at, updated_at)
|
|
339
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, strftime('%s','now'), strftime('%s','now'))`,
|
|
340
|
+
[itemId, profileId, itemName, itemSku, slug, costPrice, sellingPrice || costPrice, mrp || 0]
|
|
341
|
+
);
|
|
342
|
+
}
|
|
343
|
+
const ledgerId = generateId("stk");
|
|
344
|
+
await execute(
|
|
345
|
+
`INSERT INTO shop_stock_ledger (id, profile_id, item_id, warehouse_id, movement_type, qty_in, qty_out, unit_cost, reference_type, reference_id, created_at)
|
|
346
|
+
VALUES (?, ?, ?, ?, 'purchase', ?, 0, ?, 'goods_receipt', ?, strftime('%s','now'))`,
|
|
347
|
+
[ledgerId, profileId, itemId, warehouseId, totalLineQty, costPrice, docId]
|
|
348
|
+
);
|
|
349
|
+
const lineId = generateId("line");
|
|
350
|
+
const lineTotal = billedQty * costPrice;
|
|
351
|
+
await execute(
|
|
352
|
+
`INSERT INTO shop_document_lines (id, profile_id, document_id, item_id, description, quantity, unit_price, total_amount, created_at)
|
|
353
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, strftime('%s','now'))`,
|
|
354
|
+
[lineId, profileId, docId, itemId, itemName, billedQty, costPrice, lineTotal]
|
|
355
|
+
);
|
|
356
|
+
totalCost += lineTotal;
|
|
357
|
+
totalQty += totalLineQty;
|
|
358
|
+
processedItems.push({ item_id: itemId, sku: itemSku, name: itemName, quantity: totalLineQty, cost_price: costPrice });
|
|
359
|
+
}
|
|
360
|
+
await execute(
|
|
361
|
+
`INSERT INTO shop_documents (id, profile_id, doc_type, doc_number, vendor_id, warehouse_id, total, status, notes, created_at, updated_at)
|
|
362
|
+
VALUES (?, ?, 'goods_receipt', ?, ?, ?, ?, ?, ?, strftime('%s','now'), strftime('%s','now'))`,
|
|
363
|
+
[docId, profileId, docNumber, vendorId, warehouseId, totalCost, args.payment_status || "confirmed", args.notes || ""]
|
|
364
|
+
);
|
|
365
|
+
return {
|
|
366
|
+
success: true,
|
|
367
|
+
doc_id: docId,
|
|
368
|
+
doc_number: docNumber,
|
|
369
|
+
vendor_name,
|
|
370
|
+
invoice_number: invoice_number || null,
|
|
371
|
+
warehouse: locName,
|
|
372
|
+
total_items: processedItems.length,
|
|
373
|
+
total_quantity: totalQty,
|
|
374
|
+
grand_total: totalCost,
|
|
375
|
+
items: processedItems
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
},
|
|
379
|
+
{
|
|
380
|
+
name: "product_update_pricing",
|
|
381
|
+
domain: "shop",
|
|
382
|
+
description: "Directly update product pricing, selling price (shop_items.price), cost price (shop_items.cost_price), markup percentage, MRP, or discounts for an existing item by SKU, ID, or name.",
|
|
383
|
+
inputSchema: {
|
|
384
|
+
type: "object",
|
|
385
|
+
properties: {
|
|
386
|
+
sku: {
|
|
387
|
+
type: "string",
|
|
388
|
+
description: "Item SKU, product name, or ID (e.g. '7PKFJ7I5ND', 'Apple Mac Mini', 'item_...')"
|
|
389
|
+
},
|
|
390
|
+
selling_price: { type: "number", description: "New selling price (shop_items.price), optional." },
|
|
391
|
+
price: { type: "number", description: "Alias for selling_price, optional." },
|
|
392
|
+
cost_price: { type: "number", description: "New cost / purchase price (shop_items.cost_price), optional." },
|
|
393
|
+
markup_pct: { type: "number", description: "Markup percentage on cost_price to compute selling price, optional." },
|
|
394
|
+
mrp: { type: "number", description: "Maximum Retail Price (default_mrp), optional." },
|
|
395
|
+
discount_pct: { type: "number", description: "Default discount percentage, optional." }
|
|
396
|
+
},
|
|
397
|
+
required: ["sku"]
|
|
398
|
+
},
|
|
399
|
+
handler: async (args, ctx) => {
|
|
400
|
+
const profileId = ctx.profileId;
|
|
401
|
+
const ref = String(args.sku).trim();
|
|
402
|
+
const items = await query(
|
|
403
|
+
"SELECT id, name, sku, price, cost_price, default_mrp FROM shop_items WHERE profile_id = ? AND (sku = ? OR id = ? OR LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1",
|
|
404
|
+
[profileId, ref, ref, ref, `%${ref}%`]
|
|
405
|
+
);
|
|
406
|
+
if (items.length === 0) {
|
|
407
|
+
throw new Error(`Product not found with identifier: ${ref}`);
|
|
408
|
+
}
|
|
409
|
+
const item = items[0];
|
|
410
|
+
const updates = [];
|
|
411
|
+
const params = [];
|
|
412
|
+
let costPrice = item.cost_price;
|
|
413
|
+
if (args.cost_price !== void 0) {
|
|
414
|
+
costPrice = Number(args.cost_price);
|
|
415
|
+
updates.push("cost_price = ?");
|
|
416
|
+
params.push(costPrice);
|
|
417
|
+
}
|
|
418
|
+
let sellingPrice = args.selling_price !== void 0 ? Number(args.selling_price) : args.price !== void 0 ? Number(args.price) : void 0;
|
|
419
|
+
if (sellingPrice === void 0 && args.markup_pct !== void 0 && costPrice > 0) {
|
|
420
|
+
sellingPrice = Math.round(costPrice * (1 + Number(args.markup_pct) / 100) * 100) / 100;
|
|
421
|
+
}
|
|
422
|
+
if (sellingPrice !== void 0) {
|
|
423
|
+
updates.push("price = ?");
|
|
424
|
+
params.push(sellingPrice);
|
|
425
|
+
}
|
|
426
|
+
if (args.mrp !== void 0) {
|
|
427
|
+
updates.push("default_mrp = ?");
|
|
428
|
+
params.push(Number(args.mrp));
|
|
429
|
+
}
|
|
430
|
+
if (updates.length === 0) {
|
|
431
|
+
return { success: true, message: "No pricing updates specified.", item };
|
|
432
|
+
}
|
|
433
|
+
updates.push("updated_at = strftime('%s','now')");
|
|
434
|
+
params.push(item.id, profileId);
|
|
435
|
+
await execute(`UPDATE shop_items SET ${updates.join(", ")} WHERE id = ? AND profile_id = ?`, params);
|
|
436
|
+
return {
|
|
437
|
+
success: true,
|
|
438
|
+
sku: item.sku,
|
|
439
|
+
name: item.name,
|
|
440
|
+
previous_price: item.price,
|
|
441
|
+
new_price: sellingPrice ?? item.price,
|
|
442
|
+
previous_cost: item.cost_price,
|
|
443
|
+
new_cost: costPrice
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
},
|
|
447
|
+
{
|
|
448
|
+
name: "inventory_add_stock",
|
|
449
|
+
domain: "shop",
|
|
450
|
+
description: "Add or adjust stock quantity for a SKU, product name, or item ID. Use for restocks, counts, or corrections.",
|
|
451
|
+
inputSchema: {
|
|
452
|
+
type: "object",
|
|
453
|
+
properties: {
|
|
454
|
+
sku: { type: "string", description: "Item SKU, product name, or identifier (e.g. 'Apple Mac Mini', '2B4FYFAVIO')" },
|
|
455
|
+
quantity_delta: { type: "number", description: "Positive to add stock, negative to remove." },
|
|
456
|
+
movement_type: {
|
|
457
|
+
type: "string",
|
|
458
|
+
enum: ["purchase", "adjustment"],
|
|
459
|
+
description: "Type of movement: 'purchase' for vendor restock or 'adjustment' for manual count/correction (default: 'adjustment')."
|
|
460
|
+
},
|
|
461
|
+
unit_cost: { type: "number", description: "Unit purchase cost if applicable." },
|
|
462
|
+
vendor_name: { type: "string", description: "Vendor name if this is a purchase." },
|
|
463
|
+
invoice_number: { type: "string", description: "Invoice reference number if applicable." },
|
|
464
|
+
location: { type: "string", description: "Optional warehouse name or location tag." }
|
|
465
|
+
},
|
|
466
|
+
required: ["sku", "quantity_delta"]
|
|
467
|
+
},
|
|
468
|
+
handler: async (args, ctx) => {
|
|
469
|
+
const profileId = ctx.profileId;
|
|
470
|
+
const ref = String(args.sku).trim();
|
|
471
|
+
const delta = Number(args.quantity_delta);
|
|
472
|
+
const items = await query(
|
|
473
|
+
"SELECT id, name, sku, cost_price FROM shop_items WHERE profile_id = ? AND (sku = ? OR id = ? OR LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1",
|
|
474
|
+
[profileId, ref, ref, ref, `%${ref}%`]
|
|
475
|
+
);
|
|
476
|
+
let itemId;
|
|
477
|
+
let itemName = ref;
|
|
478
|
+
let itemSku;
|
|
479
|
+
if (items.length > 0) {
|
|
480
|
+
itemId = items[0].id;
|
|
481
|
+
itemName = items[0].name;
|
|
482
|
+
itemSku = items[0].sku;
|
|
483
|
+
} else {
|
|
484
|
+
itemId = generateId("item");
|
|
485
|
+
itemSku = generateSku();
|
|
486
|
+
const slug = `item-${ref.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
|
|
487
|
+
await execute(
|
|
488
|
+
`INSERT INTO shop_items (id, profile_id, name, sku, slug, cost_price, price, is_active, created_at, updated_at)
|
|
489
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 1, strftime('%s','now'), strftime('%s','now'))`,
|
|
490
|
+
[itemId, profileId, ref, itemSku, slug, args.unit_cost || 0, args.unit_cost || 0]
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
const loc = args.location || "Main Warehouse";
|
|
494
|
+
const whs = await query("SELECT id FROM shop_warehouses WHERE profile_id = ? LIMIT 1", [profileId]);
|
|
495
|
+
const warehouseId = whs.length > 0 ? whs[0].id : "default";
|
|
496
|
+
const qtyIn = delta > 0 ? delta : 0;
|
|
497
|
+
const qtyOut = delta < 0 ? Math.abs(delta) : 0;
|
|
498
|
+
const movementType = args.movement_type || (delta > 0 ? "adjustment" : "adjustment");
|
|
499
|
+
const ledgerId = generateId("stk");
|
|
500
|
+
await execute(
|
|
501
|
+
`INSERT INTO shop_stock_ledger (id, profile_id, item_id, warehouse_id, movement_type, qty_in, qty_out, unit_cost, notes, created_at)
|
|
502
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, strftime('%s','now'))`,
|
|
503
|
+
[ledgerId, profileId, itemId, warehouseId, movementType, qtyIn, qtyOut, args.unit_cost || 0, args.invoice_number || "Stock Adjustment"]
|
|
504
|
+
);
|
|
505
|
+
const balRes = await query(
|
|
506
|
+
"SELECT COALESCE(SUM(qty_in - qty_out), 0) as balance FROM shop_stock_ledger WHERE profile_id = ? AND item_id = ?",
|
|
507
|
+
[profileId, itemId]
|
|
508
|
+
);
|
|
509
|
+
return {
|
|
510
|
+
success: true,
|
|
511
|
+
sku: itemSku,
|
|
512
|
+
name: itemName,
|
|
513
|
+
quantity_delta: delta,
|
|
514
|
+
current_stock: Number(balRes[0]?.balance || 0),
|
|
515
|
+
movement_type: movementType
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
},
|
|
519
|
+
{
|
|
520
|
+
name: "inventory_get_levels",
|
|
521
|
+
domain: "shop",
|
|
522
|
+
description: "Look up current stock levels, optionally filtered by SKU or category.",
|
|
523
|
+
inputSchema: {
|
|
524
|
+
type: "object",
|
|
525
|
+
properties: {
|
|
526
|
+
sku: { type: "string", description: "Optional SKU or product name to query specific item balance." },
|
|
527
|
+
category: { type: "string", description: "Optional category name filter." }
|
|
528
|
+
}
|
|
529
|
+
},
|
|
530
|
+
handler: async (args, ctx) => {
|
|
531
|
+
const profileId = ctx.profileId;
|
|
532
|
+
const skuFilter = args.sku ? `%${String(args.sku).trim()}%` : null;
|
|
533
|
+
let sql = `
|
|
534
|
+
SELECT i.id, i.name, i.sku, i.price, i.cost_price,
|
|
535
|
+
COALESCE(SUM(l.qty_in - l.qty_out), 0) as stock_on_hand
|
|
536
|
+
FROM shop_items i
|
|
537
|
+
LEFT JOIN shop_stock_ledger l ON i.id = l.item_id AND l.profile_id = i.profile_id
|
|
538
|
+
WHERE i.profile_id = ?
|
|
539
|
+
`;
|
|
540
|
+
const params = [profileId];
|
|
541
|
+
if (skuFilter) {
|
|
542
|
+
sql += " AND (i.sku LIKE ? OR i.name LIKE ? OR i.id = ?)";
|
|
543
|
+
params.push(skuFilter, skuFilter, args.sku.trim());
|
|
544
|
+
}
|
|
545
|
+
sql += " GROUP BY i.id ORDER BY i.name ASC LIMIT 100";
|
|
546
|
+
const items = await query(sql, params);
|
|
547
|
+
return {
|
|
548
|
+
total: items.length,
|
|
549
|
+
items: items.map((r) => ({
|
|
550
|
+
id: r.id,
|
|
551
|
+
name: r.name,
|
|
552
|
+
sku: r.sku,
|
|
553
|
+
selling_price: r.price,
|
|
554
|
+
cost_price: r.cost_price,
|
|
555
|
+
stock_on_hand: Number(r.stock_on_hand || 0)
|
|
556
|
+
}))
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
},
|
|
560
|
+
{
|
|
561
|
+
name: "invoice_create",
|
|
562
|
+
domain: "shop",
|
|
563
|
+
description: "Create and draft a customer sales invoice in the shop billing system.",
|
|
564
|
+
inputSchema: {
|
|
565
|
+
type: "object",
|
|
566
|
+
properties: {
|
|
567
|
+
customer_name: { type: "string", description: "Customer name or company name" },
|
|
568
|
+
line_items: {
|
|
569
|
+
type: "array",
|
|
570
|
+
items: {
|
|
571
|
+
type: "object",
|
|
572
|
+
properties: {
|
|
573
|
+
description: { type: "string" },
|
|
574
|
+
quantity: { type: "number" },
|
|
575
|
+
unit_price: { type: "number" }
|
|
576
|
+
},
|
|
577
|
+
required: ["description", "quantity", "unit_price"]
|
|
578
|
+
}
|
|
579
|
+
},
|
|
580
|
+
due_date: { type: "string", description: "Due date in YYYY-MM-DD format" }
|
|
581
|
+
},
|
|
582
|
+
required: ["customer_name", "line_items"]
|
|
583
|
+
},
|
|
584
|
+
handler: async (args, ctx) => {
|
|
585
|
+
const profileId = ctx.profileId;
|
|
586
|
+
const { customer_name, line_items, due_date } = args;
|
|
587
|
+
let customerId;
|
|
588
|
+
const custs = await query(
|
|
589
|
+
"SELECT id FROM shop_customers WHERE profile_id = ? AND (LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1",
|
|
590
|
+
[profileId, customer_name.trim(), `%${customer_name.trim()}%`]
|
|
591
|
+
);
|
|
592
|
+
if (custs.length > 0) {
|
|
593
|
+
customerId = custs[0].id;
|
|
594
|
+
} else {
|
|
595
|
+
customerId = generateId("cust");
|
|
596
|
+
await execute(
|
|
597
|
+
"INSERT INTO shop_customers (id, profile_id, name, customer_type, is_active) VALUES (?, ?, ?, ?, 1)",
|
|
598
|
+
[customerId, profileId, customer_name.trim(), "individual"]
|
|
599
|
+
);
|
|
600
|
+
}
|
|
601
|
+
const cntRes = await query(
|
|
602
|
+
"SELECT COUNT(*) as cnt FROM shop_documents WHERE profile_id = ? AND doc_type = 'invoice'",
|
|
603
|
+
[profileId]
|
|
604
|
+
);
|
|
605
|
+
const seq = Number(cntRes[0]?.cnt || 0) + 1;
|
|
606
|
+
const docNumber = `INV-${String(seq).padStart(4, "0")}`;
|
|
607
|
+
const docId = generateId("doc");
|
|
608
|
+
let grandTotal = 0;
|
|
609
|
+
for (const line of line_items) {
|
|
610
|
+
const lineTotal = Number(line.quantity || 1) * Number(line.unit_price || 0);
|
|
611
|
+
grandTotal += lineTotal;
|
|
612
|
+
const lineId = generateId("line");
|
|
613
|
+
await execute(
|
|
614
|
+
`INSERT INTO shop_document_lines (id, profile_id, document_id, description, quantity, unit_price, total_amount, created_at)
|
|
615
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, strftime('%s','now'))`,
|
|
616
|
+
[lineId, profileId, docId, line.description, line.quantity, line.unit_price, lineTotal]
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
await execute(
|
|
620
|
+
`INSERT INTO shop_documents (id, profile_id, doc_type, doc_number, customer_id, total, status, notes, created_at, updated_at)
|
|
621
|
+
VALUES (?, ?, 'invoice', ?, ?, ?, 'draft', ?, strftime('%s','now'), strftime('%s','now'))`,
|
|
622
|
+
[docId, profileId, docNumber, customerId, grandTotal, due_date ? `Due: ${due_date}` : ""]
|
|
623
|
+
);
|
|
624
|
+
return {
|
|
625
|
+
success: true,
|
|
626
|
+
invoice_id: docId,
|
|
627
|
+
invoice_number: docNumber,
|
|
628
|
+
customer_name,
|
|
629
|
+
total: grandTotal,
|
|
630
|
+
status: "draft"
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
},
|
|
634
|
+
{
|
|
635
|
+
name: "invoice_send",
|
|
636
|
+
domain: "shop",
|
|
637
|
+
description: "Mark a sales invoice as issued and ready for customer dispatch.",
|
|
638
|
+
inputSchema: {
|
|
639
|
+
type: "object",
|
|
640
|
+
properties: {
|
|
641
|
+
invoice_id: { type: "string", description: "Invoice document ID or invoice number (e.g. 'doc_...' or 'INV-0001')" },
|
|
642
|
+
recipient_email: { type: "string", description: "Customer email to send the invoice notification to" }
|
|
643
|
+
},
|
|
644
|
+
required: ["invoice_id"]
|
|
645
|
+
},
|
|
646
|
+
handler: async (args, ctx) => {
|
|
647
|
+
const profileId = ctx.profileId;
|
|
648
|
+
const ref = String(args.invoice_id).trim();
|
|
649
|
+
const docs = await query(
|
|
650
|
+
"SELECT id, doc_number, status FROM shop_documents WHERE profile_id = ? AND (id = ? OR doc_number = ?) LIMIT 1",
|
|
651
|
+
[profileId, ref, ref]
|
|
652
|
+
);
|
|
653
|
+
if (docs.length === 0) {
|
|
654
|
+
throw new Error(`Invoice not found with identifier: ${ref}`);
|
|
655
|
+
}
|
|
656
|
+
await execute(
|
|
657
|
+
"UPDATE shop_documents SET status = 'sent', updated_at = strftime('%s','now') WHERE id = ? AND profile_id = ?",
|
|
658
|
+
[docs[0].id, profileId]
|
|
659
|
+
);
|
|
660
|
+
return {
|
|
661
|
+
success: true,
|
|
662
|
+
invoice_id: docs[0].id,
|
|
663
|
+
invoice_number: docs[0].doc_number,
|
|
664
|
+
status: "sent",
|
|
665
|
+
recipient_email: args.recipient_email || null
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
},
|
|
669
|
+
{
|
|
670
|
+
name: "shop_create_new_bill",
|
|
671
|
+
domain: "shop",
|
|
672
|
+
description: "Create a new customer sale bill / sales invoice from natural-language or handwritten-bill input. Resolves or auto-creates items, records stock ledger movements (sale), and writes a SAL-NNNN document.",
|
|
673
|
+
inputSchema: {
|
|
674
|
+
type: "object",
|
|
675
|
+
properties: {
|
|
676
|
+
customer_name: { type: "string", description: "Customer name, company, or 'Counter Sale' for walk-in (optional)." },
|
|
677
|
+
customer_id: { type: "string", description: "Existing customer ID if known (optional)." },
|
|
678
|
+
bill_date: { type: "string", description: "Bill date in YYYY-MM-DD or human format (optional, defaults to today)." },
|
|
679
|
+
payment_status: { type: "string", enum: ["paid", "due", "credit"], description: "Payment status: 'paid', 'due'. Default: 'paid'." },
|
|
680
|
+
payment_method: { type: "string", description: "Payment method: 'cash', 'upi', 'bank_transfer', 'credit'. Default: 'cash'." },
|
|
681
|
+
bill_discount_pct: { type: "number", description: "Optional bill-level discount % applied to total." },
|
|
682
|
+
bill_discount_amt: { type: "number", description: "Optional flat bill discount amount." },
|
|
683
|
+
notes: { type: "string", description: "Optional bill notes or remarks." },
|
|
684
|
+
line_items: {
|
|
685
|
+
type: "array",
|
|
686
|
+
items: {
|
|
687
|
+
type: "object",
|
|
688
|
+
properties: {
|
|
689
|
+
item: { type: "string", description: "Product name, SKU, or ID (e.g. 'Tellzy 40 Tab', 'URISPAS TAB')." },
|
|
690
|
+
qty: { type: "number", description: "Quantity to bill (e.g. 5, 10)." },
|
|
691
|
+
price: { type: "number", description: "Custom unit selling price." },
|
|
692
|
+
unit_price: { type: "number", description: "Alias for price." },
|
|
693
|
+
rate: { type: "number", description: "Alias for price." },
|
|
694
|
+
discount_pct: { type: "number", description: "Line-level discount %." },
|
|
695
|
+
tax: { type: "number", description: "GST / Tax % for this line." },
|
|
696
|
+
mrp: { type: "number", description: "MRP for this item, optional." },
|
|
697
|
+
sku: { type: "string", description: "Explicit SKU code if provided." }
|
|
698
|
+
},
|
|
699
|
+
required: ["item", "qty"]
|
|
700
|
+
},
|
|
701
|
+
description: "List of items on this bill."
|
|
702
|
+
}
|
|
703
|
+
},
|
|
704
|
+
required: ["line_items"]
|
|
705
|
+
},
|
|
706
|
+
handler: async (args, ctx) => {
|
|
707
|
+
const profileId = ctx.profileId;
|
|
708
|
+
const customerName = args.customer_name?.trim() || "Counter Sale";
|
|
709
|
+
const lineItems = args.line_items || [];
|
|
710
|
+
let customerId;
|
|
711
|
+
const custs = await query(
|
|
712
|
+
"SELECT id FROM shop_customers WHERE profile_id = ? AND (LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1",
|
|
713
|
+
[profileId, customerName, `%${customerName}%`]
|
|
714
|
+
);
|
|
715
|
+
if (custs.length > 0) {
|
|
716
|
+
customerId = custs[0].id;
|
|
717
|
+
} else {
|
|
718
|
+
customerId = generateId("cust");
|
|
719
|
+
await execute(
|
|
720
|
+
"INSERT INTO shop_customers (id, profile_id, name, customer_type, is_active) VALUES (?, ?, ?, ?, 1)",
|
|
721
|
+
[customerId, profileId, customerName, "walk_in"]
|
|
722
|
+
);
|
|
723
|
+
}
|
|
724
|
+
const whs = await query("SELECT id FROM shop_warehouses WHERE profile_id = ? LIMIT 1", [profileId]);
|
|
725
|
+
const warehouseId = whs.length > 0 ? whs[0].id : "default";
|
|
726
|
+
const cntRes = await query(
|
|
727
|
+
"SELECT COUNT(*) as cnt FROM shop_documents WHERE profile_id = ? AND doc_type = 'invoice' AND doc_number LIKE 'SAL-%'",
|
|
728
|
+
[profileId]
|
|
729
|
+
);
|
|
730
|
+
const seq = Number(cntRes[0]?.cnt || 0) + 1;
|
|
731
|
+
const docNumber = `SAL-${String(seq).padStart(4, "0")}`;
|
|
732
|
+
const docId = generateId("doc");
|
|
733
|
+
let subtotal = 0;
|
|
734
|
+
const billedItems = [];
|
|
735
|
+
for (const line of lineItems) {
|
|
736
|
+
const itemRef = String(line.item || "").trim();
|
|
737
|
+
const qty = Number(line.qty || 1);
|
|
738
|
+
let rate = Number(line.price ?? line.unit_price ?? line.rate ?? 0);
|
|
739
|
+
const discountPct = Number(line.discount_pct || 0);
|
|
740
|
+
let itemId;
|
|
741
|
+
let itemSku;
|
|
742
|
+
let itemName = itemRef;
|
|
743
|
+
const itemsFound = await query(
|
|
744
|
+
"SELECT id, name, sku, price FROM shop_items WHERE profile_id = ? AND (sku = ? OR id = ? OR LOWER(name) = LOWER(?) OR name LIKE ?) LIMIT 1",
|
|
745
|
+
[profileId, itemRef, itemRef, itemRef, `%${itemRef}%`]
|
|
746
|
+
);
|
|
747
|
+
if (itemsFound.length > 0) {
|
|
748
|
+
itemId = itemsFound[0].id;
|
|
749
|
+
itemName = itemsFound[0].name;
|
|
750
|
+
itemSku = itemsFound[0].sku;
|
|
751
|
+
if (rate <= 0) {
|
|
752
|
+
rate = itemsFound[0].price || 0;
|
|
753
|
+
}
|
|
754
|
+
} else {
|
|
755
|
+
itemId = generateId("item");
|
|
756
|
+
itemSku = generateSku();
|
|
757
|
+
const slug = `item-${itemName.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
|
|
758
|
+
await execute(
|
|
759
|
+
`INSERT INTO shop_items (id, profile_id, name, sku, slug, price, cost_price, is_active, created_at, updated_at)
|
|
760
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 1, strftime('%s','now'), strftime('%s','now'))`,
|
|
761
|
+
[itemId, profileId, itemName, itemSku, slug, rate, 0]
|
|
762
|
+
);
|
|
763
|
+
}
|
|
764
|
+
const discountedRate = rate * (1 - discountPct / 100);
|
|
765
|
+
const lineTotal = Math.round(discountedRate * qty * 100) / 100;
|
|
766
|
+
subtotal += lineTotal;
|
|
767
|
+
const ledgerId = generateId("stk");
|
|
768
|
+
await execute(
|
|
769
|
+
`INSERT INTO shop_stock_ledger (id, profile_id, item_id, warehouse_id, movement_type, qty_in, qty_out, unit_cost, reference_type, reference_id, created_at)
|
|
770
|
+
VALUES (?, ?, ?, ?, 'sale', 0, ?, ?, 'invoice', ?, strftime('%s','now'))`,
|
|
771
|
+
[ledgerId, profileId, itemId, warehouseId, qty, rate, docId]
|
|
772
|
+
);
|
|
773
|
+
const lineId = generateId("line");
|
|
774
|
+
await execute(
|
|
775
|
+
`INSERT INTO shop_document_lines (id, profile_id, document_id, item_id, description, quantity, unit_price, total_amount, created_at)
|
|
776
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, strftime('%s','now'))`,
|
|
777
|
+
[lineId, profileId, docId, itemId, itemName, qty, rate, lineTotal]
|
|
778
|
+
);
|
|
779
|
+
billedItems.push({ sku: itemSku, name: itemName, qty, unit_price: rate, total: lineTotal });
|
|
780
|
+
}
|
|
781
|
+
let finalTotal = subtotal;
|
|
782
|
+
if (args.bill_discount_pct) {
|
|
783
|
+
finalTotal = Math.round(subtotal * (1 - Number(args.bill_discount_pct) / 100) * 100) / 100;
|
|
784
|
+
} else if (args.bill_discount_amt) {
|
|
785
|
+
finalTotal = Math.max(0, subtotal - Number(args.bill_discount_amt));
|
|
786
|
+
}
|
|
787
|
+
await execute(
|
|
788
|
+
`INSERT INTO shop_documents (id, profile_id, doc_type, doc_number, customer_id, warehouse_id, total, status, notes, created_at, updated_at)
|
|
789
|
+
VALUES (?, ?, 'invoice', ?, ?, ?, ?, ?, ?, strftime('%s','now'), strftime('%s','now'))`,
|
|
790
|
+
[docId, profileId, docNumber, customerId, warehouseId, finalTotal, args.payment_status || "paid", args.notes || ""]
|
|
791
|
+
);
|
|
792
|
+
return {
|
|
793
|
+
success: true,
|
|
794
|
+
doc_id: docId,
|
|
795
|
+
doc_number: docNumber,
|
|
796
|
+
customer_name: customerName,
|
|
797
|
+
payment_status: args.payment_status || "paid",
|
|
798
|
+
payment_method: args.payment_method || "cash",
|
|
799
|
+
subtotal,
|
|
800
|
+
final_total: finalTotal,
|
|
801
|
+
items_count: billedItems.length,
|
|
802
|
+
items: billedItems
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
];
|
|
807
|
+
|
|
808
|
+
// src/tools/crm.ts
|
|
809
|
+
function nowTs() {
|
|
810
|
+
return Math.floor(Date.now() / 1e3);
|
|
811
|
+
}
|
|
812
|
+
function parseTsOrDate(val) {
|
|
813
|
+
if (val === null || val === void 0) return null;
|
|
814
|
+
if (typeof val === "number" && Number.isFinite(val)) {
|
|
815
|
+
return val > 2e10 ? Math.floor(val / 1e3) : Math.floor(val);
|
|
816
|
+
}
|
|
817
|
+
const s = String(val).trim();
|
|
818
|
+
if (!s) return null;
|
|
819
|
+
if (/^\d+$/.test(s)) {
|
|
820
|
+
const n = Number(s);
|
|
821
|
+
return n > 2e10 ? Math.floor(n / 1e3) : n;
|
|
822
|
+
}
|
|
823
|
+
const parsed = Date.parse(s);
|
|
824
|
+
return Number.isNaN(parsed) ? null : Math.floor(parsed / 1e3);
|
|
825
|
+
}
|
|
826
|
+
async function resolveContactId(profileId, ref) {
|
|
827
|
+
const r = ref.trim();
|
|
828
|
+
if (!r) throw new Error("Missing contact identifier");
|
|
829
|
+
const exact = await query(
|
|
830
|
+
`SELECT id, first_name, last_name, email, company FROM crm_contacts
|
|
831
|
+
WHERE profile_id = ? AND archived = 0 AND (id = ? OR LOWER(email) = LOWER(?)) LIMIT 1`,
|
|
832
|
+
[profileId, r, r]
|
|
833
|
+
);
|
|
834
|
+
if (exact.length > 0) {
|
|
835
|
+
const row = exact[0];
|
|
836
|
+
return {
|
|
837
|
+
id: row.id,
|
|
838
|
+
name: `${row.first_name || ""} ${row.last_name || ""}`.trim(),
|
|
839
|
+
email: row.email ?? null,
|
|
840
|
+
company: row.company ?? null
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
const like = `%${r}%`;
|
|
844
|
+
const fuzzy = await query(
|
|
845
|
+
`SELECT id, first_name, last_name, email, company FROM crm_contacts
|
|
846
|
+
WHERE profile_id = ? AND archived = 0
|
|
847
|
+
AND (LOWER(first_name || ' ' || COALESCE(last_name,'')) LIKE LOWER(?) OR LOWER(first_name) LIKE LOWER(?))
|
|
848
|
+
LIMIT 2`,
|
|
849
|
+
[profileId, like, like]
|
|
850
|
+
);
|
|
851
|
+
if (fuzzy.length === 1) {
|
|
852
|
+
const row = fuzzy[0];
|
|
853
|
+
return {
|
|
854
|
+
id: row.id,
|
|
855
|
+
name: `${row.first_name || ""} ${row.last_name || ""}`.trim(),
|
|
856
|
+
email: row.email ?? null,
|
|
857
|
+
company: row.company ?? null
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
if (fuzzy.length > 1) {
|
|
861
|
+
throw new Error(`Multiple contacts matched '${r}'; pass exact contact_id or email`);
|
|
862
|
+
}
|
|
863
|
+
throw new Error(`Contact not found: ${r}`);
|
|
864
|
+
}
|
|
865
|
+
async function getCrmConfigVal(profileId, key) {
|
|
866
|
+
const rows = await query(
|
|
867
|
+
"SELECT config_val FROM crm_config WHERE profile_id = ? AND config_key = ? LIMIT 1",
|
|
868
|
+
[profileId, key]
|
|
869
|
+
);
|
|
870
|
+
return rows[0]?.config_val ?? null;
|
|
871
|
+
}
|
|
872
|
+
async function queueApprovalItem(profileId, tool, title, args, reason, sources, sourceId, idemKey) {
|
|
873
|
+
if (idemKey) {
|
|
874
|
+
const cooldownRaw = await getCrmConfigVal(profileId, "crm.rejected_cooldowns");
|
|
875
|
+
if (cooldownRaw) {
|
|
876
|
+
try {
|
|
877
|
+
const map = JSON.parse(cooldownRaw);
|
|
878
|
+
if (typeof map[idemKey] === "number" && map[idemKey] > nowTs()) {
|
|
879
|
+
return {
|
|
880
|
+
status: "skipped_cooldown",
|
|
881
|
+
action: tool,
|
|
882
|
+
title,
|
|
883
|
+
reason: "Previously rejected within cooldown window"
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
} catch {
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
const existing = await query(
|
|
890
|
+
"SELECT id FROM agent_tasks WHERE profile_id = ? AND idempotency_key = ? AND status = 'awaiting_approval' LIMIT 1",
|
|
891
|
+
[profileId, idemKey]
|
|
892
|
+
);
|
|
893
|
+
if (existing.length > 0) {
|
|
894
|
+
return {
|
|
895
|
+
approval_id: existing[0].id,
|
|
896
|
+
status: "awaiting_approval",
|
|
897
|
+
action: tool,
|
|
898
|
+
title,
|
|
899
|
+
deduped: true
|
|
900
|
+
};
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
const taskId = generateId("apr");
|
|
904
|
+
const now = nowTs();
|
|
905
|
+
const payload = JSON.stringify({ tool, args, reason, sources, cooldown_key: idemKey });
|
|
906
|
+
await execute(
|
|
907
|
+
`INSERT OR IGNORE INTO agent_tasks
|
|
908
|
+
(id, agent_id, profile_id, title, input, status, task_type, source_id, idempotency_key, created_at, updated_at)
|
|
909
|
+
VALUES (?, 'crm', ?, ?, ?, 'awaiting_approval', 'crm_approval', ?, ?, ?, ?)`,
|
|
910
|
+
[taskId, profileId, title, payload, sourceId, idemKey, now, now]
|
|
911
|
+
);
|
|
912
|
+
return {
|
|
913
|
+
approval_id: taskId,
|
|
914
|
+
status: "awaiting_approval",
|
|
915
|
+
action: tool,
|
|
916
|
+
title,
|
|
917
|
+
reason,
|
|
918
|
+
sources
|
|
919
|
+
};
|
|
920
|
+
}
|
|
921
|
+
async function loadBrandVoice(profileId) {
|
|
922
|
+
let voice = null;
|
|
923
|
+
try {
|
|
924
|
+
const bf = await query(
|
|
925
|
+
"SELECT brand_voice, about_me, working_style FROM brand_foundation WHERE profile_id = ? LIMIT 1",
|
|
926
|
+
[profileId]
|
|
927
|
+
);
|
|
928
|
+
if (bf.length > 0) {
|
|
929
|
+
const parts = [bf[0].brand_voice, bf[0].about_me, bf[0].working_style].map((x) => x ? String(x).trim() : "").filter(Boolean);
|
|
930
|
+
if (parts.length > 0) voice = parts.join(" | ");
|
|
931
|
+
}
|
|
932
|
+
} catch {
|
|
933
|
+
}
|
|
934
|
+
return voice;
|
|
935
|
+
}
|
|
936
|
+
async function saveInboxDraftForContact(profileId, contactId, toEmail, threadIdOpt, mailboxIdOpt, subject, body) {
|
|
937
|
+
if (!toEmail.trim()) {
|
|
938
|
+
throw new Error("Contact has no email address \u2014 cannot create email draft");
|
|
939
|
+
}
|
|
940
|
+
let mailboxId = "";
|
|
941
|
+
let fromAddr = "";
|
|
942
|
+
if (mailboxIdOpt) {
|
|
943
|
+
const mb = await query(
|
|
944
|
+
"SELECT id, address FROM inbox_mailboxes WHERE id = ? AND profile_id = ? LIMIT 1",
|
|
945
|
+
[mailboxIdOpt, profileId]
|
|
946
|
+
);
|
|
947
|
+
if (mb.length === 0) throw new Error(`Mailbox not found: ${mailboxIdOpt}`);
|
|
948
|
+
mailboxId = mb[0].id;
|
|
949
|
+
fromAddr = mb[0].address || "";
|
|
950
|
+
} else {
|
|
951
|
+
const mb = await query(
|
|
952
|
+
`SELECT id, address FROM inbox_mailboxes WHERE profile_id = ? AND is_active = 1
|
|
953
|
+
ORDER BY CASE WHEN purpose = 'general' THEN 0 ELSE 1 END, created_at ASC LIMIT 1`,
|
|
954
|
+
[profileId]
|
|
955
|
+
);
|
|
956
|
+
if (mb.length === 0) throw new Error("No active mailbox configured in Inbox \u2014 connect a mailbox first");
|
|
957
|
+
mailboxId = mb[0].id;
|
|
958
|
+
fromAddr = mb[0].address || "";
|
|
959
|
+
}
|
|
960
|
+
const checkHeld = async (tid) => {
|
|
961
|
+
const held = await query(
|
|
962
|
+
`SELECT COUNT(*) as cnt FROM inbox_messages
|
|
963
|
+
WHERE thread_id = ? AND profile_id = ? AND direction = 'in'
|
|
964
|
+
AND screen_status IN ('suspicious', 'blocked')`,
|
|
965
|
+
[tid, profileId]
|
|
966
|
+
);
|
|
967
|
+
if (Number(held[0]?.cnt || 0) > 0) {
|
|
968
|
+
throw new Error("Refusing to draft on thread with suspicious/blocked inbound messages");
|
|
969
|
+
}
|
|
970
|
+
};
|
|
971
|
+
let threadId = threadIdOpt || "";
|
|
972
|
+
if (threadId) {
|
|
973
|
+
await checkHeld(threadId);
|
|
974
|
+
} else {
|
|
975
|
+
const existingThreads = await query(
|
|
976
|
+
`SELECT id FROM inbox_threads
|
|
977
|
+
WHERE profile_id = ? AND linked_entity_type = 'contact' AND linked_entity_id = ?
|
|
978
|
+
ORDER BY last_message_at DESC LIMIT 1`,
|
|
979
|
+
[profileId, contactId]
|
|
980
|
+
);
|
|
981
|
+
if (existingThreads.length > 0) {
|
|
982
|
+
threadId = existingThreads[0].id;
|
|
983
|
+
await checkHeld(threadId);
|
|
984
|
+
} else {
|
|
985
|
+
threadId = generateId("th");
|
|
986
|
+
const now2 = nowTs();
|
|
987
|
+
await execute(
|
|
988
|
+
`INSERT INTO inbox_threads
|
|
989
|
+
(id, profile_id, mailbox_id, thread_key, subject, last_message_at,
|
|
990
|
+
message_count, is_unread, state, linked_entity_type, linked_entity_id, created_at, updated_at)
|
|
991
|
+
VALUES (?, ?, ?, ?, ?, ?, 1, 0, 'awaiting', 'contact', ?, ?, ?)`,
|
|
992
|
+
[threadId, profileId, mailboxId, `crm-draft-${threadId}`, subject, now2, contactId, now2, now2]
|
|
993
|
+
);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
const msgId = generateId("msg");
|
|
997
|
+
const now = nowTs();
|
|
998
|
+
const msgHeader = `<${msgId}@businesskit.app>`;
|
|
999
|
+
const toAddrs = JSON.stringify([toEmail.trim()]);
|
|
1000
|
+
const snippet = body.slice(0, 120);
|
|
1001
|
+
await execute(
|
|
1002
|
+
`INSERT INTO inbox_messages
|
|
1003
|
+
(id, profile_id, thread_id, mailbox_id, source_mailbox_id,
|
|
1004
|
+
provider_message_id, message_id_header, direction, author, from_addr,
|
|
1005
|
+
to_addrs, subject, snippet, body_text, body_status, send_status, screen_status,
|
|
1006
|
+
is_read, has_attachments, received_at, created_at)
|
|
1007
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 'out', 'agent', ?, ?, ?, ?, ?, 'ready', 'draft', 'clean', 1, 0, ?, ?)`,
|
|
1008
|
+
[msgId, profileId, threadId, mailboxId, mailboxId, msgId, msgHeader, fromAddr, toAddrs, subject, snippet, body, now, now]
|
|
1009
|
+
);
|
|
1010
|
+
return {
|
|
1011
|
+
message_id: msgId,
|
|
1012
|
+
thread_id: threadId,
|
|
1013
|
+
mailbox_id: mailboxId,
|
|
1014
|
+
to: toEmail.trim(),
|
|
1015
|
+
subject,
|
|
1016
|
+
send_status: "draft",
|
|
1017
|
+
author: "agent",
|
|
1018
|
+
status: "draft_saved"
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
var crmTools = [
|
|
1022
|
+
{
|
|
1023
|
+
name: "contact_create",
|
|
1024
|
+
domain: "crm",
|
|
1025
|
+
description: "Create a new contact or lead in the CRM.",
|
|
1026
|
+
inputSchema: {
|
|
1027
|
+
type: "object",
|
|
1028
|
+
properties: {
|
|
1029
|
+
name: { type: "string", description: "Full name of the contact" },
|
|
1030
|
+
email: { type: "string", description: "Email address" },
|
|
1031
|
+
phone: { type: "string", description: "Phone number" },
|
|
1032
|
+
tags: { type: "array", items: { type: "string" } }
|
|
1033
|
+
},
|
|
1034
|
+
required: ["name"]
|
|
1035
|
+
},
|
|
1036
|
+
handler: async (args, ctx) => {
|
|
1037
|
+
const profileId = ctx.profileId;
|
|
1038
|
+
const name = String(args.name || "").trim();
|
|
1039
|
+
const email = String(args.email || "").trim().toLowerCase() || null;
|
|
1040
|
+
const phone = String(args.phone || "").trim() || null;
|
|
1041
|
+
const company = String(args.company || "").trim() || null;
|
|
1042
|
+
const jobTitle = String(args.job_title || "").trim() || null;
|
|
1043
|
+
const notes = String(args.notes || "").trim() || null;
|
|
1044
|
+
const status = String(args.status || "lead");
|
|
1045
|
+
const source = String(args.source || "manual");
|
|
1046
|
+
const tags = JSON.stringify(args.tags || []);
|
|
1047
|
+
if (email) {
|
|
1048
|
+
const existing = await query(
|
|
1049
|
+
"SELECT id FROM crm_contacts WHERE profile_id = ? AND LOWER(email) = LOWER(?) LIMIT 1",
|
|
1050
|
+
[profileId, email]
|
|
1051
|
+
);
|
|
1052
|
+
if (existing.length > 0) {
|
|
1053
|
+
return { contact_id: existing[0].id, name, email, status: "already_exists" };
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
const parts = name.split(/\s+/);
|
|
1057
|
+
const firstName = parts[0] || name;
|
|
1058
|
+
const lastName = parts.length > 1 ? parts.slice(1).join(" ") : null;
|
|
1059
|
+
const contactId = generateId("ct");
|
|
1060
|
+
await execute(
|
|
1061
|
+
`INSERT INTO crm_contacts
|
|
1062
|
+
(id, profile_id, first_name, last_name, email, phone, company, job_title, notes, tags,
|
|
1063
|
+
status, outreach_status, source, created_at, updated_at)
|
|
1064
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'new', ?, strftime('%s','now'), strftime('%s','now'))`,
|
|
1065
|
+
[contactId, profileId, firstName, lastName, email, phone, company, jobTitle, notes, tags, status, source]
|
|
1066
|
+
);
|
|
1067
|
+
return { contact_id: contactId, name, email, phone, status: "created" };
|
|
1068
|
+
}
|
|
1069
|
+
},
|
|
1070
|
+
{
|
|
1071
|
+
name: "contact_update",
|
|
1072
|
+
domain: "crm",
|
|
1073
|
+
description: "Update fields on an existing CRM contact.",
|
|
1074
|
+
inputSchema: {
|
|
1075
|
+
type: "object",
|
|
1076
|
+
properties: {
|
|
1077
|
+
contact_id: { type: "string", description: "Contact ID or email address" },
|
|
1078
|
+
fields: {
|
|
1079
|
+
type: "object",
|
|
1080
|
+
description: 'Partial fields to update, e.g. { "email": "...", "phone": "...", "company": "..." }'
|
|
1081
|
+
}
|
|
1082
|
+
},
|
|
1083
|
+
required: ["contact_id", "fields"]
|
|
1084
|
+
},
|
|
1085
|
+
handler: async (args, ctx) => {
|
|
1086
|
+
const profileId = ctx.profileId;
|
|
1087
|
+
const ref = String(args.contact_id).trim();
|
|
1088
|
+
const fields = args.fields || {};
|
|
1089
|
+
const contacts = await query(
|
|
1090
|
+
"SELECT id FROM crm_contacts WHERE profile_id = ? AND (id = ? OR LOWER(email) = LOWER(?)) LIMIT 1",
|
|
1091
|
+
[profileId, ref, ref]
|
|
1092
|
+
);
|
|
1093
|
+
if (contacts.length === 0) throw new Error(`Contact not found with identifier: ${ref}`);
|
|
1094
|
+
const contactId = contacts[0].id;
|
|
1095
|
+
const allowedTextCols = /* @__PURE__ */ new Set([
|
|
1096
|
+
"first_name",
|
|
1097
|
+
"last_name",
|
|
1098
|
+
"email",
|
|
1099
|
+
"phone",
|
|
1100
|
+
"company",
|
|
1101
|
+
"job_title",
|
|
1102
|
+
"website",
|
|
1103
|
+
"bio",
|
|
1104
|
+
"status",
|
|
1105
|
+
"outreach_status",
|
|
1106
|
+
"notes",
|
|
1107
|
+
"agent_notes",
|
|
1108
|
+
"tags",
|
|
1109
|
+
"next_action",
|
|
1110
|
+
"icp_match",
|
|
1111
|
+
"urgency",
|
|
1112
|
+
"buying_intent"
|
|
1113
|
+
]);
|
|
1114
|
+
const allowedNumCols = /* @__PURE__ */ new Set(["lead_score", "next_follow_up_at"]);
|
|
1115
|
+
const updates = [];
|
|
1116
|
+
const params = [];
|
|
1117
|
+
for (const [k, v] of Object.entries(fields)) {
|
|
1118
|
+
if (v === null || v === void 0) continue;
|
|
1119
|
+
if (allowedTextCols.has(k)) {
|
|
1120
|
+
updates.push(`${k} = ?`);
|
|
1121
|
+
params.push(typeof v === "object" ? JSON.stringify(v) : String(v));
|
|
1122
|
+
} else if (allowedNumCols.has(k) && !Number.isNaN(Number(v))) {
|
|
1123
|
+
updates.push(`${k} = ?`);
|
|
1124
|
+
params.push(Number(v));
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
if (updates.length === 0) return { contact_id: contactId, status: "no_changes" };
|
|
1128
|
+
updates.push("updated_at = strftime('%s','now')");
|
|
1129
|
+
params.push(contactId, profileId);
|
|
1130
|
+
await execute(`UPDATE crm_contacts SET ${updates.join(", ")} WHERE id = ? AND profile_id = ?`, params);
|
|
1131
|
+
return { contact_id: contactId, status: "updated", updated_fields: Object.keys(fields) };
|
|
1132
|
+
}
|
|
1133
|
+
},
|
|
1134
|
+
{
|
|
1135
|
+
name: "crm_search_contacts",
|
|
1136
|
+
domain: "crm",
|
|
1137
|
+
description: "Search CRM contacts by name, email, company, tag, status, or last-contacted timestamp range.",
|
|
1138
|
+
inputSchema: {
|
|
1139
|
+
type: "object",
|
|
1140
|
+
properties: {
|
|
1141
|
+
query: { type: "string", description: "Free-text search across name, email, or company" },
|
|
1142
|
+
email: { type: "string", description: "Filter by email substring" },
|
|
1143
|
+
company: { type: "string", description: "Filter by company substring" },
|
|
1144
|
+
tag: { type: "string", description: "Filter by tag name" },
|
|
1145
|
+
status: { type: "string", enum: ["lead", "prospect", "customer", "churned"], description: "Lifecycle status filter" },
|
|
1146
|
+
last_contacted_before: { type: "string", description: "Unix timestamp or YYYY-MM-DD" },
|
|
1147
|
+
last_contacted_after: { type: "string", description: "Unix timestamp or YYYY-MM-DD" },
|
|
1148
|
+
limit: { type: "number", description: "Max contacts to return (default 20, max 50)" }
|
|
1149
|
+
}
|
|
1150
|
+
},
|
|
1151
|
+
handler: async (args, ctx) => {
|
|
1152
|
+
const conds = ["profile_id = ?", "archived = 0"];
|
|
1153
|
+
const params = [ctx.profileId];
|
|
1154
|
+
if (args.query) {
|
|
1155
|
+
conds.push("(LOWER(first_name || ' ' || COALESCE(last_name,'')) LIKE LOWER(?) OR LOWER(COALESCE(email,'')) LIKE LOWER(?) OR LOWER(COALESCE(company,'')) LIKE LOWER(?))");
|
|
1156
|
+
const q = `%${String(args.query).trim()}%`;
|
|
1157
|
+
params.push(q, q, q);
|
|
1158
|
+
}
|
|
1159
|
+
if (args.email) {
|
|
1160
|
+
conds.push("LOWER(COALESCE(email,'')) LIKE LOWER(?)");
|
|
1161
|
+
params.push(`%${String(args.email).trim()}%`);
|
|
1162
|
+
}
|
|
1163
|
+
if (args.company) {
|
|
1164
|
+
conds.push("LOWER(COALESCE(company,'')) LIKE LOWER(?)");
|
|
1165
|
+
params.push(`%${String(args.company).trim()}%`);
|
|
1166
|
+
}
|
|
1167
|
+
if (args.tag) {
|
|
1168
|
+
conds.push("LOWER(tags) LIKE LOWER(?)");
|
|
1169
|
+
params.push(`%"${String(args.tag).trim()}%`);
|
|
1170
|
+
}
|
|
1171
|
+
if (args.status) {
|
|
1172
|
+
conds.push("status = ?");
|
|
1173
|
+
params.push(String(args.status));
|
|
1174
|
+
}
|
|
1175
|
+
const lcBefore = parseTsOrDate(args.last_contacted_before);
|
|
1176
|
+
if (lcBefore !== null) {
|
|
1177
|
+
conds.push("COALESCE(last_contacted_at, last_activity_at, 0) < ?");
|
|
1178
|
+
params.push(lcBefore);
|
|
1179
|
+
}
|
|
1180
|
+
const lcAfter = parseTsOrDate(args.last_contacted_after);
|
|
1181
|
+
if (lcAfter !== null) {
|
|
1182
|
+
conds.push("COALESCE(last_contacted_at, last_activity_at, 0) >= ?");
|
|
1183
|
+
params.push(lcAfter);
|
|
1184
|
+
}
|
|
1185
|
+
const limit = Math.min(50, Math.max(1, Number(args.limit) || 20));
|
|
1186
|
+
params.push(limit);
|
|
1187
|
+
const rows = await query(
|
|
1188
|
+
`SELECT id, first_name, last_name, email, phone, company, status, outreach_status,
|
|
1189
|
+
tags, lead_score, last_contacted_at, last_activity_at
|
|
1190
|
+
FROM crm_contacts WHERE ${conds.join(" AND ")}
|
|
1191
|
+
ORDER BY COALESCE(last_contacted_at, last_activity_at, updated_at) DESC LIMIT ?`,
|
|
1192
|
+
params
|
|
1193
|
+
);
|
|
1194
|
+
const contacts = rows.map((r) => ({
|
|
1195
|
+
id: r.id,
|
|
1196
|
+
name: `${r.first_name || ""} ${r.last_name || ""}`.trim(),
|
|
1197
|
+
email: r.email ?? null,
|
|
1198
|
+
phone: r.phone ?? null,
|
|
1199
|
+
company: r.company ?? null,
|
|
1200
|
+
status: r.status,
|
|
1201
|
+
outreach_status: r.outreach_status,
|
|
1202
|
+
tags: r.tags || "[]",
|
|
1203
|
+
lead_score: r.lead_score || 0,
|
|
1204
|
+
last_contacted_at: r.last_contacted_at ?? null,
|
|
1205
|
+
last_activity_at: r.last_activity_at ?? null
|
|
1206
|
+
}));
|
|
1207
|
+
return { count: contacts.length, contacts };
|
|
1208
|
+
}
|
|
1209
|
+
},
|
|
1210
|
+
{
|
|
1211
|
+
name: "crm_get_contact",
|
|
1212
|
+
domain: "crm",
|
|
1213
|
+
description: "Get full contact context: profile, deals, recent activities, notes, open tasks, linked shop customer/vendor, recent Inbox threads, and open invoices.",
|
|
1214
|
+
inputSchema: {
|
|
1215
|
+
type: "object",
|
|
1216
|
+
properties: {
|
|
1217
|
+
contact_id: { type: "string", description: "Contact ID, email, or full name" },
|
|
1218
|
+
email: { type: "string", description: "Alternative email lookup if contact_id is omitted" }
|
|
1219
|
+
}
|
|
1220
|
+
},
|
|
1221
|
+
handler: async (args, ctx) => {
|
|
1222
|
+
const refVal = args.contact_id || args.email;
|
|
1223
|
+
if (!refVal) throw new Error("Missing required field: contact_id (or email)");
|
|
1224
|
+
const resolved = await resolveContactId(ctx.profileId, String(refVal));
|
|
1225
|
+
const contactId = resolved.id;
|
|
1226
|
+
const cRows = await query(
|
|
1227
|
+
`SELECT id, first_name, last_name, email, phone, company, job_title, website,
|
|
1228
|
+
status, outreach_status, tags, notes, agent_notes, lead_score, icp_match,
|
|
1229
|
+
urgency, next_action, next_follow_up_at, last_contacted_at, last_activity_at,
|
|
1230
|
+
total_spent_cents, total_purchases
|
|
1231
|
+
FROM crm_contacts WHERE id = ? AND profile_id = ? LIMIT 1`,
|
|
1232
|
+
[contactId, ctx.profileId]
|
|
1233
|
+
);
|
|
1234
|
+
const c = cRows[0];
|
|
1235
|
+
const deals = await query(
|
|
1236
|
+
"SELECT id, title, value_cents, currency, stage, probability, expected_close_at FROM crm_deals WHERE profile_id = ? AND contact_id = ? ORDER BY created_at DESC LIMIT 10",
|
|
1237
|
+
[ctx.profileId, contactId]
|
|
1238
|
+
);
|
|
1239
|
+
const activities = await query(
|
|
1240
|
+
"SELECT id, type, direction, sender as author, subject, body as summary, outcome, source_thread_id, occurred_at FROM crm_activities WHERE profile_id = ? AND contact_id = ? ORDER BY occurred_at DESC LIMIT 15",
|
|
1241
|
+
[ctx.profileId, contactId]
|
|
1242
|
+
);
|
|
1243
|
+
const notes = await query(
|
|
1244
|
+
"SELECT id, deal_id, body, pinned, created_at FROM crm_notes WHERE profile_id = ? AND contact_id = ? ORDER BY pinned DESC, created_at DESC LIMIT 10",
|
|
1245
|
+
[ctx.profileId, contactId]
|
|
1246
|
+
);
|
|
1247
|
+
const openTasks = await query(
|
|
1248
|
+
"SELECT id, title, due_at, priority, status FROM crm_tasks WHERE profile_id = ? AND contact_id = ? AND status = 'open' ORDER BY due_at ASC LIMIT 10",
|
|
1249
|
+
[ctx.profileId, contactId]
|
|
1250
|
+
);
|
|
1251
|
+
const linkedCustomerRows = await query(
|
|
1252
|
+
"SELECT id, name, credit_used, total_orders, total_spent FROM shop_customers WHERE profile_id = ? AND (contact_id = ? OR (? IS NOT NULL AND LOWER(email) = LOWER(?))) LIMIT 1",
|
|
1253
|
+
[ctx.profileId, contactId, c.email, c.email]
|
|
1254
|
+
);
|
|
1255
|
+
const linkedVendorRows = await query(
|
|
1256
|
+
"SELECT id, name, credit_used, payment_terms FROM shop_vendors WHERE profile_id = ? AND (contact_id = ? OR (? IS NOT NULL AND LOWER(email) = LOWER(?))) LIMIT 1",
|
|
1257
|
+
[ctx.profileId, contactId, c.email, c.email]
|
|
1258
|
+
);
|
|
1259
|
+
const threads = await query(
|
|
1260
|
+
`SELECT t.id, t.subject, t.state, t.category, t.last_message_at, t.agent_summary
|
|
1261
|
+
FROM inbox_threads t
|
|
1262
|
+
WHERE t.profile_id = ? AND t.linked_entity_type = 'contact' AND t.linked_entity_id = ?
|
|
1263
|
+
AND NOT EXISTS (SELECT 1 FROM inbox_messages m WHERE m.thread_id = t.id AND m.screen_status IN ('suspicious','blocked'))
|
|
1264
|
+
ORDER BY t.last_message_at DESC LIMIT 8`,
|
|
1265
|
+
[ctx.profileId, contactId]
|
|
1266
|
+
);
|
|
1267
|
+
const openInvoices = await query(
|
|
1268
|
+
"SELECT id, invoice_number as number, status, total_cents, currency, due_at FROM crm_invoices WHERE profile_id = ? AND contact_id = ? AND status IN ('draft','sent','viewed','overdue') ORDER BY created_at DESC LIMIT 10",
|
|
1269
|
+
[ctx.profileId, contactId]
|
|
1270
|
+
);
|
|
1271
|
+
return {
|
|
1272
|
+
contact: {
|
|
1273
|
+
...c,
|
|
1274
|
+
name: `${c.first_name || ""} ${c.last_name || ""}`.trim()
|
|
1275
|
+
},
|
|
1276
|
+
deals,
|
|
1277
|
+
activities,
|
|
1278
|
+
notes,
|
|
1279
|
+
open_tasks: openTasks,
|
|
1280
|
+
linked_customer: linkedCustomerRows[0] ?? null,
|
|
1281
|
+
linked_vendor: linkedVendorRows[0] ?? null,
|
|
1282
|
+
recent_threads: threads,
|
|
1283
|
+
open_invoices: openInvoices
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
},
|
|
1287
|
+
{
|
|
1288
|
+
name: "crm_list_deals",
|
|
1289
|
+
domain: "crm",
|
|
1290
|
+
description: "List CRM pipeline deals, optionally filtered by contact, stage, or open_only.",
|
|
1291
|
+
inputSchema: {
|
|
1292
|
+
type: "object",
|
|
1293
|
+
properties: {
|
|
1294
|
+
contact_id: { type: "string", description: "Optional contact ID filter" },
|
|
1295
|
+
stage: { type: "string", description: "Optional pipeline stage filter" },
|
|
1296
|
+
open_only: { type: "boolean", description: "Exclude won/lost deals when true" },
|
|
1297
|
+
limit: { type: "number", description: "Max deals to return (default 25, max 50)" }
|
|
1298
|
+
}
|
|
1299
|
+
},
|
|
1300
|
+
handler: async (args, ctx) => {
|
|
1301
|
+
const conds = ["d.profile_id = ?"];
|
|
1302
|
+
const params = [ctx.profileId];
|
|
1303
|
+
if (args.contact_id) {
|
|
1304
|
+
conds.push("d.contact_id = ?");
|
|
1305
|
+
params.push(String(args.contact_id));
|
|
1306
|
+
}
|
|
1307
|
+
if (args.stage) {
|
|
1308
|
+
conds.push("d.stage = ?");
|
|
1309
|
+
params.push(String(args.stage));
|
|
1310
|
+
}
|
|
1311
|
+
if (args.open_only) {
|
|
1312
|
+
conds.push("d.stage NOT IN ('won', 'lost')");
|
|
1313
|
+
}
|
|
1314
|
+
const limit = Math.min(50, Math.max(1, Number(args.limit) || 25));
|
|
1315
|
+
params.push(limit);
|
|
1316
|
+
const rows = await query(
|
|
1317
|
+
`SELECT d.id, d.contact_id, d.title, d.value_cents, d.currency, d.stage,
|
|
1318
|
+
d.probability, d.expected_close_at, d.updated_at,
|
|
1319
|
+
c.first_name, c.last_name, c.company
|
|
1320
|
+
FROM crm_deals d
|
|
1321
|
+
LEFT JOIN crm_contacts c ON c.id = d.contact_id AND c.profile_id = d.profile_id
|
|
1322
|
+
WHERE ${conds.join(" AND ")} ORDER BY d.updated_at DESC LIMIT ?`,
|
|
1323
|
+
params
|
|
1324
|
+
);
|
|
1325
|
+
const deals = rows.map((r) => ({
|
|
1326
|
+
id: r.id,
|
|
1327
|
+
contact_id: r.contact_id,
|
|
1328
|
+
contact_name: `${r.first_name || ""} ${r.last_name || ""}`.trim(),
|
|
1329
|
+
company: r.company ?? null,
|
|
1330
|
+
title: r.title,
|
|
1331
|
+
value_cents: r.value_cents || 0,
|
|
1332
|
+
currency: r.currency || "usd",
|
|
1333
|
+
stage: r.stage,
|
|
1334
|
+
probability: r.probability || 0,
|
|
1335
|
+
expected_close_at: r.expected_close_at ?? null,
|
|
1336
|
+
updated_at: r.updated_at
|
|
1337
|
+
}));
|
|
1338
|
+
return { count: deals.length, deals };
|
|
1339
|
+
}
|
|
1340
|
+
},
|
|
1341
|
+
{
|
|
1342
|
+
name: "crm_get_deal",
|
|
1343
|
+
domain: "crm",
|
|
1344
|
+
description: "Get a single deal with its linked activities and proposals.",
|
|
1345
|
+
inputSchema: {
|
|
1346
|
+
type: "object",
|
|
1347
|
+
properties: {
|
|
1348
|
+
deal_id: { type: "string", description: "Deal ID" }
|
|
1349
|
+
},
|
|
1350
|
+
required: ["deal_id"]
|
|
1351
|
+
},
|
|
1352
|
+
handler: async (args, ctx) => {
|
|
1353
|
+
const dealId = String(args.deal_id || "");
|
|
1354
|
+
const deals = await query("SELECT * FROM crm_deals WHERE id = ? AND profile_id = ? LIMIT 1", [dealId, ctx.profileId]);
|
|
1355
|
+
if (deals.length === 0) throw new Error(`Deal not found: ${dealId}`);
|
|
1356
|
+
const activities = await query(
|
|
1357
|
+
"SELECT id, type, direction, sender as author, subject, body as summary, occurred_at FROM crm_activities WHERE profile_id = ? AND deal_id = ? ORDER BY occurred_at DESC LIMIT 10",
|
|
1358
|
+
[ctx.profileId, dealId]
|
|
1359
|
+
);
|
|
1360
|
+
const proposals = await query(
|
|
1361
|
+
"SELECT id, title, status, payment_amount_cents, sent_at, signed_at FROM crm_proposals WHERE profile_id = ? AND deal_id = ? ORDER BY created_at DESC LIMIT 5",
|
|
1362
|
+
[ctx.profileId, dealId]
|
|
1363
|
+
);
|
|
1364
|
+
return { deal: deals[0], activities, proposals };
|
|
1365
|
+
}
|
|
1366
|
+
},
|
|
1367
|
+
{
|
|
1368
|
+
name: "crm_list_tasks",
|
|
1369
|
+
domain: "crm",
|
|
1370
|
+
description: "List CRM follow-up tasks (due, overdue, or by contact).",
|
|
1371
|
+
inputSchema: {
|
|
1372
|
+
type: "object",
|
|
1373
|
+
properties: {
|
|
1374
|
+
status: { type: "string", enum: ["open", "done", "all"], description: "Task status filter (default 'open')" },
|
|
1375
|
+
contact_id: { type: "string", description: "Optional contact ID filter" },
|
|
1376
|
+
overdue_only: { type: "boolean", description: "Only tasks past due_at" },
|
|
1377
|
+
due_before: { type: "string", description: "Unix timestamp or YYYY-MM-DD" },
|
|
1378
|
+
limit: { type: "number", description: "Max tasks to return (default 25)" }
|
|
1379
|
+
}
|
|
1380
|
+
},
|
|
1381
|
+
handler: async (args, ctx) => {
|
|
1382
|
+
const now = nowTs();
|
|
1383
|
+
const status = String(args.status || "open");
|
|
1384
|
+
const conds = ["t.profile_id = ?"];
|
|
1385
|
+
const params = [ctx.profileId];
|
|
1386
|
+
if (status !== "all") {
|
|
1387
|
+
conds.push("t.status = ?");
|
|
1388
|
+
params.push(status);
|
|
1389
|
+
}
|
|
1390
|
+
if (args.contact_id) {
|
|
1391
|
+
conds.push("t.contact_id = ?");
|
|
1392
|
+
params.push(String(args.contact_id));
|
|
1393
|
+
}
|
|
1394
|
+
const dueBefore = parseTsOrDate(args.due_before);
|
|
1395
|
+
if (args.overdue_only) {
|
|
1396
|
+
conds.push("t.due_at IS NOT NULL AND t.due_at < ?");
|
|
1397
|
+
params.push(now);
|
|
1398
|
+
} else if (dueBefore !== null) {
|
|
1399
|
+
conds.push("t.due_at IS NOT NULL AND t.due_at <= ?");
|
|
1400
|
+
params.push(dueBefore);
|
|
1401
|
+
}
|
|
1402
|
+
const limit = Math.min(50, Math.max(1, Number(args.limit) || 25));
|
|
1403
|
+
params.push(limit);
|
|
1404
|
+
const rows = await query(
|
|
1405
|
+
`SELECT t.id, t.contact_id, t.deal_id, t.title, t.description, t.due_at, t.priority, t.status,
|
|
1406
|
+
c.first_name, c.last_name, c.email
|
|
1407
|
+
FROM crm_tasks t
|
|
1408
|
+
LEFT JOIN crm_contacts c ON c.id = t.contact_id AND c.profile_id = t.profile_id
|
|
1409
|
+
WHERE ${conds.join(" AND ")} ORDER BY COALESCE(t.due_at, 9999999999) ASC LIMIT ?`,
|
|
1410
|
+
params
|
|
1411
|
+
);
|
|
1412
|
+
const tasks = rows.map((r) => ({
|
|
1413
|
+
id: r.id,
|
|
1414
|
+
contact_id: r.contact_id ?? null,
|
|
1415
|
+
contact_name: `${r.first_name || ""} ${r.last_name || ""}`.trim(),
|
|
1416
|
+
contact_email: r.email ?? null,
|
|
1417
|
+
deal_id: r.deal_id ?? null,
|
|
1418
|
+
title: r.title,
|
|
1419
|
+
description: r.description ?? null,
|
|
1420
|
+
due_at: r.due_at ?? null,
|
|
1421
|
+
is_overdue: typeof r.due_at === "number" && r.due_at < now,
|
|
1422
|
+
priority: r.priority,
|
|
1423
|
+
status: r.status
|
|
1424
|
+
}));
|
|
1425
|
+
return { count: tasks.length, tasks };
|
|
1426
|
+
}
|
|
1427
|
+
},
|
|
1428
|
+
{
|
|
1429
|
+
name: "crm_list_stale",
|
|
1430
|
+
domain: "crm",
|
|
1431
|
+
description: "List contacts and open deals that have gone quiet (no activity for N days, default 14).",
|
|
1432
|
+
inputSchema: {
|
|
1433
|
+
type: "object",
|
|
1434
|
+
properties: {
|
|
1435
|
+
days: { type: "number", description: "Silence threshold in days (defaults to crm.stale_days or 14)" },
|
|
1436
|
+
include_deals: { type: "boolean", description: "Include stale open deals (default true)" },
|
|
1437
|
+
limit: { type: "number", description: "Max rows per list (default 20)" }
|
|
1438
|
+
}
|
|
1439
|
+
},
|
|
1440
|
+
handler: async (args, ctx) => {
|
|
1441
|
+
const cfgDays = await getCrmConfigVal(ctx.profileId, "crm.stale_days");
|
|
1442
|
+
const days = Math.max(1, Number(args.days) || (cfgDays ? Number(cfgDays) : 14));
|
|
1443
|
+
const limit = Math.min(50, Math.max(1, Number(args.limit) || 20));
|
|
1444
|
+
const now = nowTs();
|
|
1445
|
+
const cutoff = now - days * 86400;
|
|
1446
|
+
const cRows = await query(
|
|
1447
|
+
`SELECT id, first_name, last_name, email, company, status,
|
|
1448
|
+
COALESCE(last_contacted_at, last_activity_at, updated_at) AS last_ts
|
|
1449
|
+
FROM crm_contacts
|
|
1450
|
+
WHERE profile_id = ? AND archived = 0
|
|
1451
|
+
AND COALESCE(last_contacted_at, last_activity_at, updated_at) < ?
|
|
1452
|
+
ORDER BY last_ts ASC LIMIT ?`,
|
|
1453
|
+
[ctx.profileId, cutoff, limit]
|
|
1454
|
+
);
|
|
1455
|
+
const staleContacts = cRows.map((r) => ({
|
|
1456
|
+
id: r.id,
|
|
1457
|
+
name: `${r.first_name || ""} ${r.last_name || ""}`.trim(),
|
|
1458
|
+
email: r.email ?? null,
|
|
1459
|
+
company: r.company ?? null,
|
|
1460
|
+
status: r.status,
|
|
1461
|
+
last_activity_at: r.last_ts,
|
|
1462
|
+
days_silent: Math.floor(Math.max(0, now - Number(r.last_ts || 0)) / 86400)
|
|
1463
|
+
}));
|
|
1464
|
+
let staleDeals = [];
|
|
1465
|
+
if (args.include_deals !== false) {
|
|
1466
|
+
const dRows = await query(
|
|
1467
|
+
`SELECT d.id, d.contact_id, d.title, d.stage, d.value_cents, d.currency, d.updated_at,
|
|
1468
|
+
c.first_name, c.last_name
|
|
1469
|
+
FROM crm_deals d
|
|
1470
|
+
LEFT JOIN crm_contacts c ON c.id = d.contact_id AND c.profile_id = d.profile_id
|
|
1471
|
+
WHERE d.profile_id = ? AND d.stage NOT IN ('won','lost') AND d.updated_at < ?
|
|
1472
|
+
ORDER BY d.updated_at ASC LIMIT ?`,
|
|
1473
|
+
[ctx.profileId, cutoff, limit]
|
|
1474
|
+
);
|
|
1475
|
+
staleDeals = dRows.map((r) => ({
|
|
1476
|
+
id: r.id,
|
|
1477
|
+
contact_id: r.contact_id,
|
|
1478
|
+
contact_name: `${r.first_name || ""} ${r.last_name || ""}`.trim(),
|
|
1479
|
+
title: r.title,
|
|
1480
|
+
stage: r.stage,
|
|
1481
|
+
value_cents: r.value_cents || 0,
|
|
1482
|
+
currency: r.currency || "usd",
|
|
1483
|
+
days_silent: Math.floor(Math.max(0, now - Number(r.updated_at || 0)) / 86400)
|
|
1484
|
+
}));
|
|
1485
|
+
}
|
|
1486
|
+
return { threshold_days: days, stale_contacts: staleContacts, stale_deals: staleDeals };
|
|
1487
|
+
}
|
|
1488
|
+
},
|
|
1489
|
+
{
|
|
1490
|
+
name: "crm_get_client_billing",
|
|
1491
|
+
domain: "crm",
|
|
1492
|
+
description: "Read-only client billing summary across crm_invoices, crm_proposals, and linked shop_documents.",
|
|
1493
|
+
inputSchema: {
|
|
1494
|
+
type: "object",
|
|
1495
|
+
properties: {
|
|
1496
|
+
contact_id: { type: "string", description: "Contact ID or email" },
|
|
1497
|
+
email: { type: "string", description: "Alternative email lookup" }
|
|
1498
|
+
}
|
|
1499
|
+
},
|
|
1500
|
+
handler: async (args, ctx) => {
|
|
1501
|
+
const refVal = args.contact_id || args.email;
|
|
1502
|
+
if (!refVal) throw new Error("Missing required field: contact_id (or email)");
|
|
1503
|
+
const resolved = await resolveContactId(ctx.profileId, String(refVal));
|
|
1504
|
+
const now = nowTs();
|
|
1505
|
+
const crmInvRows = await query(
|
|
1506
|
+
"SELECT id, invoice_number, status, total_cents, currency, issued_at, due_at, paid_at FROM crm_invoices WHERE profile_id = ? AND contact_id = ? ORDER BY created_at DESC LIMIT 25",
|
|
1507
|
+
[ctx.profileId, resolved.id]
|
|
1508
|
+
);
|
|
1509
|
+
let crmPaidCents = 0;
|
|
1510
|
+
let crmUnpaidCents = 0;
|
|
1511
|
+
let crmOverdueCount = 0;
|
|
1512
|
+
const crmInvoices = crmInvRows.map((r) => {
|
|
1513
|
+
const isPaid = r.status === "paid" || r.paid_at !== null;
|
|
1514
|
+
const isVoid = ["cancelled", "refunded", "draft"].includes(r.status);
|
|
1515
|
+
const isOverdue = !isPaid && !isVoid && (r.status === "overdue" || typeof r.due_at === "number" && r.due_at < now);
|
|
1516
|
+
if (isPaid) crmPaidCents += Number(r.total_cents || 0);
|
|
1517
|
+
else if (!isVoid) crmUnpaidCents += Number(r.total_cents || 0);
|
|
1518
|
+
if (isOverdue) crmOverdueCount += 1;
|
|
1519
|
+
return { source: "crm_invoices", id: r.id, number: r.invoice_number, status: isOverdue ? "overdue" : r.status, total_cents: r.total_cents, currency: r.currency, due_at: r.due_at, paid_at: r.paid_at };
|
|
1520
|
+
});
|
|
1521
|
+
const proposals = await query(
|
|
1522
|
+
"SELECT id, title, status, payment_amount_cents, payment_currency as currency, sent_at, signed_at, paid_at FROM crm_proposals WHERE profile_id = ? AND contact_id = ? ORDER BY created_at DESC LIMIT 15",
|
|
1523
|
+
[ctx.profileId, resolved.id]
|
|
1524
|
+
);
|
|
1525
|
+
let shopDocs = [];
|
|
1526
|
+
let shopPaid = 0;
|
|
1527
|
+
let shopUnpaid = 0;
|
|
1528
|
+
const cust = await query(
|
|
1529
|
+
"SELECT id FROM shop_customers WHERE profile_id = ? AND (contact_id = ? OR (? IS NOT NULL AND LOWER(email) = LOWER(?))) LIMIT 1",
|
|
1530
|
+
[ctx.profileId, resolved.id, resolved.email, resolved.email]
|
|
1531
|
+
);
|
|
1532
|
+
if (cust.length > 0) {
|
|
1533
|
+
shopDocs = await query(
|
|
1534
|
+
"SELECT id, doc_type, doc_number as number, status, currency, grand_total, amount_paid, amount_due, doc_date, due_date FROM shop_documents WHERE profile_id = ? AND customer_id = ? AND doc_type IN ('invoice','sales_order','estimate') ORDER BY doc_date DESC LIMIT 25",
|
|
1535
|
+
[ctx.profileId, cust[0].id]
|
|
1536
|
+
);
|
|
1537
|
+
for (const d of shopDocs) {
|
|
1538
|
+
if (!["cancelled", "void"].includes(d.status)) {
|
|
1539
|
+
shopPaid += Number(d.amount_paid || 0);
|
|
1540
|
+
shopUnpaid += Number(d.amount_due || 0);
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
return {
|
|
1545
|
+
contact_id: resolved.id,
|
|
1546
|
+
contact_name: resolved.name,
|
|
1547
|
+
crm_invoices: crmInvoices,
|
|
1548
|
+
crm_proposals: proposals,
|
|
1549
|
+
shop_documents: shopDocs,
|
|
1550
|
+
summary: {
|
|
1551
|
+
crm_paid_cents: crmPaidCents,
|
|
1552
|
+
crm_unpaid_cents: crmUnpaidCents,
|
|
1553
|
+
crm_overdue_count: crmOverdueCount,
|
|
1554
|
+
shop_paid_amount: shopPaid,
|
|
1555
|
+
shop_unpaid_amount: shopUnpaid
|
|
1556
|
+
}
|
|
1557
|
+
};
|
|
1558
|
+
}
|
|
1559
|
+
},
|
|
1560
|
+
{
|
|
1561
|
+
name: "crm_log_activity",
|
|
1562
|
+
domain: "crm",
|
|
1563
|
+
description: "Log an activity summary (email, call, meeting, note, dm) on a contact timeline attributed author='agent'. Never stores raw email bodies.",
|
|
1564
|
+
inputSchema: {
|
|
1565
|
+
type: "object",
|
|
1566
|
+
properties: {
|
|
1567
|
+
contact_id: { type: "string", description: "Contact ID or email" },
|
|
1568
|
+
deal_id: { type: "string", description: "Optional deal ID" },
|
|
1569
|
+
activity_type: { type: "string", enum: ["email", "call", "meeting", "note", "dm", "task_done", "agent_action"] },
|
|
1570
|
+
direction: { type: "string", enum: ["inbound", "outbound"] },
|
|
1571
|
+
subject: { type: "string", description: "Short subject or headline" },
|
|
1572
|
+
summary: { type: "string", description: "Short summary (capped at 1000 chars)" },
|
|
1573
|
+
outcome: { type: "string", description: "Optional outcome" },
|
|
1574
|
+
source_thread_id: { type: "string", description: "Optional Inbox thread ID" },
|
|
1575
|
+
idempotency_key: { type: "string", description: "Optional dedupe key" }
|
|
1576
|
+
},
|
|
1577
|
+
required: ["contact_id"]
|
|
1578
|
+
},
|
|
1579
|
+
handler: async (args, ctx) => {
|
|
1580
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
1581
|
+
const actId = generateId("act");
|
|
1582
|
+
const now = nowTs();
|
|
1583
|
+
const activityType = String(args.activity_type || "note");
|
|
1584
|
+
const direction = String(args.direction || "outbound");
|
|
1585
|
+
const summary = args.summary ?? args.body ?? null;
|
|
1586
|
+
const bodyStr = summary ? String(summary).slice(0, 1e3) : null;
|
|
1587
|
+
const meta = JSON.stringify({ author: "agent", source_thread_id: args.source_thread_id ?? null });
|
|
1588
|
+
await execute(
|
|
1589
|
+
`INSERT OR IGNORE INTO crm_activities
|
|
1590
|
+
(id, profile_id, contact_id, deal_id, type, direction, sender, subject, body, outcome,
|
|
1591
|
+
metadata, approval_status, occurred_at, created_at, idempotency_key, source_thread_id)
|
|
1592
|
+
VALUES (?, ?, ?, ?, ?, ?, 'agent', ?, ?, ?, ?, 'auto_sent', ?, ?, ?, ?)`,
|
|
1593
|
+
[
|
|
1594
|
+
actId,
|
|
1595
|
+
ctx.profileId,
|
|
1596
|
+
resolved.id,
|
|
1597
|
+
args.deal_id ?? null,
|
|
1598
|
+
activityType,
|
|
1599
|
+
direction,
|
|
1600
|
+
args.subject ?? null,
|
|
1601
|
+
bodyStr,
|
|
1602
|
+
args.outcome ?? null,
|
|
1603
|
+
meta,
|
|
1604
|
+
now,
|
|
1605
|
+
now,
|
|
1606
|
+
args.idempotency_key ?? null,
|
|
1607
|
+
args.source_thread_id ?? null
|
|
1608
|
+
]
|
|
1609
|
+
);
|
|
1610
|
+
if (["email", "call", "dm", "meeting"].includes(activityType)) {
|
|
1611
|
+
await execute(
|
|
1612
|
+
"UPDATE crm_contacts SET last_activity_at = ?, last_contacted_at = ?, updated_at = ? WHERE id = ? AND profile_id = ?",
|
|
1613
|
+
[now, now, now, resolved.id, ctx.profileId]
|
|
1614
|
+
);
|
|
1615
|
+
} else {
|
|
1616
|
+
await execute(
|
|
1617
|
+
"UPDATE crm_contacts SET last_activity_at = ?, updated_at = ? WHERE id = ? AND profile_id = ?",
|
|
1618
|
+
[now, now, resolved.id, ctx.profileId]
|
|
1619
|
+
);
|
|
1620
|
+
}
|
|
1621
|
+
return { activity_id: actId, contact_id: resolved.id, type: activityType, author: "agent", status: "logged" };
|
|
1622
|
+
}
|
|
1623
|
+
},
|
|
1624
|
+
{
|
|
1625
|
+
name: "crm_add_note",
|
|
1626
|
+
domain: "crm",
|
|
1627
|
+
description: "Add a CRM note on a contact (and optionally a deal).",
|
|
1628
|
+
inputSchema: {
|
|
1629
|
+
type: "object",
|
|
1630
|
+
properties: {
|
|
1631
|
+
contact_id: { type: "string", description: "Contact ID or email" },
|
|
1632
|
+
deal_id: { type: "string", description: "Optional deal ID" },
|
|
1633
|
+
body: { type: "string", description: "Note content" },
|
|
1634
|
+
pinned: { type: "boolean", description: "Pin note to top (default false)" },
|
|
1635
|
+
idempotency_key: { type: "string", description: "Optional dedupe key" }
|
|
1636
|
+
},
|
|
1637
|
+
required: ["contact_id", "body"]
|
|
1638
|
+
},
|
|
1639
|
+
handler: async (args, ctx) => {
|
|
1640
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
1641
|
+
const body = String(args.body || "").trim();
|
|
1642
|
+
if (!body) throw new Error("Missing required field: body");
|
|
1643
|
+
const noteId = generateId("note");
|
|
1644
|
+
const now = nowTs();
|
|
1645
|
+
await execute(
|
|
1646
|
+
`INSERT OR IGNORE INTO crm_notes (id, profile_id, contact_id, deal_id, body, pinned, idempotency_key, created_at, updated_at)
|
|
1647
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
1648
|
+
[noteId, ctx.profileId, resolved.id, args.deal_id ?? null, body, args.pinned ? 1 : 0, args.idempotency_key ?? null, now, now]
|
|
1649
|
+
);
|
|
1650
|
+
return { note_id: noteId, contact_id: resolved.id, author: "agent", status: "created" };
|
|
1651
|
+
}
|
|
1652
|
+
},
|
|
1653
|
+
{
|
|
1654
|
+
name: "crm_create_task",
|
|
1655
|
+
domain: "crm",
|
|
1656
|
+
description: "Create a follow-up task in crm_tasks.",
|
|
1657
|
+
inputSchema: {
|
|
1658
|
+
type: "object",
|
|
1659
|
+
properties: {
|
|
1660
|
+
title: { type: "string", description: "Task title" },
|
|
1661
|
+
contact_id: { type: "string", description: "Optional contact ID or email" },
|
|
1662
|
+
deal_id: { type: "string", description: "Optional deal ID" },
|
|
1663
|
+
description: { type: "string", description: "Task details" },
|
|
1664
|
+
due_at: { type: "string", description: "Due date (YYYY-MM-DD or Unix timestamp)" },
|
|
1665
|
+
priority: { type: "string", enum: ["low", "medium", "high"] },
|
|
1666
|
+
idempotency_key: { type: "string", description: "Optional dedupe key" }
|
|
1667
|
+
},
|
|
1668
|
+
required: ["title"]
|
|
1669
|
+
},
|
|
1670
|
+
handler: async (args, ctx) => {
|
|
1671
|
+
const title = String(args.title || "").trim();
|
|
1672
|
+
if (!title) throw new Error("Missing required field: title");
|
|
1673
|
+
const contactId = args.contact_id ? (await resolveContactId(ctx.profileId, String(args.contact_id))).id : null;
|
|
1674
|
+
const dueAt = parseTsOrDate(args.due_at);
|
|
1675
|
+
const priority = ["low", "high"].includes(String(args.priority)) ? String(args.priority) : "medium";
|
|
1676
|
+
const taskId = generateId("tsk");
|
|
1677
|
+
const now = nowTs();
|
|
1678
|
+
await execute(
|
|
1679
|
+
`INSERT OR IGNORE INTO crm_tasks
|
|
1680
|
+
(id, profile_id, contact_id, deal_id, title, description, due_at, priority, status, idempotency_key, created_at, updated_at)
|
|
1681
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?)`,
|
|
1682
|
+
[taskId, ctx.profileId, contactId, args.deal_id ?? null, title, args.description ?? null, dueAt, priority, args.idempotency_key ?? null, now, now]
|
|
1683
|
+
);
|
|
1684
|
+
return { task_id: taskId, contact_id: contactId, title, due_at: dueAt, priority, author: "agent", status: "created" };
|
|
1685
|
+
}
|
|
1686
|
+
},
|
|
1687
|
+
{
|
|
1688
|
+
name: "crm_add_tag",
|
|
1689
|
+
domain: "crm",
|
|
1690
|
+
description: "Append a tag to a CRM contact idempotently.",
|
|
1691
|
+
inputSchema: {
|
|
1692
|
+
type: "object",
|
|
1693
|
+
properties: {
|
|
1694
|
+
contact_id: { type: "string", description: "Contact ID or email" },
|
|
1695
|
+
tag: { type: "string", description: "Tag name to add" }
|
|
1696
|
+
},
|
|
1697
|
+
required: ["contact_id", "tag"]
|
|
1698
|
+
},
|
|
1699
|
+
handler: async (args, ctx) => {
|
|
1700
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
1701
|
+
const tag = String(args.tag || "").trim();
|
|
1702
|
+
if (!tag) throw new Error("Missing required field: tag");
|
|
1703
|
+
const rows = await query("SELECT tags FROM crm_contacts WHERE id = ? AND profile_id = ? LIMIT 1", [resolved.id, ctx.profileId]);
|
|
1704
|
+
let tags = [];
|
|
1705
|
+
try {
|
|
1706
|
+
tags = JSON.parse(rows[0]?.tags || "[]");
|
|
1707
|
+
} catch {
|
|
1708
|
+
tags = [];
|
|
1709
|
+
}
|
|
1710
|
+
if (!tags.some((t) => t.toLowerCase() === tag.toLowerCase())) tags.push(tag);
|
|
1711
|
+
await execute("UPDATE crm_contacts SET tags = ?, updated_at = ? WHERE id = ? AND profile_id = ?", [
|
|
1712
|
+
JSON.stringify(tags),
|
|
1713
|
+
nowTs(),
|
|
1714
|
+
resolved.id,
|
|
1715
|
+
ctx.profileId
|
|
1716
|
+
]);
|
|
1717
|
+
return { contact_id: resolved.id, tag, tags, status: "updated" };
|
|
1718
|
+
}
|
|
1719
|
+
},
|
|
1720
|
+
{
|
|
1721
|
+
name: "crm_create_contact_from_mail",
|
|
1722
|
+
domain: "crm",
|
|
1723
|
+
description: "Propose creating a new CRM contact from an Inbox sender. Queues an approval item for the human instead of auto-creating.",
|
|
1724
|
+
inputSchema: {
|
|
1725
|
+
type: "object",
|
|
1726
|
+
properties: {
|
|
1727
|
+
email: { type: "string", description: "Sender email address" },
|
|
1728
|
+
name: { type: "string", description: "Display name" },
|
|
1729
|
+
company: { type: "string", description: "Optional company name" },
|
|
1730
|
+
thread_id: { type: "string", description: "Source Inbox thread ID" },
|
|
1731
|
+
reason: { type: "string", description: "One-line context why this contact should be added" },
|
|
1732
|
+
sources: { type: "array", items: { type: "string" } }
|
|
1733
|
+
},
|
|
1734
|
+
required: ["email"]
|
|
1735
|
+
},
|
|
1736
|
+
handler: async (args, ctx) => {
|
|
1737
|
+
const email = String(args.email || "").trim().toLowerCase();
|
|
1738
|
+
if (!email) throw new Error("Missing required field: email");
|
|
1739
|
+
const existing = await query(
|
|
1740
|
+
"SELECT id FROM crm_contacts WHERE profile_id = ? AND LOWER(email) = LOWER(?) LIMIT 1",
|
|
1741
|
+
[ctx.profileId, email]
|
|
1742
|
+
);
|
|
1743
|
+
if (existing.length > 0) return { contact_id: existing[0].id, email, status: "already_exists" };
|
|
1744
|
+
const name = String(args.name || "").trim() || email;
|
|
1745
|
+
const threadId = args.thread_id ? String(args.thread_id) : null;
|
|
1746
|
+
const sources = Array.isArray(args.sources) ? args.sources.map(String) : threadId ? [`thread:${threadId}`] : [];
|
|
1747
|
+
return queueApprovalItem(
|
|
1748
|
+
ctx.profileId,
|
|
1749
|
+
"crm_create_contact_from_mail",
|
|
1750
|
+
`New contact: ${name} (${email})`,
|
|
1751
|
+
args,
|
|
1752
|
+
String(args.reason || "New sender spotted in Inbox email"),
|
|
1753
|
+
sources,
|
|
1754
|
+
threadId,
|
|
1755
|
+
`new_contact:${ctx.profileId}:${email}`
|
|
1756
|
+
);
|
|
1757
|
+
}
|
|
1758
|
+
},
|
|
1759
|
+
{
|
|
1760
|
+
name: "crm_propose_deal",
|
|
1761
|
+
domain: "crm",
|
|
1762
|
+
description: "Propose a new pipeline deal for human approval (does not create the deal until approved).",
|
|
1763
|
+
inputSchema: {
|
|
1764
|
+
type: "object",
|
|
1765
|
+
properties: {
|
|
1766
|
+
contact_id: { type: "string", description: "Contact ID or email" },
|
|
1767
|
+
title: { type: "string", description: "Deal title" },
|
|
1768
|
+
value_cents: { type: "number", description: "Deal value in minor units (cents)" },
|
|
1769
|
+
currency: { type: "string", description: "Currency code (default 'usd')" },
|
|
1770
|
+
stage: { type: "string", description: "Initial stage (default 'new')" },
|
|
1771
|
+
expected_close_at: { type: "string", description: "Expected close date (YYYY-MM-DD or Unix timestamp)" },
|
|
1772
|
+
notes: { type: "string", description: "Deal context" },
|
|
1773
|
+
reason: { type: "string", description: "Why this deal is proposed" },
|
|
1774
|
+
sources: { type: "array", items: { type: "string" } }
|
|
1775
|
+
},
|
|
1776
|
+
required: ["contact_id", "title"]
|
|
1777
|
+
},
|
|
1778
|
+
handler: async (args, ctx) => {
|
|
1779
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
1780
|
+
const title = String(args.title || "").trim();
|
|
1781
|
+
if (!title) throw new Error("Missing required field: title");
|
|
1782
|
+
return queueApprovalItem(
|
|
1783
|
+
ctx.profileId,
|
|
1784
|
+
"crm_propose_deal",
|
|
1785
|
+
`Create deal "${title}" for ${resolved.name}`,
|
|
1786
|
+
{ ...args, contact_id: resolved.id },
|
|
1787
|
+
String(args.reason || "Deal signal detected"),
|
|
1788
|
+
Array.isArray(args.sources) ? args.sources.map(String) : [],
|
|
1789
|
+
resolved.id,
|
|
1790
|
+
`propose_deal:${ctx.profileId}:${resolved.id}:${title.toLowerCase()}`
|
|
1791
|
+
);
|
|
1792
|
+
}
|
|
1793
|
+
},
|
|
1794
|
+
{
|
|
1795
|
+
name: "crm_update_deal_stage",
|
|
1796
|
+
domain: "crm",
|
|
1797
|
+
description: "Propose moving a deal to a new pipeline stage (queued for human approval).",
|
|
1798
|
+
inputSchema: {
|
|
1799
|
+
type: "object",
|
|
1800
|
+
properties: {
|
|
1801
|
+
deal_id: { type: "string", description: "Deal ID" },
|
|
1802
|
+
stage: { type: "string", description: "Target stage" },
|
|
1803
|
+
lost_reason: { type: "string", description: "Required when stage is 'lost'" },
|
|
1804
|
+
reason: { type: "string", description: "Why the stage change is proposed" },
|
|
1805
|
+
sources: { type: "array", items: { type: "string" } }
|
|
1806
|
+
},
|
|
1807
|
+
required: ["deal_id", "stage"]
|
|
1808
|
+
},
|
|
1809
|
+
handler: async (args, ctx) => {
|
|
1810
|
+
const dealId = String(args.deal_id || "");
|
|
1811
|
+
const stage = String(args.stage || "");
|
|
1812
|
+
const deals = await query(
|
|
1813
|
+
"SELECT title, stage FROM crm_deals WHERE id = ? AND profile_id = ? LIMIT 1",
|
|
1814
|
+
[dealId, ctx.profileId]
|
|
1815
|
+
);
|
|
1816
|
+
if (deals.length === 0) throw new Error(`Deal not found: ${dealId}`);
|
|
1817
|
+
return queueApprovalItem(
|
|
1818
|
+
ctx.profileId,
|
|
1819
|
+
"crm_update_deal_stage",
|
|
1820
|
+
`Move deal "${deals[0].title}" (${deals[0].stage} -> ${stage})`,
|
|
1821
|
+
args,
|
|
1822
|
+
String(args.reason || "Pipeline stage update proposed by agent"),
|
|
1823
|
+
Array.isArray(args.sources) ? args.sources.map(String) : [],
|
|
1824
|
+
dealId,
|
|
1825
|
+
`deal_stage:${ctx.profileId}:${dealId}:${stage}`
|
|
1826
|
+
);
|
|
1827
|
+
}
|
|
1828
|
+
},
|
|
1829
|
+
{
|
|
1830
|
+
name: "crm_merge_contacts",
|
|
1831
|
+
domain: "crm",
|
|
1832
|
+
description: "Propose merging a duplicate contact into a primary contact (queued for human approval).",
|
|
1833
|
+
inputSchema: {
|
|
1834
|
+
type: "object",
|
|
1835
|
+
properties: {
|
|
1836
|
+
primary_contact_id: { type: "string", description: "Contact ID to keep" },
|
|
1837
|
+
duplicate_contact_id: { type: "string", description: "Duplicate contact ID to archive and merge" },
|
|
1838
|
+
reason: { type: "string", description: "Why these are duplicates" },
|
|
1839
|
+
sources: { type: "array", items: { type: "string" } }
|
|
1840
|
+
},
|
|
1841
|
+
required: ["primary_contact_id", "duplicate_contact_id"]
|
|
1842
|
+
},
|
|
1843
|
+
handler: async (args, ctx) => {
|
|
1844
|
+
const primary = await resolveContactId(ctx.profileId, String(args.primary_contact_id));
|
|
1845
|
+
const dup = await resolveContactId(ctx.profileId, String(args.duplicate_contact_id));
|
|
1846
|
+
if (primary.id === dup.id) throw new Error("Cannot merge a contact with itself");
|
|
1847
|
+
return queueApprovalItem(
|
|
1848
|
+
ctx.profileId,
|
|
1849
|
+
"crm_merge_contacts",
|
|
1850
|
+
`Merge contact "${dup.name}" into "${primary.name}"`,
|
|
1851
|
+
{ ...args, primary_contact_id: primary.id, duplicate_contact_id: dup.id },
|
|
1852
|
+
String(args.reason || "Duplicate contact merge proposed"),
|
|
1853
|
+
Array.isArray(args.sources) ? args.sources.map(String) : [],
|
|
1854
|
+
primary.id,
|
|
1855
|
+
`merge:${ctx.profileId}:${primary.id}:${dup.id}`
|
|
1856
|
+
);
|
|
1857
|
+
}
|
|
1858
|
+
},
|
|
1859
|
+
{
|
|
1860
|
+
name: "crm_create_proposal_draft",
|
|
1861
|
+
domain: "crm",
|
|
1862
|
+
description: "Propose creating a client proposal draft in crm_proposals (queued for human approval).",
|
|
1863
|
+
inputSchema: {
|
|
1864
|
+
type: "object",
|
|
1865
|
+
properties: {
|
|
1866
|
+
contact_id: { type: "string", description: "Contact ID or email" },
|
|
1867
|
+
deal_id: { type: "string", description: "Optional deal ID" },
|
|
1868
|
+
title: { type: "string", description: "Proposal title" },
|
|
1869
|
+
body: { type: "string", description: "Proposal body text or HTML" },
|
|
1870
|
+
excerpt: { type: "string", description: "Short summary" },
|
|
1871
|
+
payment_amount_cents: { type: "number", description: "Optional payment amount in cents" },
|
|
1872
|
+
currency: { type: "string", description: "Currency code (default 'usd')" },
|
|
1873
|
+
expires_days: { type: "number", description: "Days until expiry (default 14)" },
|
|
1874
|
+
reason: { type: "string", description: "Context for approval queue" },
|
|
1875
|
+
sources: { type: "array", items: { type: "string" } }
|
|
1876
|
+
},
|
|
1877
|
+
required: ["contact_id", "title", "body"]
|
|
1878
|
+
},
|
|
1879
|
+
handler: async (args, ctx) => {
|
|
1880
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
1881
|
+
const title = String(args.title || "").trim();
|
|
1882
|
+
const body = String(args.body || "").trim();
|
|
1883
|
+
if (!title || !body) throw new Error("Missing required fields: title and body");
|
|
1884
|
+
return queueApprovalItem(
|
|
1885
|
+
ctx.profileId,
|
|
1886
|
+
"crm_create_proposal_draft",
|
|
1887
|
+
`Create proposal draft "${title}" for ${resolved.name}`,
|
|
1888
|
+
{ ...args, contact_id: resolved.id },
|
|
1889
|
+
String(args.reason || "Proposal draft prepared for review"),
|
|
1890
|
+
Array.isArray(args.sources) ? args.sources.map(String) : [],
|
|
1891
|
+
resolved.id,
|
|
1892
|
+
`proposal_draft:${ctx.profileId}:${resolved.id}:${title.toLowerCase()}`
|
|
1893
|
+
);
|
|
1894
|
+
}
|
|
1895
|
+
},
|
|
1896
|
+
{
|
|
1897
|
+
name: "crm_draft_followup",
|
|
1898
|
+
domain: "crm",
|
|
1899
|
+
description: "Save an email follow-up draft for a contact in Inbox (author='agent', send_status='draft'). Never sends email.",
|
|
1900
|
+
inputSchema: {
|
|
1901
|
+
type: "object",
|
|
1902
|
+
properties: {
|
|
1903
|
+
contact_id: { type: "string", description: "Contact ID or email" },
|
|
1904
|
+
thread_id: { type: "string", description: "Optional existing Inbox thread ID" },
|
|
1905
|
+
mailbox_id: { type: "string", description: "Optional Inbox mailbox ID" },
|
|
1906
|
+
subject: { type: "string", description: "Email subject" },
|
|
1907
|
+
body: { type: "string", description: "Draft email body" },
|
|
1908
|
+
goal: { type: "string", description: "Goal/topic if body is generated" }
|
|
1909
|
+
},
|
|
1910
|
+
required: ["contact_id"]
|
|
1911
|
+
},
|
|
1912
|
+
handler: async (args, ctx) => {
|
|
1913
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
1914
|
+
if (!resolved.email) throw new Error("Contact does not have an email address");
|
|
1915
|
+
const voice = await loadBrandVoice(ctx.profileId);
|
|
1916
|
+
const subject = args.subject ? String(args.subject) : `Following up \u2014 ${resolved.name}`;
|
|
1917
|
+
const goal = String(args.goal || args.context || "checking in on our next steps");
|
|
1918
|
+
const co = resolved.company ? ` (${resolved.company})` : "";
|
|
1919
|
+
const body = args.body && String(args.body).trim() ? String(args.body) : `Hi ${resolved.name}${co},
|
|
1920
|
+
|
|
1921
|
+
Just following up regarding ${goal}.
|
|
1922
|
+
|
|
1923
|
+
Let me know what works best for you this week.
|
|
1924
|
+
|
|
1925
|
+
Best,`;
|
|
1926
|
+
const res = await saveInboxDraftForContact(
|
|
1927
|
+
ctx.profileId,
|
|
1928
|
+
resolved.id,
|
|
1929
|
+
resolved.email,
|
|
1930
|
+
args.thread_id,
|
|
1931
|
+
args.mailbox_id,
|
|
1932
|
+
subject,
|
|
1933
|
+
body
|
|
1934
|
+
);
|
|
1935
|
+
return { ...res, contact_id: resolved.id, brand_voice_used: voice };
|
|
1936
|
+
}
|
|
1937
|
+
},
|
|
1938
|
+
{
|
|
1939
|
+
name: "crm_draft_payment_chase",
|
|
1940
|
+
domain: "crm",
|
|
1941
|
+
description: "Save an unpaid/overdue invoice payment reminder draft in Inbox (author='agent', send_status='draft'). Never sends email.",
|
|
1942
|
+
inputSchema: {
|
|
1943
|
+
type: "object",
|
|
1944
|
+
properties: {
|
|
1945
|
+
contact_id: { type: "string", description: "Contact ID or email" },
|
|
1946
|
+
invoice_id: { type: "string", description: "Optional invoice ID or number" },
|
|
1947
|
+
thread_id: { type: "string", description: "Optional Inbox thread ID" },
|
|
1948
|
+
mailbox_id: { type: "string", description: "Optional Inbox mailbox ID" },
|
|
1949
|
+
subject: { type: "string", description: "Optional custom subject" },
|
|
1950
|
+
body: { type: "string", description: "Optional custom body" }
|
|
1951
|
+
},
|
|
1952
|
+
required: ["contact_id"]
|
|
1953
|
+
},
|
|
1954
|
+
handler: async (args, ctx) => {
|
|
1955
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
1956
|
+
if (!resolved.email) throw new Error("Contact does not have an email address");
|
|
1957
|
+
const now = nowTs();
|
|
1958
|
+
const invFilter = args.invoice_id ? String(args.invoice_id) : null;
|
|
1959
|
+
let invNumber = "";
|
|
1960
|
+
let amountDisplay = "";
|
|
1961
|
+
let daysPastDue = 0;
|
|
1962
|
+
const crmRows = await query(
|
|
1963
|
+
`SELECT id, invoice_number, total_cents, currency, due_at FROM crm_invoices
|
|
1964
|
+
WHERE profile_id = ? AND contact_id = ? AND (? IS NULL OR id = ? OR invoice_number = ?)
|
|
1965
|
+
AND status IN ('sent','viewed','overdue') AND paid_at IS NULL
|
|
1966
|
+
ORDER BY COALESCE(due_at, created_at) ASC LIMIT 1`,
|
|
1967
|
+
[ctx.profileId, resolved.id, invFilter, invFilter, invFilter]
|
|
1968
|
+
);
|
|
1969
|
+
if (crmRows.length > 0) {
|
|
1970
|
+
const r = crmRows[0];
|
|
1971
|
+
invNumber = r.invoice_number;
|
|
1972
|
+
amountDisplay = `${String(r.currency || "usd").toUpperCase()} ${(Number(r.total_cents || 0) / 100).toFixed(2)}`;
|
|
1973
|
+
if (typeof r.due_at === "number") daysPastDue = Math.floor(Math.max(0, now - r.due_at) / 86400);
|
|
1974
|
+
} else {
|
|
1975
|
+
const shopRows = await query(
|
|
1976
|
+
`SELECT d.doc_number, d.amount_due, d.currency, d.due_date
|
|
1977
|
+
FROM shop_documents d
|
|
1978
|
+
JOIN shop_customers c ON c.id = d.customer_id AND c.profile_id = d.profile_id
|
|
1979
|
+
WHERE d.profile_id = ? AND (c.contact_id = ? OR LOWER(c.email) = LOWER(?))
|
|
1980
|
+
AND d.doc_type = 'invoice' AND d.amount_due > 0 AND d.status NOT IN ('paid','cancelled','void')
|
|
1981
|
+
AND (? IS NULL OR d.id = ? OR d.doc_number = ?)
|
|
1982
|
+
ORDER BY d.doc_date ASC LIMIT 1`,
|
|
1983
|
+
[ctx.profileId, resolved.id, resolved.email, invFilter, invFilter, invFilter]
|
|
1984
|
+
);
|
|
1985
|
+
if (shopRows.length > 0) {
|
|
1986
|
+
const r = shopRows[0];
|
|
1987
|
+
invNumber = r.doc_number;
|
|
1988
|
+
amountDisplay = `${String(r.currency || "INR").toUpperCase()} ${Number(r.amount_due || 0).toFixed(2)}`;
|
|
1989
|
+
if (typeof r.due_date === "number") daysPastDue = Math.floor(Math.max(0, now - r.due_date) / 86400);
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
if (!invNumber) throw new Error("No unpaid invoice found for this contact");
|
|
1993
|
+
const voice = await loadBrandVoice(ctx.profileId);
|
|
1994
|
+
const subject = args.subject ? String(args.subject) : `Reminder: Invoice ${invNumber} (${amountDisplay})`;
|
|
1995
|
+
const body = args.body && String(args.body).trim() ? String(args.body) : daysPastDue > 0 ? `Hi ${resolved.name},
|
|
1996
|
+
|
|
1997
|
+
Friendly reminder that invoice ${invNumber} for ${amountDisplay} is ${daysPastDue} day(s) past due.
|
|
1998
|
+
|
|
1999
|
+
Could you let us know when payment is scheduled or if anything is needed from our side?
|
|
2000
|
+
|
|
2001
|
+
Thanks,` : `Hi ${resolved.name},
|
|
2002
|
+
|
|
2003
|
+
Checking in on invoice ${invNumber} for ${amountDisplay}. Let us know if you need a fresh copy or payment link.
|
|
2004
|
+
|
|
2005
|
+
Thanks,`;
|
|
2006
|
+
const res = await saveInboxDraftForContact(
|
|
2007
|
+
ctx.profileId,
|
|
2008
|
+
resolved.id,
|
|
2009
|
+
resolved.email,
|
|
2010
|
+
args.thread_id,
|
|
2011
|
+
args.mailbox_id,
|
|
2012
|
+
subject,
|
|
2013
|
+
body
|
|
2014
|
+
);
|
|
2015
|
+
return { ...res, invoice_number: invNumber, amount: amountDisplay, days_past_due: daysPastDue, brand_voice_used: voice };
|
|
2016
|
+
}
|
|
2017
|
+
},
|
|
2018
|
+
{
|
|
2019
|
+
name: "crm_list_stages",
|
|
2020
|
+
domain: "crm",
|
|
2021
|
+
description: "List configured CRM deal pipeline stages.",
|
|
2022
|
+
inputSchema: { type: "object", properties: {} },
|
|
2023
|
+
handler: async (_args, ctx) => {
|
|
2024
|
+
const rows = await query(
|
|
2025
|
+
"SELECT pipeline_stages FROM settings WHERE profile_id = ? LIMIT 1",
|
|
2026
|
+
[ctx.profileId]
|
|
2027
|
+
);
|
|
2028
|
+
let stages = ["new", "contacted", "proposal", "negotiation", "won", "lost"];
|
|
2029
|
+
if (rows[0]?.pipeline_stages) {
|
|
2030
|
+
try {
|
|
2031
|
+
const parsed = JSON.parse(rows[0].pipeline_stages);
|
|
2032
|
+
if (Array.isArray(parsed) && parsed.length > 0) stages = parsed;
|
|
2033
|
+
} catch {
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
return { stages };
|
|
2037
|
+
}
|
|
2038
|
+
},
|
|
2039
|
+
{
|
|
2040
|
+
name: "crm_set_stages",
|
|
2041
|
+
domain: "crm",
|
|
2042
|
+
description: "Configure the CRM deal pipeline stages in settings.pipeline_stages.",
|
|
2043
|
+
inputSchema: {
|
|
2044
|
+
type: "object",
|
|
2045
|
+
properties: {
|
|
2046
|
+
stages: { type: "array", items: { type: "string" }, description: "Ordered stage names" }
|
|
2047
|
+
},
|
|
2048
|
+
required: ["stages"]
|
|
2049
|
+
},
|
|
2050
|
+
handler: async (args, ctx) => {
|
|
2051
|
+
const stages = (Array.isArray(args.stages) ? args.stages : []).map((s) => String(s).trim()).filter(Boolean);
|
|
2052
|
+
if (stages.length === 0) throw new Error("stages must contain at least one stage name");
|
|
2053
|
+
const sid = generateId("set");
|
|
2054
|
+
await execute(
|
|
2055
|
+
"INSERT OR IGNORE INTO settings (id, profile_id, timezone, language, theme, updated_at) VALUES (?, ?, 'UTC', 'en', 'system', strftime('%s','now'))",
|
|
2056
|
+
[sid, ctx.profileId]
|
|
2057
|
+
);
|
|
2058
|
+
await execute(
|
|
2059
|
+
"UPDATE settings SET pipeline_stages = ?, updated_at = strftime('%s','now') WHERE profile_id = ?",
|
|
2060
|
+
[JSON.stringify(stages), ctx.profileId]
|
|
2061
|
+
);
|
|
2062
|
+
return { stages, status: "updated" };
|
|
2063
|
+
}
|
|
2064
|
+
},
|
|
2065
|
+
{
|
|
2066
|
+
name: "crm_create_group",
|
|
2067
|
+
domain: "crm",
|
|
2068
|
+
description: "Create a named CRM contact group (e.g. Clients, VIP, Retainers).",
|
|
2069
|
+
inputSchema: {
|
|
2070
|
+
type: "object",
|
|
2071
|
+
properties: {
|
|
2072
|
+
name: { type: "string", description: "Group name" },
|
|
2073
|
+
icon: { type: "string", description: "Optional emoji/icon" },
|
|
2074
|
+
color: { type: "string", description: "Optional hex color" }
|
|
2075
|
+
},
|
|
2076
|
+
required: ["name"]
|
|
2077
|
+
},
|
|
2078
|
+
handler: async (args, ctx) => {
|
|
2079
|
+
const name = String(args.name || "").trim();
|
|
2080
|
+
if (!name) throw new Error("Missing required field: name");
|
|
2081
|
+
const existing = await query(
|
|
2082
|
+
"SELECT id FROM crm_groups WHERE profile_id = ? AND LOWER(name) = LOWER(?) LIMIT 1",
|
|
2083
|
+
[ctx.profileId, name]
|
|
2084
|
+
);
|
|
2085
|
+
if (existing.length > 0) return { group_id: existing[0].id, name, status: "already_exists" };
|
|
2086
|
+
const groupId = generateId("grp");
|
|
2087
|
+
await execute(
|
|
2088
|
+
"INSERT INTO crm_groups (id, profile_id, name, icon, color, contact_count, created_at) VALUES (?, ?, ?, ?, ?, 0, strftime('%s','now'))",
|
|
2089
|
+
[groupId, ctx.profileId, name, args.icon ?? null, args.color ?? null]
|
|
2090
|
+
);
|
|
2091
|
+
return { group_id: groupId, name, status: "created" };
|
|
2092
|
+
}
|
|
2093
|
+
},
|
|
2094
|
+
{
|
|
2095
|
+
name: "crm_add_to_group",
|
|
2096
|
+
domain: "crm",
|
|
2097
|
+
description: "Add a CRM contact to a contact group.",
|
|
2098
|
+
inputSchema: {
|
|
2099
|
+
type: "object",
|
|
2100
|
+
properties: {
|
|
2101
|
+
contact_id: { type: "string", description: "Contact ID or email" },
|
|
2102
|
+
group_id: { type: "string", description: "Group ID or name" },
|
|
2103
|
+
group_name: { type: "string", description: "Alternative group name" }
|
|
2104
|
+
},
|
|
2105
|
+
required: ["contact_id"]
|
|
2106
|
+
},
|
|
2107
|
+
handler: async (args, ctx) => {
|
|
2108
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
2109
|
+
const groupRef = String(args.group_id || args.group_name || "").trim();
|
|
2110
|
+
if (!groupRef) throw new Error("Missing required field: group_id or group_name");
|
|
2111
|
+
const groups = await query(
|
|
2112
|
+
"SELECT id, name FROM crm_groups WHERE profile_id = ? AND (id = ? OR LOWER(name) = LOWER(?)) LIMIT 1",
|
|
2113
|
+
[ctx.profileId, groupRef, groupRef]
|
|
2114
|
+
);
|
|
2115
|
+
if (groups.length === 0) throw new Error(`Group not found: ${groupRef}`);
|
|
2116
|
+
const group = groups[0];
|
|
2117
|
+
await execute(
|
|
2118
|
+
"INSERT OR IGNORE INTO crm_contact_groups (contact_id, group_id, added_at) VALUES (?, ?, strftime('%s','now'))",
|
|
2119
|
+
[resolved.id, group.id]
|
|
2120
|
+
);
|
|
2121
|
+
const cRows = await query("SELECT groups FROM crm_contacts WHERE id = ? AND profile_id = ? LIMIT 1", [
|
|
2122
|
+
resolved.id,
|
|
2123
|
+
ctx.profileId
|
|
2124
|
+
]);
|
|
2125
|
+
let arr = [];
|
|
2126
|
+
try {
|
|
2127
|
+
arr = JSON.parse(cRows[0]?.groups || "[]");
|
|
2128
|
+
} catch {
|
|
2129
|
+
arr = [];
|
|
2130
|
+
}
|
|
2131
|
+
if (!arr.includes(group.id)) {
|
|
2132
|
+
arr.push(group.id);
|
|
2133
|
+
await execute("UPDATE crm_contacts SET groups = ?, updated_at = strftime('%s','now') WHERE id = ? AND profile_id = ?", [
|
|
2134
|
+
JSON.stringify(arr),
|
|
2135
|
+
resolved.id,
|
|
2136
|
+
ctx.profileId
|
|
2137
|
+
]);
|
|
2138
|
+
}
|
|
2139
|
+
await execute(
|
|
2140
|
+
"UPDATE crm_groups SET contact_count = (SELECT COUNT(*) FROM crm_contact_groups WHERE group_id = ?) WHERE id = ?",
|
|
2141
|
+
[group.id, group.id]
|
|
2142
|
+
);
|
|
2143
|
+
return { contact_id: resolved.id, group_id: group.id, group_name: group.name, status: "added" };
|
|
2144
|
+
}
|
|
2145
|
+
},
|
|
2146
|
+
{
|
|
2147
|
+
name: "crm_create_template",
|
|
2148
|
+
domain: "crm",
|
|
2149
|
+
description: "Create a reusable outreach or follow-up template in crm_templates.",
|
|
2150
|
+
inputSchema: {
|
|
2151
|
+
type: "object",
|
|
2152
|
+
properties: {
|
|
2153
|
+
name: { type: "string", description: "Template name" },
|
|
2154
|
+
template_type: { type: "string", enum: ["email", "dm", "follow_up", "proposal"] },
|
|
2155
|
+
subject: { type: "string", description: "Subject template" },
|
|
2156
|
+
body: { type: "string", description: "Body template" },
|
|
2157
|
+
platform: { type: "string", description: "Optional platform" },
|
|
2158
|
+
tags: { type: "array", items: { type: "string" } }
|
|
2159
|
+
},
|
|
2160
|
+
required: ["name", "body"]
|
|
2161
|
+
},
|
|
2162
|
+
handler: async (args, ctx) => {
|
|
2163
|
+
const name = String(args.name || "").trim();
|
|
2164
|
+
const body = String(args.body || "").trim();
|
|
2165
|
+
if (!name || !body) throw new Error("Missing required fields: name and body");
|
|
2166
|
+
const tplId = generateId("tpl");
|
|
2167
|
+
const templateType = String(args.template_type || "email");
|
|
2168
|
+
const tags = JSON.stringify(args.tags || []);
|
|
2169
|
+
const now = nowTs();
|
|
2170
|
+
await execute(
|
|
2171
|
+
`INSERT INTO crm_templates (id, profile_id, name, type, subject, body, platform, tags, created_at, updated_at)
|
|
2172
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
2173
|
+
[tplId, ctx.profileId, name, templateType, args.subject ?? null, body, args.platform ?? null, tags, now, now]
|
|
2174
|
+
);
|
|
2175
|
+
return { template_id: tplId, name, template_type: templateType, status: "created" };
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
];
|
|
2179
|
+
|
|
2180
|
+
// src/tools/content.ts
|
|
2181
|
+
var contentTools = [
|
|
2182
|
+
{
|
|
2183
|
+
name: "blog_post_create",
|
|
2184
|
+
domain: "content",
|
|
2185
|
+
description: "Create or publish a rich HTML blog post, newsletter, docs article, guide, or custom CMS entry. Clean semantic HTML body in body_html.",
|
|
2186
|
+
inputSchema: {
|
|
2187
|
+
type: "object",
|
|
2188
|
+
properties: {
|
|
2189
|
+
title: { type: "string", description: "Title of the blog post, newsletter, doc, or guide" },
|
|
2190
|
+
body_html: {
|
|
2191
|
+
type: "string",
|
|
2192
|
+
description: "Clean semantic HTML body supporting all blocks (<h2>, <h3>, <p>, lists, taskList, tables, pre data-filename, info-card, steps, accordion-group, kbd, images, video embeds). NEVER Markdown or <h1>."
|
|
2193
|
+
},
|
|
2194
|
+
content_type: {
|
|
2195
|
+
type: "string",
|
|
2196
|
+
description: "Target hub slug: 'blog' (default), 'n' (newsletter), 'docs', 'guides', or custom CMS slug."
|
|
2197
|
+
},
|
|
2198
|
+
cms_id: { type: "string", description: "Optional target CMS UUID." },
|
|
2199
|
+
collection: { type: "string", description: "Collection name, slug, or ID for Docs/Guides." },
|
|
2200
|
+
slug: { type: "string", description: "Optional custom URL slug." },
|
|
2201
|
+
excerpt: { type: "string", description: "1-2 sentence teaser summary." },
|
|
2202
|
+
ai_summary: { type: "string", description: "Concise TL;DR summary." },
|
|
2203
|
+
hero_image_url: { type: "string", description: "Optional cover/hero image URL." },
|
|
2204
|
+
media_id: { type: "string", description: "Optional Media Library item ID." },
|
|
2205
|
+
cta_button_text: { type: "string", description: "Optional CTA button label." },
|
|
2206
|
+
cta_button_url: { type: "string", description: "Optional CTA button URL." },
|
|
2207
|
+
additional_details: {
|
|
2208
|
+
type: "array",
|
|
2209
|
+
items: {
|
|
2210
|
+
type: "object",
|
|
2211
|
+
properties: {
|
|
2212
|
+
key: { type: "string" },
|
|
2213
|
+
value: { type: "string" }
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
},
|
|
2217
|
+
seo_title: { type: "string", description: "Optional SEO meta title." },
|
|
2218
|
+
seo_description: { type: "string", description: "Optional SEO meta description." },
|
|
2219
|
+
seo_keywords: { type: "string", description: "Optional SEO keywords." },
|
|
2220
|
+
status: { type: "string", enum: ["draft", "publish", "published"], default: "draft" },
|
|
2221
|
+
published: { type: "boolean", description: "Publish immediately (true) or draft (false)." },
|
|
2222
|
+
hidden: { type: "boolean", default: false },
|
|
2223
|
+
hide_author: { type: "boolean", default: false }
|
|
2224
|
+
},
|
|
2225
|
+
required: ["title", "body_html"]
|
|
2226
|
+
},
|
|
2227
|
+
handler: async (args, ctx) => {
|
|
2228
|
+
const profileId = ctx.profileId;
|
|
2229
|
+
const title = String(args.title || "").trim();
|
|
2230
|
+
const bodyHtml = String(args.body_html || "");
|
|
2231
|
+
const contentType = args.content_type || "blog";
|
|
2232
|
+
const postId = generateId("post");
|
|
2233
|
+
const rawSlug = args.slug || title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
2234
|
+
const slug = rawSlug || `post-${Date.now()}`;
|
|
2235
|
+
const isPublished = args.published === true || args.status === "publish" || args.status === "published" ? 1 : 0;
|
|
2236
|
+
const isHidden = args.hidden ? 1 : 0;
|
|
2237
|
+
const isHideAuthor = args.hide_author ? 1 : 0;
|
|
2238
|
+
const plainText = bodyHtml.replace(/<[^>]+>/g, " ");
|
|
2239
|
+
const words = plainText.trim().split(/\s+/).filter(Boolean);
|
|
2240
|
+
const wordCount = words.length;
|
|
2241
|
+
const readingTime = Math.max(1, Math.ceil(wordCount / 200));
|
|
2242
|
+
await execute(
|
|
2243
|
+
`INSERT INTO content
|
|
2244
|
+
(id, profile_id, category_id, collection_id, cms_id, slug, title, body_html, excerpt, ai_summary, hero_image_url, media_id, cta_button_text, cta_button_url, additional_details, seo_title, seo_description, seo_keywords, published, hidden, hide_author, word_count, reading_time_mins, created_at, updated_at)
|
|
2245
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, strftime('%s','now'), strftime('%s','now'))`,
|
|
2246
|
+
[
|
|
2247
|
+
postId,
|
|
2248
|
+
profileId,
|
|
2249
|
+
contentType,
|
|
2250
|
+
args.collection || null,
|
|
2251
|
+
args.cms_id || null,
|
|
2252
|
+
slug,
|
|
2253
|
+
title,
|
|
2254
|
+
bodyHtml,
|
|
2255
|
+
args.excerpt || null,
|
|
2256
|
+
args.ai_summary || null,
|
|
2257
|
+
args.hero_image_url || null,
|
|
2258
|
+
args.media_id || null,
|
|
2259
|
+
args.cta_button_text || null,
|
|
2260
|
+
args.cta_button_url || null,
|
|
2261
|
+
args.additional_details ? JSON.stringify(args.additional_details) : "[]",
|
|
2262
|
+
args.seo_title || title,
|
|
2263
|
+
args.seo_description || args.excerpt || null,
|
|
2264
|
+
args.seo_keywords || null,
|
|
2265
|
+
isPublished,
|
|
2266
|
+
isHidden,
|
|
2267
|
+
isHideAuthor,
|
|
2268
|
+
wordCount,
|
|
2269
|
+
readingTime
|
|
2270
|
+
]
|
|
2271
|
+
);
|
|
2272
|
+
return {
|
|
2273
|
+
id: postId,
|
|
2274
|
+
title,
|
|
2275
|
+
slug,
|
|
2276
|
+
content_type: contentType,
|
|
2277
|
+
published: isPublished === 1,
|
|
2278
|
+
word_count: wordCount,
|
|
2279
|
+
reading_time_mins: readingTime,
|
|
2280
|
+
status: isPublished === 1 ? "published" : "draft"
|
|
2281
|
+
};
|
|
2282
|
+
}
|
|
2283
|
+
},
|
|
2284
|
+
{
|
|
2285
|
+
name: "content_list",
|
|
2286
|
+
domain: "content",
|
|
2287
|
+
description: "List existing blog posts, newsletters, docs, guides, and custom hub entries for the active profile.",
|
|
2288
|
+
inputSchema: {
|
|
2289
|
+
type: "object",
|
|
2290
|
+
properties: {
|
|
2291
|
+
content_type: { type: "string", description: "Optional hub slug filter (e.g. 'blog', 'n', 'docs', 'guides')." },
|
|
2292
|
+
cms_id: { type: "string", description: "Optional target CMS UUID filter." },
|
|
2293
|
+
published_only: { type: "boolean", description: "If true, return only published entries.", default: false },
|
|
2294
|
+
limit: { type: "integer", description: "Maximum rows to return (default 30, max 100)." }
|
|
2295
|
+
}
|
|
2296
|
+
},
|
|
2297
|
+
handler: async (args, ctx) => {
|
|
2298
|
+
const profileId = ctx.profileId;
|
|
2299
|
+
const limit = Math.min(Number(args.limit || 30), 100);
|
|
2300
|
+
let sql = "SELECT id, title, slug, excerpt, category_id, published, word_count, created_at FROM content WHERE profile_id = ?";
|
|
2301
|
+
const params = [profileId];
|
|
2302
|
+
if (args.content_type) {
|
|
2303
|
+
sql += " AND category_id = ?";
|
|
2304
|
+
params.push(args.content_type);
|
|
2305
|
+
}
|
|
2306
|
+
if (args.cms_id) {
|
|
2307
|
+
sql += " AND cms_id = ?";
|
|
2308
|
+
params.push(args.cms_id);
|
|
2309
|
+
}
|
|
2310
|
+
if (args.published_only) {
|
|
2311
|
+
sql += " AND published = 1";
|
|
2312
|
+
}
|
|
2313
|
+
sql += " ORDER BY created_at DESC LIMIT ?";
|
|
2314
|
+
params.push(limit);
|
|
2315
|
+
const rows = await query(sql, params);
|
|
2316
|
+
return {
|
|
2317
|
+
total: rows.length,
|
|
2318
|
+
items: rows.map((r) => ({
|
|
2319
|
+
id: r.id,
|
|
2320
|
+
title: r.title,
|
|
2321
|
+
slug: r.slug,
|
|
2322
|
+
excerpt: r.excerpt,
|
|
2323
|
+
content_type: r.category_id,
|
|
2324
|
+
published: Boolean(r.published),
|
|
2325
|
+
word_count: r.word_count,
|
|
2326
|
+
created_at: r.created_at
|
|
2327
|
+
}))
|
|
2328
|
+
};
|
|
2329
|
+
}
|
|
2330
|
+
},
|
|
2331
|
+
{
|
|
2332
|
+
name: "content_get",
|
|
2333
|
+
domain: "content",
|
|
2334
|
+
description: "Fetch full HTML content and metadata for an existing blog post, newsletter, doc, guide, or custom hub entry by ID or slug.",
|
|
2335
|
+
inputSchema: {
|
|
2336
|
+
type: "object",
|
|
2337
|
+
properties: {
|
|
2338
|
+
content_id_or_slug: { type: "string", description: "Content ID (e.g. 'post_...') or URL slug." },
|
|
2339
|
+
content_type: { type: "string", description: "Optional hub slug filter." },
|
|
2340
|
+
cms_id: { type: "string", description: "Optional target CMS UUID filter." }
|
|
2341
|
+
},
|
|
2342
|
+
required: ["content_id_or_slug"]
|
|
2343
|
+
},
|
|
2344
|
+
handler: async (args, ctx) => {
|
|
2345
|
+
const profileId = ctx.profileId;
|
|
2346
|
+
const ref = String(args.content_id_or_slug).trim();
|
|
2347
|
+
const rows = await query(
|
|
2348
|
+
"SELECT * FROM content WHERE profile_id = ? AND (id = ? OR slug = ?) LIMIT 1",
|
|
2349
|
+
[profileId, ref, ref]
|
|
2350
|
+
);
|
|
2351
|
+
if (rows.length === 0) {
|
|
2352
|
+
throw new Error(`Content not found with identifier: ${ref}`);
|
|
2353
|
+
}
|
|
2354
|
+
const row = rows[0];
|
|
2355
|
+
return {
|
|
2356
|
+
id: row.id,
|
|
2357
|
+
title: row.title,
|
|
2358
|
+
slug: row.slug,
|
|
2359
|
+
body_html: row.body_html,
|
|
2360
|
+
excerpt: row.excerpt,
|
|
2361
|
+
ai_summary: row.ai_summary,
|
|
2362
|
+
hero_image_url: row.hero_image_url,
|
|
2363
|
+
content_type: row.category_id,
|
|
2364
|
+
published: Boolean(row.published),
|
|
2365
|
+
word_count: row.word_count,
|
|
2366
|
+
reading_time_mins: row.reading_time_mins,
|
|
2367
|
+
seo_title: row.seo_title,
|
|
2368
|
+
seo_description: row.seo_description
|
|
2369
|
+
};
|
|
2370
|
+
}
|
|
2371
|
+
},
|
|
2372
|
+
{
|
|
2373
|
+
name: "content_update",
|
|
2374
|
+
domain: "content",
|
|
2375
|
+
description: "Update an existing blog post, newsletter, doc, guide, or custom hub entry (HTML body, title, slug, collection, publish status, CTA, SEO).",
|
|
2376
|
+
inputSchema: {
|
|
2377
|
+
type: "object",
|
|
2378
|
+
properties: {
|
|
2379
|
+
content_id_or_slug: { type: "string", description: "Target content ID or URL slug." },
|
|
2380
|
+
title: { type: "string" },
|
|
2381
|
+
slug: { type: "string" },
|
|
2382
|
+
body_html: { type: "string" },
|
|
2383
|
+
collection: { type: "string" },
|
|
2384
|
+
excerpt: { type: "string" },
|
|
2385
|
+
ai_summary: { type: "string" },
|
|
2386
|
+
hero_image_url: { type: "string" },
|
|
2387
|
+
cta_button_text: { type: "string" },
|
|
2388
|
+
cta_button_url: { type: "string" },
|
|
2389
|
+
seo_title: { type: "string" },
|
|
2390
|
+
seo_description: { type: "string" },
|
|
2391
|
+
seo_keywords: { type: "string" },
|
|
2392
|
+
status: { type: "string", enum: ["draft", "publish", "published"] },
|
|
2393
|
+
published: { type: "boolean" },
|
|
2394
|
+
hidden: { type: "boolean" },
|
|
2395
|
+
hide_author: { type: "boolean" }
|
|
2396
|
+
},
|
|
2397
|
+
required: ["content_id_or_slug"]
|
|
2398
|
+
},
|
|
2399
|
+
handler: async (args, ctx) => {
|
|
2400
|
+
const profileId = ctx.profileId;
|
|
2401
|
+
const ref = String(args.content_id_or_slug).trim();
|
|
2402
|
+
const rows = await query("SELECT id FROM content WHERE profile_id = ? AND (id = ? OR slug = ?) LIMIT 1", [
|
|
2403
|
+
profileId,
|
|
2404
|
+
ref,
|
|
2405
|
+
ref
|
|
2406
|
+
]);
|
|
2407
|
+
if (rows.length === 0) {
|
|
2408
|
+
throw new Error(`Content not found with identifier: ${ref}`);
|
|
2409
|
+
}
|
|
2410
|
+
const id = rows[0].id;
|
|
2411
|
+
const updates = [];
|
|
2412
|
+
const params = [];
|
|
2413
|
+
const stringFields = [
|
|
2414
|
+
"title",
|
|
2415
|
+
"slug",
|
|
2416
|
+
"body_html",
|
|
2417
|
+
"collection",
|
|
2418
|
+
"excerpt",
|
|
2419
|
+
"ai_summary",
|
|
2420
|
+
"hero_image_url",
|
|
2421
|
+
"cta_button_text",
|
|
2422
|
+
"cta_button_url",
|
|
2423
|
+
"seo_title",
|
|
2424
|
+
"seo_description",
|
|
2425
|
+
"seo_keywords"
|
|
2426
|
+
];
|
|
2427
|
+
for (const field of stringFields) {
|
|
2428
|
+
if (args[field] !== void 0) {
|
|
2429
|
+
const col = field === "collection" ? "collection_id" : field;
|
|
2430
|
+
updates.push(`${col} = ?`);
|
|
2431
|
+
params.push(args[field]);
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
if (args.published !== void 0) {
|
|
2435
|
+
updates.push("published = ?");
|
|
2436
|
+
params.push(args.published ? 1 : 0);
|
|
2437
|
+
} else if (args.status !== void 0) {
|
|
2438
|
+
updates.push("published = ?");
|
|
2439
|
+
params.push(args.status === "publish" || args.status === "published" ? 1 : 0);
|
|
2440
|
+
}
|
|
2441
|
+
if (args.hidden !== void 0) {
|
|
2442
|
+
updates.push("hidden = ?");
|
|
2443
|
+
params.push(args.hidden ? 1 : 0);
|
|
2444
|
+
}
|
|
2445
|
+
if (args.hide_author !== void 0) {
|
|
2446
|
+
updates.push("hide_author = ?");
|
|
2447
|
+
params.push(args.hide_author ? 1 : 0);
|
|
2448
|
+
}
|
|
2449
|
+
if (args.body_html) {
|
|
2450
|
+
const words = args.body_html.replace(/<[^>]+>/g, " ").trim().split(/\s+/).filter(Boolean);
|
|
2451
|
+
updates.push("word_count = ?", "reading_time_mins = ?");
|
|
2452
|
+
params.push(words.length, Math.max(1, Math.ceil(words.length / 200)));
|
|
2453
|
+
}
|
|
2454
|
+
if (updates.length === 0) {
|
|
2455
|
+
return { id, status: "no_changes" };
|
|
2456
|
+
}
|
|
2457
|
+
updates.push("updated_at = strftime('%s','now')");
|
|
2458
|
+
params.push(id, profileId);
|
|
2459
|
+
await execute(`UPDATE content SET ${updates.join(", ")} WHERE id = ? AND profile_id = ?`, params);
|
|
2460
|
+
return {
|
|
2461
|
+
id,
|
|
2462
|
+
status: "updated",
|
|
2463
|
+
updated_fields: Object.keys(args).filter((k) => k !== "content_id_or_slug")
|
|
2464
|
+
};
|
|
2465
|
+
}
|
|
2466
|
+
}
|
|
2467
|
+
];
|
|
2468
|
+
|
|
2469
|
+
// src/tools/pages.ts
|
|
2470
|
+
import { existsSync, readFileSync } from "fs";
|
|
2471
|
+
import { fileURLToPath } from "url";
|
|
2472
|
+
import { dirname, join } from "path";
|
|
2473
|
+
var __dirname = dirname(fileURLToPath(import.meta.url));
|
|
2474
|
+
var sectionsCatalogCache = null;
|
|
2475
|
+
function getSectionsCatalog() {
|
|
2476
|
+
if (sectionsCatalogCache) return sectionsCatalogCache;
|
|
2477
|
+
const candidates = [
|
|
2478
|
+
join(__dirname, "..", "skills", "pages", "references", "sections-catalog.json"),
|
|
2479
|
+
join(__dirname, "..", "..", "skills", "pages", "references", "sections-catalog.json"),
|
|
2480
|
+
join(__dirname, "..", "data", "sections-catalog.json")
|
|
2481
|
+
];
|
|
2482
|
+
for (const p of candidates) {
|
|
2483
|
+
if (existsSync(p)) {
|
|
2484
|
+
try {
|
|
2485
|
+
sectionsCatalogCache = JSON.parse(readFileSync(p, "utf-8"));
|
|
2486
|
+
return sectionsCatalogCache;
|
|
2487
|
+
} catch (err) {
|
|
2488
|
+
console.error(`[Pages] Failed parsing ${p}:`, err);
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
}
|
|
2492
|
+
console.error("[Pages] Could not locate sections-catalog.json in:", candidates);
|
|
2493
|
+
return { sections: [], themes: [] };
|
|
2494
|
+
}
|
|
2495
|
+
function parseAndNormalizeSections(rawVal, contentFallback = "") {
|
|
2496
|
+
let parsedList = [];
|
|
2497
|
+
if (Array.isArray(rawVal)) {
|
|
2498
|
+
parsedList = [...rawVal];
|
|
2499
|
+
} else if (typeof rawVal === "string") {
|
|
2500
|
+
try {
|
|
2501
|
+
const parsed = JSON.parse(rawVal);
|
|
2502
|
+
if (Array.isArray(parsed)) parsedList = parsed;
|
|
2503
|
+
else if (parsed && typeof parsed === "object") parsedList = [parsed];
|
|
2504
|
+
} catch {
|
|
2505
|
+
}
|
|
2506
|
+
} else if (rawVal && typeof rawVal === "object") {
|
|
2507
|
+
parsedList = [rawVal];
|
|
2508
|
+
}
|
|
2509
|
+
if (parsedList.length === 0 && contentFallback.trim()) {
|
|
2510
|
+
parsedList.push({
|
|
2511
|
+
id: generateId("sec"),
|
|
2512
|
+
type: "text",
|
|
2513
|
+
enabled: true,
|
|
2514
|
+
order: 0,
|
|
2515
|
+
data: {
|
|
2516
|
+
text: contentFallback.trim()
|
|
2517
|
+
}
|
|
2518
|
+
});
|
|
2519
|
+
}
|
|
2520
|
+
const sectionTypes = [];
|
|
2521
|
+
const normalized = [];
|
|
2522
|
+
parsedList.forEach((item, idx) => {
|
|
2523
|
+
if (item && typeof item === "object" && !Array.isArray(item)) {
|
|
2524
|
+
const obj = { ...item };
|
|
2525
|
+
const id = typeof obj.id === "string" && obj.id.trim().length > 0 ? obj.id : generateId("sec");
|
|
2526
|
+
const secType = typeof obj.type === "string" && obj.type.trim().length > 0 ? obj.type : "text";
|
|
2527
|
+
obj.id = id;
|
|
2528
|
+
obj.type = secType;
|
|
2529
|
+
if (obj.enabled === void 0) obj.enabled = true;
|
|
2530
|
+
if (obj.order === void 0) obj.order = idx;
|
|
2531
|
+
if (obj.data === void 0) obj.data = {};
|
|
2532
|
+
sectionTypes.push(secType);
|
|
2533
|
+
normalized.push(obj);
|
|
2534
|
+
}
|
|
2535
|
+
});
|
|
2536
|
+
return {
|
|
2537
|
+
sectionsJson: JSON.stringify(normalized),
|
|
2538
|
+
sectionCount: normalized.length,
|
|
2539
|
+
sectionTypes
|
|
2540
|
+
};
|
|
2541
|
+
}
|
|
2542
|
+
function parseFaqJson(rawVal) {
|
|
2543
|
+
if (Array.isArray(rawVal)) {
|
|
2544
|
+
return JSON.stringify(rawVal);
|
|
2545
|
+
}
|
|
2546
|
+
if (typeof rawVal === "string") {
|
|
2547
|
+
try {
|
|
2548
|
+
const parsed = JSON.parse(rawVal);
|
|
2549
|
+
if (Array.isArray(parsed)) return JSON.stringify(parsed);
|
|
2550
|
+
} catch {
|
|
2551
|
+
}
|
|
2552
|
+
}
|
|
2553
|
+
return "[]";
|
|
2554
|
+
}
|
|
2555
|
+
function extractOrNormalizeSchema(args, html) {
|
|
2556
|
+
if (args.schema !== void 0) {
|
|
2557
|
+
if (Array.isArray(args.schema) && args.schema.length > 0) {
|
|
2558
|
+
return JSON.stringify(args.schema);
|
|
2559
|
+
}
|
|
2560
|
+
if (typeof args.schema === "string") {
|
|
2561
|
+
try {
|
|
2562
|
+
const parsed = JSON.parse(args.schema);
|
|
2563
|
+
if (Array.isArray(parsed) && parsed.length > 0) {
|
|
2564
|
+
return args.schema;
|
|
2565
|
+
}
|
|
2566
|
+
} catch {
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
}
|
|
2570
|
+
const fields = [];
|
|
2571
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2572
|
+
const regex = /data-field=(?:"([^"]+)"|'([^']+)')/g;
|
|
2573
|
+
let match;
|
|
2574
|
+
while ((match = regex.exec(html)) !== null) {
|
|
2575
|
+
const fieldName = (match[1] ?? match[2] ?? "").trim();
|
|
2576
|
+
if (fieldName && !seen.has(fieldName) && /^[a-zA-Z0-9_-]+$/.test(fieldName)) {
|
|
2577
|
+
seen.add(fieldName);
|
|
2578
|
+
const lower = fieldName.toLowerCase();
|
|
2579
|
+
const fieldType = lower.includes("desc") || lower.includes("subtitle") || lower.includes("text") || lower.includes("content") ? "textarea" : "text";
|
|
2580
|
+
let label = "";
|
|
2581
|
+
let prevIsLower = false;
|
|
2582
|
+
for (const ch of fieldName) {
|
|
2583
|
+
if (ch >= "A" && ch <= "Z" && prevIsLower) {
|
|
2584
|
+
label += " ";
|
|
2585
|
+
}
|
|
2586
|
+
if (label.length === 0) {
|
|
2587
|
+
label += ch.toUpperCase();
|
|
2588
|
+
} else if (ch === "_" || ch === "-") {
|
|
2589
|
+
label += " ";
|
|
2590
|
+
} else {
|
|
2591
|
+
label += ch;
|
|
2592
|
+
}
|
|
2593
|
+
prevIsLower = ch >= "a" && ch <= "z";
|
|
2594
|
+
}
|
|
2595
|
+
fields.push({ name: fieldName, label, type: fieldType });
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
2598
|
+
if (!fields.some((f) => f.name === "bgColor" || f.name === "backgroundColor")) {
|
|
2599
|
+
fields.push({ name: "bgColor", label: "Background Color", type: "color" });
|
|
2600
|
+
}
|
|
2601
|
+
if (!fields.some((f) => f.name === "textColor" || f.name === "color")) {
|
|
2602
|
+
fields.push({ name: "textColor", label: "Text Color", type: "color" });
|
|
2603
|
+
}
|
|
2604
|
+
const btnUrlFields = [];
|
|
2605
|
+
for (const f of fields) {
|
|
2606
|
+
const lower = f.name.toLowerCase();
|
|
2607
|
+
if ((lower.includes("btn") || lower.includes("button")) && !lower.endsWith("url") && !lower.endsWith("link")) {
|
|
2608
|
+
const urlName = `${f.name}Url`;
|
|
2609
|
+
if (!fields.some((x) => x.name === urlName)) {
|
|
2610
|
+
btnUrlFields.push({
|
|
2611
|
+
name: urlName,
|
|
2612
|
+
label: `${f.label} Link (URL)`,
|
|
2613
|
+
type: "url"
|
|
2614
|
+
});
|
|
2615
|
+
}
|
|
2616
|
+
}
|
|
2617
|
+
}
|
|
2618
|
+
fields.push(...btnUrlFields);
|
|
2619
|
+
return JSON.stringify(fields);
|
|
2620
|
+
}
|
|
2621
|
+
function resolveCanonicalCategories(queryStr) {
|
|
2622
|
+
const q = queryStr.trim().toLowerCase();
|
|
2623
|
+
switch (q) {
|
|
2624
|
+
case "hero":
|
|
2625
|
+
case "banner":
|
|
2626
|
+
case "intro":
|
|
2627
|
+
case "landing_hero":
|
|
2628
|
+
return ["Hero"];
|
|
2629
|
+
case "navigation":
|
|
2630
|
+
case "nav":
|
|
2631
|
+
case "navbar":
|
|
2632
|
+
case "header":
|
|
2633
|
+
case "menu":
|
|
2634
|
+
return ["Navigation"];
|
|
2635
|
+
case "features":
|
|
2636
|
+
case "feature":
|
|
2637
|
+
case "use_cases":
|
|
2638
|
+
case "use-cases":
|
|
2639
|
+
case "usecases":
|
|
2640
|
+
case "services":
|
|
2641
|
+
case "benefits":
|
|
2642
|
+
return ["Features"];
|
|
2643
|
+
case "showcase":
|
|
2644
|
+
case "workspace":
|
|
2645
|
+
case "under_the_hood":
|
|
2646
|
+
case "split":
|
|
2647
|
+
case "demo":
|
|
2648
|
+
case "product":
|
|
2649
|
+
return ["Showcase"];
|
|
2650
|
+
case "conversion":
|
|
2651
|
+
case "commercial":
|
|
2652
|
+
case "pricing":
|
|
2653
|
+
case "price":
|
|
2654
|
+
case "plans":
|
|
2655
|
+
case "cta":
|
|
2656
|
+
case "call to action":
|
|
2657
|
+
case "sales":
|
|
2658
|
+
case "buy":
|
|
2659
|
+
return ["Conversion"];
|
|
2660
|
+
case "content":
|
|
2661
|
+
case "faq":
|
|
2662
|
+
case "faqs":
|
|
2663
|
+
case "questions":
|
|
2664
|
+
case "about":
|
|
2665
|
+
case "text":
|
|
2666
|
+
case "rich_text":
|
|
2667
|
+
case "copy":
|
|
2668
|
+
case "misc":
|
|
2669
|
+
return ["Content"];
|
|
2670
|
+
case "social proof":
|
|
2671
|
+
case "social_proof":
|
|
2672
|
+
case "socialproof":
|
|
2673
|
+
case "testimonials":
|
|
2674
|
+
case "testimonial":
|
|
2675
|
+
case "reviews":
|
|
2676
|
+
case "review":
|
|
2677
|
+
case "ratings":
|
|
2678
|
+
case "trust":
|
|
2679
|
+
return ["Social Proof"];
|
|
2680
|
+
case "footer":
|
|
2681
|
+
case "bottom":
|
|
2682
|
+
return ["Footer"];
|
|
2683
|
+
case "education":
|
|
2684
|
+
case "curriculum":
|
|
2685
|
+
case "course":
|
|
2686
|
+
case "syllabus":
|
|
2687
|
+
case "modules":
|
|
2688
|
+
return ["Education"];
|
|
2689
|
+
default:
|
|
2690
|
+
return [];
|
|
2691
|
+
}
|
|
2692
|
+
}
|
|
2693
|
+
function mapFullSection(sec) {
|
|
2694
|
+
return {
|
|
2695
|
+
type: sec.type ?? null,
|
|
2696
|
+
name: sec.name ?? null,
|
|
2697
|
+
theme: sec.theme ?? null,
|
|
2698
|
+
category: sec.category ?? null,
|
|
2699
|
+
description: sec.description ?? null,
|
|
2700
|
+
ai_summary: sec.ai_summary ?? null,
|
|
2701
|
+
when_to_use: sec.when_to_use ?? null,
|
|
2702
|
+
schema: sec.schema ?? null,
|
|
2703
|
+
sample_data: sec.default_data ?? null,
|
|
2704
|
+
reference_html: sec.reference_html ?? null,
|
|
2705
|
+
reference_css: sec.reference_css ?? null
|
|
2706
|
+
};
|
|
2707
|
+
}
|
|
2708
|
+
var pagesTools = [
|
|
2709
|
+
{
|
|
2710
|
+
name: "page_create",
|
|
2711
|
+
domain: "pages",
|
|
2712
|
+
description: '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 }.',
|
|
2713
|
+
inputSchema: {
|
|
2714
|
+
type: "object",
|
|
2715
|
+
properties: {
|
|
2716
|
+
title: { type: "string", description: "Website page title (e.g. 'Home', 'About Us', 'Pricing', 'Services')" },
|
|
2717
|
+
slug: { type: "string", description: "URL slug for the page (e.g. 'home', 'about', 'pricing'), optional" },
|
|
2718
|
+
excerpt: { type: "string", description: "Short summary or meta excerpt for the page, optional" },
|
|
2719
|
+
sections: {
|
|
2720
|
+
type: "array",
|
|
2721
|
+
description: "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)",
|
|
2722
|
+
items: { type: "object" }
|
|
2723
|
+
},
|
|
2724
|
+
content: { type: "string", description: "Fallback text or markdown if sections is not provided, optional" },
|
|
2725
|
+
faq: {
|
|
2726
|
+
type: "array",
|
|
2727
|
+
description: "Optional FAQ list [{ 'question': '...', 'answer': '...' }]",
|
|
2728
|
+
items: { type: "object" }
|
|
2729
|
+
},
|
|
2730
|
+
seo_title: { type: "string", description: "SEO page title, optional" },
|
|
2731
|
+
seo_description: { type: "string", description: "SEO meta description, optional" },
|
|
2732
|
+
seo_og_image: { type: "string", description: "OpenGraph image URL, optional" },
|
|
2733
|
+
published: { type: "boolean", description: "Whether to publish immediately (defaults to false for draft)", default: false }
|
|
2734
|
+
},
|
|
2735
|
+
required: ["title"]
|
|
2736
|
+
},
|
|
2737
|
+
handler: async (args, ctx) => {
|
|
2738
|
+
const profileId = ctx.profileId;
|
|
2739
|
+
const title = String(args.title || "").trim();
|
|
2740
|
+
if (!title) {
|
|
2741
|
+
throw new Error("Title cannot be empty");
|
|
2742
|
+
}
|
|
2743
|
+
const defaultSlug = title.toLowerCase().replace(/[^a-z0-9\s-]/g, "").trim().split(/\s+/).filter(Boolean).join("-");
|
|
2744
|
+
const slug = typeof args.slug === "string" && args.slug.trim() || defaultSlug || `page-${Date.now()}`;
|
|
2745
|
+
const contentMarkdown = String(
|
|
2746
|
+
args.content ?? args.body ?? args.content_markdown ?? ""
|
|
2747
|
+
);
|
|
2748
|
+
const { sectionsJson, sectionCount, sectionTypes } = parseAndNormalizeSections(
|
|
2749
|
+
args.sections,
|
|
2750
|
+
contentMarkdown
|
|
2751
|
+
);
|
|
2752
|
+
const faqJson = parseFaqJson(args.faq);
|
|
2753
|
+
const published = Boolean(args.published);
|
|
2754
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
2755
|
+
const pageId = generateId("page");
|
|
2756
|
+
try {
|
|
2757
|
+
await execute(
|
|
2758
|
+
`INSERT INTO pages
|
|
2759
|
+
(id, profile_id, user_id, updated_by, slug, title, excerpt, sections, faq,
|
|
2760
|
+
published, nav_active, menu_active, footer_active,
|
|
2761
|
+
seo_title, seo_description, seo_og_image, created_at, updated_at)
|
|
2762
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 1, ?, ?, ?, ?, ?)`,
|
|
2763
|
+
[
|
|
2764
|
+
pageId,
|
|
2765
|
+
profileId,
|
|
2766
|
+
"agent",
|
|
2767
|
+
"agent",
|
|
2768
|
+
slug,
|
|
2769
|
+
title,
|
|
2770
|
+
args.excerpt ?? null,
|
|
2771
|
+
sectionsJson,
|
|
2772
|
+
faqJson,
|
|
2773
|
+
published ? 1 : 0,
|
|
2774
|
+
args.seo_title ?? null,
|
|
2775
|
+
args.seo_description ?? null,
|
|
2776
|
+
args.seo_og_image ?? null,
|
|
2777
|
+
now,
|
|
2778
|
+
now
|
|
2779
|
+
]
|
|
2780
|
+
);
|
|
2781
|
+
} catch (err) {
|
|
2782
|
+
if (String(err?.message || err).includes("no column named updated_by")) {
|
|
2783
|
+
try {
|
|
2784
|
+
await execute("ALTER TABLE pages ADD COLUMN updated_by TEXT", []);
|
|
2785
|
+
} catch {
|
|
2786
|
+
}
|
|
2787
|
+
await execute(
|
|
2788
|
+
`INSERT INTO pages
|
|
2789
|
+
(id, profile_id, user_id, slug, title, excerpt, sections, faq,
|
|
2790
|
+
published, nav_active, menu_active, footer_active,
|
|
2791
|
+
seo_title, seo_description, seo_og_image, created_at, updated_at)
|
|
2792
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 1, ?, ?, ?, ?, ?)`,
|
|
2793
|
+
[
|
|
2794
|
+
pageId,
|
|
2795
|
+
profileId,
|
|
2796
|
+
"agent",
|
|
2797
|
+
slug,
|
|
2798
|
+
title,
|
|
2799
|
+
args.excerpt ?? null,
|
|
2800
|
+
sectionsJson,
|
|
2801
|
+
faqJson,
|
|
2802
|
+
published ? 1 : 0,
|
|
2803
|
+
args.seo_title ?? null,
|
|
2804
|
+
args.seo_description ?? null,
|
|
2805
|
+
args.seo_og_image ?? null,
|
|
2806
|
+
now,
|
|
2807
|
+
now
|
|
2808
|
+
]
|
|
2809
|
+
);
|
|
2810
|
+
} else {
|
|
2811
|
+
throw err;
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
return {
|
|
2815
|
+
success: true,
|
|
2816
|
+
page: {
|
|
2817
|
+
id: pageId,
|
|
2818
|
+
title,
|
|
2819
|
+
slug,
|
|
2820
|
+
published,
|
|
2821
|
+
section_count: sectionCount,
|
|
2822
|
+
section_types: sectionTypes,
|
|
2823
|
+
url: `/dashboard/pages/${pageId}`
|
|
2824
|
+
},
|
|
2825
|
+
message: `Website page '${title}' created successfully with ${sectionCount} section(s) (slug: /${slug})`
|
|
2826
|
+
};
|
|
2827
|
+
}
|
|
2828
|
+
},
|
|
2829
|
+
{
|
|
2830
|
+
name: "page_get",
|
|
2831
|
+
domain: "pages",
|
|
2832
|
+
description: "Fetch a website page and all its visual sections, faq, and metadata by page ID or slug.",
|
|
2833
|
+
inputSchema: {
|
|
2834
|
+
type: "object",
|
|
2835
|
+
properties: {
|
|
2836
|
+
page_id_or_slug: { type: "string", description: "Page ID or slug (e.g. 'about', 'pricing', 'page_xyz')" }
|
|
2837
|
+
},
|
|
2838
|
+
required: ["page_id_or_slug"]
|
|
2839
|
+
},
|
|
2840
|
+
handler: async (args, ctx) => {
|
|
2841
|
+
const profileId = ctx.profileId;
|
|
2842
|
+
const target = String(args.page_id_or_slug ?? args.id ?? args.slug ?? "").trim();
|
|
2843
|
+
if (!target) {
|
|
2844
|
+
throw new Error("Missing required parameter: page_id_or_slug");
|
|
2845
|
+
}
|
|
2846
|
+
const rows = await query(
|
|
2847
|
+
`SELECT id, profile_id, slug, title, excerpt, sections, faq, published,
|
|
2848
|
+
nav_active, menu_active, footer_active, seo_title, seo_description,
|
|
2849
|
+
seo_og_image, created_at, updated_at
|
|
2850
|
+
FROM pages
|
|
2851
|
+
WHERE profile_id = ? AND (id = ? OR slug = ?)
|
|
2852
|
+
LIMIT 1`,
|
|
2853
|
+
[profileId, target, target]
|
|
2854
|
+
);
|
|
2855
|
+
if (rows.length === 0) {
|
|
2856
|
+
throw new Error(`Page with id or slug '${target}' not found`);
|
|
2857
|
+
}
|
|
2858
|
+
const p = rows[0];
|
|
2859
|
+
let sections = [];
|
|
2860
|
+
let faq = [];
|
|
2861
|
+
try {
|
|
2862
|
+
const parsed = JSON.parse(p.sections || "[]");
|
|
2863
|
+
if (Array.isArray(parsed)) sections = parsed;
|
|
2864
|
+
} catch {
|
|
2865
|
+
}
|
|
2866
|
+
try {
|
|
2867
|
+
const parsed = JSON.parse(p.faq || "[]");
|
|
2868
|
+
if (Array.isArray(parsed)) faq = parsed;
|
|
2869
|
+
} catch {
|
|
2870
|
+
}
|
|
2871
|
+
return {
|
|
2872
|
+
success: true,
|
|
2873
|
+
page: {
|
|
2874
|
+
id: p.id,
|
|
2875
|
+
profile_id: p.profile_id,
|
|
2876
|
+
slug: p.slug,
|
|
2877
|
+
title: p.title,
|
|
2878
|
+
excerpt: p.excerpt ?? null,
|
|
2879
|
+
sections,
|
|
2880
|
+
faq,
|
|
2881
|
+
section_count: sections.length,
|
|
2882
|
+
published: Number(p.published || 0) !== 0,
|
|
2883
|
+
nav_active: Number(p.nav_active ?? 1) !== 0,
|
|
2884
|
+
menu_active: Number(p.menu_active ?? 1) !== 0,
|
|
2885
|
+
footer_active: Number(p.footer_active ?? 1) !== 0,
|
|
2886
|
+
seo_title: p.seo_title ?? null,
|
|
2887
|
+
seo_description: p.seo_description ?? null,
|
|
2888
|
+
seo_og_image: p.seo_og_image ?? null,
|
|
2889
|
+
created_at: p.created_at,
|
|
2890
|
+
updated_at: p.updated_at,
|
|
2891
|
+
url: `/dashboard/pages/${p.id}`
|
|
2892
|
+
}
|
|
2893
|
+
};
|
|
2894
|
+
}
|
|
2895
|
+
},
|
|
2896
|
+
{
|
|
2897
|
+
name: "page_update",
|
|
2898
|
+
domain: "pages",
|
|
2899
|
+
description: "Update an existing website page's visual sections, title, slug, excerpt, FAQ, SEO metadata, or published status.",
|
|
2900
|
+
inputSchema: {
|
|
2901
|
+
type: "object",
|
|
2902
|
+
properties: {
|
|
2903
|
+
page_id_or_slug: { type: "string", description: "Page ID or slug (e.g. 'about', 'pricing', 'page_xyz')" },
|
|
2904
|
+
title: { type: "string", description: "New website page title, optional" },
|
|
2905
|
+
slug: { type: "string", description: "New URL slug, optional" },
|
|
2906
|
+
excerpt: { type: "string", description: "New excerpt or summary, optional" },
|
|
2907
|
+
sections: {
|
|
2908
|
+
type: "array",
|
|
2909
|
+
description: "Updated list of section blocks (see page_create for section schemas)",
|
|
2910
|
+
items: { type: "object" }
|
|
2911
|
+
},
|
|
2912
|
+
faq: { type: "array", description: "Updated FAQ items, optional", items: { type: "object" } },
|
|
2913
|
+
published: { type: "boolean", description: "Publish (true) or draft (false) status, optional" },
|
|
2914
|
+
seo_title: { type: "string", description: "Updated SEO title, optional" },
|
|
2915
|
+
seo_description: { type: "string", description: "Updated SEO description, optional" },
|
|
2916
|
+
seo_og_image: { type: "string", description: "Updated OpenGraph image URL, optional" }
|
|
2917
|
+
},
|
|
2918
|
+
required: ["page_id_or_slug"]
|
|
2919
|
+
},
|
|
2920
|
+
handler: async (args, ctx) => {
|
|
2921
|
+
const profileId = ctx.profileId;
|
|
2922
|
+
const target = String(args.page_id_or_slug ?? args.id ?? args.slug ?? "").trim();
|
|
2923
|
+
if (!target) {
|
|
2924
|
+
throw new Error("Missing required parameter: page_id_or_slug");
|
|
2925
|
+
}
|
|
2926
|
+
const pages = await query(
|
|
2927
|
+
"SELECT id, slug, title FROM pages WHERE profile_id = ? AND (id = ? OR slug = ?) LIMIT 1",
|
|
2928
|
+
[profileId, target, target]
|
|
2929
|
+
);
|
|
2930
|
+
if (pages.length === 0) {
|
|
2931
|
+
throw new Error(`Page with id or slug '${target}' not found`);
|
|
2932
|
+
}
|
|
2933
|
+
const pageId = pages[0].id;
|
|
2934
|
+
let finalTitle = pages[0].title;
|
|
2935
|
+
let finalSlug = pages[0].slug;
|
|
2936
|
+
const updates = [];
|
|
2937
|
+
const params = [];
|
|
2938
|
+
if (typeof args.title === "string" && args.title.trim()) {
|
|
2939
|
+
finalTitle = args.title.trim();
|
|
2940
|
+
updates.push("title = ?");
|
|
2941
|
+
params.push(finalTitle);
|
|
2942
|
+
}
|
|
2943
|
+
if (typeof args.slug === "string" && args.slug.trim()) {
|
|
2944
|
+
finalSlug = args.slug.trim();
|
|
2945
|
+
updates.push("slug = ?");
|
|
2946
|
+
params.push(finalSlug);
|
|
2947
|
+
}
|
|
2948
|
+
if (typeof args.excerpt === "string") {
|
|
2949
|
+
updates.push("excerpt = ?");
|
|
2950
|
+
params.push(args.excerpt);
|
|
2951
|
+
}
|
|
2952
|
+
let sectionCount = null;
|
|
2953
|
+
let sectionTypes = null;
|
|
2954
|
+
if (args.sections !== void 0 || args.content !== void 0 || args.body !== void 0 || args.content_markdown !== void 0) {
|
|
2955
|
+
const contentFb = String(
|
|
2956
|
+
args.content ?? args.body ?? args.content_markdown ?? ""
|
|
2957
|
+
);
|
|
2958
|
+
const normalized = parseAndNormalizeSections(args.sections, contentFb);
|
|
2959
|
+
updates.push("sections = ?");
|
|
2960
|
+
params.push(normalized.sectionsJson);
|
|
2961
|
+
sectionCount = normalized.sectionCount;
|
|
2962
|
+
sectionTypes = normalized.sectionTypes;
|
|
2963
|
+
}
|
|
2964
|
+
if (args.faq !== void 0) {
|
|
2965
|
+
updates.push("faq = ?");
|
|
2966
|
+
params.push(parseFaqJson(args.faq));
|
|
2967
|
+
}
|
|
2968
|
+
if (typeof args.published === "boolean") {
|
|
2969
|
+
updates.push("published = ?");
|
|
2970
|
+
params.push(args.published ? 1 : 0);
|
|
2971
|
+
}
|
|
2972
|
+
if (typeof args.seo_title === "string") {
|
|
2973
|
+
updates.push("seo_title = ?");
|
|
2974
|
+
params.push(args.seo_title);
|
|
2975
|
+
}
|
|
2976
|
+
if (typeof args.seo_description === "string") {
|
|
2977
|
+
updates.push("seo_description = ?");
|
|
2978
|
+
params.push(args.seo_description);
|
|
2979
|
+
}
|
|
2980
|
+
if (typeof args.seo_og_image === "string") {
|
|
2981
|
+
updates.push("seo_og_image = ?");
|
|
2982
|
+
params.push(args.seo_og_image);
|
|
2983
|
+
}
|
|
2984
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
2985
|
+
const baseParams = [...params];
|
|
2986
|
+
const baseUpdates = [...updates];
|
|
2987
|
+
updates.push("updated_at = ?", "updated_by = ?");
|
|
2988
|
+
params.push(now, "agent", profileId, pageId);
|
|
2989
|
+
try {
|
|
2990
|
+
await execute(
|
|
2991
|
+
`UPDATE pages SET ${updates.join(", ")} WHERE profile_id = ? AND id = ?`,
|
|
2992
|
+
params
|
|
2993
|
+
);
|
|
2994
|
+
} catch (err) {
|
|
2995
|
+
if (String(err?.message || err).includes("no column named updated_by")) {
|
|
2996
|
+
baseUpdates.push("updated_at = ?");
|
|
2997
|
+
baseParams.push(now, profileId, pageId);
|
|
2998
|
+
await execute(
|
|
2999
|
+
`UPDATE pages SET ${baseUpdates.join(", ")} WHERE profile_id = ? AND id = ?`,
|
|
3000
|
+
baseParams
|
|
3001
|
+
);
|
|
3002
|
+
} else {
|
|
3003
|
+
throw err;
|
|
3004
|
+
}
|
|
3005
|
+
}
|
|
3006
|
+
return {
|
|
3007
|
+
success: true,
|
|
3008
|
+
page: {
|
|
3009
|
+
id: pageId,
|
|
3010
|
+
title: finalTitle,
|
|
3011
|
+
slug: finalSlug,
|
|
3012
|
+
section_count: sectionCount,
|
|
3013
|
+
section_types: sectionTypes,
|
|
3014
|
+
url: `/dashboard/pages/${pageId}`
|
|
3015
|
+
},
|
|
3016
|
+
message: `Website page '${finalTitle}' updated successfully`
|
|
3017
|
+
};
|
|
3018
|
+
}
|
|
3019
|
+
},
|
|
3020
|
+
{
|
|
3021
|
+
name: "page_publish",
|
|
3022
|
+
domain: "pages",
|
|
3023
|
+
description: "Toggle published or draft status for a website page by ID or slug.",
|
|
3024
|
+
inputSchema: {
|
|
3025
|
+
type: "object",
|
|
3026
|
+
properties: {
|
|
3027
|
+
page_id_or_slug: { type: "string", description: "Page ID or slug (e.g. 'about', 'page_xyz')" },
|
|
3028
|
+
published: {
|
|
3029
|
+
type: "boolean",
|
|
3030
|
+
description: "True to publish, false to unpublish/draft (defaults to true)",
|
|
3031
|
+
default: true
|
|
3032
|
+
}
|
|
3033
|
+
},
|
|
3034
|
+
required: ["page_id_or_slug"]
|
|
3035
|
+
},
|
|
3036
|
+
handler: async (args, ctx) => {
|
|
3037
|
+
const profileId = ctx.profileId;
|
|
3038
|
+
const target = String(args.page_id_or_slug ?? args.id ?? args.slug ?? "").trim();
|
|
3039
|
+
if (!target) {
|
|
3040
|
+
throw new Error("Missing required parameter: page_id_or_slug");
|
|
3041
|
+
}
|
|
3042
|
+
const rawPub = args.published !== void 0 ? args.published : args.publish;
|
|
3043
|
+
const publishState = typeof rawPub === "boolean" ? rawPub : true;
|
|
3044
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
3045
|
+
let res;
|
|
3046
|
+
try {
|
|
3047
|
+
res = await execute(
|
|
3048
|
+
`UPDATE pages
|
|
3049
|
+
SET published = ?, updated_at = ?, updated_by = ?
|
|
3050
|
+
WHERE profile_id = ? AND (id = ? OR slug = ?)`,
|
|
3051
|
+
[publishState ? 1 : 0, now, "agent", profileId, target, target]
|
|
3052
|
+
);
|
|
3053
|
+
} catch (err) {
|
|
3054
|
+
if (String(err?.message || err).includes("no column named updated_by")) {
|
|
3055
|
+
res = await execute(
|
|
3056
|
+
`UPDATE pages
|
|
3057
|
+
SET published = ?, updated_at = ?
|
|
3058
|
+
WHERE profile_id = ? AND (id = ? OR slug = ?)`,
|
|
3059
|
+
[publishState ? 1 : 0, now, profileId, target, target]
|
|
3060
|
+
);
|
|
3061
|
+
} else {
|
|
3062
|
+
throw err;
|
|
3063
|
+
}
|
|
3064
|
+
}
|
|
3065
|
+
if (res.rowsAffected === 0) {
|
|
3066
|
+
throw new Error(`Page with id or slug '${target}' not found`);
|
|
3067
|
+
}
|
|
3068
|
+
return {
|
|
3069
|
+
success: true,
|
|
3070
|
+
target,
|
|
3071
|
+
published: publishState,
|
|
3072
|
+
message: `Page '${target}' is now ${publishState ? "published" : "draft"}`
|
|
3073
|
+
};
|
|
3074
|
+
}
|
|
3075
|
+
},
|
|
3076
|
+
{
|
|
3077
|
+
name: "page_list",
|
|
3078
|
+
domain: "pages",
|
|
3079
|
+
description: "List all website pages, URLs, slugs, and publication statuses for the profile.",
|
|
3080
|
+
inputSchema: {
|
|
3081
|
+
type: "object",
|
|
3082
|
+
properties: {
|
|
3083
|
+
published_only: { type: "boolean", description: "Filter to only show published pages, optional" }
|
|
3084
|
+
}
|
|
3085
|
+
},
|
|
3086
|
+
handler: async (args, ctx) => {
|
|
3087
|
+
const profileId = ctx.profileId;
|
|
3088
|
+
let sql = "SELECT id, title, slug, excerpt, published, sections, updated_at FROM pages WHERE profile_id = ?";
|
|
3089
|
+
if (args.published_only) {
|
|
3090
|
+
sql += " AND published = 1";
|
|
3091
|
+
}
|
|
3092
|
+
sql += " ORDER BY updated_at DESC LIMIT 50";
|
|
3093
|
+
const rows = await query(sql, [profileId]);
|
|
3094
|
+
return {
|
|
3095
|
+
total: rows.length,
|
|
3096
|
+
pages: rows.map((r) => {
|
|
3097
|
+
let sectionCount = 0;
|
|
3098
|
+
try {
|
|
3099
|
+
const parsed = JSON.parse(r.sections || "[]");
|
|
3100
|
+
if (Array.isArray(parsed)) sectionCount = parsed.length;
|
|
3101
|
+
} catch {
|
|
3102
|
+
}
|
|
3103
|
+
return {
|
|
3104
|
+
id: r.id,
|
|
3105
|
+
title: r.title,
|
|
3106
|
+
slug: r.slug,
|
|
3107
|
+
excerpt: r.excerpt ?? null,
|
|
3108
|
+
published: Number(r.published || 0) !== 0,
|
|
3109
|
+
section_count: sectionCount,
|
|
3110
|
+
updated_at: r.updated_at
|
|
3111
|
+
};
|
|
3112
|
+
})
|
|
3113
|
+
};
|
|
3114
|
+
}
|
|
3115
|
+
},
|
|
3116
|
+
{
|
|
3117
|
+
name: "component_create",
|
|
3118
|
+
domain: "pages",
|
|
3119
|
+
description: "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.",
|
|
3120
|
+
inputSchema: {
|
|
3121
|
+
type: "object",
|
|
3122
|
+
properties: {
|
|
3123
|
+
name: { type: "string", description: "Component name (e.g. 'ROI Profit Calculator', 'Interactive Timeline', 'Hero Banner')" },
|
|
3124
|
+
html: {
|
|
3125
|
+
type: "string",
|
|
3126
|
+
description: '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.'
|
|
3127
|
+
},
|
|
3128
|
+
css: { type: "string", description: "Scoped CSS styles for the component (e.g. `.comp-name { ... }`), optional" },
|
|
3129
|
+
js: { type: "string", description: "Client-side JavaScript interaction logic, optional" },
|
|
3130
|
+
ts: { type: "string", description: "TypeScript / TSX component source if maintaining a Qwik or React component definition, optional" },
|
|
3131
|
+
schema: {
|
|
3132
|
+
type: "array",
|
|
3133
|
+
description: "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'.",
|
|
3134
|
+
items: {
|
|
3135
|
+
type: "object",
|
|
3136
|
+
properties: {
|
|
3137
|
+
name: { type: "string" },
|
|
3138
|
+
label: { type: "string" },
|
|
3139
|
+
type: { type: "string", enum: ["text", "textarea", "color", "url", "image", "select", "boolean"] },
|
|
3140
|
+
options: { type: "array", items: { type: "string" } }
|
|
3141
|
+
},
|
|
3142
|
+
required: ["name", "label", "type"]
|
|
3143
|
+
}
|
|
3144
|
+
},
|
|
3145
|
+
collection: { type: "string", description: "Category or collection name (e.g. 'Hero', 'Marketing', 'Widgets', 'Custom'), default 'Custom'" }
|
|
3146
|
+
},
|
|
3147
|
+
required: ["name", "html"]
|
|
3148
|
+
},
|
|
3149
|
+
handler: async (args, ctx) => {
|
|
3150
|
+
const profileId = ctx.profileId;
|
|
3151
|
+
const name = String(args.name || "").trim();
|
|
3152
|
+
if (!name) throw new Error("Parameter name cannot be empty");
|
|
3153
|
+
const html = String(args.html || "").trim();
|
|
3154
|
+
if (!html) throw new Error("Parameter html cannot be empty");
|
|
3155
|
+
const css = typeof args.css === "string" ? args.css : "";
|
|
3156
|
+
const js = typeof args.js === "string" ? args.js : "";
|
|
3157
|
+
const ts = typeof args.ts === "string" ? args.ts : "";
|
|
3158
|
+
const rawCollection = typeof args.collection === "string" ? args.collection.trim() : "";
|
|
3159
|
+
const rawType = typeof args.type === "string" ? args.type.trim() : "";
|
|
3160
|
+
let collection = "Custom";
|
|
3161
|
+
let compType = "custom";
|
|
3162
|
+
if (rawCollection) {
|
|
3163
|
+
const colMap = {
|
|
3164
|
+
hero: "Hero",
|
|
3165
|
+
navigation: "Navigation",
|
|
3166
|
+
nav: "Navigation",
|
|
3167
|
+
header: "Navigation",
|
|
3168
|
+
content: "Content",
|
|
3169
|
+
conversion: "Conversion",
|
|
3170
|
+
pricing: "Conversion",
|
|
3171
|
+
commercial: "Conversion",
|
|
3172
|
+
"social proof": "Social Proof",
|
|
3173
|
+
social_proof: "Social Proof",
|
|
3174
|
+
testimonials: "Social Proof",
|
|
3175
|
+
showcase: "Showcase",
|
|
3176
|
+
footer: "Footer",
|
|
3177
|
+
education: "Education",
|
|
3178
|
+
curriculum: "Education"
|
|
3179
|
+
};
|
|
3180
|
+
collection = colMap[rawCollection.toLowerCase()] ?? rawCollection;
|
|
3181
|
+
compType = rawType || collection.toLowerCase();
|
|
3182
|
+
} else {
|
|
3183
|
+
const nameLower = name.toLowerCase();
|
|
3184
|
+
const typeLower = rawType.toLowerCase();
|
|
3185
|
+
if (nameLower.includes("hero") || typeLower.includes("hero")) {
|
|
3186
|
+
collection = "Hero";
|
|
3187
|
+
compType = "hero";
|
|
3188
|
+
} else if (nameLower.includes("nav") || nameLower.includes("header") || typeLower.includes("nav")) {
|
|
3189
|
+
collection = "Navigation";
|
|
3190
|
+
compType = "sc_navbar";
|
|
3191
|
+
} else if (nameLower.includes("footer") || typeLower.includes("footer")) {
|
|
3192
|
+
collection = "Footer";
|
|
3193
|
+
compType = "sc_footer";
|
|
3194
|
+
} else if (nameLower.includes("price") || nameLower.includes("pricing") || typeLower.includes("pricing")) {
|
|
3195
|
+
collection = "Conversion";
|
|
3196
|
+
compType = "pricing";
|
|
3197
|
+
} else if (nameLower.includes("testimonial") || nameLower.includes("review")) {
|
|
3198
|
+
collection = "Social Proof";
|
|
3199
|
+
compType = "testimonials";
|
|
3200
|
+
} else if (nameLower.includes("faq") || nameLower.includes("question")) {
|
|
3201
|
+
collection = "Content";
|
|
3202
|
+
compType = "faq";
|
|
3203
|
+
} else if (nameLower.includes("showcase") || nameLower.includes("feature")) {
|
|
3204
|
+
collection = "Showcase";
|
|
3205
|
+
compType = "features";
|
|
3206
|
+
}
|
|
3207
|
+
}
|
|
3208
|
+
const isGlobal = args.is_global === true || Number(args.is_global) === 1 ? 1 : 0;
|
|
3209
|
+
const compId = generateId("comp");
|
|
3210
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
3211
|
+
const schemaJson = extractOrNormalizeSchema(args, html);
|
|
3212
|
+
try {
|
|
3213
|
+
await execute(
|
|
3214
|
+
`INSERT INTO user_components
|
|
3215
|
+
(id, profile_id, name, thumbnail_url, html, css, js, ts, schema, source, type, collection, is_primary, is_global, created_at)
|
|
3216
|
+
VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?, 'agent', ?, ?, 0, ?, ?)`,
|
|
3217
|
+
[compId, profileId, name, html, css, js, ts, schemaJson, compType, collection, isGlobal, now]
|
|
3218
|
+
);
|
|
3219
|
+
} catch (err) {
|
|
3220
|
+
const msg = String(err?.message || err);
|
|
3221
|
+
if (msg.includes("no column named is_global")) {
|
|
3222
|
+
try {
|
|
3223
|
+
await execute("ALTER TABLE user_components ADD COLUMN is_global INTEGER DEFAULT 0", []);
|
|
3224
|
+
} catch {
|
|
3225
|
+
}
|
|
3226
|
+
await execute(
|
|
3227
|
+
`INSERT INTO user_components
|
|
3228
|
+
(id, profile_id, name, thumbnail_url, html, css, js, ts, schema, source, type, collection, is_primary, is_global, created_at)
|
|
3229
|
+
VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?, 'agent', ?, ?, 0, ?, ?)`,
|
|
3230
|
+
[compId, profileId, name, html, css, js, ts, schemaJson, compType, collection, isGlobal, now]
|
|
3231
|
+
);
|
|
3232
|
+
} else if (msg.includes("no column named ts")) {
|
|
3233
|
+
try {
|
|
3234
|
+
await execute("ALTER TABLE user_components ADD COLUMN ts TEXT", []);
|
|
3235
|
+
} catch {
|
|
3236
|
+
}
|
|
3237
|
+
await execute(
|
|
3238
|
+
`INSERT INTO user_components
|
|
3239
|
+
(id, profile_id, name, thumbnail_url, html, css, js, schema, source, type, collection, is_primary, created_at)
|
|
3240
|
+
VALUES (?, ?, ?, NULL, ?, ?, ?, ?, 'agent', ?, ?, 0, ?)`,
|
|
3241
|
+
[compId, profileId, name, html, css, js, schemaJson, compType, collection, now]
|
|
3242
|
+
);
|
|
3243
|
+
} else {
|
|
3244
|
+
throw err;
|
|
3245
|
+
}
|
|
3246
|
+
}
|
|
3247
|
+
return {
|
|
3248
|
+
success: true,
|
|
3249
|
+
component: {
|
|
3250
|
+
id: compId,
|
|
3251
|
+
name,
|
|
3252
|
+
collection,
|
|
3253
|
+
is_global: isGlobal,
|
|
3254
|
+
section_reference: {
|
|
3255
|
+
type: "custom",
|
|
3256
|
+
component_id: compId
|
|
3257
|
+
}
|
|
3258
|
+
},
|
|
3259
|
+
message: `Custom component '${name}' created successfully with ID '${compId}'. Add to a page with {'type': 'custom', 'component_id': '${compId}'}.`
|
|
3260
|
+
};
|
|
3261
|
+
}
|
|
3262
|
+
},
|
|
3263
|
+
{
|
|
3264
|
+
name: "component_list",
|
|
3265
|
+
domain: "pages",
|
|
3266
|
+
description: "List all custom components stored in user_components for the profile.",
|
|
3267
|
+
inputSchema: {
|
|
3268
|
+
type: "object",
|
|
3269
|
+
properties: {
|
|
3270
|
+
collection: { type: "string", description: "Optional collection filter, optional" }
|
|
3271
|
+
}
|
|
3272
|
+
},
|
|
3273
|
+
handler: async (args, ctx) => {
|
|
3274
|
+
const profileId = ctx.profileId;
|
|
3275
|
+
const collectionFilter = typeof args.collection === "string" ? args.collection.trim() : "";
|
|
3276
|
+
let rows = [];
|
|
3277
|
+
try {
|
|
3278
|
+
const sql = collectionFilter ? "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" : "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";
|
|
3279
|
+
rows = await query(sql, collectionFilter ? [profileId, collectionFilter] : [profileId]);
|
|
3280
|
+
} catch {
|
|
3281
|
+
const fbSql = collectionFilter ? "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" : "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";
|
|
3282
|
+
rows = await query(fbSql, collectionFilter ? [profileId, collectionFilter] : [profileId]);
|
|
3283
|
+
}
|
|
3284
|
+
return {
|
|
3285
|
+
total: rows.length,
|
|
3286
|
+
components: rows.map((r) => ({
|
|
3287
|
+
id: r.id,
|
|
3288
|
+
name: r.name,
|
|
3289
|
+
collection: r.collection || "Custom",
|
|
3290
|
+
type: r.type || "custom",
|
|
3291
|
+
source: r.source || "manual",
|
|
3292
|
+
is_global: Number(r.is_global || 0),
|
|
3293
|
+
created_at: r.created_at
|
|
3294
|
+
}))
|
|
3295
|
+
};
|
|
3296
|
+
}
|
|
3297
|
+
},
|
|
3298
|
+
{
|
|
3299
|
+
name: "component_get",
|
|
3300
|
+
domain: "pages",
|
|
3301
|
+
description: "Fetch a custom component by its ID with full HTML, CSS, and JS source.",
|
|
3302
|
+
inputSchema: {
|
|
3303
|
+
type: "object",
|
|
3304
|
+
properties: {
|
|
3305
|
+
component_id: { type: "string", description: "Component ID (e.g. 'comp_xyz')" }
|
|
3306
|
+
},
|
|
3307
|
+
required: ["component_id"]
|
|
3308
|
+
},
|
|
3309
|
+
handler: async (args, ctx) => {
|
|
3310
|
+
const profileId = ctx.profileId;
|
|
3311
|
+
const componentId = String(args.component_id ?? args.id ?? "").trim();
|
|
3312
|
+
if (!componentId) {
|
|
3313
|
+
throw new Error("Missing required parameter: component_id");
|
|
3314
|
+
}
|
|
3315
|
+
let rows = [];
|
|
3316
|
+
try {
|
|
3317
|
+
rows = await query(
|
|
3318
|
+
"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",
|
|
3319
|
+
[profileId, componentId]
|
|
3320
|
+
);
|
|
3321
|
+
} catch {
|
|
3322
|
+
rows = await query(
|
|
3323
|
+
"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",
|
|
3324
|
+
[profileId, componentId]
|
|
3325
|
+
);
|
|
3326
|
+
}
|
|
3327
|
+
if (rows.length === 0) {
|
|
3328
|
+
throw new Error(`Custom component with ID '${componentId}' not found`);
|
|
3329
|
+
}
|
|
3330
|
+
const c = rows[0];
|
|
3331
|
+
return {
|
|
3332
|
+
component: {
|
|
3333
|
+
id: c.id,
|
|
3334
|
+
name: c.name,
|
|
3335
|
+
html: c.html || "",
|
|
3336
|
+
css: c.css || "",
|
|
3337
|
+
js: c.js || "",
|
|
3338
|
+
schema: c.schema || "[]",
|
|
3339
|
+
collection: c.collection || "Custom",
|
|
3340
|
+
type: c.type || "custom",
|
|
3341
|
+
source: c.source || "manual",
|
|
3342
|
+
is_global: Number(c.is_global || 0),
|
|
3343
|
+
created_at: c.created_at
|
|
3344
|
+
}
|
|
3345
|
+
};
|
|
3346
|
+
}
|
|
3347
|
+
},
|
|
3348
|
+
{
|
|
3349
|
+
name: "page_get_section_schema",
|
|
3350
|
+
domain: "pages",
|
|
3351
|
+
description: `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'.`,
|
|
3352
|
+
inputSchema: {
|
|
3353
|
+
type: "object",
|
|
3354
|
+
properties: {
|
|
3355
|
+
category: {
|
|
3356
|
+
type: "string",
|
|
3357
|
+
description: "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."
|
|
3358
|
+
},
|
|
3359
|
+
section_type: {
|
|
3360
|
+
type: "string",
|
|
3361
|
+
description: "Specific section type (e.g. 'sc_hero', 'pricing', 'faq'), comma-separated types, or theme discovery ('themes')."
|
|
3362
|
+
},
|
|
3363
|
+
section_types: {
|
|
3364
|
+
type: "array",
|
|
3365
|
+
items: { type: "string" },
|
|
3366
|
+
description: "Array of specific section types to inspect simultaneously (e.g. ['sc_hero', 'hero_section'])."
|
|
3367
|
+
},
|
|
3368
|
+
theme: {
|
|
3369
|
+
type: "string",
|
|
3370
|
+
description: "Theme name filter (e.g. 'superconsole', 'classic', 'nike', 'tesla', or 'list' to discover all themes)."
|
|
3371
|
+
},
|
|
3372
|
+
limit: {
|
|
3373
|
+
type: "number",
|
|
3374
|
+
description: "Max number of sections to return (e.g. 5). Defaults to returning all matching sections."
|
|
3375
|
+
}
|
|
3376
|
+
}
|
|
3377
|
+
},
|
|
3378
|
+
handler: async (args, _ctx) => {
|
|
3379
|
+
const catalog = getSectionsCatalog();
|
|
3380
|
+
const sections = Array.isArray(catalog.sections) ? catalog.sections : [];
|
|
3381
|
+
const themesList = Array.isArray(catalog.themes) ? catalog.themes : [];
|
|
3382
|
+
const requestedTypes = [];
|
|
3383
|
+
const arrInput = args.section_types ?? args.types;
|
|
3384
|
+
if (Array.isArray(arrInput)) {
|
|
3385
|
+
for (const v of arrInput) {
|
|
3386
|
+
if (typeof v === "string") {
|
|
3387
|
+
const t = v.trim().toLowerCase();
|
|
3388
|
+
if (t && !requestedTypes.includes(t)) requestedTypes.push(t);
|
|
3389
|
+
}
|
|
3390
|
+
}
|
|
3391
|
+
} else if (typeof args.section_type === "string") {
|
|
3392
|
+
for (const part of args.section_type.split(",")) {
|
|
3393
|
+
const t = part.trim().toLowerCase();
|
|
3394
|
+
if (t && !requestedTypes.includes(t)) requestedTypes.push(t);
|
|
3395
|
+
}
|
|
3396
|
+
}
|
|
3397
|
+
const themeFilter = String(args.theme ?? "").trim().toLowerCase();
|
|
3398
|
+
const categoryFilter = String(args.category ?? "").trim().toLowerCase();
|
|
3399
|
+
const limit = typeof args.limit === "number" && args.limit >= 0 ? Math.floor(args.limit) : void 0;
|
|
3400
|
+
if (requestedTypes.includes("themes") || themeFilter === "list" || themeFilter === "all") {
|
|
3401
|
+
return {
|
|
3402
|
+
available_themes: themesList,
|
|
3403
|
+
usage: "To fetch all section blocks tailored to a specific theme, call page_get_section_schema with theme (e.g. 'superconsole', 'classic', 'nike', 'tesla')."
|
|
3404
|
+
};
|
|
3405
|
+
}
|
|
3406
|
+
if (categoryFilter) {
|
|
3407
|
+
if (categoryFilter === "list" || categoryFilter === "all") {
|
|
3408
|
+
return {
|
|
3409
|
+
categories: [
|
|
3410
|
+
{ name: "Hero", description: "Hero banners, main headlines, intro sections", sections: ["sc_hero", "hero_section"] },
|
|
3411
|
+
{ name: "Navigation", description: "Top navigation header with brand and links", sections: ["sc_navbar"] },
|
|
3412
|
+
{ name: "Features", description: "Feature highlights, interactive tabs, capability grids", sections: ["sc_use_cases"] },
|
|
3413
|
+
{ name: "Showcase", description: "Split product previews, architecture, live terminals", sections: ["sc_workspace", "sc_under_the_hood"] },
|
|
3414
|
+
{ name: "Conversion", description: "Pricing tiers, subscription plans, CTA banners", sections: ["pricing", "cta_section"] },
|
|
3415
|
+
{ name: "Content", description: "FAQ accordions, about company, rich text articles", sections: ["faq", "about_section", "text"] },
|
|
3416
|
+
{ name: "Social Proof", description: "Customer testimonials, reviews, trust badges", sections: ["testimonials"] },
|
|
3417
|
+
{ name: "Footer", description: "Site footer, copyright, legal links, status indicator", sections: ["sc_footer"] },
|
|
3418
|
+
{ name: "Education", description: "Curriculum, course modules, lesson plans", sections: ["curriculum"] }
|
|
3419
|
+
],
|
|
3420
|
+
guidance: "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."
|
|
3421
|
+
};
|
|
3422
|
+
}
|
|
3423
|
+
const matchedCategories = resolveCanonicalCategories(categoryFilter);
|
|
3424
|
+
let matches = sections.filter((sec) => {
|
|
3425
|
+
const secCat = String(sec.category ?? "");
|
|
3426
|
+
if (matchedCategories.length > 0) {
|
|
3427
|
+
return matchedCategories.some((c) => c.toLowerCase() === secCat.toLowerCase());
|
|
3428
|
+
}
|
|
3429
|
+
return secCat.toLowerCase().includes(categoryFilter) || String(sec.type ?? "").toLowerCase() === categoryFilter;
|
|
3430
|
+
}).map(mapFullSection);
|
|
3431
|
+
if (limit !== void 0) matches = matches.slice(0, limit);
|
|
3432
|
+
return {
|
|
3433
|
+
category: matchedCategories[0] ?? categoryFilter,
|
|
3434
|
+
filter: `category: ${categoryFilter}`,
|
|
3435
|
+
count: matches.length,
|
|
3436
|
+
sections: matches,
|
|
3437
|
+
guidance: "MANDATORY: Learn layout structure, typography scale, responsive breakpoints, and CSS variables from these matching category blueprints before building custom components."
|
|
3438
|
+
};
|
|
3439
|
+
}
|
|
3440
|
+
if (requestedTypes.length > 1) {
|
|
3441
|
+
let matches = [];
|
|
3442
|
+
for (const req of requestedTypes) {
|
|
3443
|
+
const found = sections.find((sec) => {
|
|
3444
|
+
const matchesType = String(sec.type ?? "").toLowerCase() === req;
|
|
3445
|
+
const matchesAlias = Array.isArray(sec.aliases) && sec.aliases.some((a) => String(a).toLowerCase() === req);
|
|
3446
|
+
return matchesType || matchesAlias;
|
|
3447
|
+
});
|
|
3448
|
+
if (found) matches.push(mapFullSection(found));
|
|
3449
|
+
}
|
|
3450
|
+
if (limit !== void 0) matches = matches.slice(0, limit);
|
|
3451
|
+
return {
|
|
3452
|
+
requested_types: requestedTypes,
|
|
3453
|
+
count: matches.length,
|
|
3454
|
+
sections: matches,
|
|
3455
|
+
guidance: "Compare the reference blueprints to craft your bespoke custom component."
|
|
3456
|
+
};
|
|
3457
|
+
}
|
|
3458
|
+
if (requestedTypes.length === 1) {
|
|
3459
|
+
const singleType = requestedTypes[0];
|
|
3460
|
+
if (singleType !== "list" && singleType !== "all") {
|
|
3461
|
+
const canonicalCats = resolveCanonicalCategories(singleType);
|
|
3462
|
+
const isCategoryWord = [
|
|
3463
|
+
"hero",
|
|
3464
|
+
"content",
|
|
3465
|
+
"features",
|
|
3466
|
+
"showcase",
|
|
3467
|
+
"conversion",
|
|
3468
|
+
"commercial",
|
|
3469
|
+
"social proof",
|
|
3470
|
+
"social_proof",
|
|
3471
|
+
"footer",
|
|
3472
|
+
"navigation",
|
|
3473
|
+
"education"
|
|
3474
|
+
].includes(singleType);
|
|
3475
|
+
if (isCategoryWord && canonicalCats.length > 0) {
|
|
3476
|
+
let categoryMatches = sections.filter(
|
|
3477
|
+
(sec) => canonicalCats.some(
|
|
3478
|
+
(c) => c.toLowerCase() === String(sec.category ?? "").toLowerCase()
|
|
3479
|
+
)
|
|
3480
|
+
).map(mapFullSection);
|
|
3481
|
+
if (categoryMatches.length > 0) {
|
|
3482
|
+
if (limit !== void 0) categoryMatches = categoryMatches.slice(0, limit);
|
|
3483
|
+
return {
|
|
3484
|
+
query: singleType,
|
|
3485
|
+
category: canonicalCats[0],
|
|
3486
|
+
category_matches: categoryMatches.length,
|
|
3487
|
+
sections: categoryMatches,
|
|
3488
|
+
guidance: "Compare reference blueprints and 'when_to_use' to choose or craft the best section."
|
|
3489
|
+
};
|
|
3490
|
+
}
|
|
3491
|
+
}
|
|
3492
|
+
const exactMatch = sections.find((sec) => {
|
|
3493
|
+
const matchesType = String(sec.type ?? "").toLowerCase() === singleType;
|
|
3494
|
+
const matchesAlias = Array.isArray(sec.aliases) && sec.aliases.some((a) => String(a).toLowerCase() === singleType);
|
|
3495
|
+
return matchesType || matchesAlias;
|
|
3496
|
+
});
|
|
3497
|
+
if (exactMatch) {
|
|
3498
|
+
const secCat = exactMatch.category || "Custom";
|
|
3499
|
+
return {
|
|
3500
|
+
...mapFullSection(exactMatch),
|
|
3501
|
+
rules: exactMatch.rules ?? null,
|
|
3502
|
+
category_guidance: `To inspect all native blueprints in the '${secCat}' category, call page_get_section_schema(category: '${secCat}')`
|
|
3503
|
+
};
|
|
3504
|
+
}
|
|
3505
|
+
let subMatches = sections.filter((sec) => String(sec.category ?? "").toLowerCase().includes(singleType)).map(mapFullSection);
|
|
3506
|
+
if (subMatches.length > 0) {
|
|
3507
|
+
if (limit !== void 0) subMatches = subMatches.slice(0, limit);
|
|
3508
|
+
return {
|
|
3509
|
+
query: singleType,
|
|
3510
|
+
category_matches: subMatches.length,
|
|
3511
|
+
sections: subMatches,
|
|
3512
|
+
guidance: "Compare reference blueprints and 'when_to_use' to choose or craft the best section."
|
|
3513
|
+
};
|
|
3514
|
+
}
|
|
3515
|
+
}
|
|
3516
|
+
}
|
|
3517
|
+
if (themeFilter) {
|
|
3518
|
+
let matches = sections.filter((sec) => String(sec.theme ?? "").toLowerCase() === themeFilter).map(mapFullSection);
|
|
3519
|
+
if (limit !== void 0) matches = matches.slice(0, limit);
|
|
3520
|
+
return {
|
|
3521
|
+
filter: `theme: ${themeFilter}`,
|
|
3522
|
+
count: matches.length,
|
|
3523
|
+
sections: matches,
|
|
3524
|
+
guidance: "Assemble landing page using sections from this theme to ensure unified visual aesthetics."
|
|
3525
|
+
};
|
|
3526
|
+
}
|
|
3527
|
+
const effectiveLimit = limit ?? 12;
|
|
3528
|
+
const list = sections.slice(0, effectiveLimit).map((sec) => ({
|
|
3529
|
+
type: sec.type ?? null,
|
|
3530
|
+
name: sec.name ?? null,
|
|
3531
|
+
theme: sec.theme ?? null,
|
|
3532
|
+
category: sec.category ?? null,
|
|
3533
|
+
description: sec.description ?? null,
|
|
3534
|
+
ai_summary: sec.ai_summary ?? null,
|
|
3535
|
+
when_to_use: sec.when_to_use ?? null
|
|
3536
|
+
}));
|
|
3537
|
+
return {
|
|
3538
|
+
catalog_summary: "BusinessKit native visual sections catalog (single source of truth from pagex).",
|
|
3539
|
+
returned_sections: list.length,
|
|
3540
|
+
total_available: sections.length,
|
|
3541
|
+
available_sections: list,
|
|
3542
|
+
usage: "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')."
|
|
3543
|
+
};
|
|
3544
|
+
}
|
|
3545
|
+
}
|
|
3546
|
+
];
|
|
3547
|
+
|
|
3548
|
+
// src/tools/domains.ts
|
|
3549
|
+
var domainTools = [
|
|
3550
|
+
{
|
|
3551
|
+
name: "domain_list_expiring",
|
|
3552
|
+
domain: "domains",
|
|
3553
|
+
description: "List tracked domains from my_domains that are expired or expiring within N days (defaults to 30 days). Returns days left, registrar, auto-renew status, renewal price, and notes.",
|
|
3554
|
+
inputSchema: {
|
|
3555
|
+
type: "object",
|
|
3556
|
+
properties: {
|
|
3557
|
+
days: { type: "number", description: "Lookahead horizon in days (e.g. 7, 30, 60). Defaults to 30." }
|
|
3558
|
+
}
|
|
3559
|
+
},
|
|
3560
|
+
handler: async (args, ctx) => {
|
|
3561
|
+
const profileId = ctx.profileId;
|
|
3562
|
+
const days = Number(args.days || 30);
|
|
3563
|
+
const horizonSecs = Math.floor(Date.now() / 1e3) + days * 86400;
|
|
3564
|
+
const rows = await query(
|
|
3565
|
+
`SELECT id, domain_name, registrar, expiry_date, auto_renew, renewal_price, agent_notes, status
|
|
3566
|
+
FROM my_domains
|
|
3567
|
+
WHERE profile_id = ? AND (expiry_date <= ? OR status = 'expired')
|
|
3568
|
+
ORDER BY expiry_date ASC LIMIT 50`,
|
|
3569
|
+
[profileId, horizonSecs]
|
|
3570
|
+
);
|
|
3571
|
+
return {
|
|
3572
|
+
lookahead_days: days,
|
|
3573
|
+
total: rows.length,
|
|
3574
|
+
domains: rows.map((r) => ({
|
|
3575
|
+
id: r.id,
|
|
3576
|
+
domain: r.domain_name,
|
|
3577
|
+
registrar: r.registrar,
|
|
3578
|
+
expiry_date: r.expiry_date,
|
|
3579
|
+
auto_renew: Boolean(r.auto_renew),
|
|
3580
|
+
renewal_price: r.renewal_price,
|
|
3581
|
+
agent_notes: r.agent_notes,
|
|
3582
|
+
status: r.status
|
|
3583
|
+
}))
|
|
3584
|
+
};
|
|
3585
|
+
}
|
|
3586
|
+
},
|
|
3587
|
+
{
|
|
3588
|
+
name: "domain_set_agent_notes",
|
|
3589
|
+
domain: "domains",
|
|
3590
|
+
description: "Record agent analysis, recommendation, or renewal reminders into agent_notes on a domain without overwriting user notes.",
|
|
3591
|
+
inputSchema: {
|
|
3592
|
+
type: "object",
|
|
3593
|
+
properties: {
|
|
3594
|
+
id: { type: "string", description: "Domain row ID or domain name (e.g. 'dom_xyz' or 'example.com')" },
|
|
3595
|
+
text: { type: "string", description: "Agent analysis or notes to save" }
|
|
3596
|
+
},
|
|
3597
|
+
required: ["id", "text"]
|
|
3598
|
+
},
|
|
3599
|
+
handler: async (args, ctx) => {
|
|
3600
|
+
const profileId = ctx.profileId;
|
|
3601
|
+
const ref = String(args.id).trim();
|
|
3602
|
+
const text = String(args.text).trim();
|
|
3603
|
+
const domains = await query(
|
|
3604
|
+
"SELECT id, domain_name FROM my_domains WHERE profile_id = ? AND (id = ? OR domain_name = ?) LIMIT 1",
|
|
3605
|
+
[profileId, ref, ref]
|
|
3606
|
+
);
|
|
3607
|
+
if (domains.length === 0) {
|
|
3608
|
+
throw new Error(`Domain not found with identifier: ${ref}`);
|
|
3609
|
+
}
|
|
3610
|
+
const domain = domains[0];
|
|
3611
|
+
await execute(
|
|
3612
|
+
"UPDATE my_domains SET agent_notes = ?, updated_at = strftime('%s','now') WHERE id = ? AND profile_id = ?",
|
|
3613
|
+
[text, domain.id, profileId]
|
|
3614
|
+
);
|
|
3615
|
+
return {
|
|
3616
|
+
id: domain.id,
|
|
3617
|
+
domain: domain.domain_name,
|
|
3618
|
+
agent_notes: text,
|
|
3619
|
+
status: "updated"
|
|
3620
|
+
};
|
|
3621
|
+
}
|
|
3622
|
+
}
|
|
3623
|
+
];
|
|
3624
|
+
|
|
3625
|
+
// src/tools/inbox.ts
|
|
3626
|
+
var inboxTools = [
|
|
3627
|
+
{
|
|
3628
|
+
name: "inbox_tool_set_category",
|
|
3629
|
+
domain: "inbox",
|
|
3630
|
+
description: "Classify an email thread into a named category bucket (e.g. 'billing', 'support', 'sales', 'spam').",
|
|
3631
|
+
inputSchema: {
|
|
3632
|
+
type: "object",
|
|
3633
|
+
properties: {
|
|
3634
|
+
thread_id: { type: "string", description: "Thread ID to classify (e.g. th_...)" },
|
|
3635
|
+
category: { type: "string", description: "Category label to apply (e.g. 'billing', 'support', 'sales')" }
|
|
3636
|
+
},
|
|
3637
|
+
required: ["thread_id", "category"]
|
|
3638
|
+
},
|
|
3639
|
+
handler: async (args, ctx) => {
|
|
3640
|
+
const profileId = ctx.profileId;
|
|
3641
|
+
const threadId = String(args.thread_id).trim();
|
|
3642
|
+
const category = String(args.category).trim();
|
|
3643
|
+
await execute(
|
|
3644
|
+
"UPDATE inbox_threads SET category = ?, updated_at = strftime('%s','now') WHERE id = ? AND profile_id = ?",
|
|
3645
|
+
[category, threadId, profileId]
|
|
3646
|
+
);
|
|
3647
|
+
return { thread_id: threadId, category, status: "updated" };
|
|
3648
|
+
}
|
|
3649
|
+
},
|
|
3650
|
+
{
|
|
3651
|
+
name: "inbox_tool_set_state",
|
|
3652
|
+
domain: "inbox",
|
|
3653
|
+
description: "Transition an email thread state: open \u2192 snoozed, closed, or archived.",
|
|
3654
|
+
inputSchema: {
|
|
3655
|
+
type: "object",
|
|
3656
|
+
properties: {
|
|
3657
|
+
thread_id: { type: "string", description: "Thread ID (e.g. th_...)" },
|
|
3658
|
+
state: { type: "string", enum: ["open", "snoozed", "closed", "archived"], description: "New thread state" }
|
|
3659
|
+
},
|
|
3660
|
+
required: ["thread_id", "state"]
|
|
3661
|
+
},
|
|
3662
|
+
handler: async (args, ctx) => {
|
|
3663
|
+
const profileId = ctx.profileId;
|
|
3664
|
+
const threadId = String(args.thread_id).trim();
|
|
3665
|
+
const state = String(args.state).trim();
|
|
3666
|
+
await execute(
|
|
3667
|
+
"UPDATE inbox_threads SET state = ?, updated_at = strftime('%s','now') WHERE id = ? AND profile_id = ?",
|
|
3668
|
+
[state, threadId, profileId]
|
|
3669
|
+
);
|
|
3670
|
+
return { thread_id: threadId, state, status: "updated" };
|
|
3671
|
+
}
|
|
3672
|
+
},
|
|
3673
|
+
{
|
|
3674
|
+
name: "inbox_tool_add_label",
|
|
3675
|
+
domain: "inbox",
|
|
3676
|
+
description: "Append a label tag to a thread's label list.",
|
|
3677
|
+
inputSchema: {
|
|
3678
|
+
type: "object",
|
|
3679
|
+
properties: {
|
|
3680
|
+
thread_id: { type: "string", description: "Thread ID" },
|
|
3681
|
+
label: { type: "string", description: "Label to add (e.g. 'vip', 'follow-up')" }
|
|
3682
|
+
},
|
|
3683
|
+
required: ["thread_id", "label"]
|
|
3684
|
+
},
|
|
3685
|
+
handler: async (args, ctx) => {
|
|
3686
|
+
const profileId = ctx.profileId;
|
|
3687
|
+
const threadId = String(args.thread_id).trim();
|
|
3688
|
+
const label = String(args.label).trim();
|
|
3689
|
+
const threads = await query(
|
|
3690
|
+
"SELECT labels FROM inbox_threads WHERE id = ? AND profile_id = ? LIMIT 1",
|
|
3691
|
+
[threadId, profileId]
|
|
3692
|
+
);
|
|
3693
|
+
let labels = [];
|
|
3694
|
+
if (threads.length > 0 && threads[0].labels) {
|
|
3695
|
+
try {
|
|
3696
|
+
labels = JSON.parse(threads[0].labels);
|
|
3697
|
+
} catch {
|
|
3698
|
+
}
|
|
3699
|
+
}
|
|
3700
|
+
if (!labels.includes(label)) {
|
|
3701
|
+
labels.push(label);
|
|
3702
|
+
}
|
|
3703
|
+
await execute(
|
|
3704
|
+
"UPDATE inbox_threads SET labels = ?, updated_at = strftime('%s','now') WHERE id = ? AND profile_id = ?",
|
|
3705
|
+
[JSON.stringify(labels), threadId, profileId]
|
|
3706
|
+
);
|
|
3707
|
+
return { thread_id: threadId, labels, status: "updated" };
|
|
3708
|
+
}
|
|
3709
|
+
},
|
|
3710
|
+
{
|
|
3711
|
+
name: "inbox_tool_link_entity",
|
|
3712
|
+
domain: "inbox",
|
|
3713
|
+
description: "Link an email thread to a CRM entity such as a contact, deal, or order.",
|
|
3714
|
+
inputSchema: {
|
|
3715
|
+
type: "object",
|
|
3716
|
+
properties: {
|
|
3717
|
+
thread_id: { type: "string", description: "Thread ID" },
|
|
3718
|
+
entity_type: { type: "string", description: "Entity type (e.g. 'contact', 'deal', 'order')" },
|
|
3719
|
+
entity_id: { type: "string", description: "Entity ID (e.g. ct_..., deal_...)" }
|
|
3720
|
+
},
|
|
3721
|
+
required: ["thread_id", "entity_type", "entity_id"]
|
|
3722
|
+
},
|
|
3723
|
+
handler: async (args, ctx) => {
|
|
3724
|
+
const profileId = ctx.profileId;
|
|
3725
|
+
const threadId = String(args.thread_id).trim();
|
|
3726
|
+
const entityType = String(args.entity_type).trim();
|
|
3727
|
+
const entityId = String(args.entity_id).trim();
|
|
3728
|
+
await execute(
|
|
3729
|
+
"UPDATE inbox_threads SET entity_type = ?, entity_id = ?, updated_at = strftime('%s','now') WHERE id = ? AND profile_id = ?",
|
|
3730
|
+
[entityType, entityId, threadId, profileId]
|
|
3731
|
+
);
|
|
3732
|
+
return { thread_id: threadId, entity_type: entityType, entity_id: entityId, status: "linked" };
|
|
3733
|
+
}
|
|
3734
|
+
},
|
|
3735
|
+
{
|
|
3736
|
+
name: "inbox_tool_draft_reply",
|
|
3737
|
+
domain: "inbox",
|
|
3738
|
+
description: "Draft an outbound email reply stored with author=agent.",
|
|
3739
|
+
inputSchema: {
|
|
3740
|
+
type: "object",
|
|
3741
|
+
properties: {
|
|
3742
|
+
thread_id: { type: "string", description: "Thread ID to reply to" },
|
|
3743
|
+
mailbox_id: { type: "string", description: "Mailbox ID to send from" },
|
|
3744
|
+
body: { type: "string", description: "Email body text" },
|
|
3745
|
+
subject: { type: "string", description: "Email subject line (default: 'Re:')" },
|
|
3746
|
+
to_addrs: { type: "string", description: "Comma-separated recipient addresses" }
|
|
3747
|
+
},
|
|
3748
|
+
required: ["thread_id", "mailbox_id", "body"]
|
|
3749
|
+
},
|
|
3750
|
+
handler: async (args, ctx) => {
|
|
3751
|
+
const profileId = ctx.profileId;
|
|
3752
|
+
const msgId = generateId("msg");
|
|
3753
|
+
const threadId = String(args.thread_id).trim();
|
|
3754
|
+
const mailboxId = String(args.mailbox_id).trim();
|
|
3755
|
+
const body = String(args.body);
|
|
3756
|
+
const subject = String(args.subject || "Re:");
|
|
3757
|
+
const toAddrs = String(args.to_addrs || "");
|
|
3758
|
+
await execute(
|
|
3759
|
+
`INSERT INTO inbox_messages
|
|
3760
|
+
(id, profile_id, thread_id, mailbox_id, direction, author, subject, body_html, to_addrs, state, created_at, updated_at)
|
|
3761
|
+
VALUES (?, ?, ?, ?, 'outbound', 'agent', ?, ?, ?, 'draft', strftime('%s','now'), strftime('%s','now'))`,
|
|
3762
|
+
[msgId, profileId, threadId, mailboxId, subject, body, toAddrs]
|
|
3763
|
+
);
|
|
3764
|
+
return {
|
|
3765
|
+
message_id: msgId,
|
|
3766
|
+
thread_id: threadId,
|
|
3767
|
+
status: "draft_created",
|
|
3768
|
+
author: "agent"
|
|
3769
|
+
};
|
|
3770
|
+
}
|
|
3771
|
+
},
|
|
3772
|
+
{
|
|
3773
|
+
name: "inbox_tool_schedule_send",
|
|
3774
|
+
domain: "inbox",
|
|
3775
|
+
description: "Schedule a draft message to be sent at a future Unix timestamp.",
|
|
3776
|
+
inputSchema: {
|
|
3777
|
+
type: "object",
|
|
3778
|
+
properties: {
|
|
3779
|
+
message_id: { type: "string", description: "Draft message ID" },
|
|
3780
|
+
send_after: { type: "integer", description: "Unix timestamp (seconds) when to send" }
|
|
3781
|
+
},
|
|
3782
|
+
required: ["message_id", "send_after"]
|
|
3783
|
+
},
|
|
3784
|
+
handler: async (args, ctx) => {
|
|
3785
|
+
const profileId = ctx.profileId;
|
|
3786
|
+
const msgId = String(args.message_id).trim();
|
|
3787
|
+
const sendAfter = Number(args.send_after);
|
|
3788
|
+
await execute(
|
|
3789
|
+
"UPDATE inbox_messages SET send_after = ?, state = 'scheduled', updated_at = strftime('%s','now') WHERE id = ? AND profile_id = ?",
|
|
3790
|
+
[sendAfter, msgId, profileId]
|
|
3791
|
+
);
|
|
3792
|
+
return { message_id: msgId, send_after: sendAfter, status: "scheduled" };
|
|
3793
|
+
}
|
|
3794
|
+
},
|
|
3795
|
+
{
|
|
3796
|
+
name: "inbox_tool_archive",
|
|
3797
|
+
domain: "inbox",
|
|
3798
|
+
description: "Archive an email thread \u2014 sets state=archived.",
|
|
3799
|
+
inputSchema: {
|
|
3800
|
+
type: "object",
|
|
3801
|
+
properties: {
|
|
3802
|
+
thread_id: { type: "string", description: "Thread ID to archive" }
|
|
3803
|
+
},
|
|
3804
|
+
required: ["thread_id"]
|
|
3805
|
+
},
|
|
3806
|
+
handler: async (args, ctx) => {
|
|
3807
|
+
const profileId = ctx.profileId;
|
|
3808
|
+
const threadId = String(args.thread_id).trim();
|
|
3809
|
+
await execute(
|
|
3810
|
+
"UPDATE inbox_threads SET state = 'archived', updated_at = strftime('%s','now') WHERE id = ? AND profile_id = ?",
|
|
3811
|
+
[threadId, profileId]
|
|
3812
|
+
);
|
|
3813
|
+
return { thread_id: threadId, status: "archived" };
|
|
3814
|
+
}
|
|
3815
|
+
},
|
|
3816
|
+
{
|
|
3817
|
+
name: "inbox_tool_extract_verification_code",
|
|
3818
|
+
domain: "inbox",
|
|
3819
|
+
description: "Extract an OTP, PIN, or verification code from the latest inbound message in a thread.",
|
|
3820
|
+
inputSchema: {
|
|
3821
|
+
type: "object",
|
|
3822
|
+
properties: {
|
|
3823
|
+
thread_id: { type: "string", description: "Thread ID to scan for verification codes" }
|
|
3824
|
+
},
|
|
3825
|
+
required: ["thread_id"]
|
|
3826
|
+
},
|
|
3827
|
+
handler: async (args, ctx) => {
|
|
3828
|
+
const profileId = ctx.profileId;
|
|
3829
|
+
const threadId = String(args.thread_id).trim();
|
|
3830
|
+
const msgs = await query(
|
|
3831
|
+
"SELECT body_html FROM inbox_messages WHERE thread_id = ? AND profile_id = ? AND direction = 'inbound' ORDER BY created_at DESC LIMIT 1",
|
|
3832
|
+
[threadId, profileId]
|
|
3833
|
+
);
|
|
3834
|
+
if (msgs.length === 0) {
|
|
3835
|
+
return { thread_id: threadId, code: null, message: "No inbound messages found in thread" };
|
|
3836
|
+
}
|
|
3837
|
+
const text = msgs[0].body_html || "";
|
|
3838
|
+
const match = text.match(/\b(?:\d{4}|\d{6}|\d{8})\b/);
|
|
3839
|
+
return {
|
|
3840
|
+
thread_id: threadId,
|
|
3841
|
+
code: match ? match[0] : null
|
|
3842
|
+
};
|
|
3843
|
+
}
|
|
3844
|
+
},
|
|
3845
|
+
{
|
|
3846
|
+
name: "inbox_tool_save_attachments",
|
|
3847
|
+
domain: "inbox",
|
|
3848
|
+
description: "Flag all attachments on a message to be auto-filed into the media library.",
|
|
3849
|
+
inputSchema: {
|
|
3850
|
+
type: "object",
|
|
3851
|
+
properties: {
|
|
3852
|
+
message_id: { type: "string", description: "Message ID whose attachments should be filed" }
|
|
3853
|
+
},
|
|
3854
|
+
required: ["message_id"]
|
|
3855
|
+
},
|
|
3856
|
+
handler: async (args, ctx) => {
|
|
3857
|
+
const profileId = ctx.profileId;
|
|
3858
|
+
const messageId = String(args.message_id).trim();
|
|
3859
|
+
await execute(
|
|
3860
|
+
"UPDATE inbox_attachments SET storage = 'media' WHERE message_id = ? AND profile_id = ?",
|
|
3861
|
+
[messageId, profileId]
|
|
3862
|
+
);
|
|
3863
|
+
return { message_id: messageId, status: "attachments_filed" };
|
|
3864
|
+
}
|
|
3865
|
+
}
|
|
3866
|
+
];
|
|
3867
|
+
|
|
3868
|
+
// src/tools/system.ts
|
|
3869
|
+
var systemTools = [
|
|
3870
|
+
{
|
|
3871
|
+
name: "system_get_capabilities",
|
|
3872
|
+
domain: "system",
|
|
3873
|
+
description: "Discover all available BusinessKit platform capabilities, domains, tool counts, and features. Call when the user asks what abilities, tools, or domains exist.",
|
|
3874
|
+
inputSchema: {
|
|
3875
|
+
type: "object",
|
|
3876
|
+
properties: {
|
|
3877
|
+
domain: { type: "string", description: "Optional domain filter (e.g. 'shop', 'crm', 'content', 'pages', 'domains')" }
|
|
3878
|
+
}
|
|
3879
|
+
},
|
|
3880
|
+
handler: async (args, _ctx) => {
|
|
3881
|
+
const filter = args.domain?.toLowerCase()?.trim();
|
|
3882
|
+
const domains = [
|
|
3883
|
+
{ name: "shop", description: "Shop, inventory restock, purchase invoices, billing, and stock ledger" },
|
|
3884
|
+
{ name: "crm", description: "Customer relationship management, leads, contacts, and outreach" },
|
|
3885
|
+
{
|
|
3886
|
+
name: "content",
|
|
3887
|
+
description: "Multi-hub CMS content publishing (blog, docs, guides, notes, newsletter) with rich HTML"
|
|
3888
|
+
},
|
|
3889
|
+
{ name: "pages", description: "Website pages, landing pages, site content, and publishing" },
|
|
3890
|
+
{ name: "domains", description: "Domain portfolio management, RDAP status, expiry tracking, and renewal reminders" },
|
|
3891
|
+
{ name: "inbox", description: "Unified inbox \u2014 thread triage, labelling, reply drafting, scheduling, and archiving" },
|
|
3892
|
+
{ name: "system", description: "Platform introspection, profile switching, and agent system utilities" }
|
|
3893
|
+
];
|
|
3894
|
+
const matchingDomains = filter && filter !== "all" ? domains.filter((d) => d.name === filter) : domains;
|
|
3895
|
+
return {
|
|
3896
|
+
platform: "BusinessKit",
|
|
3897
|
+
architecture: "Model Context Protocol (MCP) stdio JSON-RPC server",
|
|
3898
|
+
active_domains: matchingDomains,
|
|
3899
|
+
database_connected: isDbConfigured(),
|
|
3900
|
+
total_tools: 36
|
|
3901
|
+
};
|
|
3902
|
+
}
|
|
3903
|
+
},
|
|
3904
|
+
{
|
|
3905
|
+
name: "profile_list",
|
|
3906
|
+
domain: "system",
|
|
3907
|
+
description: "List all business/organization profiles available in the active database and check which one is active.",
|
|
3908
|
+
inputSchema: {
|
|
3909
|
+
type: "object",
|
|
3910
|
+
properties: {}
|
|
3911
|
+
},
|
|
3912
|
+
handler: async (_args, ctx) => {
|
|
3913
|
+
let profiles = [];
|
|
3914
|
+
if (isDbConfigured()) {
|
|
3915
|
+
try {
|
|
3916
|
+
profiles = await query("SELECT id, title, slug FROM profiles LIMIT 50");
|
|
3917
|
+
} catch (err) {
|
|
3918
|
+
console.error("[Profile] Profiles query error:", err);
|
|
3919
|
+
}
|
|
3920
|
+
}
|
|
3921
|
+
return {
|
|
3922
|
+
active_profile: ctx.profileId,
|
|
3923
|
+
available_profiles: profiles.length > 0 ? profiles : [{ id: ctx.profileId, title: "Default Business" }],
|
|
3924
|
+
total: profiles.length > 0 ? profiles.length : 1
|
|
3925
|
+
};
|
|
3926
|
+
}
|
|
3927
|
+
},
|
|
3928
|
+
{
|
|
3929
|
+
name: "profile_switch",
|
|
3930
|
+
domain: "system",
|
|
3931
|
+
description: "Switch the active business/organization profile for this MCP session.",
|
|
3932
|
+
inputSchema: {
|
|
3933
|
+
type: "object",
|
|
3934
|
+
properties: {
|
|
3935
|
+
profile_id: { type: "string", description: "The profile ID to switch to" }
|
|
3936
|
+
},
|
|
3937
|
+
required: ["profile_id"]
|
|
3938
|
+
},
|
|
3939
|
+
handler: async (args, _ctx) => {
|
|
3940
|
+
const newProfileId = String(args.profile_id).trim();
|
|
3941
|
+
if (!newProfileId) {
|
|
3942
|
+
throw new Error("profile_id is required");
|
|
3943
|
+
}
|
|
3944
|
+
setActiveProfileId(newProfileId);
|
|
3945
|
+
return {
|
|
3946
|
+
success: true,
|
|
3947
|
+
active_profile: newProfileId,
|
|
3948
|
+
status: "switched"
|
|
3949
|
+
};
|
|
3950
|
+
}
|
|
3951
|
+
}
|
|
3952
|
+
];
|
|
3953
|
+
|
|
3954
|
+
// src/tools/index.ts
|
|
3955
|
+
var allTools = [
|
|
3956
|
+
...shopTools,
|
|
3957
|
+
...crmTools,
|
|
3958
|
+
...contentTools,
|
|
3959
|
+
...pagesTools,
|
|
3960
|
+
...domainTools,
|
|
3961
|
+
...inboxTools,
|
|
3962
|
+
...systemTools
|
|
3963
|
+
];
|
|
3964
|
+
var toolMap = /* @__PURE__ */ new Map();
|
|
3965
|
+
for (const tool of allTools) {
|
|
3966
|
+
toolMap.set(tool.name, tool);
|
|
3967
|
+
}
|
|
3968
|
+
var WRITE_TOOLS = /* @__PURE__ */ new Set([
|
|
3969
|
+
"inventory_receive_purchase_invoice",
|
|
3970
|
+
"product_update_pricing",
|
|
3971
|
+
"inventory_add_stock",
|
|
3972
|
+
"invoice_create",
|
|
3973
|
+
"invoice_send",
|
|
3974
|
+
"shop_create_new_bill",
|
|
3975
|
+
"contact_create",
|
|
3976
|
+
"contact_update",
|
|
3977
|
+
"crm_log_activity",
|
|
3978
|
+
"crm_add_note",
|
|
3979
|
+
"crm_create_task",
|
|
3980
|
+
"crm_add_tag",
|
|
3981
|
+
"crm_create_contact_from_mail",
|
|
3982
|
+
"crm_propose_deal",
|
|
3983
|
+
"crm_update_deal_stage",
|
|
3984
|
+
"crm_merge_contacts",
|
|
3985
|
+
"crm_create_proposal_draft",
|
|
3986
|
+
"crm_draft_followup",
|
|
3987
|
+
"crm_draft_payment_chase",
|
|
3988
|
+
"crm_set_stages",
|
|
3989
|
+
"crm_create_group",
|
|
3990
|
+
"crm_add_to_group",
|
|
3991
|
+
"crm_create_template",
|
|
3992
|
+
"blog_post_create",
|
|
3993
|
+
"content_update",
|
|
3994
|
+
"page_create",
|
|
3995
|
+
"page_update",
|
|
3996
|
+
"page_publish",
|
|
3997
|
+
"component_create",
|
|
3998
|
+
"domain_set_agent_notes",
|
|
3999
|
+
"inbox_tool_set_category",
|
|
4000
|
+
"inbox_tool_set_state",
|
|
4001
|
+
"inbox_tool_add_label",
|
|
4002
|
+
"inbox_tool_link_entity",
|
|
4003
|
+
"inbox_tool_draft_reply",
|
|
4004
|
+
"inbox_tool_schedule_send",
|
|
4005
|
+
"inbox_tool_archive",
|
|
4006
|
+
"inbox_tool_save_attachments",
|
|
4007
|
+
"profile_switch"
|
|
4008
|
+
]);
|
|
4009
|
+
function getAllToolDefinitions() {
|
|
4010
|
+
return allTools.map((t) => ({
|
|
4011
|
+
name: t.name,
|
|
4012
|
+
description: t.description,
|
|
4013
|
+
inputSchema: t.inputSchema
|
|
4014
|
+
}));
|
|
4015
|
+
}
|
|
4016
|
+
async function dispatchTool(name, args) {
|
|
4017
|
+
const tool = toolMap.get(name);
|
|
4018
|
+
if (!tool) {
|
|
4019
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
4020
|
+
}
|
|
4021
|
+
const offlineTools = ["system_get_capabilities", "page_get_section_schema"];
|
|
4022
|
+
if (offlineTools.includes(name)) {
|
|
4023
|
+
return await tool.handler(args, { profileId: "system" });
|
|
4024
|
+
}
|
|
4025
|
+
if (!isDbConfigured()) {
|
|
4026
|
+
throw new Error(
|
|
4027
|
+
`Database connection not configured. To execute '${name}', please set TURSO_DATABASE_URL and TURSO_AUTH_TOKEN in your .env file or environment variables.`
|
|
4028
|
+
);
|
|
4029
|
+
}
|
|
4030
|
+
if (WRITE_TOOLS.has(name) && isDbReadOnly()) {
|
|
4031
|
+
throw new Error(
|
|
4032
|
+
`Operation rejected: Database is connected in read-only mode (read-only token). Write tool '${name}' is disabled.`
|
|
4033
|
+
);
|
|
4034
|
+
}
|
|
4035
|
+
const profileId = await getActiveProfileId();
|
|
4036
|
+
const ctx = {
|
|
4037
|
+
profileId
|
|
4038
|
+
};
|
|
4039
|
+
return await tool.handler(args, ctx);
|
|
4040
|
+
}
|
|
4041
|
+
|
|
4042
|
+
// src/server.ts
|
|
4043
|
+
async function startServer() {
|
|
4044
|
+
const server = new Server(
|
|
4045
|
+
{
|
|
4046
|
+
name: "io.github.businesskitai/agent",
|
|
4047
|
+
version: "1.0.7"
|
|
4048
|
+
},
|
|
4049
|
+
{
|
|
4050
|
+
capabilities: {
|
|
4051
|
+
tools: {}
|
|
4052
|
+
}
|
|
4053
|
+
}
|
|
4054
|
+
);
|
|
4055
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
4056
|
+
return {
|
|
4057
|
+
tools: getAllToolDefinitions()
|
|
4058
|
+
};
|
|
4059
|
+
});
|
|
4060
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
4061
|
+
const { name, arguments: args } = request.params;
|
|
4062
|
+
try {
|
|
4063
|
+
const result = await dispatchTool(name, args || {});
|
|
4064
|
+
return {
|
|
4065
|
+
content: [
|
|
4066
|
+
{
|
|
4067
|
+
type: "text",
|
|
4068
|
+
text: typeof result === "string" ? result : JSON.stringify(result, null, 2)
|
|
4069
|
+
}
|
|
4070
|
+
],
|
|
4071
|
+
isError: false
|
|
4072
|
+
};
|
|
4073
|
+
} catch (err) {
|
|
4074
|
+
console.error(`[MCP Error] tool '${name}' failed:`, err);
|
|
4075
|
+
return {
|
|
4076
|
+
content: [
|
|
4077
|
+
{
|
|
4078
|
+
type: "text",
|
|
4079
|
+
text: err?.message || String(err)
|
|
4080
|
+
}
|
|
4081
|
+
],
|
|
4082
|
+
isError: true
|
|
4083
|
+
};
|
|
4084
|
+
}
|
|
4085
|
+
});
|
|
4086
|
+
const transport = new StdioServerTransport();
|
|
4087
|
+
await server.connect(transport);
|
|
4088
|
+
console.error("[BusinessKit MCP] Server listening on stdio transport.");
|
|
4089
|
+
console.error(`[BusinessKit MCP] Database connection status: ${isDbConfigured() ? "CONFIGURED" : "NOT CONFIGURED (set TURSO_DATABASE_URL and TURSO_AUTH_TOKEN in .env)"}`);
|
|
4090
|
+
}
|
|
4091
|
+
if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith("server.js") || process.argv[1]?.endsWith("server.ts")) {
|
|
4092
|
+
startServer().catch((err) => {
|
|
4093
|
+
console.error("[BusinessKit MCP] Fatal startup error:", err);
|
|
4094
|
+
process.exit(1);
|
|
4095
|
+
});
|
|
4096
|
+
}
|
|
4097
|
+
export {
|
|
4098
|
+
startServer
|
|
4099
|
+
};
|