@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/src/tools/crm.ts
ADDED
|
@@ -0,0 +1,1416 @@
|
|
|
1
|
+
// src/tools/crm.ts
|
|
2
|
+
// WHAT: CRM MCP Tools for BusinessKit (1:1 parity with src-tauri/src/commands/agents/tools/crm.ts).
|
|
3
|
+
// HOW: Executes parameterized LibSQL queries scoped by ctx.profileId against UserDB.
|
|
4
|
+
// Approval-gated writes queue structured proposals in agent_tasks (status='awaiting_approval').
|
|
5
|
+
// Draft tools save outbound drafts (author='agent', send_status='draft') in inbox_messages.
|
|
6
|
+
|
|
7
|
+
import { execute, generateId, query } from '../db.js';
|
|
8
|
+
import type { ToolDefinition, ToolContext } from './types.js';
|
|
9
|
+
|
|
10
|
+
function nowTs(): number {
|
|
11
|
+
return Math.floor(Date.now() / 1000);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function parseTsOrDate(val: any): number | null {
|
|
15
|
+
if (val === null || val === undefined) return null;
|
|
16
|
+
if (typeof val === 'number' && Number.isFinite(val)) {
|
|
17
|
+
return val > 20_000_000_000 ? Math.floor(val / 1000) : Math.floor(val);
|
|
18
|
+
}
|
|
19
|
+
const s = String(val).trim();
|
|
20
|
+
if (!s) return null;
|
|
21
|
+
if (/^\d+$/.test(s)) {
|
|
22
|
+
const n = Number(s);
|
|
23
|
+
return n > 20_000_000_000 ? Math.floor(n / 1000) : n;
|
|
24
|
+
}
|
|
25
|
+
const parsed = Date.parse(s);
|
|
26
|
+
return Number.isNaN(parsed) ? null : Math.floor(parsed / 1000);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function resolveContactId(
|
|
30
|
+
profileId: string,
|
|
31
|
+
ref: string
|
|
32
|
+
): Promise<{ id: string; name: string; email: string | null; company: string | null }> {
|
|
33
|
+
const r = ref.trim();
|
|
34
|
+
if (!r) throw new Error('Missing contact identifier');
|
|
35
|
+
|
|
36
|
+
const exact = await query<any>(
|
|
37
|
+
`SELECT id, first_name, last_name, email, company FROM crm_contacts
|
|
38
|
+
WHERE profile_id = ? AND archived = 0 AND (id = ? OR LOWER(email) = LOWER(?)) LIMIT 1`,
|
|
39
|
+
[profileId, r, r]
|
|
40
|
+
);
|
|
41
|
+
if (exact.length > 0) {
|
|
42
|
+
const row = exact[0];
|
|
43
|
+
return {
|
|
44
|
+
id: row.id,
|
|
45
|
+
name: `${row.first_name || ''} ${row.last_name || ''}`.trim(),
|
|
46
|
+
email: row.email ?? null,
|
|
47
|
+
company: row.company ?? null,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const like = `%${r}%`;
|
|
52
|
+
const fuzzy = await query<any>(
|
|
53
|
+
`SELECT id, first_name, last_name, email, company FROM crm_contacts
|
|
54
|
+
WHERE profile_id = ? AND archived = 0
|
|
55
|
+
AND (LOWER(first_name || ' ' || COALESCE(last_name,'')) LIKE LOWER(?) OR LOWER(first_name) LIKE LOWER(?))
|
|
56
|
+
LIMIT 2`,
|
|
57
|
+
[profileId, like, like]
|
|
58
|
+
);
|
|
59
|
+
if (fuzzy.length === 1) {
|
|
60
|
+
const row = fuzzy[0];
|
|
61
|
+
return {
|
|
62
|
+
id: row.id,
|
|
63
|
+
name: `${row.first_name || ''} ${row.last_name || ''}`.trim(),
|
|
64
|
+
email: row.email ?? null,
|
|
65
|
+
company: row.company ?? null,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
if (fuzzy.length > 1) {
|
|
69
|
+
throw new Error(`Multiple contacts matched '${r}'; pass exact contact_id or email`);
|
|
70
|
+
}
|
|
71
|
+
throw new Error(`Contact not found: ${r}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function getCrmConfigVal(profileId: string, key: string): Promise<string | null> {
|
|
75
|
+
const rows = await query<{ config_val: string }>(
|
|
76
|
+
'SELECT config_val FROM crm_config WHERE profile_id = ? AND config_key = ? LIMIT 1',
|
|
77
|
+
[profileId, key]
|
|
78
|
+
);
|
|
79
|
+
return rows[0]?.config_val ?? null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function queueApprovalItem(
|
|
83
|
+
profileId: string,
|
|
84
|
+
tool: string,
|
|
85
|
+
title: string,
|
|
86
|
+
args: Record<string, any>,
|
|
87
|
+
reason: string,
|
|
88
|
+
sources: string[],
|
|
89
|
+
sourceId: string | null,
|
|
90
|
+
idemKey: string | null
|
|
91
|
+
) {
|
|
92
|
+
if (idemKey) {
|
|
93
|
+
const cooldownRaw = await getCrmConfigVal(profileId, 'crm.rejected_cooldowns');
|
|
94
|
+
if (cooldownRaw) {
|
|
95
|
+
try {
|
|
96
|
+
const map = JSON.parse(cooldownRaw);
|
|
97
|
+
if (typeof map[idemKey] === 'number' && map[idemKey] > nowTs()) {
|
|
98
|
+
return {
|
|
99
|
+
status: 'skipped_cooldown',
|
|
100
|
+
action: tool,
|
|
101
|
+
title,
|
|
102
|
+
reason: 'Previously rejected within cooldown window',
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
} catch {
|
|
106
|
+
// ignore invalid JSON
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const existing = await query<{ id: string }>(
|
|
111
|
+
"SELECT id FROM agent_tasks WHERE profile_id = ? AND idempotency_key = ? AND status = 'awaiting_approval' LIMIT 1",
|
|
112
|
+
[profileId, idemKey]
|
|
113
|
+
);
|
|
114
|
+
if (existing.length > 0) {
|
|
115
|
+
return {
|
|
116
|
+
approval_id: existing[0].id,
|
|
117
|
+
status: 'awaiting_approval',
|
|
118
|
+
action: tool,
|
|
119
|
+
title,
|
|
120
|
+
deduped: true,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const taskId = generateId('apr');
|
|
126
|
+
const now = nowTs();
|
|
127
|
+
const payload = JSON.stringify({ tool, args, reason, sources, cooldown_key: idemKey });
|
|
128
|
+
|
|
129
|
+
await execute(
|
|
130
|
+
`INSERT OR IGNORE INTO agent_tasks
|
|
131
|
+
(id, agent_id, profile_id, title, input, status, task_type, source_id, idempotency_key, created_at, updated_at)
|
|
132
|
+
VALUES (?, 'crm', ?, ?, ?, 'awaiting_approval', 'crm_approval', ?, ?, ?, ?)`,
|
|
133
|
+
[taskId, profileId, title, payload, sourceId, idemKey, now, now]
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
return {
|
|
137
|
+
approval_id: taskId,
|
|
138
|
+
status: 'awaiting_approval',
|
|
139
|
+
action: tool,
|
|
140
|
+
title,
|
|
141
|
+
reason,
|
|
142
|
+
sources,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function loadBrandVoice(profileId: string): Promise<string | null> {
|
|
147
|
+
let voice: string | null = null;
|
|
148
|
+
try {
|
|
149
|
+
const bf = await query<any>(
|
|
150
|
+
'SELECT brand_voice, about_me, working_style FROM brand_foundation WHERE profile_id = ? LIMIT 1',
|
|
151
|
+
[profileId]
|
|
152
|
+
);
|
|
153
|
+
if (bf.length > 0) {
|
|
154
|
+
const parts = [bf[0].brand_voice, bf[0].about_me, bf[0].working_style]
|
|
155
|
+
.map((x) => (x ? String(x).trim() : ''))
|
|
156
|
+
.filter(Boolean);
|
|
157
|
+
if (parts.length > 0) voice = parts.join(' | ');
|
|
158
|
+
}
|
|
159
|
+
} catch {
|
|
160
|
+
// optional table
|
|
161
|
+
}
|
|
162
|
+
return voice;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function saveInboxDraftForContact(
|
|
166
|
+
profileId: string,
|
|
167
|
+
contactId: string,
|
|
168
|
+
toEmail: string,
|
|
169
|
+
threadIdOpt: string | undefined,
|
|
170
|
+
mailboxIdOpt: string | undefined,
|
|
171
|
+
subject: string,
|
|
172
|
+
body: string
|
|
173
|
+
) {
|
|
174
|
+
if (!toEmail.trim()) {
|
|
175
|
+
throw new Error('Contact has no email address — cannot create email draft');
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
let mailboxId = '';
|
|
179
|
+
let fromAddr = '';
|
|
180
|
+
if (mailboxIdOpt) {
|
|
181
|
+
const mb = await query<any>(
|
|
182
|
+
'SELECT id, address FROM inbox_mailboxes WHERE id = ? AND profile_id = ? LIMIT 1',
|
|
183
|
+
[mailboxIdOpt, profileId]
|
|
184
|
+
);
|
|
185
|
+
if (mb.length === 0) throw new Error(`Mailbox not found: ${mailboxIdOpt}`);
|
|
186
|
+
mailboxId = mb[0].id;
|
|
187
|
+
fromAddr = mb[0].address || '';
|
|
188
|
+
} else {
|
|
189
|
+
const mb = await query<any>(
|
|
190
|
+
`SELECT id, address FROM inbox_mailboxes WHERE profile_id = ? AND is_active = 1
|
|
191
|
+
ORDER BY CASE WHEN purpose = 'general' THEN 0 ELSE 1 END, created_at ASC LIMIT 1`,
|
|
192
|
+
[profileId]
|
|
193
|
+
);
|
|
194
|
+
if (mb.length === 0) throw new Error('No active mailbox configured in Inbox — connect a mailbox first');
|
|
195
|
+
mailboxId = mb[0].id;
|
|
196
|
+
fromAddr = mb[0].address || '';
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const checkHeld = async (tid: string) => {
|
|
200
|
+
const held = await query<{ cnt: number }>(
|
|
201
|
+
`SELECT COUNT(*) as cnt FROM inbox_messages
|
|
202
|
+
WHERE thread_id = ? AND profile_id = ? AND direction = 'in'
|
|
203
|
+
AND screen_status IN ('suspicious', 'blocked')`,
|
|
204
|
+
[tid, profileId]
|
|
205
|
+
);
|
|
206
|
+
if (Number(held[0]?.cnt || 0) > 0) {
|
|
207
|
+
throw new Error('Refusing to draft on thread with suspicious/blocked inbound messages');
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
let threadId = threadIdOpt || '';
|
|
212
|
+
if (threadId) {
|
|
213
|
+
await checkHeld(threadId);
|
|
214
|
+
} else {
|
|
215
|
+
const existingThreads = await query<{ id: string }>(
|
|
216
|
+
`SELECT id FROM inbox_threads
|
|
217
|
+
WHERE profile_id = ? AND linked_entity_type = 'contact' AND linked_entity_id = ?
|
|
218
|
+
ORDER BY last_message_at DESC LIMIT 1`,
|
|
219
|
+
[profileId, contactId]
|
|
220
|
+
);
|
|
221
|
+
if (existingThreads.length > 0) {
|
|
222
|
+
threadId = existingThreads[0].id;
|
|
223
|
+
await checkHeld(threadId);
|
|
224
|
+
} else {
|
|
225
|
+
threadId = generateId('th');
|
|
226
|
+
const now = nowTs();
|
|
227
|
+
await execute(
|
|
228
|
+
`INSERT INTO inbox_threads
|
|
229
|
+
(id, profile_id, mailbox_id, thread_key, subject, last_message_at,
|
|
230
|
+
message_count, is_unread, state, linked_entity_type, linked_entity_id, created_at, updated_at)
|
|
231
|
+
VALUES (?, ?, ?, ?, ?, ?, 1, 0, 'awaiting', 'contact', ?, ?, ?)`,
|
|
232
|
+
[threadId, profileId, mailboxId, `crm-draft-${threadId}`, subject, now, contactId, now, now]
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const msgId = generateId('msg');
|
|
238
|
+
const now = nowTs();
|
|
239
|
+
const msgHeader = `<${msgId}@businesskit.app>`;
|
|
240
|
+
const toAddrs = JSON.stringify([toEmail.trim()]);
|
|
241
|
+
const snippet = body.slice(0, 120);
|
|
242
|
+
|
|
243
|
+
await execute(
|
|
244
|
+
`INSERT INTO inbox_messages
|
|
245
|
+
(id, profile_id, thread_id, mailbox_id, source_mailbox_id,
|
|
246
|
+
provider_message_id, message_id_header, direction, author, from_addr,
|
|
247
|
+
to_addrs, subject, snippet, body_text, body_status, send_status, screen_status,
|
|
248
|
+
is_read, has_attachments, received_at, created_at)
|
|
249
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 'out', 'agent', ?, ?, ?, ?, ?, 'ready', 'draft', 'clean', 1, 0, ?, ?)`,
|
|
250
|
+
[msgId, profileId, threadId, mailboxId, mailboxId, msgId, msgHeader, fromAddr, toAddrs, subject, snippet, body, now, now]
|
|
251
|
+
);
|
|
252
|
+
|
|
253
|
+
return {
|
|
254
|
+
message_id: msgId,
|
|
255
|
+
thread_id: threadId,
|
|
256
|
+
mailbox_id: mailboxId,
|
|
257
|
+
to: toEmail.trim(),
|
|
258
|
+
subject,
|
|
259
|
+
send_status: 'draft',
|
|
260
|
+
author: 'agent',
|
|
261
|
+
status: 'draft_saved',
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export const crmTools: ToolDefinition[] = [
|
|
266
|
+
{
|
|
267
|
+
name: 'contact_create',
|
|
268
|
+
domain: 'crm',
|
|
269
|
+
description: 'Create a new contact or lead in the CRM.',
|
|
270
|
+
inputSchema: {
|
|
271
|
+
type: 'object',
|
|
272
|
+
properties: {
|
|
273
|
+
name: { type: 'string', description: 'Full name of the contact' },
|
|
274
|
+
email: { type: 'string', description: 'Email address' },
|
|
275
|
+
phone: { type: 'string', description: 'Phone number' },
|
|
276
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
277
|
+
},
|
|
278
|
+
required: ['name'],
|
|
279
|
+
},
|
|
280
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
281
|
+
const profileId = ctx.profileId;
|
|
282
|
+
const name = String(args.name || '').trim();
|
|
283
|
+
const email = String(args.email || '').trim().toLowerCase() || null;
|
|
284
|
+
const phone = String(args.phone || '').trim() || null;
|
|
285
|
+
const company = String(args.company || '').trim() || null;
|
|
286
|
+
const jobTitle = String(args.job_title || '').trim() || null;
|
|
287
|
+
const notes = String(args.notes || '').trim() || null;
|
|
288
|
+
const status = String(args.status || 'lead');
|
|
289
|
+
const source = String(args.source || 'manual');
|
|
290
|
+
const tags = JSON.stringify(args.tags || []);
|
|
291
|
+
|
|
292
|
+
if (email) {
|
|
293
|
+
const existing = await query<{ id: string }>(
|
|
294
|
+
'SELECT id FROM crm_contacts WHERE profile_id = ? AND LOWER(email) = LOWER(?) LIMIT 1',
|
|
295
|
+
[profileId, email]
|
|
296
|
+
);
|
|
297
|
+
if (existing.length > 0) {
|
|
298
|
+
return { contact_id: existing[0].id, name, email, status: 'already_exists' };
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const parts = name.split(/\s+/);
|
|
303
|
+
const firstName = parts[0] || name;
|
|
304
|
+
const lastName = parts.length > 1 ? parts.slice(1).join(' ') : null;
|
|
305
|
+
const contactId = generateId('ct');
|
|
306
|
+
|
|
307
|
+
await execute(
|
|
308
|
+
`INSERT INTO crm_contacts
|
|
309
|
+
(id, profile_id, first_name, last_name, email, phone, company, job_title, notes, tags,
|
|
310
|
+
status, outreach_status, source, created_at, updated_at)
|
|
311
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'new', ?, strftime('%s','now'), strftime('%s','now'))`,
|
|
312
|
+
[contactId, profileId, firstName, lastName, email, phone, company, jobTitle, notes, tags, status, source]
|
|
313
|
+
);
|
|
314
|
+
|
|
315
|
+
return { contact_id: contactId, name, email, phone, status: 'created' };
|
|
316
|
+
},
|
|
317
|
+
},
|
|
318
|
+
{
|
|
319
|
+
name: 'contact_update',
|
|
320
|
+
domain: 'crm',
|
|
321
|
+
description: 'Update fields on an existing CRM contact.',
|
|
322
|
+
inputSchema: {
|
|
323
|
+
type: 'object',
|
|
324
|
+
properties: {
|
|
325
|
+
contact_id: { type: 'string', description: 'Contact ID or email address' },
|
|
326
|
+
fields: {
|
|
327
|
+
type: 'object',
|
|
328
|
+
description: 'Partial fields to update, e.g. { "email": "...", "phone": "...", "company": "..." }',
|
|
329
|
+
},
|
|
330
|
+
},
|
|
331
|
+
required: ['contact_id', 'fields'],
|
|
332
|
+
},
|
|
333
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
334
|
+
const profileId = ctx.profileId;
|
|
335
|
+
const ref = String(args.contact_id).trim();
|
|
336
|
+
const fields = args.fields || {};
|
|
337
|
+
|
|
338
|
+
const contacts = await query<{ id: string }>(
|
|
339
|
+
'SELECT id FROM crm_contacts WHERE profile_id = ? AND (id = ? OR LOWER(email) = LOWER(?)) LIMIT 1',
|
|
340
|
+
[profileId, ref, ref]
|
|
341
|
+
);
|
|
342
|
+
if (contacts.length === 0) throw new Error(`Contact not found with identifier: ${ref}`);
|
|
343
|
+
|
|
344
|
+
const contactId = contacts[0].id;
|
|
345
|
+
const allowedTextCols = new Set([
|
|
346
|
+
'first_name', 'last_name', 'email', 'phone', 'company', 'job_title',
|
|
347
|
+
'website', 'bio', 'status', 'outreach_status', 'notes', 'agent_notes',
|
|
348
|
+
'tags', 'next_action', 'icp_match', 'urgency', 'buying_intent',
|
|
349
|
+
]);
|
|
350
|
+
const allowedNumCols = new Set(['lead_score', 'next_follow_up_at']);
|
|
351
|
+
|
|
352
|
+
const updates: string[] = [];
|
|
353
|
+
const params: any[] = [];
|
|
354
|
+
for (const [k, v] of Object.entries(fields)) {
|
|
355
|
+
if (v === null || v === undefined) continue;
|
|
356
|
+
if (allowedTextCols.has(k)) {
|
|
357
|
+
updates.push(`${k} = ?`);
|
|
358
|
+
params.push(typeof v === 'object' ? JSON.stringify(v) : String(v));
|
|
359
|
+
} else if (allowedNumCols.has(k) && !Number.isNaN(Number(v))) {
|
|
360
|
+
updates.push(`${k} = ?`);
|
|
361
|
+
params.push(Number(v));
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
if (updates.length === 0) return { contact_id: contactId, status: 'no_changes' };
|
|
366
|
+
updates.push("updated_at = strftime('%s','now')");
|
|
367
|
+
params.push(contactId, profileId);
|
|
368
|
+
|
|
369
|
+
await execute(`UPDATE crm_contacts SET ${updates.join(', ')} WHERE id = ? AND profile_id = ?`, params);
|
|
370
|
+
return { contact_id: contactId, status: 'updated', updated_fields: Object.keys(fields) };
|
|
371
|
+
},
|
|
372
|
+
},
|
|
373
|
+
{
|
|
374
|
+
name: 'crm_search_contacts',
|
|
375
|
+
domain: 'crm',
|
|
376
|
+
description: 'Search CRM contacts by name, email, company, tag, status, or last-contacted timestamp range.',
|
|
377
|
+
inputSchema: {
|
|
378
|
+
type: 'object',
|
|
379
|
+
properties: {
|
|
380
|
+
query: { type: 'string', description: 'Free-text search across name, email, or company' },
|
|
381
|
+
email: { type: 'string', description: 'Filter by email substring' },
|
|
382
|
+
company: { type: 'string', description: 'Filter by company substring' },
|
|
383
|
+
tag: { type: 'string', description: 'Filter by tag name' },
|
|
384
|
+
status: { type: 'string', enum: ['lead', 'prospect', 'customer', 'churned'], description: 'Lifecycle status filter' },
|
|
385
|
+
last_contacted_before: { type: 'string', description: 'Unix timestamp or YYYY-MM-DD' },
|
|
386
|
+
last_contacted_after: { type: 'string', description: 'Unix timestamp or YYYY-MM-DD' },
|
|
387
|
+
limit: { type: 'number', description: 'Max contacts to return (default 20, max 50)' },
|
|
388
|
+
},
|
|
389
|
+
},
|
|
390
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
391
|
+
const conds = ['profile_id = ?', 'archived = 0'];
|
|
392
|
+
const params: any[] = [ctx.profileId];
|
|
393
|
+
if (args.query) {
|
|
394
|
+
conds.push("(LOWER(first_name || ' ' || COALESCE(last_name,'')) LIKE LOWER(?) OR LOWER(COALESCE(email,'')) LIKE LOWER(?) OR LOWER(COALESCE(company,'')) LIKE LOWER(?))");
|
|
395
|
+
const q = `%${String(args.query).trim()}%`;
|
|
396
|
+
params.push(q, q, q);
|
|
397
|
+
}
|
|
398
|
+
if (args.email) {
|
|
399
|
+
conds.push("LOWER(COALESCE(email,'')) LIKE LOWER(?)");
|
|
400
|
+
params.push(`%${String(args.email).trim()}%`);
|
|
401
|
+
}
|
|
402
|
+
if (args.company) {
|
|
403
|
+
conds.push("LOWER(COALESCE(company,'')) LIKE LOWER(?)");
|
|
404
|
+
params.push(`%${String(args.company).trim()}%`);
|
|
405
|
+
}
|
|
406
|
+
if (args.tag) {
|
|
407
|
+
conds.push('LOWER(tags) LIKE LOWER(?)');
|
|
408
|
+
params.push(`%"${String(args.tag).trim()}%`);
|
|
409
|
+
}
|
|
410
|
+
if (args.status) {
|
|
411
|
+
conds.push('status = ?');
|
|
412
|
+
params.push(String(args.status));
|
|
413
|
+
}
|
|
414
|
+
const lcBefore = parseTsOrDate(args.last_contacted_before);
|
|
415
|
+
if (lcBefore !== null) {
|
|
416
|
+
conds.push('COALESCE(last_contacted_at, last_activity_at, 0) < ?');
|
|
417
|
+
params.push(lcBefore);
|
|
418
|
+
}
|
|
419
|
+
const lcAfter = parseTsOrDate(args.last_contacted_after);
|
|
420
|
+
if (lcAfter !== null) {
|
|
421
|
+
conds.push('COALESCE(last_contacted_at, last_activity_at, 0) >= ?');
|
|
422
|
+
params.push(lcAfter);
|
|
423
|
+
}
|
|
424
|
+
const limit = Math.min(50, Math.max(1, Number(args.limit) || 20));
|
|
425
|
+
params.push(limit);
|
|
426
|
+
|
|
427
|
+
const rows = await query<any>(
|
|
428
|
+
`SELECT id, first_name, last_name, email, phone, company, status, outreach_status,
|
|
429
|
+
tags, lead_score, last_contacted_at, last_activity_at
|
|
430
|
+
FROM crm_contacts WHERE ${conds.join(' AND ')}
|
|
431
|
+
ORDER BY COALESCE(last_contacted_at, last_activity_at, updated_at) DESC LIMIT ?`,
|
|
432
|
+
params
|
|
433
|
+
);
|
|
434
|
+
const contacts = rows.map((r) => ({
|
|
435
|
+
id: r.id,
|
|
436
|
+
name: `${r.first_name || ''} ${r.last_name || ''}`.trim(),
|
|
437
|
+
email: r.email ?? null,
|
|
438
|
+
phone: r.phone ?? null,
|
|
439
|
+
company: r.company ?? null,
|
|
440
|
+
status: r.status,
|
|
441
|
+
outreach_status: r.outreach_status,
|
|
442
|
+
tags: r.tags || '[]',
|
|
443
|
+
lead_score: r.lead_score || 0,
|
|
444
|
+
last_contacted_at: r.last_contacted_at ?? null,
|
|
445
|
+
last_activity_at: r.last_activity_at ?? null,
|
|
446
|
+
}));
|
|
447
|
+
return { count: contacts.length, contacts };
|
|
448
|
+
},
|
|
449
|
+
},
|
|
450
|
+
{
|
|
451
|
+
name: 'crm_get_contact',
|
|
452
|
+
domain: 'crm',
|
|
453
|
+
description: 'Get full contact context: profile, deals, recent activities, notes, open tasks, linked shop customer/vendor, recent Inbox threads, and open invoices.',
|
|
454
|
+
inputSchema: {
|
|
455
|
+
type: 'object',
|
|
456
|
+
properties: {
|
|
457
|
+
contact_id: { type: 'string', description: 'Contact ID, email, or full name' },
|
|
458
|
+
email: { type: 'string', description: 'Alternative email lookup if contact_id is omitted' },
|
|
459
|
+
},
|
|
460
|
+
},
|
|
461
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
462
|
+
const refVal = args.contact_id || args.email;
|
|
463
|
+
if (!refVal) throw new Error('Missing required field: contact_id (or email)');
|
|
464
|
+
const resolved = await resolveContactId(ctx.profileId, String(refVal));
|
|
465
|
+
const contactId = resolved.id;
|
|
466
|
+
|
|
467
|
+
const cRows = await query<any>(
|
|
468
|
+
`SELECT id, first_name, last_name, email, phone, company, job_title, website,
|
|
469
|
+
status, outreach_status, tags, notes, agent_notes, lead_score, icp_match,
|
|
470
|
+
urgency, next_action, next_follow_up_at, last_contacted_at, last_activity_at,
|
|
471
|
+
total_spent_cents, total_purchases
|
|
472
|
+
FROM crm_contacts WHERE id = ? AND profile_id = ? LIMIT 1`,
|
|
473
|
+
[contactId, ctx.profileId]
|
|
474
|
+
);
|
|
475
|
+
const c = cRows[0];
|
|
476
|
+
const deals = await query<any>(
|
|
477
|
+
'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',
|
|
478
|
+
[ctx.profileId, contactId]
|
|
479
|
+
);
|
|
480
|
+
const activities = await query<any>(
|
|
481
|
+
'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',
|
|
482
|
+
[ctx.profileId, contactId]
|
|
483
|
+
);
|
|
484
|
+
const notes = await query<any>(
|
|
485
|
+
'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',
|
|
486
|
+
[ctx.profileId, contactId]
|
|
487
|
+
);
|
|
488
|
+
const openTasks = await query<any>(
|
|
489
|
+
"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",
|
|
490
|
+
[ctx.profileId, contactId]
|
|
491
|
+
);
|
|
492
|
+
const linkedCustomerRows = await query<any>(
|
|
493
|
+
'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',
|
|
494
|
+
[ctx.profileId, contactId, c.email, c.email]
|
|
495
|
+
);
|
|
496
|
+
const linkedVendorRows = await query<any>(
|
|
497
|
+
'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',
|
|
498
|
+
[ctx.profileId, contactId, c.email, c.email]
|
|
499
|
+
);
|
|
500
|
+
const threads = await query<any>(
|
|
501
|
+
`SELECT t.id, t.subject, t.state, t.category, t.last_message_at, t.agent_summary
|
|
502
|
+
FROM inbox_threads t
|
|
503
|
+
WHERE t.profile_id = ? AND t.linked_entity_type = 'contact' AND t.linked_entity_id = ?
|
|
504
|
+
AND NOT EXISTS (SELECT 1 FROM inbox_messages m WHERE m.thread_id = t.id AND m.screen_status IN ('suspicious','blocked'))
|
|
505
|
+
ORDER BY t.last_message_at DESC LIMIT 8`,
|
|
506
|
+
[ctx.profileId, contactId]
|
|
507
|
+
);
|
|
508
|
+
const openInvoices = await query<any>(
|
|
509
|
+
"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",
|
|
510
|
+
[ctx.profileId, contactId]
|
|
511
|
+
);
|
|
512
|
+
|
|
513
|
+
return {
|
|
514
|
+
contact: {
|
|
515
|
+
...c,
|
|
516
|
+
name: `${c.first_name || ''} ${c.last_name || ''}`.trim(),
|
|
517
|
+
},
|
|
518
|
+
deals,
|
|
519
|
+
activities,
|
|
520
|
+
notes,
|
|
521
|
+
open_tasks: openTasks,
|
|
522
|
+
linked_customer: linkedCustomerRows[0] ?? null,
|
|
523
|
+
linked_vendor: linkedVendorRows[0] ?? null,
|
|
524
|
+
recent_threads: threads,
|
|
525
|
+
open_invoices: openInvoices,
|
|
526
|
+
};
|
|
527
|
+
},
|
|
528
|
+
},
|
|
529
|
+
{
|
|
530
|
+
name: 'crm_list_deals',
|
|
531
|
+
domain: 'crm',
|
|
532
|
+
description: 'List CRM pipeline deals, optionally filtered by contact, stage, or open_only.',
|
|
533
|
+
inputSchema: {
|
|
534
|
+
type: 'object',
|
|
535
|
+
properties: {
|
|
536
|
+
contact_id: { type: 'string', description: 'Optional contact ID filter' },
|
|
537
|
+
stage: { type: 'string', description: 'Optional pipeline stage filter' },
|
|
538
|
+
open_only: { type: 'boolean', description: 'Exclude won/lost deals when true' },
|
|
539
|
+
limit: { type: 'number', description: 'Max deals to return (default 25, max 50)' },
|
|
540
|
+
},
|
|
541
|
+
},
|
|
542
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
543
|
+
const conds = ['d.profile_id = ?'];
|
|
544
|
+
const params: any[] = [ctx.profileId];
|
|
545
|
+
if (args.contact_id) {
|
|
546
|
+
conds.push('d.contact_id = ?');
|
|
547
|
+
params.push(String(args.contact_id));
|
|
548
|
+
}
|
|
549
|
+
if (args.stage) {
|
|
550
|
+
conds.push('d.stage = ?');
|
|
551
|
+
params.push(String(args.stage));
|
|
552
|
+
}
|
|
553
|
+
if (args.open_only) {
|
|
554
|
+
conds.push("d.stage NOT IN ('won', 'lost')");
|
|
555
|
+
}
|
|
556
|
+
const limit = Math.min(50, Math.max(1, Number(args.limit) || 25));
|
|
557
|
+
params.push(limit);
|
|
558
|
+
|
|
559
|
+
const rows = await query<any>(
|
|
560
|
+
`SELECT d.id, d.contact_id, d.title, d.value_cents, d.currency, d.stage,
|
|
561
|
+
d.probability, d.expected_close_at, d.updated_at,
|
|
562
|
+
c.first_name, c.last_name, c.company
|
|
563
|
+
FROM crm_deals d
|
|
564
|
+
LEFT JOIN crm_contacts c ON c.id = d.contact_id AND c.profile_id = d.profile_id
|
|
565
|
+
WHERE ${conds.join(' AND ')} ORDER BY d.updated_at DESC LIMIT ?`,
|
|
566
|
+
params
|
|
567
|
+
);
|
|
568
|
+
const deals = rows.map((r) => ({
|
|
569
|
+
id: r.id,
|
|
570
|
+
contact_id: r.contact_id,
|
|
571
|
+
contact_name: `${r.first_name || ''} ${r.last_name || ''}`.trim(),
|
|
572
|
+
company: r.company ?? null,
|
|
573
|
+
title: r.title,
|
|
574
|
+
value_cents: r.value_cents || 0,
|
|
575
|
+
currency: r.currency || 'usd',
|
|
576
|
+
stage: r.stage,
|
|
577
|
+
probability: r.probability || 0,
|
|
578
|
+
expected_close_at: r.expected_close_at ?? null,
|
|
579
|
+
updated_at: r.updated_at,
|
|
580
|
+
}));
|
|
581
|
+
return { count: deals.length, deals };
|
|
582
|
+
},
|
|
583
|
+
},
|
|
584
|
+
{
|
|
585
|
+
name: 'crm_get_deal',
|
|
586
|
+
domain: 'crm',
|
|
587
|
+
description: 'Get a single deal with its linked activities and proposals.',
|
|
588
|
+
inputSchema: {
|
|
589
|
+
type: 'object',
|
|
590
|
+
properties: {
|
|
591
|
+
deal_id: { type: 'string', description: 'Deal ID' },
|
|
592
|
+
},
|
|
593
|
+
required: ['deal_id'],
|
|
594
|
+
},
|
|
595
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
596
|
+
const dealId = String(args.deal_id || '');
|
|
597
|
+
const deals = await query<any>('SELECT * FROM crm_deals WHERE id = ? AND profile_id = ? LIMIT 1', [dealId, ctx.profileId]);
|
|
598
|
+
if (deals.length === 0) throw new Error(`Deal not found: ${dealId}`);
|
|
599
|
+
const activities = await query<any>(
|
|
600
|
+
'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',
|
|
601
|
+
[ctx.profileId, dealId]
|
|
602
|
+
);
|
|
603
|
+
const proposals = await query<any>(
|
|
604
|
+
'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',
|
|
605
|
+
[ctx.profileId, dealId]
|
|
606
|
+
);
|
|
607
|
+
return { deal: deals[0], activities, proposals };
|
|
608
|
+
},
|
|
609
|
+
},
|
|
610
|
+
{
|
|
611
|
+
name: 'crm_list_tasks',
|
|
612
|
+
domain: 'crm',
|
|
613
|
+
description: 'List CRM follow-up tasks (due, overdue, or by contact).',
|
|
614
|
+
inputSchema: {
|
|
615
|
+
type: 'object',
|
|
616
|
+
properties: {
|
|
617
|
+
status: { type: 'string', enum: ['open', 'done', 'all'], description: "Task status filter (default 'open')" },
|
|
618
|
+
contact_id: { type: 'string', description: 'Optional contact ID filter' },
|
|
619
|
+
overdue_only: { type: 'boolean', description: 'Only tasks past due_at' },
|
|
620
|
+
due_before: { type: 'string', description: 'Unix timestamp or YYYY-MM-DD' },
|
|
621
|
+
limit: { type: 'number', description: 'Max tasks to return (default 25)' },
|
|
622
|
+
},
|
|
623
|
+
},
|
|
624
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
625
|
+
const now = nowTs();
|
|
626
|
+
const status = String(args.status || 'open');
|
|
627
|
+
const conds = ['t.profile_id = ?'];
|
|
628
|
+
const params: any[] = [ctx.profileId];
|
|
629
|
+
if (status !== 'all') {
|
|
630
|
+
conds.push('t.status = ?');
|
|
631
|
+
params.push(status);
|
|
632
|
+
}
|
|
633
|
+
if (args.contact_id) {
|
|
634
|
+
conds.push('t.contact_id = ?');
|
|
635
|
+
params.push(String(args.contact_id));
|
|
636
|
+
}
|
|
637
|
+
const dueBefore = parseTsOrDate(args.due_before);
|
|
638
|
+
if (args.overdue_only) {
|
|
639
|
+
conds.push('t.due_at IS NOT NULL AND t.due_at < ?');
|
|
640
|
+
params.push(now);
|
|
641
|
+
} else if (dueBefore !== null) {
|
|
642
|
+
conds.push('t.due_at IS NOT NULL AND t.due_at <= ?');
|
|
643
|
+
params.push(dueBefore);
|
|
644
|
+
}
|
|
645
|
+
const limit = Math.min(50, Math.max(1, Number(args.limit) || 25));
|
|
646
|
+
params.push(limit);
|
|
647
|
+
|
|
648
|
+
const rows = await query<any>(
|
|
649
|
+
`SELECT t.id, t.contact_id, t.deal_id, t.title, t.description, t.due_at, t.priority, t.status,
|
|
650
|
+
c.first_name, c.last_name, c.email
|
|
651
|
+
FROM crm_tasks t
|
|
652
|
+
LEFT JOIN crm_contacts c ON c.id = t.contact_id AND c.profile_id = t.profile_id
|
|
653
|
+
WHERE ${conds.join(' AND ')} ORDER BY COALESCE(t.due_at, 9999999999) ASC LIMIT ?`,
|
|
654
|
+
params
|
|
655
|
+
);
|
|
656
|
+
const tasks = rows.map((r) => ({
|
|
657
|
+
id: r.id,
|
|
658
|
+
contact_id: r.contact_id ?? null,
|
|
659
|
+
contact_name: `${r.first_name || ''} ${r.last_name || ''}`.trim(),
|
|
660
|
+
contact_email: r.email ?? null,
|
|
661
|
+
deal_id: r.deal_id ?? null,
|
|
662
|
+
title: r.title,
|
|
663
|
+
description: r.description ?? null,
|
|
664
|
+
due_at: r.due_at ?? null,
|
|
665
|
+
is_overdue: typeof r.due_at === 'number' && r.due_at < now,
|
|
666
|
+
priority: r.priority,
|
|
667
|
+
status: r.status,
|
|
668
|
+
}));
|
|
669
|
+
return { count: tasks.length, tasks };
|
|
670
|
+
},
|
|
671
|
+
},
|
|
672
|
+
{
|
|
673
|
+
name: 'crm_list_stale',
|
|
674
|
+
domain: 'crm',
|
|
675
|
+
description: 'List contacts and open deals that have gone quiet (no activity for N days, default 14).',
|
|
676
|
+
inputSchema: {
|
|
677
|
+
type: 'object',
|
|
678
|
+
properties: {
|
|
679
|
+
days: { type: 'number', description: 'Silence threshold in days (defaults to crm.stale_days or 14)' },
|
|
680
|
+
include_deals: { type: 'boolean', description: 'Include stale open deals (default true)' },
|
|
681
|
+
limit: { type: 'number', description: 'Max rows per list (default 20)' },
|
|
682
|
+
},
|
|
683
|
+
},
|
|
684
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
685
|
+
const cfgDays = await getCrmConfigVal(ctx.profileId, 'crm.stale_days');
|
|
686
|
+
const days = Math.max(1, Number(args.days) || (cfgDays ? Number(cfgDays) : 14));
|
|
687
|
+
const limit = Math.min(50, Math.max(1, Number(args.limit) || 20));
|
|
688
|
+
const now = nowTs();
|
|
689
|
+
const cutoff = now - days * 86_400;
|
|
690
|
+
|
|
691
|
+
const cRows = await query<any>(
|
|
692
|
+
`SELECT id, first_name, last_name, email, company, status,
|
|
693
|
+
COALESCE(last_contacted_at, last_activity_at, updated_at) AS last_ts
|
|
694
|
+
FROM crm_contacts
|
|
695
|
+
WHERE profile_id = ? AND archived = 0
|
|
696
|
+
AND COALESCE(last_contacted_at, last_activity_at, updated_at) < ?
|
|
697
|
+
ORDER BY last_ts ASC LIMIT ?`,
|
|
698
|
+
[ctx.profileId, cutoff, limit]
|
|
699
|
+
);
|
|
700
|
+
const staleContacts = cRows.map((r) => ({
|
|
701
|
+
id: r.id,
|
|
702
|
+
name: `${r.first_name || ''} ${r.last_name || ''}`.trim(),
|
|
703
|
+
email: r.email ?? null,
|
|
704
|
+
company: r.company ?? null,
|
|
705
|
+
status: r.status,
|
|
706
|
+
last_activity_at: r.last_ts,
|
|
707
|
+
days_silent: Math.floor(Math.max(0, now - Number(r.last_ts || 0)) / 86_400),
|
|
708
|
+
}));
|
|
709
|
+
|
|
710
|
+
let staleDeals: any[] = [];
|
|
711
|
+
if (args.include_deals !== false) {
|
|
712
|
+
const dRows = await query<any>(
|
|
713
|
+
`SELECT d.id, d.contact_id, d.title, d.stage, d.value_cents, d.currency, d.updated_at,
|
|
714
|
+
c.first_name, c.last_name
|
|
715
|
+
FROM crm_deals d
|
|
716
|
+
LEFT JOIN crm_contacts c ON c.id = d.contact_id AND c.profile_id = d.profile_id
|
|
717
|
+
WHERE d.profile_id = ? AND d.stage NOT IN ('won','lost') AND d.updated_at < ?
|
|
718
|
+
ORDER BY d.updated_at ASC LIMIT ?`,
|
|
719
|
+
[ctx.profileId, cutoff, limit]
|
|
720
|
+
);
|
|
721
|
+
staleDeals = dRows.map((r) => ({
|
|
722
|
+
id: r.id,
|
|
723
|
+
contact_id: r.contact_id,
|
|
724
|
+
contact_name: `${r.first_name || ''} ${r.last_name || ''}`.trim(),
|
|
725
|
+
title: r.title,
|
|
726
|
+
stage: r.stage,
|
|
727
|
+
value_cents: r.value_cents || 0,
|
|
728
|
+
currency: r.currency || 'usd',
|
|
729
|
+
days_silent: Math.floor(Math.max(0, now - Number(r.updated_at || 0)) / 86_400),
|
|
730
|
+
}));
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
return { threshold_days: days, stale_contacts: staleContacts, stale_deals: staleDeals };
|
|
734
|
+
},
|
|
735
|
+
},
|
|
736
|
+
{
|
|
737
|
+
name: 'crm_get_client_billing',
|
|
738
|
+
domain: 'crm',
|
|
739
|
+
description: 'Read-only client billing summary across crm_invoices, crm_proposals, and linked shop_documents.',
|
|
740
|
+
inputSchema: {
|
|
741
|
+
type: 'object',
|
|
742
|
+
properties: {
|
|
743
|
+
contact_id: { type: 'string', description: 'Contact ID or email' },
|
|
744
|
+
email: { type: 'string', description: 'Alternative email lookup' },
|
|
745
|
+
},
|
|
746
|
+
},
|
|
747
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
748
|
+
const refVal = args.contact_id || args.email;
|
|
749
|
+
if (!refVal) throw new Error('Missing required field: contact_id (or email)');
|
|
750
|
+
const resolved = await resolveContactId(ctx.profileId, String(refVal));
|
|
751
|
+
const now = nowTs();
|
|
752
|
+
|
|
753
|
+
const crmInvRows = await query<any>(
|
|
754
|
+
'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',
|
|
755
|
+
[ctx.profileId, resolved.id]
|
|
756
|
+
);
|
|
757
|
+
let crmPaidCents = 0;
|
|
758
|
+
let crmUnpaidCents = 0;
|
|
759
|
+
let crmOverdueCount = 0;
|
|
760
|
+
const crmInvoices = crmInvRows.map((r) => {
|
|
761
|
+
const isPaid = r.status === 'paid' || r.paid_at !== null;
|
|
762
|
+
const isVoid = ['cancelled', 'refunded', 'draft'].includes(r.status);
|
|
763
|
+
const isOverdue = !isPaid && !isVoid && (r.status === 'overdue' || (typeof r.due_at === 'number' && r.due_at < now));
|
|
764
|
+
if (isPaid) crmPaidCents += Number(r.total_cents || 0);
|
|
765
|
+
else if (!isVoid) crmUnpaidCents += Number(r.total_cents || 0);
|
|
766
|
+
if (isOverdue) crmOverdueCount += 1;
|
|
767
|
+
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 };
|
|
768
|
+
});
|
|
769
|
+
|
|
770
|
+
const proposals = await query<any>(
|
|
771
|
+
'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',
|
|
772
|
+
[ctx.profileId, resolved.id]
|
|
773
|
+
);
|
|
774
|
+
|
|
775
|
+
let shopDocs: any[] = [];
|
|
776
|
+
let shopPaid = 0;
|
|
777
|
+
let shopUnpaid = 0;
|
|
778
|
+
const cust = await query<{ id: string }>(
|
|
779
|
+
'SELECT id FROM shop_customers WHERE profile_id = ? AND (contact_id = ? OR (? IS NOT NULL AND LOWER(email) = LOWER(?))) LIMIT 1',
|
|
780
|
+
[ctx.profileId, resolved.id, resolved.email, resolved.email]
|
|
781
|
+
);
|
|
782
|
+
if (cust.length > 0) {
|
|
783
|
+
shopDocs = await query<any>(
|
|
784
|
+
"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",
|
|
785
|
+
[ctx.profileId, cust[0].id]
|
|
786
|
+
);
|
|
787
|
+
for (const d of shopDocs) {
|
|
788
|
+
if (!['cancelled', 'void'].includes(d.status)) {
|
|
789
|
+
shopPaid += Number(d.amount_paid || 0);
|
|
790
|
+
shopUnpaid += Number(d.amount_due || 0);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
return {
|
|
796
|
+
contact_id: resolved.id,
|
|
797
|
+
contact_name: resolved.name,
|
|
798
|
+
crm_invoices: crmInvoices,
|
|
799
|
+
crm_proposals: proposals,
|
|
800
|
+
shop_documents: shopDocs,
|
|
801
|
+
summary: {
|
|
802
|
+
crm_paid_cents: crmPaidCents,
|
|
803
|
+
crm_unpaid_cents: crmUnpaidCents,
|
|
804
|
+
crm_overdue_count: crmOverdueCount,
|
|
805
|
+
shop_paid_amount: shopPaid,
|
|
806
|
+
shop_unpaid_amount: shopUnpaid,
|
|
807
|
+
},
|
|
808
|
+
};
|
|
809
|
+
},
|
|
810
|
+
},
|
|
811
|
+
{
|
|
812
|
+
name: 'crm_log_activity',
|
|
813
|
+
domain: 'crm',
|
|
814
|
+
description: "Log an activity summary (email, call, meeting, note, dm) on a contact timeline attributed author='agent'. Never stores raw email bodies.",
|
|
815
|
+
inputSchema: {
|
|
816
|
+
type: 'object',
|
|
817
|
+
properties: {
|
|
818
|
+
contact_id: { type: 'string', description: 'Contact ID or email' },
|
|
819
|
+
deal_id: { type: 'string', description: 'Optional deal ID' },
|
|
820
|
+
activity_type: { type: 'string', enum: ['email', 'call', 'meeting', 'note', 'dm', 'task_done', 'agent_action'] },
|
|
821
|
+
direction: { type: 'string', enum: ['inbound', 'outbound'] },
|
|
822
|
+
subject: { type: 'string', description: 'Short subject or headline' },
|
|
823
|
+
summary: { type: 'string', description: 'Short summary (capped at 1000 chars)' },
|
|
824
|
+
outcome: { type: 'string', description: 'Optional outcome' },
|
|
825
|
+
source_thread_id: { type: 'string', description: 'Optional Inbox thread ID' },
|
|
826
|
+
idempotency_key: { type: 'string', description: 'Optional dedupe key' },
|
|
827
|
+
},
|
|
828
|
+
required: ['contact_id'],
|
|
829
|
+
},
|
|
830
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
831
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
832
|
+
const actId = generateId('act');
|
|
833
|
+
const now = nowTs();
|
|
834
|
+
const activityType = String(args.activity_type || 'note');
|
|
835
|
+
const direction = String(args.direction || 'outbound');
|
|
836
|
+
const summary = args.summary ?? args.body ?? null;
|
|
837
|
+
const bodyStr = summary ? String(summary).slice(0, 1000) : null;
|
|
838
|
+
const meta = JSON.stringify({ author: 'agent', source_thread_id: args.source_thread_id ?? null });
|
|
839
|
+
|
|
840
|
+
await execute(
|
|
841
|
+
`INSERT OR IGNORE INTO crm_activities
|
|
842
|
+
(id, profile_id, contact_id, deal_id, type, direction, sender, subject, body, outcome,
|
|
843
|
+
metadata, approval_status, occurred_at, created_at, idempotency_key, source_thread_id)
|
|
844
|
+
VALUES (?, ?, ?, ?, ?, ?, 'agent', ?, ?, ?, ?, 'auto_sent', ?, ?, ?, ?)`,
|
|
845
|
+
[
|
|
846
|
+
actId, ctx.profileId, resolved.id, args.deal_id ?? null, activityType, direction,
|
|
847
|
+
args.subject ?? null, bodyStr, args.outcome ?? null, meta, now, now,
|
|
848
|
+
args.idempotency_key ?? null, args.source_thread_id ?? null,
|
|
849
|
+
]
|
|
850
|
+
);
|
|
851
|
+
|
|
852
|
+
if (['email', 'call', 'dm', 'meeting'].includes(activityType)) {
|
|
853
|
+
await execute(
|
|
854
|
+
'UPDATE crm_contacts SET last_activity_at = ?, last_contacted_at = ?, updated_at = ? WHERE id = ? AND profile_id = ?',
|
|
855
|
+
[now, now, now, resolved.id, ctx.profileId]
|
|
856
|
+
);
|
|
857
|
+
} else {
|
|
858
|
+
await execute(
|
|
859
|
+
'UPDATE crm_contacts SET last_activity_at = ?, updated_at = ? WHERE id = ? AND profile_id = ?',
|
|
860
|
+
[now, now, resolved.id, ctx.profileId]
|
|
861
|
+
);
|
|
862
|
+
}
|
|
863
|
+
return { activity_id: actId, contact_id: resolved.id, type: activityType, author: 'agent', status: 'logged' };
|
|
864
|
+
},
|
|
865
|
+
},
|
|
866
|
+
{
|
|
867
|
+
name: 'crm_add_note',
|
|
868
|
+
domain: 'crm',
|
|
869
|
+
description: 'Add a CRM note on a contact (and optionally a deal).',
|
|
870
|
+
inputSchema: {
|
|
871
|
+
type: 'object',
|
|
872
|
+
properties: {
|
|
873
|
+
contact_id: { type: 'string', description: 'Contact ID or email' },
|
|
874
|
+
deal_id: { type: 'string', description: 'Optional deal ID' },
|
|
875
|
+
body: { type: 'string', description: 'Note content' },
|
|
876
|
+
pinned: { type: 'boolean', description: 'Pin note to top (default false)' },
|
|
877
|
+
idempotency_key: { type: 'string', description: 'Optional dedupe key' },
|
|
878
|
+
},
|
|
879
|
+
required: ['contact_id', 'body'],
|
|
880
|
+
},
|
|
881
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
882
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
883
|
+
const body = String(args.body || '').trim();
|
|
884
|
+
if (!body) throw new Error('Missing required field: body');
|
|
885
|
+
const noteId = generateId('note');
|
|
886
|
+
const now = nowTs();
|
|
887
|
+
await execute(
|
|
888
|
+
`INSERT OR IGNORE INTO crm_notes (id, profile_id, contact_id, deal_id, body, pinned, idempotency_key, created_at, updated_at)
|
|
889
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
890
|
+
[noteId, ctx.profileId, resolved.id, args.deal_id ?? null, body, args.pinned ? 1 : 0, args.idempotency_key ?? null, now, now]
|
|
891
|
+
);
|
|
892
|
+
return { note_id: noteId, contact_id: resolved.id, author: 'agent', status: 'created' };
|
|
893
|
+
},
|
|
894
|
+
},
|
|
895
|
+
{
|
|
896
|
+
name: 'crm_create_task',
|
|
897
|
+
domain: 'crm',
|
|
898
|
+
description: 'Create a follow-up task in crm_tasks.',
|
|
899
|
+
inputSchema: {
|
|
900
|
+
type: 'object',
|
|
901
|
+
properties: {
|
|
902
|
+
title: { type: 'string', description: 'Task title' },
|
|
903
|
+
contact_id: { type: 'string', description: 'Optional contact ID or email' },
|
|
904
|
+
deal_id: { type: 'string', description: 'Optional deal ID' },
|
|
905
|
+
description: { type: 'string', description: 'Task details' },
|
|
906
|
+
due_at: { type: 'string', description: 'Due date (YYYY-MM-DD or Unix timestamp)' },
|
|
907
|
+
priority: { type: 'string', enum: ['low', 'medium', 'high'] },
|
|
908
|
+
idempotency_key: { type: 'string', description: 'Optional dedupe key' },
|
|
909
|
+
},
|
|
910
|
+
required: ['title'],
|
|
911
|
+
},
|
|
912
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
913
|
+
const title = String(args.title || '').trim();
|
|
914
|
+
if (!title) throw new Error('Missing required field: title');
|
|
915
|
+
const contactId = args.contact_id ? (await resolveContactId(ctx.profileId, String(args.contact_id))).id : null;
|
|
916
|
+
const dueAt = parseTsOrDate(args.due_at);
|
|
917
|
+
const priority = ['low', 'high'].includes(String(args.priority)) ? String(args.priority) : 'medium';
|
|
918
|
+
const taskId = generateId('tsk');
|
|
919
|
+
const now = nowTs();
|
|
920
|
+
|
|
921
|
+
await execute(
|
|
922
|
+
`INSERT OR IGNORE INTO crm_tasks
|
|
923
|
+
(id, profile_id, contact_id, deal_id, title, description, due_at, priority, status, idempotency_key, created_at, updated_at)
|
|
924
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?)`,
|
|
925
|
+
[taskId, ctx.profileId, contactId, args.deal_id ?? null, title, args.description ?? null, dueAt, priority, args.idempotency_key ?? null, now, now]
|
|
926
|
+
);
|
|
927
|
+
return { task_id: taskId, contact_id: contactId, title, due_at: dueAt, priority, author: 'agent', status: 'created' };
|
|
928
|
+
},
|
|
929
|
+
},
|
|
930
|
+
{
|
|
931
|
+
name: 'crm_add_tag',
|
|
932
|
+
domain: 'crm',
|
|
933
|
+
description: 'Append a tag to a CRM contact idempotently.',
|
|
934
|
+
inputSchema: {
|
|
935
|
+
type: 'object',
|
|
936
|
+
properties: {
|
|
937
|
+
contact_id: { type: 'string', description: 'Contact ID or email' },
|
|
938
|
+
tag: { type: 'string', description: 'Tag name to add' },
|
|
939
|
+
},
|
|
940
|
+
required: ['contact_id', 'tag'],
|
|
941
|
+
},
|
|
942
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
943
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
944
|
+
const tag = String(args.tag || '').trim();
|
|
945
|
+
if (!tag) throw new Error('Missing required field: tag');
|
|
946
|
+
const rows = await query<{ tags: string }>('SELECT tags FROM crm_contacts WHERE id = ? AND profile_id = ? LIMIT 1', [resolved.id, ctx.profileId]);
|
|
947
|
+
let tags: string[] = [];
|
|
948
|
+
try {
|
|
949
|
+
tags = JSON.parse(rows[0]?.tags || '[]');
|
|
950
|
+
} catch {
|
|
951
|
+
tags = [];
|
|
952
|
+
}
|
|
953
|
+
if (!tags.some((t) => t.toLowerCase() === tag.toLowerCase())) tags.push(tag);
|
|
954
|
+
await execute('UPDATE crm_contacts SET tags = ?, updated_at = ? WHERE id = ? AND profile_id = ?', [
|
|
955
|
+
JSON.stringify(tags), nowTs(), resolved.id, ctx.profileId,
|
|
956
|
+
]);
|
|
957
|
+
return { contact_id: resolved.id, tag, tags, status: 'updated' };
|
|
958
|
+
},
|
|
959
|
+
},
|
|
960
|
+
{
|
|
961
|
+
name: 'crm_create_contact_from_mail',
|
|
962
|
+
domain: 'crm',
|
|
963
|
+
description: 'Propose creating a new CRM contact from an Inbox sender. Queues an approval item for the human instead of auto-creating.',
|
|
964
|
+
inputSchema: {
|
|
965
|
+
type: 'object',
|
|
966
|
+
properties: {
|
|
967
|
+
email: { type: 'string', description: 'Sender email address' },
|
|
968
|
+
name: { type: 'string', description: 'Display name' },
|
|
969
|
+
company: { type: 'string', description: 'Optional company name' },
|
|
970
|
+
thread_id: { type: 'string', description: 'Source Inbox thread ID' },
|
|
971
|
+
reason: { type: 'string', description: 'One-line context why this contact should be added' },
|
|
972
|
+
sources: { type: 'array', items: { type: 'string' } },
|
|
973
|
+
},
|
|
974
|
+
required: ['email'],
|
|
975
|
+
},
|
|
976
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
977
|
+
const email = String(args.email || '').trim().toLowerCase();
|
|
978
|
+
if (!email) throw new Error('Missing required field: email');
|
|
979
|
+
const existing = await query<{ id: string }>(
|
|
980
|
+
'SELECT id FROM crm_contacts WHERE profile_id = ? AND LOWER(email) = LOWER(?) LIMIT 1',
|
|
981
|
+
[ctx.profileId, email]
|
|
982
|
+
);
|
|
983
|
+
if (existing.length > 0) return { contact_id: existing[0].id, email, status: 'already_exists' };
|
|
984
|
+
const name = String(args.name || '').trim() || email;
|
|
985
|
+
const threadId = args.thread_id ? String(args.thread_id) : null;
|
|
986
|
+
const sources = Array.isArray(args.sources) ? args.sources.map(String) : threadId ? [`thread:${threadId}`] : [];
|
|
987
|
+
return queueApprovalItem(
|
|
988
|
+
ctx.profileId,
|
|
989
|
+
'crm_create_contact_from_mail',
|
|
990
|
+
`New contact: ${name} (${email})`,
|
|
991
|
+
args,
|
|
992
|
+
String(args.reason || 'New sender spotted in Inbox email'),
|
|
993
|
+
sources,
|
|
994
|
+
threadId,
|
|
995
|
+
`new_contact:${ctx.profileId}:${email}`
|
|
996
|
+
);
|
|
997
|
+
},
|
|
998
|
+
},
|
|
999
|
+
{
|
|
1000
|
+
name: 'crm_propose_deal',
|
|
1001
|
+
domain: 'crm',
|
|
1002
|
+
description: 'Propose a new pipeline deal for human approval (does not create the deal until approved).',
|
|
1003
|
+
inputSchema: {
|
|
1004
|
+
type: 'object',
|
|
1005
|
+
properties: {
|
|
1006
|
+
contact_id: { type: 'string', description: 'Contact ID or email' },
|
|
1007
|
+
title: { type: 'string', description: 'Deal title' },
|
|
1008
|
+
value_cents: { type: 'number', description: 'Deal value in minor units (cents)' },
|
|
1009
|
+
currency: { type: 'string', description: "Currency code (default 'usd')" },
|
|
1010
|
+
stage: { type: 'string', description: "Initial stage (default 'new')" },
|
|
1011
|
+
expected_close_at: { type: 'string', description: 'Expected close date (YYYY-MM-DD or Unix timestamp)' },
|
|
1012
|
+
notes: { type: 'string', description: 'Deal context' },
|
|
1013
|
+
reason: { type: 'string', description: 'Why this deal is proposed' },
|
|
1014
|
+
sources: { type: 'array', items: { type: 'string' } },
|
|
1015
|
+
},
|
|
1016
|
+
required: ['contact_id', 'title'],
|
|
1017
|
+
},
|
|
1018
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
1019
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
1020
|
+
const title = String(args.title || '').trim();
|
|
1021
|
+
if (!title) throw new Error('Missing required field: title');
|
|
1022
|
+
return queueApprovalItem(
|
|
1023
|
+
ctx.profileId,
|
|
1024
|
+
'crm_propose_deal',
|
|
1025
|
+
`Create deal "${title}" for ${resolved.name}`,
|
|
1026
|
+
{ ...args, contact_id: resolved.id },
|
|
1027
|
+
String(args.reason || 'Deal signal detected'),
|
|
1028
|
+
Array.isArray(args.sources) ? args.sources.map(String) : [],
|
|
1029
|
+
resolved.id,
|
|
1030
|
+
`propose_deal:${ctx.profileId}:${resolved.id}:${title.toLowerCase()}`
|
|
1031
|
+
);
|
|
1032
|
+
},
|
|
1033
|
+
},
|
|
1034
|
+
{
|
|
1035
|
+
name: 'crm_update_deal_stage',
|
|
1036
|
+
domain: 'crm',
|
|
1037
|
+
description: 'Propose moving a deal to a new pipeline stage (queued for human approval).',
|
|
1038
|
+
inputSchema: {
|
|
1039
|
+
type: 'object',
|
|
1040
|
+
properties: {
|
|
1041
|
+
deal_id: { type: 'string', description: 'Deal ID' },
|
|
1042
|
+
stage: { type: 'string', description: 'Target stage' },
|
|
1043
|
+
lost_reason: { type: 'string', description: "Required when stage is 'lost'" },
|
|
1044
|
+
reason: { type: 'string', description: 'Why the stage change is proposed' },
|
|
1045
|
+
sources: { type: 'array', items: { type: 'string' } },
|
|
1046
|
+
},
|
|
1047
|
+
required: ['deal_id', 'stage'],
|
|
1048
|
+
},
|
|
1049
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
1050
|
+
const dealId = String(args.deal_id || '');
|
|
1051
|
+
const stage = String(args.stage || '');
|
|
1052
|
+
const deals = await query<{ title: string; stage: string }>(
|
|
1053
|
+
'SELECT title, stage FROM crm_deals WHERE id = ? AND profile_id = ? LIMIT 1',
|
|
1054
|
+
[dealId, ctx.profileId]
|
|
1055
|
+
);
|
|
1056
|
+
if (deals.length === 0) throw new Error(`Deal not found: ${dealId}`);
|
|
1057
|
+
return queueApprovalItem(
|
|
1058
|
+
ctx.profileId,
|
|
1059
|
+
'crm_update_deal_stage',
|
|
1060
|
+
`Move deal "${deals[0].title}" (${deals[0].stage} -> ${stage})`,
|
|
1061
|
+
args,
|
|
1062
|
+
String(args.reason || 'Pipeline stage update proposed by agent'),
|
|
1063
|
+
Array.isArray(args.sources) ? args.sources.map(String) : [],
|
|
1064
|
+
dealId,
|
|
1065
|
+
`deal_stage:${ctx.profileId}:${dealId}:${stage}`
|
|
1066
|
+
);
|
|
1067
|
+
},
|
|
1068
|
+
},
|
|
1069
|
+
{
|
|
1070
|
+
name: 'crm_merge_contacts',
|
|
1071
|
+
domain: 'crm',
|
|
1072
|
+
description: 'Propose merging a duplicate contact into a primary contact (queued for human approval).',
|
|
1073
|
+
inputSchema: {
|
|
1074
|
+
type: 'object',
|
|
1075
|
+
properties: {
|
|
1076
|
+
primary_contact_id: { type: 'string', description: 'Contact ID to keep' },
|
|
1077
|
+
duplicate_contact_id: { type: 'string', description: 'Duplicate contact ID to archive and merge' },
|
|
1078
|
+
reason: { type: 'string', description: 'Why these are duplicates' },
|
|
1079
|
+
sources: { type: 'array', items: { type: 'string' } },
|
|
1080
|
+
},
|
|
1081
|
+
required: ['primary_contact_id', 'duplicate_contact_id'],
|
|
1082
|
+
},
|
|
1083
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
1084
|
+
const primary = await resolveContactId(ctx.profileId, String(args.primary_contact_id));
|
|
1085
|
+
const dup = await resolveContactId(ctx.profileId, String(args.duplicate_contact_id));
|
|
1086
|
+
if (primary.id === dup.id) throw new Error('Cannot merge a contact with itself');
|
|
1087
|
+
return queueApprovalItem(
|
|
1088
|
+
ctx.profileId,
|
|
1089
|
+
'crm_merge_contacts',
|
|
1090
|
+
`Merge contact "${dup.name}" into "${primary.name}"`,
|
|
1091
|
+
{ ...args, primary_contact_id: primary.id, duplicate_contact_id: dup.id },
|
|
1092
|
+
String(args.reason || 'Duplicate contact merge proposed'),
|
|
1093
|
+
Array.isArray(args.sources) ? args.sources.map(String) : [],
|
|
1094
|
+
primary.id,
|
|
1095
|
+
`merge:${ctx.profileId}:${primary.id}:${dup.id}`
|
|
1096
|
+
);
|
|
1097
|
+
},
|
|
1098
|
+
},
|
|
1099
|
+
{
|
|
1100
|
+
name: 'crm_create_proposal_draft',
|
|
1101
|
+
domain: 'crm',
|
|
1102
|
+
description: 'Propose creating a client proposal draft in crm_proposals (queued for human approval).',
|
|
1103
|
+
inputSchema: {
|
|
1104
|
+
type: 'object',
|
|
1105
|
+
properties: {
|
|
1106
|
+
contact_id: { type: 'string', description: 'Contact ID or email' },
|
|
1107
|
+
deal_id: { type: 'string', description: 'Optional deal ID' },
|
|
1108
|
+
title: { type: 'string', description: 'Proposal title' },
|
|
1109
|
+
body: { type: 'string', description: 'Proposal body text or HTML' },
|
|
1110
|
+
excerpt: { type: 'string', description: 'Short summary' },
|
|
1111
|
+
payment_amount_cents: { type: 'number', description: 'Optional payment amount in cents' },
|
|
1112
|
+
currency: { type: 'string', description: "Currency code (default 'usd')" },
|
|
1113
|
+
expires_days: { type: 'number', description: 'Days until expiry (default 14)' },
|
|
1114
|
+
reason: { type: 'string', description: 'Context for approval queue' },
|
|
1115
|
+
sources: { type: 'array', items: { type: 'string' } },
|
|
1116
|
+
},
|
|
1117
|
+
required: ['contact_id', 'title', 'body'],
|
|
1118
|
+
},
|
|
1119
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
1120
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
1121
|
+
const title = String(args.title || '').trim();
|
|
1122
|
+
const body = String(args.body || '').trim();
|
|
1123
|
+
if (!title || !body) throw new Error('Missing required fields: title and body');
|
|
1124
|
+
return queueApprovalItem(
|
|
1125
|
+
ctx.profileId,
|
|
1126
|
+
'crm_create_proposal_draft',
|
|
1127
|
+
`Create proposal draft "${title}" for ${resolved.name}`,
|
|
1128
|
+
{ ...args, contact_id: resolved.id },
|
|
1129
|
+
String(args.reason || 'Proposal draft prepared for review'),
|
|
1130
|
+
Array.isArray(args.sources) ? args.sources.map(String) : [],
|
|
1131
|
+
resolved.id,
|
|
1132
|
+
`proposal_draft:${ctx.profileId}:${resolved.id}:${title.toLowerCase()}`
|
|
1133
|
+
);
|
|
1134
|
+
},
|
|
1135
|
+
},
|
|
1136
|
+
{
|
|
1137
|
+
name: 'crm_draft_followup',
|
|
1138
|
+
domain: 'crm',
|
|
1139
|
+
description: "Save an email follow-up draft for a contact in Inbox (author='agent', send_status='draft'). Never sends email.",
|
|
1140
|
+
inputSchema: {
|
|
1141
|
+
type: 'object',
|
|
1142
|
+
properties: {
|
|
1143
|
+
contact_id: { type: 'string', description: 'Contact ID or email' },
|
|
1144
|
+
thread_id: { type: 'string', description: 'Optional existing Inbox thread ID' },
|
|
1145
|
+
mailbox_id: { type: 'string', description: 'Optional Inbox mailbox ID' },
|
|
1146
|
+
subject: { type: 'string', description: 'Email subject' },
|
|
1147
|
+
body: { type: 'string', description: 'Draft email body' },
|
|
1148
|
+
goal: { type: 'string', description: 'Goal/topic if body is generated' },
|
|
1149
|
+
},
|
|
1150
|
+
required: ['contact_id'],
|
|
1151
|
+
},
|
|
1152
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
1153
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
1154
|
+
if (!resolved.email) throw new Error('Contact does not have an email address');
|
|
1155
|
+
const voice = await loadBrandVoice(ctx.profileId);
|
|
1156
|
+
const subject = args.subject ? String(args.subject) : `Following up — ${resolved.name}`;
|
|
1157
|
+
const goal = String(args.goal || args.context || 'checking in on our next steps');
|
|
1158
|
+
const co = resolved.company ? ` (${resolved.company})` : '';
|
|
1159
|
+
const body =
|
|
1160
|
+
args.body && String(args.body).trim()
|
|
1161
|
+
? String(args.body)
|
|
1162
|
+
: `Hi ${resolved.name}${co},\n\nJust following up regarding ${goal}.\n\nLet me know what works best for you this week.\n\nBest,`;
|
|
1163
|
+
|
|
1164
|
+
const res = await saveInboxDraftForContact(
|
|
1165
|
+
ctx.profileId,
|
|
1166
|
+
resolved.id,
|
|
1167
|
+
resolved.email,
|
|
1168
|
+
args.thread_id,
|
|
1169
|
+
args.mailbox_id,
|
|
1170
|
+
subject,
|
|
1171
|
+
body
|
|
1172
|
+
);
|
|
1173
|
+
return { ...res, contact_id: resolved.id, brand_voice_used: voice };
|
|
1174
|
+
},
|
|
1175
|
+
},
|
|
1176
|
+
{
|
|
1177
|
+
name: 'crm_draft_payment_chase',
|
|
1178
|
+
domain: 'crm',
|
|
1179
|
+
description: "Save an unpaid/overdue invoice payment reminder draft in Inbox (author='agent', send_status='draft'). Never sends email.",
|
|
1180
|
+
inputSchema: {
|
|
1181
|
+
type: 'object',
|
|
1182
|
+
properties: {
|
|
1183
|
+
contact_id: { type: 'string', description: 'Contact ID or email' },
|
|
1184
|
+
invoice_id: { type: 'string', description: 'Optional invoice ID or number' },
|
|
1185
|
+
thread_id: { type: 'string', description: 'Optional Inbox thread ID' },
|
|
1186
|
+
mailbox_id: { type: 'string', description: 'Optional Inbox mailbox ID' },
|
|
1187
|
+
subject: { type: 'string', description: 'Optional custom subject' },
|
|
1188
|
+
body: { type: 'string', description: 'Optional custom body' },
|
|
1189
|
+
},
|
|
1190
|
+
required: ['contact_id'],
|
|
1191
|
+
},
|
|
1192
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
1193
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
1194
|
+
if (!resolved.email) throw new Error('Contact does not have an email address');
|
|
1195
|
+
const now = nowTs();
|
|
1196
|
+
const invFilter = args.invoice_id ? String(args.invoice_id) : null;
|
|
1197
|
+
|
|
1198
|
+
let invNumber = '';
|
|
1199
|
+
let amountDisplay = '';
|
|
1200
|
+
let daysPastDue = 0;
|
|
1201
|
+
|
|
1202
|
+
const crmRows = await query<any>(
|
|
1203
|
+
`SELECT id, invoice_number, total_cents, currency, due_at FROM crm_invoices
|
|
1204
|
+
WHERE profile_id = ? AND contact_id = ? AND (? IS NULL OR id = ? OR invoice_number = ?)
|
|
1205
|
+
AND status IN ('sent','viewed','overdue') AND paid_at IS NULL
|
|
1206
|
+
ORDER BY COALESCE(due_at, created_at) ASC LIMIT 1`,
|
|
1207
|
+
[ctx.profileId, resolved.id, invFilter, invFilter, invFilter]
|
|
1208
|
+
);
|
|
1209
|
+
if (crmRows.length > 0) {
|
|
1210
|
+
const r = crmRows[0];
|
|
1211
|
+
invNumber = r.invoice_number;
|
|
1212
|
+
amountDisplay = `${String(r.currency || 'usd').toUpperCase()} ${(Number(r.total_cents || 0) / 100).toFixed(2)}`;
|
|
1213
|
+
if (typeof r.due_at === 'number') daysPastDue = Math.floor(Math.max(0, now - r.due_at) / 86_400);
|
|
1214
|
+
} else {
|
|
1215
|
+
const shopRows = await query<any>(
|
|
1216
|
+
`SELECT d.doc_number, d.amount_due, d.currency, d.due_date
|
|
1217
|
+
FROM shop_documents d
|
|
1218
|
+
JOIN shop_customers c ON c.id = d.customer_id AND c.profile_id = d.profile_id
|
|
1219
|
+
WHERE d.profile_id = ? AND (c.contact_id = ? OR LOWER(c.email) = LOWER(?))
|
|
1220
|
+
AND d.doc_type = 'invoice' AND d.amount_due > 0 AND d.status NOT IN ('paid','cancelled','void')
|
|
1221
|
+
AND (? IS NULL OR d.id = ? OR d.doc_number = ?)
|
|
1222
|
+
ORDER BY d.doc_date ASC LIMIT 1`,
|
|
1223
|
+
[ctx.profileId, resolved.id, resolved.email, invFilter, invFilter, invFilter]
|
|
1224
|
+
);
|
|
1225
|
+
if (shopRows.length > 0) {
|
|
1226
|
+
const r = shopRows[0];
|
|
1227
|
+
invNumber = r.doc_number;
|
|
1228
|
+
amountDisplay = `${String(r.currency || 'INR').toUpperCase()} ${Number(r.amount_due || 0).toFixed(2)}`;
|
|
1229
|
+
if (typeof r.due_date === 'number') daysPastDue = Math.floor(Math.max(0, now - r.due_date) / 86_400);
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
if (!invNumber) throw new Error('No unpaid invoice found for this contact');
|
|
1234
|
+
const voice = await loadBrandVoice(ctx.profileId);
|
|
1235
|
+
const subject = args.subject ? String(args.subject) : `Reminder: Invoice ${invNumber} (${amountDisplay})`;
|
|
1236
|
+
const body =
|
|
1237
|
+
args.body && String(args.body).trim()
|
|
1238
|
+
? String(args.body)
|
|
1239
|
+
: daysPastDue > 0
|
|
1240
|
+
? `Hi ${resolved.name},\n\nFriendly reminder that invoice ${invNumber} for ${amountDisplay} is ${daysPastDue} day(s) past due.\n\nCould you let us know when payment is scheduled or if anything is needed from our side?\n\nThanks,`
|
|
1241
|
+
: `Hi ${resolved.name},\n\nChecking in on invoice ${invNumber} for ${amountDisplay}. Let us know if you need a fresh copy or payment link.\n\nThanks,`;
|
|
1242
|
+
|
|
1243
|
+
const res = await saveInboxDraftForContact(
|
|
1244
|
+
ctx.profileId,
|
|
1245
|
+
resolved.id,
|
|
1246
|
+
resolved.email,
|
|
1247
|
+
args.thread_id,
|
|
1248
|
+
args.mailbox_id,
|
|
1249
|
+
subject,
|
|
1250
|
+
body
|
|
1251
|
+
);
|
|
1252
|
+
return { ...res, invoice_number: invNumber, amount: amountDisplay, days_past_due: daysPastDue, brand_voice_used: voice };
|
|
1253
|
+
},
|
|
1254
|
+
},
|
|
1255
|
+
{
|
|
1256
|
+
name: 'crm_list_stages',
|
|
1257
|
+
domain: 'crm',
|
|
1258
|
+
description: 'List configured CRM deal pipeline stages.',
|
|
1259
|
+
inputSchema: { type: 'object', properties: {} },
|
|
1260
|
+
handler: async (_args: Record<string, any>, ctx: ToolContext) => {
|
|
1261
|
+
const rows = await query<{ pipeline_stages: string }>(
|
|
1262
|
+
'SELECT pipeline_stages FROM settings WHERE profile_id = ? LIMIT 1',
|
|
1263
|
+
[ctx.profileId]
|
|
1264
|
+
);
|
|
1265
|
+
let stages = ['new', 'contacted', 'proposal', 'negotiation', 'won', 'lost'];
|
|
1266
|
+
if (rows[0]?.pipeline_stages) {
|
|
1267
|
+
try {
|
|
1268
|
+
const parsed = JSON.parse(rows[0].pipeline_stages);
|
|
1269
|
+
if (Array.isArray(parsed) && parsed.length > 0) stages = parsed;
|
|
1270
|
+
} catch {
|
|
1271
|
+
// keep default
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
return { stages };
|
|
1275
|
+
},
|
|
1276
|
+
},
|
|
1277
|
+
{
|
|
1278
|
+
name: 'crm_set_stages',
|
|
1279
|
+
domain: 'crm',
|
|
1280
|
+
description: 'Configure the CRM deal pipeline stages in settings.pipeline_stages.',
|
|
1281
|
+
inputSchema: {
|
|
1282
|
+
type: 'object',
|
|
1283
|
+
properties: {
|
|
1284
|
+
stages: { type: 'array', items: { type: 'string' }, description: 'Ordered stage names' },
|
|
1285
|
+
},
|
|
1286
|
+
required: ['stages'],
|
|
1287
|
+
},
|
|
1288
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
1289
|
+
const stages = (Array.isArray(args.stages) ? args.stages : [])
|
|
1290
|
+
.map((s: any) => String(s).trim())
|
|
1291
|
+
.filter(Boolean);
|
|
1292
|
+
if (stages.length === 0) throw new Error('stages must contain at least one stage name');
|
|
1293
|
+
const sid = generateId('set');
|
|
1294
|
+
await execute(
|
|
1295
|
+
"INSERT OR IGNORE INTO settings (id, profile_id, timezone, language, theme, updated_at) VALUES (?, ?, 'UTC', 'en', 'system', strftime('%s','now'))",
|
|
1296
|
+
[sid, ctx.profileId]
|
|
1297
|
+
);
|
|
1298
|
+
await execute(
|
|
1299
|
+
"UPDATE settings SET pipeline_stages = ?, updated_at = strftime('%s','now') WHERE profile_id = ?",
|
|
1300
|
+
[JSON.stringify(stages), ctx.profileId]
|
|
1301
|
+
);
|
|
1302
|
+
return { stages, status: 'updated' };
|
|
1303
|
+
},
|
|
1304
|
+
},
|
|
1305
|
+
{
|
|
1306
|
+
name: 'crm_create_group',
|
|
1307
|
+
domain: 'crm',
|
|
1308
|
+
description: 'Create a named CRM contact group (e.g. Clients, VIP, Retainers).',
|
|
1309
|
+
inputSchema: {
|
|
1310
|
+
type: 'object',
|
|
1311
|
+
properties: {
|
|
1312
|
+
name: { type: 'string', description: 'Group name' },
|
|
1313
|
+
icon: { type: 'string', description: 'Optional emoji/icon' },
|
|
1314
|
+
color: { type: 'string', description: 'Optional hex color' },
|
|
1315
|
+
},
|
|
1316
|
+
required: ['name'],
|
|
1317
|
+
},
|
|
1318
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
1319
|
+
const name = String(args.name || '').trim();
|
|
1320
|
+
if (!name) throw new Error('Missing required field: name');
|
|
1321
|
+
const existing = await query<{ id: string }>(
|
|
1322
|
+
'SELECT id FROM crm_groups WHERE profile_id = ? AND LOWER(name) = LOWER(?) LIMIT 1',
|
|
1323
|
+
[ctx.profileId, name]
|
|
1324
|
+
);
|
|
1325
|
+
if (existing.length > 0) return { group_id: existing[0].id, name, status: 'already_exists' };
|
|
1326
|
+
const groupId = generateId('grp');
|
|
1327
|
+
await execute(
|
|
1328
|
+
"INSERT INTO crm_groups (id, profile_id, name, icon, color, contact_count, created_at) VALUES (?, ?, ?, ?, ?, 0, strftime('%s','now'))",
|
|
1329
|
+
[groupId, ctx.profileId, name, args.icon ?? null, args.color ?? null]
|
|
1330
|
+
);
|
|
1331
|
+
return { group_id: groupId, name, status: 'created' };
|
|
1332
|
+
},
|
|
1333
|
+
},
|
|
1334
|
+
{
|
|
1335
|
+
name: 'crm_add_to_group',
|
|
1336
|
+
domain: 'crm',
|
|
1337
|
+
description: 'Add a CRM contact to a contact group.',
|
|
1338
|
+
inputSchema: {
|
|
1339
|
+
type: 'object',
|
|
1340
|
+
properties: {
|
|
1341
|
+
contact_id: { type: 'string', description: 'Contact ID or email' },
|
|
1342
|
+
group_id: { type: 'string', description: 'Group ID or name' },
|
|
1343
|
+
group_name: { type: 'string', description: 'Alternative group name' },
|
|
1344
|
+
},
|
|
1345
|
+
required: ['contact_id'],
|
|
1346
|
+
},
|
|
1347
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
1348
|
+
const resolved = await resolveContactId(ctx.profileId, String(args.contact_id));
|
|
1349
|
+
const groupRef = String(args.group_id || args.group_name || '').trim();
|
|
1350
|
+
if (!groupRef) throw new Error('Missing required field: group_id or group_name');
|
|
1351
|
+
const groups = await query<{ id: string; name: string }>(
|
|
1352
|
+
'SELECT id, name FROM crm_groups WHERE profile_id = ? AND (id = ? OR LOWER(name) = LOWER(?)) LIMIT 1',
|
|
1353
|
+
[ctx.profileId, groupRef, groupRef]
|
|
1354
|
+
);
|
|
1355
|
+
if (groups.length === 0) throw new Error(`Group not found: ${groupRef}`);
|
|
1356
|
+
const group = groups[0];
|
|
1357
|
+
|
|
1358
|
+
await execute(
|
|
1359
|
+
"INSERT OR IGNORE INTO crm_contact_groups (contact_id, group_id, added_at) VALUES (?, ?, strftime('%s','now'))",
|
|
1360
|
+
[resolved.id, group.id]
|
|
1361
|
+
);
|
|
1362
|
+
const cRows = await query<{ groups: string }>('SELECT groups FROM crm_contacts WHERE id = ? AND profile_id = ? LIMIT 1', [
|
|
1363
|
+
resolved.id, ctx.profileId,
|
|
1364
|
+
]);
|
|
1365
|
+
let arr: string[] = [];
|
|
1366
|
+
try {
|
|
1367
|
+
arr = JSON.parse(cRows[0]?.groups || '[]');
|
|
1368
|
+
} catch {
|
|
1369
|
+
arr = [];
|
|
1370
|
+
}
|
|
1371
|
+
if (!arr.includes(group.id)) {
|
|
1372
|
+
arr.push(group.id);
|
|
1373
|
+
await execute("UPDATE crm_contacts SET groups = ?, updated_at = strftime('%s','now') WHERE id = ? AND profile_id = ?", [
|
|
1374
|
+
JSON.stringify(arr), resolved.id, ctx.profileId,
|
|
1375
|
+
]);
|
|
1376
|
+
}
|
|
1377
|
+
await execute(
|
|
1378
|
+
'UPDATE crm_groups SET contact_count = (SELECT COUNT(*) FROM crm_contact_groups WHERE group_id = ?) WHERE id = ?',
|
|
1379
|
+
[group.id, group.id]
|
|
1380
|
+
);
|
|
1381
|
+
return { contact_id: resolved.id, group_id: group.id, group_name: group.name, status: 'added' };
|
|
1382
|
+
},
|
|
1383
|
+
},
|
|
1384
|
+
{
|
|
1385
|
+
name: 'crm_create_template',
|
|
1386
|
+
domain: 'crm',
|
|
1387
|
+
description: 'Create a reusable outreach or follow-up template in crm_templates.',
|
|
1388
|
+
inputSchema: {
|
|
1389
|
+
type: 'object',
|
|
1390
|
+
properties: {
|
|
1391
|
+
name: { type: 'string', description: 'Template name' },
|
|
1392
|
+
template_type: { type: 'string', enum: ['email', 'dm', 'follow_up', 'proposal'] },
|
|
1393
|
+
subject: { type: 'string', description: 'Subject template' },
|
|
1394
|
+
body: { type: 'string', description: 'Body template' },
|
|
1395
|
+
platform: { type: 'string', description: 'Optional platform' },
|
|
1396
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
1397
|
+
},
|
|
1398
|
+
required: ['name', 'body'],
|
|
1399
|
+
},
|
|
1400
|
+
handler: async (args: Record<string, any>, ctx: ToolContext) => {
|
|
1401
|
+
const name = String(args.name || '').trim();
|
|
1402
|
+
const body = String(args.body || '').trim();
|
|
1403
|
+
if (!name || !body) throw new Error('Missing required fields: name and body');
|
|
1404
|
+
const tplId = generateId('tpl');
|
|
1405
|
+
const templateType = String(args.template_type || 'email');
|
|
1406
|
+
const tags = JSON.stringify(args.tags || []);
|
|
1407
|
+
const now = nowTs();
|
|
1408
|
+
await execute(
|
|
1409
|
+
`INSERT INTO crm_templates (id, profile_id, name, type, subject, body, platform, tags, created_at, updated_at)
|
|
1410
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
1411
|
+
[tplId, ctx.profileId, name, templateType, args.subject ?? null, body, args.platform ?? null, tags, now, now]
|
|
1412
|
+
);
|
|
1413
|
+
return { template_id: tplId, name, template_type: templateType, status: 'created' };
|
|
1414
|
+
},
|
|
1415
|
+
},
|
|
1416
|
+
];
|