@datasynx/agentic-crm 1.5.0 → 1.7.0
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/dist/cli.js +70 -76
- package/dist/cli.js.map +1 -1
- package/dist/daemon/worker.js +40 -1
- package/dist/daemon/worker.js.map +1 -1
- package/dist/{imap-o6PRuBvm.js → imap-BRgNh3T3.js} +2 -2
- package/dist/{imap-o6PRuBvm.js.map → imap-BRgNh3T3.js.map} +1 -1
- package/dist/imap-DzeqMdZ3.js +2 -0
- package/dist/{index-FzDsNSSb.d.ts → index-BBAlKZg6.d.ts} +3 -3
- package/dist/{index-FzDsNSSb.d.ts.map → index-BBAlKZg6.d.ts.map} +1 -1
- package/dist/{index-B5_QnkG8.d.cts → index-DcDaz_cu.d.cts} +16 -16
- package/dist/index-DcDaz_cu.d.cts.map +1 -0
- package/dist/index.d.cts +16 -16
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/{knowledge-base-Bx2PKQR2.js → knowledge-base-Cc0niBFf.js} +2 -1
- package/dist/knowledge-base-Cc0niBFf.js.map +1 -0
- package/dist/{login-CYgla6-A.js → login-yt9OOQQk.js} +3 -2
- package/dist/{login-CYgla6-A.js.map → login-yt9OOQQk.js.map} +1 -1
- package/dist/mailbox-config-Bu-J1O4I.js +2 -0
- package/dist/mailbox-config-Dn2xTn9N.js +67 -0
- package/dist/mailbox-config-Dn2xTn9N.js.map +1 -0
- package/dist/mailbox-poll-B8dvFAXT.js +80 -0
- package/dist/mailbox-poll-B8dvFAXT.js.map +1 -0
- package/dist/mcp-CdTJWTJf.d.cts.map +1 -1
- package/dist/mcp-CdTJWTJf.d.ts.map +1 -1
- package/dist/mcp.cjs +289 -130
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts.map +1 -1
- package/dist/mcp.d.ts.map +1 -1
- package/dist/mcp.js +289 -130
- package/dist/mcp.js.map +1 -1
- package/dist/{microsoft-DgbVlHdT.js → microsoft-dsC1fQQG.js} +2 -38
- package/dist/microsoft-dsC1fQQG.js.map +1 -0
- package/dist/{server-uqXUhF4H.js → server-BbInMUgp.js} +172 -130
- package/dist/server-BbInMUgp.js.map +1 -0
- package/dist/snapshots-B6aOhoXs.js +2 -0
- package/dist/snapshots-CQSOaIMs.js +161 -0
- package/dist/snapshots-CQSOaIMs.js.map +1 -0
- package/dist/{token-resolver-BRLOmRvF.js → token-resolver-D98qPOOf.js} +3 -2
- package/dist/{token-resolver-BRLOmRvF.js.map → token-resolver-D98qPOOf.js.map} +1 -1
- package/dist/token-store-B0h0USqe.js +43 -0
- package/dist/token-store-B0h0USqe.js.map +1 -0
- package/dist/token-store-CEmz8d-0.js +2 -0
- package/package.json +2 -2
- package/dist/index-B5_QnkG8.d.cts.map +0 -1
- package/dist/knowledge-base-Bx2PKQR2.js.map +0 -1
- package/dist/microsoft-DgbVlHdT.js.map +0 -1
- package/dist/server-uqXUhF4H.js.map +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -42,8 +42,8 @@ declare const GlobalSourcesSchema: z.ZodObject<{
|
|
|
42
42
|
version: z.ZodDefault<z.ZodNumber>;
|
|
43
43
|
created: z.ZodString;
|
|
44
44
|
}, "strip", z.ZodTypeAny, {
|
|
45
|
-
created: string;
|
|
46
45
|
version: number;
|
|
46
|
+
created: string;
|
|
47
47
|
gmail?: {
|
|
48
48
|
type: "gmail";
|
|
49
49
|
query: string;
|
|
@@ -95,12 +95,12 @@ declare const MainFactsSchema: z.ZodObject<{
|
|
|
95
95
|
created: z.ZodEffects<z.ZodString, string, unknown>;
|
|
96
96
|
updated: z.ZodEffects<z.ZodString, string, unknown>;
|
|
97
97
|
}, "strip", z.ZodTypeAny, {
|
|
98
|
+
created: string;
|
|
98
99
|
name: string;
|
|
100
|
+
relationship_stage: "prospect" | "active" | "churned" | "paused";
|
|
99
101
|
currency: string;
|
|
100
|
-
updated: string;
|
|
101
|
-
created: string;
|
|
102
102
|
tags: string[];
|
|
103
|
-
|
|
103
|
+
updated: string;
|
|
104
104
|
domain?: string | undefined;
|
|
105
105
|
email?: string | undefined;
|
|
106
106
|
phone?: string | undefined;
|
|
@@ -111,17 +111,17 @@ declare const MainFactsSchema: z.ZodObject<{
|
|
|
111
111
|
}, {
|
|
112
112
|
name: string;
|
|
113
113
|
relationship_stage: "prospect" | "active" | "churned" | "paused";
|
|
114
|
-
currency?: string | undefined;
|
|
115
|
-
updated?: unknown;
|
|
116
114
|
created?: unknown;
|
|
117
|
-
tags?: string[] | undefined;
|
|
118
115
|
domain?: string | undefined;
|
|
119
116
|
email?: string | undefined;
|
|
120
117
|
phone?: string | undefined;
|
|
121
118
|
industry?: string | undefined;
|
|
122
119
|
deal_value?: number | undefined;
|
|
120
|
+
currency?: string | undefined;
|
|
123
121
|
primary_contact?: string | undefined;
|
|
124
122
|
timezone?: string | undefined;
|
|
123
|
+
tags?: string[] | undefined;
|
|
124
|
+
updated?: unknown;
|
|
125
125
|
}>;
|
|
126
126
|
type MainFacts = z.infer<typeof MainFactsSchema>;
|
|
127
127
|
//# sourceMappingURL=main-facts.d.ts.map
|
|
@@ -140,8 +140,8 @@ declare const InteractionEntrySchema: z.ZodObject<{
|
|
|
140
140
|
sourceRef: z.ZodString;
|
|
141
141
|
synced: z.ZodString;
|
|
142
142
|
}, "strip", z.ZodTypeAny, {
|
|
143
|
-
type: "Email" | "Call" | "Meeting" | "Note" | "Demo" | "Proposal" | "Contract" | "Other";
|
|
144
143
|
date: string;
|
|
144
|
+
type: "Email" | "Call" | "Meeting" | "Note" | "Demo" | "Proposal" | "Contract" | "Other";
|
|
145
145
|
with: string;
|
|
146
146
|
summary: string;
|
|
147
147
|
nextSteps: string[];
|
|
@@ -151,8 +151,8 @@ declare const InteractionEntrySchema: z.ZodObject<{
|
|
|
151
151
|
subject?: string | undefined;
|
|
152
152
|
attachments?: string[] | undefined;
|
|
153
153
|
}, {
|
|
154
|
-
type: "Email" | "Call" | "Meeting" | "Note" | "Demo" | "Proposal" | "Contract" | "Other";
|
|
155
154
|
date: string;
|
|
155
|
+
type: "Email" | "Call" | "Meeting" | "Note" | "Demo" | "Proposal" | "Contract" | "Other";
|
|
156
156
|
with: string;
|
|
157
157
|
summary: string;
|
|
158
158
|
sourceRef: string;
|
|
@@ -177,17 +177,17 @@ declare const PipelineDealSchema: z.ZodObject<{
|
|
|
177
177
|
updated: z.ZodString;
|
|
178
178
|
}, "strip", z.ZodTypeAny, {
|
|
179
179
|
name: string;
|
|
180
|
-
stage: "lead" | "qualified" | "proposal" | "negotiation" | "won" | "lost";
|
|
181
180
|
currency: string;
|
|
182
181
|
updated: string;
|
|
182
|
+
stage: "lead" | "qualified" | "proposal" | "negotiation" | "won" | "lost";
|
|
183
183
|
value?: number | undefined;
|
|
184
184
|
probability?: number | undefined;
|
|
185
185
|
close_date?: string | undefined;
|
|
186
186
|
notes?: string | undefined;
|
|
187
187
|
}, {
|
|
188
188
|
name: string;
|
|
189
|
-
stage: "lead" | "qualified" | "proposal" | "negotiation" | "won" | "lost";
|
|
190
189
|
updated: string;
|
|
190
|
+
stage: "lead" | "qualified" | "proposal" | "negotiation" | "won" | "lost";
|
|
191
191
|
value?: number | undefined;
|
|
192
192
|
currency?: string | undefined;
|
|
193
193
|
probability?: number | undefined;
|
|
@@ -212,19 +212,19 @@ declare const TicketSchema: z.ZodObject<{
|
|
|
212
212
|
description: z.ZodOptional<z.ZodString>;
|
|
213
213
|
}, "strip", z.ZodTypeAny, {
|
|
214
214
|
status: "open" | "in-progress" | "waiting" | "resolved" | "closed";
|
|
215
|
+
created: string;
|
|
215
216
|
id: string;
|
|
216
217
|
title: string;
|
|
217
218
|
priority: "urgent" | "high" | "normal" | "low";
|
|
218
|
-
created: string;
|
|
219
219
|
resolved?: string | undefined;
|
|
220
220
|
assignee?: string | undefined;
|
|
221
221
|
slaDue?: string | undefined;
|
|
222
222
|
description?: string | undefined;
|
|
223
223
|
}, {
|
|
224
224
|
status: "open" | "in-progress" | "waiting" | "resolved" | "closed";
|
|
225
|
+
created: string;
|
|
225
226
|
id: string;
|
|
226
227
|
title: string;
|
|
227
|
-
created: string;
|
|
228
228
|
resolved?: string | undefined;
|
|
229
229
|
priority?: "urgent" | "high" | "normal" | "low" | undefined;
|
|
230
230
|
assignee?: string | undefined;
|
|
@@ -345,11 +345,11 @@ declare const KbArticleSchema: z.ZodObject<{
|
|
|
345
345
|
updatedAt: z.ZodString;
|
|
346
346
|
sourceTicketId: z.ZodOptional<z.ZodString>;
|
|
347
347
|
}, "strip", z.ZodTypeAny, {
|
|
348
|
+
tags: string[];
|
|
348
349
|
id: string;
|
|
349
350
|
title: string;
|
|
350
351
|
createdAt: string;
|
|
351
352
|
category: string;
|
|
352
|
-
tags: string[];
|
|
353
353
|
public: boolean;
|
|
354
354
|
updatedAt: string;
|
|
355
355
|
sourceTicketId?: string | undefined;
|
|
@@ -358,8 +358,8 @@ declare const KbArticleSchema: z.ZodObject<{
|
|
|
358
358
|
title: string;
|
|
359
359
|
createdAt: string;
|
|
360
360
|
updatedAt: string;
|
|
361
|
-
category?: string | undefined;
|
|
362
361
|
tags?: string[] | undefined;
|
|
362
|
+
category?: string | undefined;
|
|
363
363
|
public?: boolean | undefined;
|
|
364
364
|
sourceTicketId?: string | undefined;
|
|
365
365
|
}>;
|
|
@@ -543,4 +543,4 @@ declare const VERSION = "0.1.0";
|
|
|
543
543
|
|
|
544
544
|
//#endregion
|
|
545
545
|
export { type GlobalSources, type InteractionEntry, type KbArticle, type MainFacts, type PipelineDeal, type QuoteLineItem, type Quote as QuoteRecord, type SurveyDefinition, type SurveyResponse, type TicketPriority, type Ticket as TicketRecord, type TicketStatus, VERSION, canSeeCustomer, clearSession, createCustomer, customerExists, filterAuditLog, getRbacConfig, getRole, getSession, readAuditLog, readMainFacts, runAudit, runBackup, runValidate, setSession };
|
|
546
|
-
//# sourceMappingURL=index-
|
|
546
|
+
//# sourceMappingURL=index-DcDaz_cu.d.cts.map
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-
|
|
1
|
+
{"version":3,"file":"index-DcDaz_cu.d.cts","names":[],"sources":["../src/schemas/sources.ts","../src/schemas/main-facts.ts","../src/schemas/interaction.ts","../src/schemas/pipeline.ts","../src/schemas/ticket.ts","../src/schemas/quote.ts","../src/schemas/kb-article.ts","../src/schemas/survey.ts","../src/commands/create.ts","../src/commands/backup.ts","../src/commands/audit.ts","../src/commands/validate.ts","../src/fs/customer-dir.ts","../src/fs/audit-log.ts","../src/core/rbac.ts","../src/core/session-store.ts","../src/version.ts"],"mappings":";;;;cAea,qBAAmB,CAAA,CAAA;;IAAA,IAAA,cAAA,CAAA,OAAA,CAAA;IAAA,KAAA,aAAA;IAUpB,OAAA,cAAa,aAAA,CAAA;EAAA,CAAA,EAAA,OAAA,cAAA,EAAA;IAAkB,IAAA,EAAA,OAAA;IAAf,KAAE,EAAA,MAAA;IAAK,OAAA,EAAA,OAAA;;;;ICvBtB,OAAA,CAAA,EAAA,OAoBX,GAAA,SAAA;EAAA,CAAA,CAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;SApB0B,EAAA,MAAA;EAAA,OAAA,EAAA,MAAA;EAsBhB,KAAA,CAAA,EAAA;IAAS,IAAA,EAAA,OAAA;IAAkB,KAAA,EAAA,MAAA;IAAf,OAAE,EAAA,OAAA;EAAK,CAAA,GAAA,SAAA;;;;ECtBlB,WAAA,CAAA,EAAA;IAYX,IAAA,EAAA,YAAA;;;;;;;;;;;;;;;;;;IAZiC,OAAA,CAAA,EAAA,OAAA,GAAA,SAAA;IAAA,UAAA,CAAA,EAAA,MAAA,EAAA,GAAA,SAAA;EAcvB,CAAA,GAAA,SAAA;EAAgB,OAAA,CAAA,EAAA,MAAA,GAAA,SAAA;;KFShB,aAAA,GAAgB,CAAA,CAAE,aAAa;;;;cCvB9B,iBAAe,CAAA,CAAA;;EDaf,MAAA,eAAA,YAMX,CAAA;EAAA,KA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;;;;IAER;;;;KC/DS,IAAA;UAEK,UAAA;UACP,eAAe;EdQZ,OAAA,CAAA,EcPD,IdOC;EAMX,eAAA,CAAA,EcZkB,MdYlB,CAAA,MAAA,EAAA,MAAA,EAAA,CAAA;;ccVY,eAAe;;iBAsBb,aAAA,mBAAgC;iBAUhC,OAAA,kCAAyC;iBAuBzC,cAAA;;;;;;;;UClEC,OAAA;;;EfeJ,SAAA,EAAA,MAAA;EAMX,KAAA,CAAA,EAAA,MAAA;;iBeZc,UAAA,IAAc;iBAId,UAAA,CAAA,GAAc;iBAId,YAAA,CAAA;;;;cCjBH,OAAA"}
|
package/dist/index.d.ts
CHANGED
|
@@ -141,8 +141,8 @@ declare const InteractionEntrySchema: z.ZodObject<{
|
|
|
141
141
|
sourceRef: z.ZodString;
|
|
142
142
|
synced: z.ZodString;
|
|
143
143
|
}, "strip", z.ZodTypeAny, {
|
|
144
|
-
date: string;
|
|
145
144
|
type: "Email" | "Call" | "Meeting" | "Note" | "Demo" | "Proposal" | "Contract" | "Other";
|
|
145
|
+
date: string;
|
|
146
146
|
with: string;
|
|
147
147
|
summary: string;
|
|
148
148
|
nextSteps: string[];
|
|
@@ -152,8 +152,8 @@ declare const InteractionEntrySchema: z.ZodObject<{
|
|
|
152
152
|
subject?: string | undefined;
|
|
153
153
|
attachments?: string[] | undefined;
|
|
154
154
|
}, {
|
|
155
|
-
date: string;
|
|
156
155
|
type: "Email" | "Call" | "Meeting" | "Note" | "Demo" | "Proposal" | "Contract" | "Other";
|
|
156
|
+
date: string;
|
|
157
157
|
with: string;
|
|
158
158
|
summary: string;
|
|
159
159
|
sourceRef: string;
|
|
@@ -544,4 +544,4 @@ declare const VERSION = "0.1.0";
|
|
|
544
544
|
|
|
545
545
|
//#endregion
|
|
546
546
|
export { type GlobalSources, type InteractionEntry, type KbArticle, type MainFacts, type PipelineDeal, type QuoteLineItem, type Quote as QuoteRecord, type SurveyDefinition, type SurveyResponse, type TicketPriority, type Ticket as TicketRecord, type TicketStatus, VERSION, canSeeCustomer, clearSession, createCustomer, customerExists, filterAuditLog, getRbacConfig, getRole, getSession, readAuditLog, readMainFacts, runAudit, runBackup, runValidate, setSession };
|
|
547
|
-
//# sourceMappingURL=index-
|
|
547
|
+
//# sourceMappingURL=index-BBAlKZg6.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-
|
|
1
|
+
{"version":3,"file":"index-BBAlKZg6.d.ts","names":[],"sources":["../src/schemas/sources.ts","../src/schemas/main-facts.ts","../src/schemas/interaction.ts","../src/schemas/pipeline.ts","../src/schemas/ticket.ts","../src/schemas/quote.ts","../src/schemas/kb-article.ts","../src/schemas/survey.ts","../src/commands/create.ts","../src/commands/backup.ts","../src/commands/audit.ts","../src/commands/validate.ts","../src/fs/customer-dir.ts","../src/fs/audit-log.ts","../src/core/rbac.ts","../src/core/session-store.ts","../src/version.ts"],"mappings":";;;;;cAea,qBAAmB,CAAA,CAAA;;;IAAA,KAAA,aAAA;IAAA,OAAA,cAAA,aAAA,CAAA;EAUpB,CAAA,EAAA,OAAA,cAAa,EAAA;IAAA,IAAA,EAAA,OAAA;IAAkB,KAAA,EAAA,MAAA;IAAf,OAAE,EAAA,OAAA;EAAK,CAAA,EAAA;;;;ECvBtB,CAAA,CAAA,CAAA;EAoBX,QAAA,eAAA,YAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;SApB0B,EAAA,MAAA;EAAA,KAAA,CAAA,EAAA;IAsBhB,IAAA,EAAA,OAAS;IAAA,KAAA,EAAA,MAAA;IAAkB,OAAA,EAAA,OAAA;MAAf,SAAE;EAAK,QAAA,CAAA,EAAA;;;;ICtBlB,IAAA,EAAA,YAAA;IAYX,OAAA,EAAA,OAAA;;;;;;;;;;;;;;;;;;IAZiC,UAAA,CAAA,EAAA,MAAA,EAAA,GAAA,SAAA;EAAA,CAAA,GAAA,SAAA;EAcvB,OAAA,CAAA,EAAA,MAAA,GAAgB,SA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A,MAAA,EAAA,CAAA;EAAA;ccVY,eAAe;;iBAsBb,aAAA,mBAAgC;iBAUhC,OAAA,kCAAyC;iBAuBzC,cAAA;;;;;;;;UClEC,OAAA;;;;EfeJ,KAAA,CAAA,EAAA,MAAA;;iBeNG,UAAA,IAAc;iBAId,UAAA,CAAA,GAAc;iBAId,YAAA,CAAA;;;;cCjBH,OAAA"}
|
|
@@ -102,6 +102,7 @@ Config: \`.agentic/rbac.json\` | Actor: \`DXCRM_ACTOR\` env var
|
|
|
102
102
|
| get_audit_log | Read audit log — all write operations with actor, tool, customer | admin |
|
|
103
103
|
| get_logs | Query/aggregate the structured application log (level, component, errors) | admin |
|
|
104
104
|
| get_diagnostics | Self-diagnostic health check (data integrity, temp files, log errors, backups) | admin |
|
|
105
|
+
| get_pipeline_changes | Pipeline time-travel: what changed (won/lost/moved/value) since a date | any |
|
|
105
106
|
| define_custom_object | Define a runtime custom object type with typed fields (no migration) | admin |
|
|
106
107
|
| create_record | Create a record of a custom object (validated against its schema) | rep+ |
|
|
107
108
|
| list_records | List records of a custom object | any |
|
|
@@ -1040,4 +1041,4 @@ function getKbMetaForExport(article) {
|
|
|
1040
1041
|
//#endregion
|
|
1041
1042
|
export { searchKbSimple as a, listKbArticles as i, getKbArticle as n, writeKbArticle as o, getKbMetaForExport as r, CAPABILITIES_TEXT as s, deleteKbArticle as t };
|
|
1042
1043
|
|
|
1043
|
-
//# sourceMappingURL=knowledge-base-
|
|
1044
|
+
//# sourceMappingURL=knowledge-base-Cc0niBFf.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"knowledge-base-Cc0niBFf.js","names":[],"sources":["../src/mcp/capabilities.ts","../src/schemas/kb-article.ts","../src/fs/knowledge-base.ts"],"sourcesContent":["// src/mcp/capabilities.ts\n// Single Source of Truth for capability documentation.\n// Used by get_capabilities() MCP tool AND dxcrm guide CLI command.\n\nexport const CAPABILITIES_TEXT = `\n# DatasynxOpenCRM — Agent Guide\n\n## Product\nDatasynxOpenCRM is a local-first, MCP-native CRM. All customer data lives in markdown\nfiles on your machine. No cloud, no HubSpot, no per-seat pricing.\n\n## Agent Wake (Telegram Notifications)\n\\`dxcrm agent spawn\\` enables a wake-triggered agent for a customer. When new emails arrive,\nthe agent sends a Telegram notification so you never miss an inbound message.\n\\`\\`\\`\ndxcrm agent spawn acme-corp --channel telegram\n\\`\\`\\`\nRequires: \\`TELEGRAM_BOT_TOKEN\\` + \\`TELEGRAM_CHAT_ID\\` env vars.\n\n## Golden Path — Agent Session Workflow\n\nThe recommended sequence for a productive agent session:\n\n1. \\`get_capabilities()\\` — understand available tools (this guide)\n2. \\`get_active_session()\\` — check for an active customer session\n3. \\`get_customer_context({ slug })\\` — load full briefing for the customer\n4. \\`search_customer_knowledge({ slug, query })\\` — find specific historical information\n5. \\`log_interaction()\\` / \\`update_deal()\\` — write back what happened\n\n## RBAC — Role-Based Access Control\n\nTools enforce the \\`DXCRM_ACTOR\\` environment variable for identity. Configure roles with \\`dxcrm rbac set\\`.\n\n| Role | Permissions |\n|---|---|\n| admin | All tools, all customers |\n| manager | log_interaction, update_deal, pursue_goal + all read tools |\n| rep | log_interaction, update_deal (own customers only) + all read tools |\n\nDefault role: rep (when DXCRM_ACTOR is not set or has no assigned role).\n\nConfig: \\`.agentic/rbac.json\\` | Actor: \\`DXCRM_ACTOR\\` env var\n\n## Available Tools\n\n| Tool | Purpose | RBAC |\n|---|---|---|\n| get_capabilities | Returns this guide — understand what the CRM can do | any |\n| get_active_session | Check which customer session is currently active | any |\n| get_customer_context | Full LLM-ready briefing for a customer (last 10 interactions, pipeline, contacts) | any (rep: own only) |\n| search_customer_knowledge | Hybrid vector + full-text search across emails and transcripts for a customer | any |\n| list_customers | List all customers with stage, last interaction date, and deal value | any (rep: own only) |\n| log_interaction | Write a new interaction entry (call, email, meeting, note) — immediately searchable | rep+ |\n| update_deal | Create or update a deal in pipeline.md — upserts by deal name | rep+ |\n| update_customer_facts | Update fields in customer profile (domain, contact, stage, tags) | admin |\n| export_customer | Export all customer data (incl. attachment contents) as JSON or Markdown | admin |\n| get_deal_health | Score deal health 0–100 (A–F grade) based on activity, velocity, close date, probability | any |\n| get_pipeline_forecast | Aggregate weighted pipeline revenue across all customers grouped by stage | any |\n| get_pipeline_stages | List all configured pipeline stages (defaults: lead, qualified, proposal, negotiation, won, lost) | any |\n| summarize_meeting | LLM-summarize a transcript and log it as a Meeting interaction | rep+ |\n| get_market_intelligence | Semantic search across all customers for patterns and common topics | any |\n| get_relationship_graph | Stakeholder map: champions, blockers, economic buyers, warm intro paths | any |\n| get_relationship_health | Health scores (0–100, A–F, trend) per contact with decay detection and risk flags | any |\n| run_deal_agent | Analyze deal and generate prioritized action plan (observe/suggest/act autonomy levels) | rep+ |\n| approve_agent_action | Approve or reject a pending action from the deal agent queue | rep+ |\n| simulate_revenue | Monte Carlo pipeline forecast — P10/P50/P90, sensitivity map, at-risk revenue | any |\n| get_playbook | Retrieve playbooks matching current deal situation (trigger-matched, sorted by success rate) | any |\n| create_playbook | Create or update a playbook with trigger DSL encoding proven tactics | rep+ |\n| list_playbooks | List all playbooks for a customer (metadata only, no body) | any |\n| distill_playbook | LLM-extract a reusable playbook from a won or lost deal's interaction history | rep+ |\n| pursue_goal | Set a revenue/pipeline goal and get an AI-decomposed action plan with sub-goals | manager+ |\n| get_goal_status | Get all active goals or a specific goal with progress, days remaining, sub-goals | any |\n| register_push_subscription | Register real-time push subscription (Gmail Pub/Sub, MS Graph, Slack Events) | admin |\n| get_push_status | Show all push subscriptions: expiry, events processed, renewal needs | any |\n| get_org_intelligence | Stakeholder map with champions, buyers, blockers, health scores, risk flags, recommendation | any |\n| open_deal_room | Multi-agent deal brief: graph + health + deal health + simulation + playbook in one call | any |\n| get_proactive_briefing | Daily briefing: urgent alerts, opportunities, P50/P90 forecast, top action | any |\n| list_email_templates | List all saved email templates with id, name, category, subject | any |\n| get_email_template | Retrieve a single email template with full body and detected variables | any |\n| draft_email | Draft a personalized email from a template with auto-filled customer variables | rep+ |\n| enroll_in_sequence | Enroll a contact in a multi-step email sequence | rep+ |\n| list_sequence_enrollments | List active sequence enrollments filtered by customer or status | any |\n| unenroll_from_sequence | Pause (soft-unenroll) a contact from an active sequence | rep+ |\n| list_sequences | List all defined email sequences with step count and enrollment count | any |\n| generate_quote | Generate a professional HTML quote with line items, VAT, subtotal, total | rep+ |\n| get_quote_status | Retrieve a generated quote by number or list all quotes for a customer | any |\n| get_booking_link | Get a Calendly booking link for a customer — optionally pre-fills name/email | rep+ |\n| create_ticket | Create a support ticket with auto-calculated SLA due date based on priority | rep+ |\n| update_ticket | Update ticket status or assignee (resolved auto-sets resolution date) | rep+ |\n| list_tickets | List tickets filtered by customer, status, priority, or assignee | any |\n| close_ticket | Close a ticket and optionally log resolution as an interaction | rep+ |\n| send_nps_survey | Generate NPS/CSAT survey token + HTML email draft (does not send automatically) | rep+ |\n| get_survey_results | NPS score, promoter/passive/detractor breakdown, all responses for a survey | any |\n| search_knowledge_base | Full-text search across KB articles (title, body, tags) with category and public filters | any |\n| create_kb_article | Create a new knowledge base article stored as Markdown in .agentic/knowledge-base/ | rep+ |\n| backup_now | Trigger immediate backup of customers/ + .agentic/ with SHA-256 integrity check | admin |\n| list_backups | List available backups with date, size, verification status, and customer count | any |\n| trigger_sync | Force immediate Gmail sync for one or all customers | rep+ |\n| get_audit_log | Read audit log — all write operations with actor, tool, customer | admin |\n| get_logs | Query/aggregate the structured application log (level, component, errors) | admin |\n| get_diagnostics | Self-diagnostic health check (data integrity, temp files, log errors, backups) | admin |\n| get_pipeline_changes | Pipeline time-travel: what changed (won/lost/moved/value) since a date | any |\n| define_custom_object | Define a runtime custom object type with typed fields (no migration) | admin |\n| create_record | Create a record of a custom object (validated against its schema) | rep+ |\n| list_records | List records of a custom object | any |\n| list_custom_objects | List all defined custom objects and their schemas | any |\n\n## MCP Resources (read-only)\n\nBesides Tools, the server exposes read-only Resources you can fetch via resources/read:\n- crm://customers — list of all customer slugs (JSON)\n- crm://customer/{slug} — LLM-ready briefing (main facts, recent interactions, pipeline)\n- crm://pipeline/{slug} — deals for a customer (JSON)\n- crm://timeline/{slug} — newest-first interaction history (Markdown)\n\n## MCP Prompts (playbooks)\n\nReusable playbook prompts via prompts/get (argument: slug):\n- deal_risk_review — assess deal health and risk, recommend next steps\n- draft_follow_up — draft a personalized follow-up email\n- account_brief — concise executive account brief\n- pipeline_summary — pipeline + forecast summary\n\n## Tool Reference\n\n### get_capabilities()\nReturns all available MCP tools, their inputs, and the CRM workflow guide.\n- Input: none\n- Returns: This guide text\n\n### get_active_session()\nCheck which customer is currently active in the session store.\n- Input: none\n- Returns: { hasSession: boolean, customerSlug?, customerName?, startedAt?, owner? }\n\n### get_customer_context({ slug? })\nLoad complete briefing for a customer. Reads main_facts.md, last 10 interactions,\nand pipeline deals. Returns a structured markdown context block.\nAutomatically triggers a background Gmail sync if last sync was >30 minutes ago.\n- Input: { slug?: string } — Customer ID (e.g. \"acme-corp\"). Leave empty for active session.\n- Returns: Formatted markdown with Quick Reference, Contacts, Critical Context,\n Recent Activity, Pipeline, and Open Questions\n- Performance: <3 seconds. Token budget: <3000 tokens.\n\n### search_customer_knowledge({ slug, query, limit? })\nHybrid vector + full-text search across all emails and transcripts for a customer.\nSearches the LanceDB docs table for the given customer.\n- Input: { slug: string, query: string, limit?: number (default 5, max 50) }\n- Returns: { results: Array<{ content, score, source }> }\n\n### list_customers({ filter? })\nList all customers with their stage, last interaction date, and deal value.\nRBAC: rep role only sees owned customers.\n- Input: { filter?: string } — Optional substring filter on name or slug (case-insensitive)\n- Returns: Array of { slug, name, stage, lastInteraction?, dealValue? }\n\n### log_interaction({ slug, type, summary, with, nextSteps?, direction?, source?, date? })\nWrite a new interaction entry to interactions.md. Immediately searchable.\nAlso auto-updates the relationship graph and health scores (fire-and-forget).\nUse after every call, meeting, or email.\nRBAC: rep+\n- Input:\n slug: Customer ID\n type: \"Email\" | \"Call\" | \"Meeting\" | \"Note\" | \"Demo\" | \"Proposal\" | \"Contract\" | \"Other\"\n summary: 2-5 sentences describing what happened\n with: Who was involved (name or email)\n nextSteps?: Array of action items\n direction?: \"inbound\" | \"outbound\"\n source?: Source reference string (auto-generated if omitted)\n date?: Interaction date YYYY-MM-DD (defaults to today)\n- Returns: { success: boolean, path: string, entry: string }\n\n### update_deal({ slug, dealName, stage?, value?, probability?, closeDate?, notes? })\nUpdate or create a deal in pipeline.md. Upserts by deal name.\nRBAC: rep+\n- Input:\n slug: Customer ID\n dealName: Deal name (used as unique key)\n stage?: \"lead\" | \"qualified\" | \"proposal\" | \"negotiation\" | \"won\" | \"lost\"\n value?: Deal value in euros\n probability?: Win probability (0-100)\n closeDate?: Expected close date (YYYY-MM-DD)\n notes?: Free-text notes\n- Returns: { success: boolean, deal: object }\n\n### update_customer_facts({ slug, name?, domain?, email?, phone?, industry?, relationshipStage?, dealValue?, primaryContact?, timezone?, tags? })\nUpdate fields in a customer's main_facts.md profile. Merges patch into existing data. Sets updated = today.\nRBAC: admin\n- Input: slug (required) + any combination of the optional fields\n- Returns: { success: boolean, facts: object }\n\n### export_customer({ slug, format?, includeAttachmentContent? })\nExport all customer data (main_facts + interactions + pipeline + attachments).\nSet includeAttachmentContent to inline every attachment's converted Markdown —\na single sendable bundle of all conversations and documents for the customer.\nRBAC: admin\n- Input: { slug: string, format?: \"json\" | \"markdown\" (default \"json\"), includeAttachmentContent?: boolean (default false) }\n- Returns (JSON): { slug, exportedAt, mainFacts, interactionsCount, pipeline, attachments[, attachmentContents] }\n- Returns (Markdown): Formatted document with all sections (and attachment contents when requested)\n\n### get_deal_health({ slug })\nScore the health of all deals for a customer based on activity recency, stage velocity,\nclose date proximity, and probability.\n- Input: { slug: string }\n- Returns: { slug, deals: [{ deal, stage, score, grade, signals, warnings }] }\n\n### get_pipeline_forecast({ filter? })\nAggregate weighted pipeline revenue across all customers. Groups open deals by stage,\ncomputes probability-weighted expected revenue. Excludes won/lost deals.\n- Input: { filter?: string } — Optional filter by customer slug substring\n- Returns: { deals: [...], totalWeightedValue: number, byStage: { stage: { count, weightedValue } } }\n\n### get_pipeline_stages()\nReturns all configured pipeline stages. Falls back to default stages if no custom stages configured.\n- Input: none\n- Returns: { stages: [{ id, label, order, probability, color, final }] }\n\n### summarize_meeting({ slug, transcript, with?, date? })\nLLM-summarize a meeting transcript and log it as a Meeting interaction.\nFalls back to raw text slice if LLM unavailable.\nRBAC: rep+\n- Input:\n slug: Customer ID\n transcript: Full meeting transcript text\n with?: Participant names\n date?: Meeting date YYYY-MM-DD (defaults to today)\n- Returns: { success, summary, nextSteps, sourceRef }\n\n### get_market_intelligence({ query, excludeCurrentCustomer?, slug? })\nSearch across all customers to find patterns, common topics, or similar issues.\nUses semantic search (LanceDB) across all customer knowledge bases.\nResults use slug (not real names) for privacy.\n- Input: { query: string, excludeCurrentCustomer?: boolean, slug?: string }\n- Returns: { query, results: CrossCustomerResult[], totalCustomersSearched }\n\n### get_relationship_graph({ slug })\nReturns the knowledge graph for a customer: contacts, companies, and their relationships.\nAuto-populated from every log_interaction call. Shows stakeholder map with champions, blockers,\neconomic buyers, and warm intro paths.\n- Input: { slug: string }\n- Returns: { nodeCount, edgeCount, updatedAt, stakeholders: { champions[], blockers[], economicBuyers[], allContacts[], missingRoles[] }, warmIntroPaths[], nodes[], edges[] }\n\n### get_relationship_health({ slug })\nReturns health scores (0-100, A-F grade) for all contacts. Scores decay when cadence breaks.\nRisk flags: NO_CONTACT_14D, NO_CONTACT_30D, CHAMPION_SILENT.\nRecomputes automatically if stale (>1h) or missing.\n- Input: { slug: string }\n- Returns: { overallHealth, updatedAt, atRiskContacts[], coldContacts[], contacts: ContactHealth[] }\n\n### run_deal_agent({ slug, dealName, autonomyLevel?, instruction?, valueThreshold? })\nAnalyzes deal situation (health, relationships, stakeholder gaps) via LLM (rule-based fallback).\nReturns prioritized action plan with confidence scores and full reasoning trace.\nautonomyLevel: \"observe\" (read-only) | \"suggest\" (queue for review, default) | \"act\" (auto-execute if confidence ≥ 0.7 and value < valueThreshold)\nRBAC: rep+\n- Input: { slug, dealName, autonomyLevel?: \"observe\"|\"suggest\"|\"act\", instruction?, valueThreshold?: number (default 50000) }\n- Returns: { assessment, riskLevel, plan[], actionsQueued[], actionsExecuted[], trace }\n\n### approve_agent_action({ slug, actionId, approved })\nExecute (approved=true) or reject (approved=false) a pending deal agent action.\nFind actionId in run_deal_agent response.actionsQueued[].actionId\nRBAC: rep+\n- Input: { slug, actionId, approved: boolean }\n- Returns: { success, actionId, status }\n\n### simulate_revenue({ horizon?, iterations? })\nMonte Carlo simulation over all active deals. Adjusts probabilities via health score (D12) and\nchampion presence (D11). Returns P10/P50/P90 confidence interval + sensitivity map.\nhorizon: \"quarter\" (default) | \"year\"\n- Returns: { forecast: { p10, p50, p90, expected, stdDev, atRiskRevenue, byCloseMonth, topRisks, sensitivityMap }, confidence, dealCount, horizon }\n\n### get_playbook({ slug, stage?, value?, healthScore?, daysSinceContact?, championPresent? })\nReturns playbooks matching the current deal situation. Without deal context, returns all playbooks.\nPlaybooks are sorted by success rate (highest first). run_deal_agent uses playbooks automatically.\n- Input: slug (required) + optional deal context fields for trigger matching\n- Returns: { matches: [{ name, score, matchedConditions, trigger, successRate, usedCount, content }], totalPlaybooks, slug }\n\n### create_playbook({ slug, name, trigger, content, successRate? })\nCreate or update a playbook encoding proven tactics for a specific deal situation.\nTrigger DSL uses AND-only conditions: deal_stage_<s> | value > N | value < N | days_stalled > N | health < N | health > N | no_champion | has_champion\nRBAC: rep+\n- Input: slug, name, trigger (DSL string), content (markdown), successRate? (0–1, default 0.5)\n- Returns: { success: true, playbook: { name, trigger, successRate, usedCount, lastUpdated, path } }\n\n### list_playbooks({ slug })\nList all playbooks for a customer (metadata only — no body content for performance).\n- Input: { slug: string }\n- Returns: { playbooks: [{ name, trigger, successRate, usedCount, lastUpdated }], count, slug }\n\n### distill_playbook({ slug, dealName, outcome })\nLLM analyzes a deal's interaction history and extracts a reusable playbook.\nRun after every won or lost deal to build procedural memory.\nRBAC: rep+\noutcome: \"won\" | \"lost\"\n- Returns: { success: true, playbook: { name, trigger, successRate, path }, reasoning }\n\n### pursue_goal({ goal, deadline, context? })\nSet a revenue or pipeline goal and get an AI-decomposed action plan.\nAnalyzes current pipeline (P50 forecast) and decomposes the gap into prioritized sub-goals per deal.\nPersists goal to .agentic/goals.json for tracking.\nRBAC: manager+\n- Input: { goal: string, deadline: \"YYYY-MM-DD\", context?: string }\n- Returns: { goalId, description, target, deadline, decomposition: { analysis, currentPipeline, gap, subGoals, probabilisticOutcome } }\n\n### get_goal_status({ goalId? })\nGet the status of active goals. Without goalId, returns all active goals.\n- Input: { goalId?: string } — omit for all active goals\n- Returns: { goals: [{ id, description, target, progress, status, deadline, daysRemaining, subGoals }], activeCount, completedCount }\n\n### register_push_subscription({ provider, slug, webhookUrl, ... })\nRegister a real-time push subscription so providers send events in real-time (no polling).\nRBAC: admin only\n- Input:\n provider: \"gmail\" | \"microsoft-graph\" | \"slack\"\n slug: Customer slug to receive events for\n webhookUrl: Public HTTPS URL for provider callbacks\n gmailTopicName?: (Gmail) Cloud Pub/Sub topic name\n microsoftClientState?: (MS Graph) Secret for HMAC verification\n microsoftResource?: (MS Graph) Resource path\n slackTeamId?: (Slack) Workspace team ID\n slackChannelId?: (Slack) Optional specific channel\n- Returns: { subscriptionId, provider, slug, status, expiresAt, createdAt, warning? }\n\n### get_push_status({ slug?, provider? })\nShow all push subscriptions with expiry and event counts.\n- Input: { slug?: string, provider?: \"gmail\" | \"microsoft-graph\" | \"slack\" }\n- Returns: { subscriptions: [{ id, provider, slug, status, expiresAt, expiresInHours, needsRenewal, lastEventAt, eventsProcessed }], summary: { total, active, expiringSoon, expired } }\n\n### get_org_intelligence({ slug, dealName? })\nBuild a stakeholder map for a customer: champions, economic buyers, blockers, health scores, risk flags, and a prioritised recommendation.\n- Input: { slug: string, dealName?: string }\n- Returns: { slug, updatedAt, people: [{ name, email, role, healthScore, daysSinceContact, contactStrength, riskFlags }], missingRoles, riskAssessment, recommendation }\n\n### open_deal_room({ slug, dealName })\nMulti-agent deal brief: orchestrates relationship graph, health scores, deal health, Monte Carlo simulation, and playbook matching into a unified brief with executive summary, top priorities, and risk score (0–100).\n- Input: { slug: string, dealName: string }\n- Returns: { slug, dealName, generatedAt, stakeholders, relationshipHealth, dealHealth, revenueSimulation, recommendedPlaybook, executiveSummary, topPriorities, riskScore }\n\n### get_proactive_briefing({ date? })\nGenerate a proactive daily briefing: urgent alerts (relationship decay, deal risk, overdue close dates),\npipeline forecast (P50/P90), and a single top-action recommendation.\n- Input: { date?: \"YYYY-MM-DD\" } — defaults to today\n- Returns: { date, generatedAt, urgent: string[], opportunities: string[], forecast: string, topAction: string }\n\n### list_email_templates({ category? })\nList available email templates. Optionally filter by category.\n- Input: { category?: string } — e.g. \"outreach\", \"followup\", \"support\"\n- Returns: Array of { id, name, category, subject } (body excluded for performance)\n\n### get_email_template({ id })\nGet a specific email template with full body and detected template variables.\n- Input: { id: string } — Template ID (e.g. \"enterprise-intro\")\n- Returns: { id, name, category, subject, body, detectedVariables: string[] }\n\n### draft_email({ slug, templateId, overrides?, tone? })\nDraft a personalized email for a customer using a stored template.\nVariables are auto-filled from the customer's main_facts.md.\nOptional tone (e.g. \"formal\", \"friendly\", \"concise\") LLM-polishes the body;\nfalls back to plain template-fill without an ANTHROPIC_API_KEY.\nDoes NOT send automatically — returns the draft for review.\nRBAC: rep+\n- Input: { slug, templateId, overrides?: Record<string, string> }\n- Returns: { subject, body, to, slug, templateId, resolvedVariables }\n\n### enroll_in_sequence({ slug, contactEmail, sequenceId })\nEnroll a contact in an email sequence. Validates that the sequence and first template exist.\nRBAC: rep+\n- Input: { slug: string, contactEmail: string, sequenceId: string }\n- Returns: { enrollmentId, sequenceName, totalSteps }\n\n### list_sequence_enrollments({ slug?, status? })\nList email sequence enrollments. Filter by customer slug or status.\n- Input: { slug?: string, status?: \"active\" | \"paused\" | \"completed\" }\n- Returns: { enrollments: SequenceEnrollment[] }\n\n### unenroll_from_sequence({ enrollmentId })\nPause (soft-unenroll) a contact from an email sequence. Sets status to \"paused\".\nRBAC: rep+\n- Input: { enrollmentId: string }\n- Returns: { success: boolean }\n\n### list_sequences()\nList all defined email sequences with step count and current enrollment count.\n- Input: none\n- Returns: { sequences: [{ id, name, stepCount, enrollmentCount }] }\n\n### generate_quote({ slug, dealName, lineItems, vatPercent?, validUntilDays?, currency? })\nGenerate a professional HTML quote for a customer deal.\nCalculates subtotal, VAT, and total. Saves JSON + HTML to .agentic/quotes/.\nRBAC: rep+\n- Input:\n slug: Customer slug\n dealName: Deal name this quote is for\n lineItems: Array<{ description, quantity, unitPrice }>\n vatPercent?: VAT percentage (default 19)\n validUntilDays?: Quote validity in days (default 30)\n currency?: Currency code (default EUR)\n- Returns: { quoteNumber, htmlPath, total, subtotal, vat, vatPercent, currency, validUntil, status }\n\n### get_quote_status({ quoteNumber?, slug? })\nGet quote status and details. Filter by quoteNumber (single quote) or slug (all quotes for customer).\n- Input: { quoteNumber?: string, slug?: string }\n- Returns (single): Full quote object with status: draft | sent | viewed | accepted | declined\n- Returns (list): { quotes: [...] }\n\n### get_booking_link({ slug, eventType?, prefillName? })\nGet a Calendly booking link for a customer. Optionally pre-fills the customer's name/email.\nRequires CALENDLY_API_KEY env var or .agentic/integrations/calendly.yaml config.\nRBAC: rep+\n- Input: { slug, eventType?: string, prefillName?: boolean }\n- Returns: { bookingUrl, eventType, duration }\n\n### create_ticket({ slug, title, description?, priority?, assignee? })\nCreate a support ticket. Auto-calculates SLA due date based on priority.\nSLA defaults: urgent=4h, high=24h, normal=72h, low=168h.\nRBAC: rep+\n- Input:\n slug: Customer slug\n title: Ticket title\n description?: Detailed description\n priority?: \"urgent\" | \"high\" | \"normal\" | \"low\" (default: normal)\n assignee?: Assignee name or email\n- Returns: { ticket } with id T-NNN, status=open, slaDue\n\n### update_ticket({ slug, ticketId, status?, assignee? })\nUpdate a ticket's status or assignee. Setting status=resolved auto-sets resolved date.\nRBAC: rep+\n- Input: { slug, ticketId, status?: \"open\"|\"in-progress\"|\"waiting\"|\"resolved\"|\"closed\", assignee?: string }\n- Returns: { ticket }\n\n### list_tickets({ slug?, status?, priority?, assignee? })\nList support tickets sorted by priority then date. Filter by any combination of fields.\n- Input: { slug?, status?: \"open\"|\"in-progress\"|\"waiting\"|\"resolved\"|\"closed\", priority?: \"urgent\"|\"high\"|\"normal\"|\"low\", assignee? }\n- Returns: { tickets: Array<{ slug, ticket }> }\n\n### close_ticket({ slug, ticketId, resolution? })\nClose a ticket and optionally log the resolution as an interaction in interactions.md.\nRBAC: rep+\n- Input: { slug, ticketId, resolution?: string }\n- Returns: { ticket } with status=closed\n\n### send_nps_survey({ slug, contactEmail, surveyId, serverUrl? })\nGenerate an NPS/CSAT survey email draft. Returns subject, HTML body, and a token-based response URL.\nDoes NOT send automatically — returns draft for review.\nRequires survey definition in .agentic/surveys/.\nRBAC: rep+\n- Input: { slug, contactEmail, surveyId, serverUrl?: string }\n- Returns: { token, subject, body, surveyUrl, note }\n\n### get_survey_results({ surveyId, slug? })\nCalculate NPS score and breakdown for a survey. Optionally filter to a single customer.\n- Input: { surveyId: string, slug?: string }\n- Returns: { surveyId, totalResponses, npsScore (-100 to 100), promoters, passives, detractors, responses: [{ slug, email, score, comment?, respondedAt }] }\n\n### search_knowledge_base({ query, category?, publicOnly?, limit? })\nFull-text search across all KB articles (title, body, tags).\n- Input: { query, category?: string, publicOnly?: boolean, limit?: number (default 10) }\n- Returns: { query, count, articles: [{ id, title, category, excerpt, public, tags }] }\n\n### create_kb_article({ id, title, body, category?, tags?, public?, sourceTicketId? })\nCreate a new knowledge base article. Articles are stored as Markdown in .agentic/knowledge-base/.\nReturns an error if an article with the same ID already exists.\nRBAC: rep+\n- Input:\n id: Article slug (e.g. \"troubleshoot-api-timeout\")\n title: Article title\n body: Article body in Markdown\n category?: Category (default: \"general\")\n tags?: Array of tags for search\n public?: Make publicly accessible (default: false)\n sourceTicketId?: Ticket this article was created from\n- Returns: { id, title, category, path }\n\n### backup_now({ remote?, note? })\nTrigger an immediate backup of all CRM data (customers/ + .agentic/).\nCreates a timestamped ZIP with SHA-256 manifest. Optionally uploads to S3/rsync/local.\nRBAC: admin\n- Input: { remote?: string, note?: string }\n- Returns: { path, createdAt, customerCount, fileCount, sizeMb, directories, verified, uploadedTo? }\n\n### list_backups({ limit? })\nList available CRM backups with metadata. Shows log-tracked backups first, falls back to directory scan.\n- Input: { limit?: number (default 10, max 50) }\n- Returns: { count, totalAvailable, backups: [{ filename, createdAt, sizeMb, verified, encrypted, customerCount, fileCount }] }\n\n## Data Structure\n\nCustomer data lives in \\`customers/<slug>/\\`:\n- \\`main_facts.md\\` — YAML frontmatter + free-text sections\n- \\`interactions.md\\` — Chronological log (newest first)\n- \\`pipeline.md\\` — Deal table in Markdown\n- \\`sources.json\\` — Gmail/transcript sync config per customer\n\nAgentic data lives in \\`.agentic/\\`:\n- \\`goals.json\\` — Active goals and decompositions\n- \\`push-subscriptions.json\\` — Real-time push registrations\n- \\`backup-log.json\\` — Backup history\n- \\`rbac.json\\` — Role assignments\n- \\`audit.log\\` — Full audit trail\n- \\`knowledge-base/\\` — KB articles\n- \\`quotes/\\` — Generated quote files\n\n## Response Format\n\nAlways cite sources (gmail://thread/... or file://...) when available.\n\n## Framework Integration\n\n| Framework | Tier | Config |\n|---|---|---|\n| Claude Code | 1 | CLAUDE.md + ~/.claude.json + .claude/settings.json |\n| Codex CLI | 1 | AGENTS.md + ~/.codex/config.toml |\n| Grok Build (xAI) | 1 | AGENTS.md + ~/.grok/user-settings.json + .grok/settings.json |\n| OpenClaw | 1 | SOUL.md + AGENTS.md + TOOLS.md |\n| Hermes Agent | 1 | SOUL.md + Skill |\n| Antigravity CLI | 1 | GEMINI.md + AGENTS.md + SKILL.md |\n| Cursor | 2 | .cursor/rules/datasynx-crm.mdc |\n| Windsurf | 2 | MCP config only |\n| Cline | 2 | MCP config only |\n| Claude Desktop | 2 | MCP config only |\n\n### Manual Grok Build configuration\n\\`\\`\\`json\n// ~/.grok/user-settings.json (mcpServers is an ARRAY in Grok, not a map)\n{\n \"mcpServers\": [\n {\n \"name\": \"datasynx-opencrm\",\n \"transport\": {\n \"type\": \"stdio\",\n \"command\": \"node\",\n \"args\": [\"/path/to/node_modules/datasynx-opencrm/dist/mcp.js\"],\n \"env\": { \"DXCRM_DATA_DIR\": \"~/.dxcrm\" }\n }\n }\n ]\n}\n\\`\\`\\`\nRun \\`grok inspect\\` to verify the server is discovered.\n\n## CLI Reference (Phase 2)\n\n### dxcrm status\nShow daemon status, customer count, sync ages, and unmatched transcript queue.\n\\`\\`\\`\ndxcrm status\ndxcrm status --unmatched # list full unmatched transcript queue\n\\`\\`\\`\n\n### dxcrm agent spawn <slug>\nSpawn a wake-triggered agent for a customer. Sends Telegram notifications on new email.\n\\`\\`\\`\ndxcrm agent spawn acme-corp --channel telegram\ndxcrm agent spawn acme-corp --channel telegram --chat-id 12345\ndxcrm agent status\ndxcrm agent remove acme-corp\n\\`\\`\\`\nRequires: \\`TELEGRAM_BOT_TOKEN\\` + \\`TELEGRAM_CHAT_ID\\` env vars.\n\n### dxcrm import <path>\nImport customers and interactions from HubSpot or generic CSV export.\n\\`\\`\\`\ndxcrm import contacts.csv --from csv\ndxcrm import hubspot-export.csv --from hubspot\ndxcrm import hubspot-export.csv --from hubspot --dry-run\n\\`\\`\\`\n- Two-pass: creates customers first, then imports activities\n- Idempotent: re-running skips already-imported rows\n- sourceRef format: \\`hubspot://activity/<id>\\` or \\`csv://row/<hash>\\`\n\n## CLI Reference (Phase 3 — Team)\n\n### dxcrm server start\nStart a shared HTTP MCP server. Multiple team members connect via URL.\n\\`\\`\\`\ndxcrm server start --data /mnt/crm-data --port 3847\ndxcrm server status\n\\`\\`\\`\nSet actor identity: \\`export DXCRM_ACTOR=alice\\`\n\n### dxcrm audit\nShow who changed what and when. Audit trail at \\`.agentic/audit.log\\`.\n\\`\\`\\`\ndxcrm audit # Last 20 entries\ndxcrm audit --slug acme-corp # Filter by customer\ndxcrm audit --actor alice # Filter by actor\n\\`\\`\\`\nLog format: \\`2026-06-01T09:14:00Z | alice | log_interaction | acme-corp | summary\\`\n\n### session ownership\n\\`\\`\\`\ndxcrm session open acme-corp --owner alice\n# or: DXCRM_ACTOR=alice dxcrm session open acme-corp\n\\`\\`\\`\n\\`get_active_session()\\` returns \\`{ owner: \"alice\", ... }\\` when owner is set.\n\n## CLI Reference (Phase 5 — Migration)\n\n### dxcrm import — Pipedrive API\n\\`\\`\\`\ndxcrm import --from pipedrive --mode api --token <tok> --url https://myco.pipedrive.com\n\\`\\`\\`\nTwo-pass: persons → customers, activities → interactions.\nsourceRef: \\`pipedrive://activity/<id>\\`\n\n### CSV LLM Field Mapping\nGeneric CSV imports now use LLM-assisted column detection (fallback to heuristics when ANTHROPIC_API_KEY is unset).\n\n## CLI Reference (Enterprise — Sprints R1–R5)\n\n### dxcrm stages\nManage custom pipeline stages.\n\\`\\`\\`\ndxcrm stages list # List all stages\ndxcrm stages set <id> <label> [--order N] [--probability N] [--color #hex] [--final]\ndxcrm stages delete <id> # Remove a stage\ndxcrm stages reset # Reset to defaults\n\\`\\`\\`\nDefault stages: lead → qualified → proposal → negotiation → won → lost\n\n### dxcrm rbac\nRole-based access control. Roles: admin > manager > rep.\n\\`\\`\\`\ndxcrm rbac set alice admin # Assign role\ndxcrm rbac show # List all roles\ndxcrm rbac check alice update_deal # Permission check\n\\`\\`\\`\nConfig: \\`.agentic/rbac.json\\` | Actor: \\`DXCRM_ACTOR\\` env var\nEnforcement: per MCP tool call | Default role: rep\n\n### dxcrm gdpr\nGDPR erasure with dry-run safety and audit trail.\n\\`\\`\\`\ndxcrm gdpr erase acme-corp # Dry-run (shows plan)\ndxcrm gdpr erase acme-corp --confirm # Permanent deletion\ndxcrm gdpr list-erasures # Erasure history\n\\`\\`\\`\nOn confirm: deletes customers/<slug>/, writes audit.log, appends gdpr-erasures.json\n\n### dxcrm security-report\nGenerate Markdown security questionnaire for procurement/SOC2 review.\n\\`\\`\\`\ndxcrm security-report\ndxcrm security-report --output sec-report.md\n\\`\\`\\`\n\n### Microsoft Outlook Sync\n\\`\\`\\`\ndxcrm sync --provider microsoft\n\\`\\`\\`\nPrerequisites: write \\`.agentic/microsoft-token.json\\` with \\`{ \"accessToken\": \"...\" }\\`\nsourceRef: \\`microsoft://message/<id>\\` | API: Microsoft Graph v1.0\n\n### Salesforce Import\n\\`\\`\\`\ndxcrm import --from salesforce --mode api --token <tok> --url https://myco.salesforce.com\n\\`\\`\\`\nTwo-pass: contacts → customers, tasks → interactions (WhoId attribution)\nsourceRef: \\`salesforce://task/<id>\\` | API: Salesforce REST v58.0\n\n## CLI Reference (D16 — Goal-Based Orchestration)\n\n### dxcrm goal set\nSet a goal and get a decomposed action plan based on current pipeline state.\n\\`\\`\\`\ndxcrm goal set \"Close €500k ARR this quarter\" --deadline 2026-09-30\n\\`\\`\\`\n\n### dxcrm goal status\nShow all active goals with progress bars and days remaining.\n\\`\\`\\`\ndxcrm goal status\n\\`\\`\\`\n\n### dxcrm goal update\nManually update goal progress (0–100%).\n\\`\\`\\`\ndxcrm goal update goal_abc123 --progress 45\n\\`\\`\\`\n\n### dxcrm goal cancel\nCancel an active goal.\n\\`\\`\\`\ndxcrm goal cancel goal_abc123\n\\`\\`\\`\n\n## CLI Reference (D17 — Real-Time Push Ingestion)\n\n### dxcrm push register\nRegister a push subscription so providers send events in real-time (no polling).\n\\`\\`\\`\ndxcrm push register acme-corp --provider gmail --webhook-url https://myserver.com/webhooks/gmail --topic-name projects/x/topics/gmail-push\ndxcrm push register acme-corp --provider microsoft-graph --webhook-url https://myserver.com/webhooks/microsoft --client-state <secret>\ndxcrm push register acme-corp --provider slack --webhook-url https://myserver.com/webhooks/slack --team-id T12345\n\\`\\`\\`\n\n### dxcrm push status\nShow all push subscriptions, expiry and events processed.\n\\`\\`\\`\ndxcrm push status\ndxcrm push status --slug acme-corp\ndxcrm push status --provider gmail\n\\`\\`\\`\n\n### dxcrm push revoke\nRevoke a push subscription by ID.\n\\`\\`\\`\ndxcrm push revoke psub_1716892800_a1b2c3\n\\`\\`\\`\n\n### dxcrm push renew\nRenew expiring push subscriptions (also runs automatically daily at 06:00).\n\\`\\`\\`\ndxcrm push renew --all\n\\`\\`\\`\n\n### register_push_subscription (MCP)\nRegister a real-time push subscription. Admin only.\n\\`\\`\\`\nregister_push_subscription({ provider: \"gmail\", slug: \"acme-corp\", webhookUrl: \"https://myserver.com/webhooks/gmail\", gmailTopicName: \"projects/x/topics/y\" })\n\\`\\`\\`\nReturns: { subscriptionId, provider, slug, status, expiresAt, warning? }\n\n### get_push_status (MCP)\nShow all push subscriptions with expiry and event counts.\n\\`\\`\\`\nget_push_status() // all subscriptions\nget_push_status({ slug: \"acme-corp\" }) // filter by customer\nget_push_status({ provider: \"gmail\" }) // filter by provider\n\\`\\`\\`\nReturns: { subscriptions: [...], summary: { total, active, expiringSoon, expired } }\n\n### get_org_intelligence (MCP)\nBuild a stakeholder map for a customer: champions, economic buyers, blockers, health scores, risk flags, and a prioritised recommendation.\n\\`\\`\\`\nget_org_intelligence({ slug: \"acme-corp\" })\nget_org_intelligence({ slug: \"acme-corp\", dealName: \"Enterprise License\" })\n\\`\\`\\`\nReturns: { slug, updatedAt, people: [{ name, email, role, healthScore, daysSinceContact, contactStrength, riskFlags }], missingRoles, riskAssessment, recommendation }\n\n### open_deal_room (MCP)\nMulti-agent deal brief: orchestrates stakeholder map, relationship health, deal health, Monte Carlo simulation, and playbook matching into a single structured brief.\n\\`\\`\\`\nopen_deal_room({ slug: \"acme-corp\", dealName: \"Enterprise License 2026\" })\n\\`\\`\\`\nReturns: { slug, dealName, generatedAt, stakeholders, relationshipHealth, dealHealth, revenueSimulation, recommendedPlaybook, executiveSummary, topPriorities, riskScore }\n\n### get_proactive_briefing (MCP)\nGenerate a proactive daily briefing: urgent alerts (relationship decay, imminent close dates), opportunities (high-health customers with active pipeline), P50/P90 forecast, and a single top-action recommendation.\n\\`\\`\\`\nget_proactive_briefing() // today\nget_proactive_briefing({ date: \"2026-05-28\" }) // specific date\n\\`\\`\\`\nReturns: { date, generatedAt, urgent: string[], opportunities: string[], forecast: string, topAction: string }\n\n## H2 — Email Templates\n\n### list_email_templates (MCP)\nList all saved email templates. Returns id, name, category, subject, and body preview.\n\\`\\`\\`\nlist_email_templates()\nlist_email_templates({ category: \"follow-up\" })\n\\`\\`\\`\nReturns: { templates: [{ id, name, category, subject, bodyPreview }] }\n\n### get_email_template (MCP)\nRetrieve a single email template with full body and all variables.\n\\`\\`\\`\nget_email_template({ id: \"proposal-follow-up\" })\n\\`\\`\\`\nReturns: { id, name, category, subject, body, variables: string[] }\n\n### draft_email (MCP)\nDraft a personalized email from a template, substituting variables from customer context.\n\\`\\`\\`\ndraft_email({ slug: \"acme-corp\", templateId: \"proposal-follow-up\", overrides: { subject: \"Following up on your proposal\" } })\n\\`\\`\\`\nReturns: { subject, body, suggestedTo, suggestedCc?, variables }\n\n## H1 — Email Sequences\n\n### enroll_in_sequence (MCP)\nEnroll a customer contact in a multi-step email sequence. Steps are sent automatically.\n\\`\\`\\`\nenroll_in_sequence({ slug: \"acme-corp\", sequenceId: \"onboarding-7day\", contactEmail: \"alice@acme.com\" })\n\\`\\`\\`\nReturns: { enrollmentId, slug, sequenceId, contactEmail, enrolledAt, nextStepDue, totalSteps }\n\n### list_sequence_enrollments (MCP)\nList active (and optionally completed) sequence enrollments.\n\\`\\`\\`\nlist_sequence_enrollments()\nlist_sequence_enrollments({ slug: \"acme-corp\", status: \"active\" })\n\\`\\`\\`\nReturns: { enrollments: [{ enrollmentId, slug, sequenceId, contactEmail, currentStep, nextStepDue, status }] }\n\n### unenroll_from_sequence (MCP)\nRemove a contact from an active sequence (marks as cancelled).\n\\`\\`\\`\nunenroll_from_sequence({ enrollmentId: \"enr_abc123\" })\n\\`\\`\\`\nReturns: { success: boolean, enrollmentId }\n\n### list_sequences (MCP)\nList all defined email sequences with step count and description.\n\\`\\`\\`\nlist_sequences()\n\\`\\`\\`\nReturns: { sequences: [{ id, name, description, steps: number, triggerOn? }] }\n\n## H4 — Quotes\n\n### generate_quote (MCP)\nGenerate a structured quote document for a customer deal.\n\\`\\`\\`\ngenerate_quote({ slug: \"acme-corp\", dealName: \"Enterprise License\", lineItems: [{ description: \"Platform (12 mo)\", quantity: 1, unitPrice: 24000 }], validDays: 30 })\n\\`\\`\\`\nReturns: { quoteId, slug, dealName, total, currency, validUntil, markdownTable, fullText }\n\n### get_quote_status (MCP)\nRetrieve a generated quote with full line items and total.\n\\`\\`\\`\nget_quote_status({ quoteId: \"Q-2026-001\" })\n\\`\\`\\`\nReturns: { quoteId, slug, dealName, lineItems, subtotal, total, validUntil, status }\n\n## H3 — Meeting Scheduler\n\n### get_booking_link (MCP)\nGet a scheduling link for a meeting with a customer. Configure via DXCRM_CALENDLY_URL or per-customer sources.json.\n\\`\\`\\`\nget_booking_link({ slug: \"acme-corp\", meetingType: \"demo\" })\n\\`\\`\\`\nReturns: { url, meetingType, calendarProvider, prefillEmail?, note? }\n\n## H6 — Ticket Management\n\n### create_ticket (MCP)\nCreate a support ticket. Auto-sets SLA due date: critical=4h, high=24h, medium=72h, low=168h.\n\\`\\`\\`\ncreate_ticket({ slug: \"acme-corp\", title: \"Login broken\", priority: \"high\", description: \"Cannot login since yesterday\", assignee: \"alice\" })\n\\`\\`\\`\nReturns: { ticketId, slug, title, priority, status, slaDue, assignee?, createdAt }\n\n### update_ticket (MCP)\nUpdate ticket status or assignee.\n\\`\\`\\`\nupdate_ticket({ slug: \"acme-corp\", ticketId: \"T-001\", status: \"in-progress\", assignee: \"bob\" })\n\\`\\`\\`\nReturns: { ticketId, status, updatedAt }\n\n### list_tickets (MCP)\nList tickets sorted by priority. Filter by customer, status, priority, or assignee.\n\\`\\`\\`\nlist_tickets()\nlist_tickets({ slug: \"acme-corp\", status: \"open\" })\nlist_tickets({ priority: \"high\", assignee: \"alice\" })\n\\`\\`\\`\nReturns: { tickets: [{ ticketId, slug, title, priority, status, slaDue, assignee?, createdAt }] }\n\n### close_ticket (MCP)\nClose a ticket and optionally log a resolution note to interactions.md.\n\\`\\`\\`\nclose_ticket({ slug: \"acme-corp\", ticketId: \"T-001\", resolution: \"Fixed by updating oauth token\" })\n\\`\\`\\`\nReturns: { ticketId, status: \"closed\", closedAt, resolution? }\n\n## H7 — NPS/CSAT Survey Engine\n\n### send_nps_survey (MCP)\nGenerate a survey token and HTML email body. Customers click a score button (0–10) which\nposts to your server's /survey/respond endpoint. Set DXCRM_SERVER_URL or pass serverUrl.\n\\`\\`\\`\nsend_nps_survey({ slug: \"acme-corp\", contactEmail: \"alice@acme.com\", surveyId: \"q1-nps\" })\nsend_nps_survey({ slug: \"acme-corp\", contactEmail: \"alice@acme.com\", surveyId: \"q1-nps\", serverUrl: \"https://crm.myco.com\" })\n\\`\\`\\`\nReturns: { token, emailSubject, emailBody (HTML), surveyId, expiresAt }\n\n### get_survey_results (MCP)\nCalculate NPS score and breakdown by promoter/passive/detractor.\n\\`\\`\\`\nget_survey_results({ surveyId: \"q1-nps\" })\nget_survey_results({ surveyId: \"q1-nps\", slug: \"acme-corp\" })\n\\`\\`\\`\nReturns: { surveyId, npsScore (-100 to 100), responseCount, promoters, passives, detractors, responses: [{ slug, contactEmail, score, comment?, respondedAt }] }\n\n## H8 — Knowledge Base\n\n### search_knowledge_base (MCP)\nFull-text search across all KB articles (title, body, tags).\n\\`\\`\\`\nsearch_knowledge_base({ query: \"password reset\" })\nsearch_knowledge_base({ query: \"billing\", publicOnly: true })\n\\`\\`\\`\nReturns: { results: [{ id, title, category, excerpt, public, tags }] }\n\n### create_kb_article (MCP)\nCreate or update a knowledge base article (upserts by ID).\n\\`\\`\\`\ncreate_kb_article({ id: \"password-reset\", title: \"How to reset your password\", body: \"## Steps\\\\n1. Go to login...\", category: \"account\", tags: [\"password\", \"auth\"], public: true })\n\\`\\`\\`\nReturns: { id, title, createdAt, updatedAt, public }\n\n## Enterprise Backup\n\n### backup_now (MCP)\nTrigger an immediate backup of customers/ + .agentic/. Creates a timestamped ZIP with\nSHA-256 manifest. Optionally encrypts (AES-256-GCM) and uploads to S3/rsync/local.\n\\`\\`\\`\nbackup_now({})\nbackup_now({ remote: \"s3://my-bucket/crm-backups/\", note: \"Pre-migration backup\" })\n\\`\\`\\`\nReturns: { path, createdAt, customerCount, fileCount, sizeMb, directories, verified, uploadedTo? }\n\n### list_backups (MCP)\nList available CRM backups with metadata from .agentic/backup-log.json.\nFalls back to directory scan if log unavailable.\n\\`\\`\\`\nlist_backups({ limit: 10 })\n\\`\\`\\`\nReturns: { count, totalAvailable, backups: [{ filename, createdAt, sizeMb, verified, encrypted, customerCount, fileCount }] }\n\n### trigger_sync (MCP)\nForce an immediate Gmail sync without waiting for the 30-minute daemon cycle.\n\\`\\`\\`\ntrigger_sync({ slug: \"acme-corp\" }) // sync one customer\ntrigger_sync({}) // sync all customers\ntrigger_sync({ since: \"2026-06-01\" }) // sync from specific date\n\\`\\`\\`\nReturns: { success, synced, skipped, customers: [...], errors: [...] }\n\n### get_audit_log (MCP)\nRead the append-only CRM audit log of all write operations.\n\\`\\`\\`\nget_audit_log({}) // last 50 entries\nget_audit_log({ slug: \"acme-corp\" }) // filtered by customer\nget_audit_log({ actor: \"alice\", limit: 20 }) // filtered by actor\n\\`\\`\\`\nReturns: { total, returned, entries: [{ timestamp, actor, tool, slug, summary }] }\n`.trim();\n","import { z } from \"zod\";\n\nexport const KbArticleSchema = z.object({\n id: z.string().min(1),\n title: z.string().min(1),\n category: z.string().default(\"general\"),\n tags: z.array(z.string()).default([]),\n public: z.boolean().default(false),\n createdAt: z.string(),\n updatedAt: z.string(),\n sourceTicketId: z.string().optional(),\n});\n\nexport type KbArticleMeta = z.infer<typeof KbArticleSchema>;\nexport type KbArticle = KbArticleMeta & { body: string };\n","import fs from \"fs\";\nimport path from \"path\";\nimport matter from \"gray-matter\";\nimport { KbArticleSchema, type KbArticle, type KbArticleMeta } from \"../schemas/kb-article.js\";\nimport { writeFileAtomic } from \"./atomic-write.js\";\nimport { assertSafePathSegment, isSafePathSegment } from \"./safe-path.js\";\n\nexport function kbDir(dataDir: string): string {\n return path.join(dataDir, \".agentic\", \"knowledge-base\");\n}\n\n/** Category subdirectories of the knowledge base. */\nfunction kbCategories(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n return fs.readdirSync(dir).filter((f) => {\n try {\n return fs.statSync(path.join(dir, f)).isDirectory();\n } catch {\n return false;\n }\n });\n}\n\nexport function listKbArticles(\n dataDir: string,\n opts?: { category?: string; publicOnly?: boolean }\n): KbArticle[] {\n const dir = kbDir(dataDir);\n const results: KbArticle[] = [];\n\n for (const cat of kbCategories(dir)) {\n const catDir = path.join(dir, cat);\n const files = fs.readdirSync(catDir).filter((f) => f.endsWith(\".md\"));\n for (const file of files) {\n try {\n const content = fs.readFileSync(path.join(catDir, file), \"utf-8\") as string;\n const parsed = matter(content);\n const meta = KbArticleSchema.safeParse(parsed.data);\n if (!meta.success) continue;\n if (opts?.category && meta.data.category !== opts.category) continue;\n if (opts?.publicOnly && !meta.data.public) continue;\n results.push({ ...meta.data, body: parsed.content.trim() });\n } catch {\n continue;\n }\n }\n }\n\n return results;\n}\n\nexport function getKbArticle(dataDir: string, id: string): KbArticle | null {\n if (!isSafePathSegment(id)) return null;\n // Articles are stored as <category>/<id>.md, so locate the file directly\n // instead of parsing the whole knowledge base to find one by id.\n const dir = kbDir(dataDir);\n for (const cat of kbCategories(dir)) {\n const filePath = path.join(dir, cat, `${id}.md`);\n if (!fs.existsSync(filePath)) continue;\n try {\n const parsed = matter(fs.readFileSync(filePath, \"utf-8\") as string);\n const meta = KbArticleSchema.safeParse(parsed.data);\n if (!meta.success) return null;\n return { ...meta.data, body: parsed.content.trim() };\n } catch {\n return null;\n }\n }\n return null;\n}\n\nexport function writeKbArticle(dataDir: string, article: KbArticle): void {\n assertSafePathSegment(article.category, \"knowledge-base category\");\n assertSafePathSegment(article.id, \"knowledge-base article id\");\n const { body, ...meta } = article;\n const content = matter.stringify(body, meta as Record<string, unknown>);\n writeFileAtomic(path.join(kbDir(dataDir), article.category, `${article.id}.md`), content);\n}\n\nexport function deleteKbArticle(dataDir: string, id: string): boolean {\n if (!isSafePathSegment(id)) return false;\n // Locate <category>/<id>.md directly rather than parsing every article.\n const dir = kbDir(dataDir);\n for (const cat of kbCategories(dir)) {\n const p = path.join(dir, cat, `${id}.md`);\n if (fs.existsSync(p)) {\n fs.unlinkSync(p);\n return true;\n }\n }\n return false;\n}\n\nexport function searchKbSimple(\n dataDir: string,\n query: string,\n opts?: { publicOnly?: boolean }\n): KbArticle[] {\n const all = listKbArticles(dataDir, opts?.publicOnly ? { publicOnly: true } : {});\n const lower = query.toLowerCase();\n return all.filter(\n (a) =>\n a.title.toLowerCase().includes(lower) ||\n a.body.toLowerCase().includes(lower) ||\n a.tags.some((t) => t.toLowerCase().includes(lower))\n );\n}\n\nexport function getKbMetaForExport(article: KbArticle): KbArticleMeta {\n const { body: _body, ...meta } = article;\n return meta;\n}\n"],"mappings":";;;;;;;AAIA,MAAa,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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sBAAsB,QAAQ,UAAU,yBAAyB;CACjE,sBAAsB,QAAQ,IAAI,2BAA2B;CAC7D,MAAM,EAAE,MAAM,GAAG,SAAS;CAC1B,MAAM,UAAU,OAAO,UAAU,MAAM,IAA+B;CACtE,gBAAgB,KAAK,KAAK,MAAM,OAAO,GAAG,QAAQ,UAAU,GAAG,QAAQ,GAAG,IAAI,GAAG,OAAO;AAC1F;AAEA,SAAgB,gBAAgB,SAAiB,IAAqB;CACpE,IAAI,CAAC,kBAAkB,EAAE,GAAG,OAAO;CAEnC,MAAM,MAAM,MAAM,OAAO;CACzB,KAAK,MAAM,OAAO,aAAa,GAAG,GAAG;EACnC,MAAM,IAAI,KAAK,KAAK,KAAK,KAAK,GAAG,GAAG,IAAI;EACxC,IAAI,GAAG,WAAW,CAAC,GAAG;GACpB,GAAG,WAAW,CAAC;GACf,OAAO;EACT;CACF;CACA,OAAO;AACT;AAEA,SAAgB,eACd,SACA,OACA,MACa;CACb,MAAM,MAAM,eAAe,SAAS,MAAM,aAAa,EAAE,YAAY,KAAK,IAAI,CAAC,CAAC;CAChF,MAAM,QAAQ,MAAM,YAAY;CAChC,OAAO,IAAI,QACR,MACC,EAAE,MAAM,YAAY,EAAE,SAAS,KAAK,KACpC,EAAE,KAAK,YAAY,EAAE,SAAS,KAAK,KACnC,EAAE,KAAK,MAAM,MAAM,EAAE,YAAY,EAAE,SAAS,KAAK,CAAC,CACtD;AACF;AAEA,SAAgB,mBAAmB,SAAmC;CACpE,MAAM,EAAE,MAAM,OAAO,GAAG,SAAS;CACjC,OAAO;AACT"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as saveMailboxToken } from "./token-store-B0h0USqe.js";
|
|
2
|
+
import { a as buildAuthUrl, o as createOAuthClient, r as requestDeviceCode, s as exchangeCodeForTokens, t as pollForToken } from "./microsoft-dsC1fQQG.js";
|
|
2
3
|
//#region src/sync/oauth/login.ts
|
|
3
4
|
/** Accept either a raw auth code or the full loopback redirect URL and return the code. */
|
|
4
5
|
function extractAuthCode(input) {
|
|
@@ -70,4 +71,4 @@ async function runMicrosoftLogin(opts) {
|
|
|
70
71
|
//#endregion
|
|
71
72
|
export { runGmailLogin, runMicrosoftLogin };
|
|
72
73
|
|
|
73
|
-
//# sourceMappingURL=login-
|
|
74
|
+
//# sourceMappingURL=login-yt9OOQQk.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"login-
|
|
1
|
+
{"version":3,"file":"login-yt9OOQQk.js","names":[],"sources":["../src/sync/oauth/login.ts"],"sourcesContent":["// src/sync/oauth/login.ts\nimport { saveMailboxToken, type MailboxToken } from \"./token-store.js\";\nimport {\n createOAuthClient,\n buildAuthUrl,\n exchangeCodeForTokens,\n DEFAULT_REDIRECT,\n type GoogleOAuthClient,\n} from \"./google.js\";\nimport {\n requestDeviceCode,\n pollForToken,\n type DeviceCodeResponse,\n type MicrosoftTokens,\n} from \"./microsoft.js\";\n\n/** Accept either a raw auth code or the full loopback redirect URL and return the code. */\nexport function extractAuthCode(input: string): string {\n const trimmed = input.trim();\n if (trimmed.includes(\"code=\")) {\n const m = trimmed.match(/[?&]code=([^&\\s]+)/);\n if (m?.[1]) return decodeURIComponent(m[1]);\n }\n return trimmed;\n}\n\nexport interface GmailLoginOptions {\n dataDir: string;\n clientId: string;\n clientSecret: string;\n user: string;\n prompt: (question: string) => Promise<string>;\n print: (line: string) => void;\n redirectUri?: string;\n // Injection points for tests:\n createClient?: (id: string, secret: string, redirect: string) => GoogleOAuthClient;\n exchange?: typeof exchangeCodeForTokens;\n}\n\n/**\n * Drive the Gmail installed-app OAuth flow: show the consent URL, read back the\n * authorization code (or the pasted redirect URL), exchange it for tokens with\n * the full `mail.google.com` IMAP scope, and persist them.\n */\nexport async function runGmailLogin(opts: GmailLoginOptions): Promise<MailboxToken> {\n const redirect = opts.redirectUri ?? DEFAULT_REDIRECT;\n const create = opts.createClient ?? createOAuthClient;\n const exchange = opts.exchange ?? exchangeCodeForTokens;\n\n const client = create(opts.clientId, opts.clientSecret, redirect);\n const authUrl = buildAuthUrl(client, redirect);\n\n opts.print(\"Authorize Gmail IMAP access by visiting this URL:\\n\");\n opts.print(authUrl + \"\\n\");\n opts.print(\n \"After approving, your browser is redirected to a 127.0.0.1 URL that won't load — \" +\n \"copy that whole URL (or just the code) and paste it here.\"\n );\n\n const answer = await opts.prompt(\"Paste the redirect URL or code: \");\n const code = extractAuthCode(answer);\n if (!code) throw new Error(\"No authorization code provided.\");\n\n const tokens = await exchange(client, code);\n if (!tokens.refreshToken) {\n opts.print(\n \"Warning: Google did not return a refresh token. Remove the app's access at \" +\n \"myaccount.google.com/permissions and log in again to force a fresh consent.\"\n );\n }\n\n const token: MailboxToken = {\n provider: \"gmail\",\n user: opts.user,\n accessToken: tokens.accessToken,\n ...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}),\n expiresAt: tokens.expiresAt,\n scope: \"https://mail.google.com/\",\n };\n saveMailboxToken(opts.dataDir, token);\n return token;\n}\n\nexport interface MicrosoftLoginOptions {\n dataDir: string;\n clientId: string;\n user: string;\n tenant?: string;\n print: (line: string) => void;\n // Injection points for tests:\n requestDeviceCodeFn?: (clientId: string, tenant: string) => Promise<DeviceCodeResponse>;\n pollFn?: (opts: {\n clientId: string;\n deviceCode: string;\n tenant: string;\n interval: number;\n expiresIn: number;\n }) => Promise<MicrosoftTokens>;\n}\n\n/**\n * Drive the Microsoft device-code flow: print the short user code + URL, poll\n * until the user authorizes, and persist the IMAP tokens.\n */\nexport async function runMicrosoftLogin(opts: MicrosoftLoginOptions): Promise<MailboxToken> {\n const tenant = opts.tenant ?? \"common\";\n const requestCode =\n opts.requestDeviceCodeFn ?? ((id: string, t: string) => requestDeviceCode(id, t));\n const poll =\n opts.pollFn ??\n ((o: {\n clientId: string;\n deviceCode: string;\n tenant: string;\n interval: number;\n expiresIn: number;\n }) => pollForToken(o));\n\n const device = await requestCode(opts.clientId, tenant);\n opts.print(`\\nTo sign in, open ${device.verification_uri} and enter code: ${device.user_code}\\n`);\n opts.print(\"Waiting for authorization…\");\n\n const tokens = await poll({\n clientId: opts.clientId,\n deviceCode: device.device_code,\n tenant,\n interval: device.interval,\n expiresIn: device.expires_in,\n });\n\n const token: MailboxToken = {\n provider: \"microsoft\",\n user: opts.user,\n accessToken: tokens.accessToken,\n ...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}),\n expiresAt: tokens.expiresAt,\n scope: \"https://outlook.office365.com/IMAP.AccessAsUser.All\",\n };\n saveMailboxToken(opts.dataDir, token);\n return token;\n}\n"],"mappings":";;;;AAiBA,SAAgB,gBAAgB,OAAuB;CACrD,MAAM,UAAU,MAAM,KAAK;CAC3B,IAAI,QAAQ,SAAS,OAAO,GAAG;EAC7B,MAAM,IAAI,QAAQ,MAAM,oBAAoB;EAC5C,IAAI,IAAI,IAAI,OAAO,mBAAmB,EAAE,EAAE;CAC5C;CACA,OAAO;AACT;;;;;;AAoBA,eAAsB,cAAc,MAAgD;CAClF,MAAM,WAAW,KAAK,eAAA;CACtB,MAAM,SAAS,KAAK,gBAAgB;CACpC,MAAM,WAAW,KAAK,YAAY;CAElC,MAAM,SAAS,OAAO,KAAK,UAAU,KAAK,cAAc,QAAQ;CAChE,MAAM,UAAU,aAAa,QAAQ,QAAQ;CAE7C,KAAK,MAAM,qDAAqD;CAChE,KAAK,MAAM,UAAU,IAAI;CACzB,KAAK,MACH,4IAEF;CAGA,MAAM,OAAO,gBAAgB,MADR,KAAK,OAAO,kCAAkC,CAChC;CACnC,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,iCAAiC;CAE5D,MAAM,SAAS,MAAM,SAAS,QAAQ,IAAI;CAC1C,IAAI,CAAC,OAAO,cACV,KAAK,MACH,wJAEF;CAGF,MAAM,QAAsB;EAC1B,UAAU;EACV,MAAM,KAAK;EACX,aAAa,OAAO;EACpB,GAAI,OAAO,eAAe,EAAE,cAAc,OAAO,aAAa,IAAI,CAAC;EACnE,WAAW,OAAO;EAClB,OAAO;CACT;CACA,iBAAiB,KAAK,SAAS,KAAK;CACpC,OAAO;AACT;;;;;AAuBA,eAAsB,kBAAkB,MAAoD;CAC1F,MAAM,SAAS,KAAK,UAAU;CAC9B,MAAM,cACJ,KAAK,yBAAyB,IAAY,MAAc,kBAAkB,IAAI,CAAC;CACjF,MAAM,OACJ,KAAK,YACH,MAMI,aAAa,CAAC;CAEtB,MAAM,SAAS,MAAM,YAAY,KAAK,UAAU,MAAM;CACtD,KAAK,MAAM,sBAAsB,OAAO,iBAAiB,mBAAmB,OAAO,UAAU,GAAG;CAChG,KAAK,MAAM,4BAA4B;CAEvC,MAAM,SAAS,MAAM,KAAK;EACxB,UAAU,KAAK;EACf,YAAY,OAAO;EACnB;EACA,UAAU,OAAO;EACjB,WAAW,OAAO;CACpB,CAAC;CAED,MAAM,QAAsB;EAC1B,UAAU;EACV,MAAM,KAAK;EACX,aAAa,OAAO;EACpB,GAAI,OAAO,eAAe,EAAE,cAAc,OAAO,aAAa,IAAI,CAAC;EACnE,WAAW,OAAO;EAClB,OAAO;CACT;CACA,iBAAiB,KAAK,SAAS,KAAK;CACpC,OAAO;AACT"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
//#region src/sync/mailbox-config.ts
|
|
2
|
+
/** Default IMAP endpoints for OAuth providers. */
|
|
3
|
+
const PROVIDER_IMAP_HOST = {
|
|
4
|
+
gmail: {
|
|
5
|
+
host: "imap.gmail.com",
|
|
6
|
+
port: 993
|
|
7
|
+
},
|
|
8
|
+
microsoft: {
|
|
9
|
+
host: "outlook.office365.com",
|
|
10
|
+
port: 993
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
/** Read IMAP mailbox connection settings from the environment. */
|
|
14
|
+
function imapConfigFromEnv(env = process.env) {
|
|
15
|
+
const host = env["DXCRM_IMAP_HOST"];
|
|
16
|
+
const user = env["DXCRM_IMAP_USER"];
|
|
17
|
+
const pass = env["DXCRM_IMAP_PASS"];
|
|
18
|
+
const accessToken = env["DXCRM_IMAP_TOKEN"];
|
|
19
|
+
if (!host || !user || !pass && !accessToken) return null;
|
|
20
|
+
return {
|
|
21
|
+
host,
|
|
22
|
+
port: env["DXCRM_IMAP_PORT"] ? Number(env["DXCRM_IMAP_PORT"]) : 993,
|
|
23
|
+
secure: env["DXCRM_IMAP_SECURE"] !== "false",
|
|
24
|
+
mailbox: env["DXCRM_IMAP_MAILBOX"] ?? "INBOX",
|
|
25
|
+
auth: accessToken ? {
|
|
26
|
+
user,
|
|
27
|
+
accessToken
|
|
28
|
+
} : {
|
|
29
|
+
user,
|
|
30
|
+
pass
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** Parse a "provider:user" account string. */
|
|
35
|
+
function parseAccount(account) {
|
|
36
|
+
const idx = account.indexOf(":");
|
|
37
|
+
if (idx < 0) return null;
|
|
38
|
+
const provider = account.slice(0, idx);
|
|
39
|
+
const user = account.slice(idx + 1);
|
|
40
|
+
if (provider !== "gmail" && provider !== "microsoft" || !user) return null;
|
|
41
|
+
return {
|
|
42
|
+
provider,
|
|
43
|
+
user
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** Build an IMAP config for a stored OAuth account, refreshing the token if needed. */
|
|
47
|
+
async function resolveAccountConfig(dataDir, account, env = process.env, mailbox) {
|
|
48
|
+
const parsed = parseAccount(account);
|
|
49
|
+
if (!parsed) throw new Error(`Invalid account '${account}'. Use 'gmail:you@gmail.com' or 'microsoft:you@org.com'.`);
|
|
50
|
+
const { getFreshAccessToken } = await import("./token-resolver-D98qPOOf.js");
|
|
51
|
+
const accessToken = await getFreshAccessToken(dataDir, parsed.provider, parsed.user, { env });
|
|
52
|
+
const { host, port } = PROVIDER_IMAP_HOST[parsed.provider];
|
|
53
|
+
return {
|
|
54
|
+
host,
|
|
55
|
+
port,
|
|
56
|
+
secure: true,
|
|
57
|
+
mailbox: mailbox ?? env["DXCRM_IMAP_MAILBOX"] ?? "INBOX",
|
|
58
|
+
auth: {
|
|
59
|
+
user: parsed.user,
|
|
60
|
+
accessToken
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
export { resolveAccountConfig as i, imapConfigFromEnv as n, parseAccount as r, PROVIDER_IMAP_HOST as t };
|
|
66
|
+
|
|
67
|
+
//# sourceMappingURL=mailbox-config-Dn2xTn9N.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mailbox-config-Dn2xTn9N.js","names":[],"sources":["../src/sync/mailbox-config.ts"],"sourcesContent":["// src/sync/mailbox-config.ts\n// Mailbox connection resolution shared by the CLI command and the daemon.\nimport type { ImapMailboxConfig } from \"./connectors/imap.js\";\n\n/** Default IMAP endpoints for OAuth providers. */\nexport const PROVIDER_IMAP_HOST: Record<\"gmail\" | \"microsoft\", { host: string; port: number }> = {\n gmail: { host: \"imap.gmail.com\", port: 993 },\n microsoft: { host: \"outlook.office365.com\", port: 993 },\n};\n\n/** Read IMAP mailbox connection settings from the environment. */\nexport function imapConfigFromEnv(env: NodeJS.ProcessEnv = process.env): ImapMailboxConfig | null {\n const host = env[\"DXCRM_IMAP_HOST\"];\n const user = env[\"DXCRM_IMAP_USER\"];\n const pass = env[\"DXCRM_IMAP_PASS\"];\n const accessToken = env[\"DXCRM_IMAP_TOKEN\"];\n if (!host || !user || (!pass && !accessToken)) return null;\n\n return {\n host,\n port: env[\"DXCRM_IMAP_PORT\"] ? Number(env[\"DXCRM_IMAP_PORT\"]) : 993,\n secure: env[\"DXCRM_IMAP_SECURE\"] !== \"false\",\n mailbox: env[\"DXCRM_IMAP_MAILBOX\"] ?? \"INBOX\",\n auth: accessToken ? { user, accessToken } : { user, pass: pass! },\n };\n}\n\n/** Parse a \"provider:user\" account string. */\nexport function parseAccount(\n account: string\n): { provider: \"gmail\" | \"microsoft\"; user: string } | null {\n const idx = account.indexOf(\":\");\n if (idx < 0) return null;\n const provider = account.slice(0, idx);\n const user = account.slice(idx + 1);\n if ((provider !== \"gmail\" && provider !== \"microsoft\") || !user) return null;\n return { provider, user };\n}\n\n/** Build an IMAP config for a stored OAuth account, refreshing the token if needed. */\nexport async function resolveAccountConfig(\n dataDir: string,\n account: string,\n env: NodeJS.ProcessEnv = process.env,\n mailbox?: string\n): Promise<ImapMailboxConfig> {\n const parsed = parseAccount(account);\n if (!parsed) {\n throw new Error(\n `Invalid account '${account}'. Use 'gmail:you@gmail.com' or 'microsoft:you@org.com'.`\n );\n }\n const { getFreshAccessToken } = await import(\"./oauth/token-resolver.js\");\n const accessToken = await getFreshAccessToken(dataDir, parsed.provider, parsed.user, { env });\n const { host, port } = PROVIDER_IMAP_HOST[parsed.provider];\n return {\n host,\n port,\n secure: true,\n mailbox: mailbox ?? env[\"DXCRM_IMAP_MAILBOX\"] ?? \"INBOX\",\n auth: { user: parsed.user, accessToken },\n };\n}\n"],"mappings":";;AAKA,MAAa,qBAAoF;CAC/F,OAAO;EAAE,MAAM;EAAkB,MAAM;CAAI;CAC3C,WAAW;EAAE,MAAM;EAAyB,MAAM;CAAI;AACxD;;AAGA,SAAgB,kBAAkB,MAAyB,QAAQ,KAA+B;CAChG,MAAM,OAAO,IAAI;CACjB,MAAM,OAAO,IAAI;CACjB,MAAM,OAAO,IAAI;CACjB,MAAM,cAAc,IAAI;CACxB,IAAI,CAAC,QAAQ,CAAC,QAAS,CAAC,QAAQ,CAAC,aAAc,OAAO;CAEtD,OAAO;EACL;EACA,MAAM,IAAI,qBAAqB,OAAO,IAAI,kBAAkB,IAAI;EAChE,QAAQ,IAAI,yBAAyB;EACrC,SAAS,IAAI,yBAAyB;EACtC,MAAM,cAAc;GAAE;GAAM;EAAY,IAAI;GAAE;GAAY;EAAM;CAClE;AACF;;AAGA,SAAgB,aACd,SAC0D;CAC1D,MAAM,MAAM,QAAQ,QAAQ,GAAG;CAC/B,IAAI,MAAM,GAAG,OAAO;CACpB,MAAM,WAAW,QAAQ,MAAM,GAAG,GAAG;CACrC,MAAM,OAAO,QAAQ,MAAM,MAAM,CAAC;CAClC,IAAK,aAAa,WAAW,aAAa,eAAgB,CAAC,MAAM,OAAO;CACxE,OAAO;EAAE;EAAU;CAAK;AAC1B;;AAGA,eAAsB,qBACpB,SACA,SACA,MAAyB,QAAQ,KACjC,SAC4B;CAC5B,MAAM,SAAS,aAAa,OAAO;CACnC,IAAI,CAAC,QACH,MAAM,IAAI,MACR,oBAAoB,QAAQ,yDAC9B;CAEF,MAAM,EAAE,wBAAwB,MAAM,OAAO;CAC7C,MAAM,cAAc,MAAM,oBAAoB,SAAS,OAAO,UAAU,OAAO,MAAM,EAAE,IAAI,CAAC;CAC5F,MAAM,EAAE,MAAM,SAAS,mBAAmB,OAAO;CACjD,OAAO;EACL;EACA;EACA,QAAQ;EACR,SAAS,WAAW,IAAI,yBAAyB;EACjD,MAAM;GAAE,MAAM,OAAO;GAAM;EAAY;CACzC;AACF"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { n as logger } from "./logger-Dyl4VcLO.js";
|
|
2
|
+
import { i as resolveAccountConfig, n as imapConfigFromEnv } from "./mailbox-config-Dn2xTn9N.js";
|
|
3
|
+
import { n as listMailboxTokens } from "./token-store-B0h0USqe.js";
|
|
4
|
+
import { n as syncImapMailbox } from "./imap-BRgNh3T3.js";
|
|
5
|
+
//#region src/daemon/mailbox-poll.ts
|
|
6
|
+
/**
|
|
7
|
+
* Poll every configured mailbox once and auto-route new mail to customers.
|
|
8
|
+
* Resolves a fresh access token per OAuth account (refreshing as needed) and
|
|
9
|
+
* also syncs an env-configured IMAP mailbox when present. Per-account failures
|
|
10
|
+
* are collected, never thrown, so one bad mailbox can't stall the daemon.
|
|
11
|
+
*/
|
|
12
|
+
async function runMailboxPollCycle(dataDir, since, deps = {}) {
|
|
13
|
+
const env = deps.env ?? process.env;
|
|
14
|
+
const listTokens = deps.listTokens ?? listMailboxTokens;
|
|
15
|
+
const resolveConfig = deps.resolveConfig ?? resolveAccountConfig;
|
|
16
|
+
const envConfig = deps.envConfig ?? imapConfigFromEnv;
|
|
17
|
+
const syncFn = deps.syncFn ?? ((o) => syncImapMailbox({
|
|
18
|
+
dataDir: o.dataDir,
|
|
19
|
+
config: o.config,
|
|
20
|
+
since: o.since
|
|
21
|
+
}));
|
|
22
|
+
const result = {
|
|
23
|
+
accounts: 0,
|
|
24
|
+
synced: 0,
|
|
25
|
+
skipped: 0,
|
|
26
|
+
unrouted: 0,
|
|
27
|
+
errors: []
|
|
28
|
+
};
|
|
29
|
+
const configs = [];
|
|
30
|
+
for (const token of listTokens(dataDir)) {
|
|
31
|
+
if (token.provider !== "gmail" && token.provider !== "microsoft") continue;
|
|
32
|
+
const label = `${token.provider}:${token.user}`;
|
|
33
|
+
try {
|
|
34
|
+
configs.push({
|
|
35
|
+
label,
|
|
36
|
+
config: await resolveConfig(dataDir, label, env)
|
|
37
|
+
});
|
|
38
|
+
} catch (err) {
|
|
39
|
+
result.errors.push(`${label}: ${err.message}`);
|
|
40
|
+
logger.warn("daemon", "mailbox token unusable", {
|
|
41
|
+
account: label,
|
|
42
|
+
error: err.message
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const envCfg = envConfig(env);
|
|
47
|
+
if (envCfg) configs.push({
|
|
48
|
+
label: `imap:${envCfg.auth.user}`,
|
|
49
|
+
config: envCfg
|
|
50
|
+
});
|
|
51
|
+
for (const { label, config } of configs) {
|
|
52
|
+
result.accounts++;
|
|
53
|
+
try {
|
|
54
|
+
const r = await syncFn({
|
|
55
|
+
dataDir,
|
|
56
|
+
config,
|
|
57
|
+
since
|
|
58
|
+
});
|
|
59
|
+
result.synced += r.synced;
|
|
60
|
+
result.skipped += r.skipped;
|
|
61
|
+
result.unrouted += r.unrouted;
|
|
62
|
+
if (r.synced > 0 || r.unrouted > 0) logger.info("daemon", "mailbox polled", {
|
|
63
|
+
account: label,
|
|
64
|
+
synced: r.synced,
|
|
65
|
+
unrouted: r.unrouted
|
|
66
|
+
});
|
|
67
|
+
} catch (err) {
|
|
68
|
+
result.errors.push(`${label}: ${err.message}`);
|
|
69
|
+
logger.error("daemon", "mailbox poll failed", {
|
|
70
|
+
account: label,
|
|
71
|
+
error: err.message
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return result;
|
|
76
|
+
}
|
|
77
|
+
//#endregion
|
|
78
|
+
export { runMailboxPollCycle };
|
|
79
|
+
|
|
80
|
+
//# sourceMappingURL=mailbox-poll-B8dvFAXT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mailbox-poll-B8dvFAXT.js","names":[],"sources":["../src/daemon/mailbox-poll.ts"],"sourcesContent":["// src/daemon/mailbox-poll.ts\n// Background polling of every configured mailbox (stored OAuth accounts +\n// optional env-configured IMAP). Each mailbox is auto-routed to customers by\n// domain. Kept separate from worker.ts so it is unit-testable.\nimport { logger } from \"../core/logger.js\";\nimport { listMailboxTokens } from \"../sync/oauth/token-store.js\";\nimport { resolveAccountConfig, imapConfigFromEnv } from \"../sync/mailbox-config.js\";\nimport {\n syncImapMailbox,\n type ImapMailboxConfig,\n type SyncImapResult,\n} from \"../sync/connectors/imap.js\";\n\nexport interface MailboxPollResult {\n accounts: number;\n synced: number;\n skipped: number;\n unrouted: number;\n errors: string[];\n}\n\nexport interface MailboxPollDeps {\n env?: NodeJS.ProcessEnv;\n listTokens?: typeof listMailboxTokens;\n resolveConfig?: typeof resolveAccountConfig;\n envConfig?: (env: NodeJS.ProcessEnv) => ImapMailboxConfig | null;\n syncFn?: (opts: {\n dataDir: string;\n config: ImapMailboxConfig;\n since: Date;\n }) => Promise<SyncImapResult>;\n}\n\n/**\n * Poll every configured mailbox once and auto-route new mail to customers.\n * Resolves a fresh access token per OAuth account (refreshing as needed) and\n * also syncs an env-configured IMAP mailbox when present. Per-account failures\n * are collected, never thrown, so one bad mailbox can't stall the daemon.\n */\nexport async function runMailboxPollCycle(\n dataDir: string,\n since: Date,\n deps: MailboxPollDeps = {}\n): Promise<MailboxPollResult> {\n const env = deps.env ?? process.env;\n const listTokens = deps.listTokens ?? listMailboxTokens;\n const resolveConfig = deps.resolveConfig ?? resolveAccountConfig;\n const envConfig = deps.envConfig ?? imapConfigFromEnv;\n const syncFn =\n deps.syncFn ??\n ((o: { dataDir: string; config: ImapMailboxConfig; since: Date }) =>\n syncImapMailbox({ dataDir: o.dataDir, config: o.config, since: o.since }));\n\n const result: MailboxPollResult = { accounts: 0, synced: 0, skipped: 0, unrouted: 0, errors: [] };\n\n // 1. Build the list of mailbox configs to poll (OAuth accounts + env IMAP).\n const configs: Array<{ label: string; config: ImapMailboxConfig }> = [];\n for (const token of listTokens(dataDir)) {\n if (token.provider !== \"gmail\" && token.provider !== \"microsoft\") continue;\n const label = `${token.provider}:${token.user}`;\n try {\n configs.push({ label, config: await resolveConfig(dataDir, label, env) });\n } catch (err) {\n result.errors.push(`${label}: ${(err as Error).message}`);\n logger.warn(\"daemon\", \"mailbox token unusable\", {\n account: label,\n error: (err as Error).message,\n });\n }\n }\n const envCfg = envConfig(env);\n if (envCfg) configs.push({ label: `imap:${envCfg.auth.user}`, config: envCfg });\n\n // 2. Sync each mailbox (auto-route).\n for (const { label, config } of configs) {\n result.accounts++;\n try {\n const r = await syncFn({ dataDir, config, since });\n result.synced += r.synced;\n result.skipped += r.skipped;\n result.unrouted += r.unrouted;\n if (r.synced > 0 || r.unrouted > 0) {\n logger.info(\"daemon\", \"mailbox polled\", {\n account: label,\n synced: r.synced,\n unrouted: r.unrouted,\n });\n }\n } catch (err) {\n result.errors.push(`${label}: ${(err as Error).message}`);\n logger.error(\"daemon\", \"mailbox poll failed\", {\n account: label,\n error: (err as Error).message,\n });\n }\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;AAuCA,eAAsB,oBACpB,SACA,OACA,OAAwB,CAAC,GACG;CAC5B,MAAM,MAAM,KAAK,OAAO,QAAQ;CAChC,MAAM,aAAa,KAAK,cAAc;CACtC,MAAM,gBAAgB,K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AAS;IACT,OAAQ,IAAc;GACxB,CAAC;EACH;CACF;CAEA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-CdTJWTJf.d.cts","names":[],"sources":["../src/mcp/server.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"mcp-CdTJWTJf.d.cts","names":[],"sources":["../src/mcp/server.ts"],"mappings":";;;iBAwFgB,kBAAA;iBAWA,eAAA,CAAA,GAAmB;AAXnB,iBAmFM,UAAA,CAAA,CAnFY,EAmFE,OAnFF,CAAA,IAAA,CAAA;AAWlB,iBAkFM,SAAA,CAlFa,IAAS,CAAT,EAAS,MAAA,CAAA,EAkFE,OAlFF,CAAA,IAAA,CAAA;AAwE5C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-CdTJWTJf.d.ts","names":[],"sources":["../src/mcp/server.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"mcp-CdTJWTJf.d.ts","names":[],"sources":["../src/mcp/server.ts"],"mappings":";;;iBAwFgB,kBAAA;iBAWA,eAAA,CAAA,GAAmB;AAXnB,iBAmFM,UAAA,CAAA,CAnFY,EAmFE,OAnFF,CAAA,IAAA,CAAA;AAWlB,iBAkFM,SAAA,CAlFa,IAAS,CAAT,EAAS,MAAA,CAAA,EAkFE,OAlFF,CAAA,IAAA,CAAA;AAwE5C"}
|