@contractspec/lib.support-bot 1.57.0 → 1.58.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.
Files changed (62) hide show
  1. package/dist/bot/auto-responder.d.ts +19 -23
  2. package/dist/bot/auto-responder.d.ts.map +1 -1
  3. package/dist/bot/auto-responder.js +86 -68
  4. package/dist/bot/feedback-loop.d.ts +13 -17
  5. package/dist/bot/feedback-loop.d.ts.map +1 -1
  6. package/dist/bot/feedback-loop.js +38 -34
  7. package/dist/bot/index.d.ts +4 -4
  8. package/dist/bot/index.d.ts.map +1 -0
  9. package/dist/bot/index.js +268 -4
  10. package/dist/bot/tools.d.ts +9 -13
  11. package/dist/bot/tools.d.ts.map +1 -1
  12. package/dist/bot/tools.js +118 -123
  13. package/dist/browser/bot/auto-responder.js +101 -0
  14. package/dist/browser/bot/feedback-loop.js +38 -0
  15. package/dist/browser/bot/index.js +268 -0
  16. package/dist/browser/bot/tools.js +131 -0
  17. package/dist/browser/index.js +517 -0
  18. package/dist/browser/rag/index.js +65 -0
  19. package/dist/browser/rag/ticket-resolver.js +65 -0
  20. package/dist/browser/spec.js +33 -0
  21. package/dist/browser/tickets/classifier.js +156 -0
  22. package/dist/browser/tickets/index.js +156 -0
  23. package/dist/browser/types.js +0 -0
  24. package/dist/index.d.ts +6 -11
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +518 -9
  27. package/dist/node/bot/auto-responder.js +101 -0
  28. package/dist/node/bot/feedback-loop.js +38 -0
  29. package/dist/node/bot/index.js +268 -0
  30. package/dist/node/bot/tools.js +131 -0
  31. package/dist/node/index.js +517 -0
  32. package/dist/node/rag/index.js +65 -0
  33. package/dist/node/rag/ticket-resolver.js +65 -0
  34. package/dist/node/spec.js +33 -0
  35. package/dist/node/tickets/classifier.js +156 -0
  36. package/dist/node/tickets/index.js +156 -0
  37. package/dist/node/types.js +0 -0
  38. package/dist/rag/index.d.ts +2 -2
  39. package/dist/rag/index.d.ts.map +1 -0
  40. package/dist/rag/index.js +66 -3
  41. package/dist/rag/ticket-resolver.d.ts +17 -21
  42. package/dist/rag/ticket-resolver.d.ts.map +1 -1
  43. package/dist/rag/ticket-resolver.js +65 -63
  44. package/dist/spec.d.ts +7 -11
  45. package/dist/spec.d.ts.map +1 -1
  46. package/dist/spec.js +31 -32
  47. package/dist/tickets/classifier.d.ts +18 -22
  48. package/dist/tickets/classifier.d.ts.map +1 -1
  49. package/dist/tickets/classifier.js +153 -195
  50. package/dist/tickets/index.d.ts +2 -2
  51. package/dist/tickets/index.d.ts.map +1 -0
  52. package/dist/tickets/index.js +156 -2
  53. package/dist/types.d.ts +62 -66
  54. package/dist/types.d.ts.map +1 -1
  55. package/dist/types.js +1 -0
  56. package/package.json +127 -38
  57. package/dist/bot/auto-responder.js.map +0 -1
  58. package/dist/bot/feedback-loop.js.map +0 -1
  59. package/dist/bot/tools.js.map +0 -1
  60. package/dist/rag/ticket-resolver.js.map +0 -1
  61. package/dist/spec.js.map +0 -1
  62. package/dist/tickets/classifier.js.map +0 -1
@@ -0,0 +1,65 @@
1
+ // src/rag/ticket-resolver.ts
2
+ class TicketResolver {
3
+ knowledge;
4
+ minConfidence;
5
+ prependPrompt;
6
+ constructor(options) {
7
+ this.knowledge = options.knowledge;
8
+ this.minConfidence = options.minConfidence ?? 0.65;
9
+ this.prependPrompt = options.prependPrompt;
10
+ }
11
+ async resolve(ticket) {
12
+ const question = this.buildQuestion(ticket);
13
+ const answer = await this.knowledge.query(question);
14
+ return this.toResolution(ticket, answer);
15
+ }
16
+ buildQuestion(ticket) {
17
+ const header = [`Subject: ${ticket.subject}`, `Channel: ${ticket.channel}`];
18
+ if (ticket.customerName)
19
+ header.push(`Customer: ${ticket.customerName}`);
20
+ const sections = [
21
+ this.prependPrompt,
22
+ header.join(`
23
+ `),
24
+ "---",
25
+ ticket.body
26
+ ].filter(Boolean);
27
+ return sections.join(`
28
+ `);
29
+ }
30
+ toResolution(ticket, answer) {
31
+ const citations = answer.references.map((ref) => {
32
+ const label = typeof ref.payload?.title === "string" ? ref.payload.title : typeof ref.payload?.documentId === "string" ? ref.payload.documentId : ref.id;
33
+ return {
34
+ label,
35
+ url: typeof ref.payload?.url === "string" ? ref.payload.url : undefined,
36
+ snippet: typeof ref.payload?.text === "string" ? ref.payload.text.slice(0, 280) : undefined,
37
+ score: ref.score
38
+ };
39
+ });
40
+ const confidence = this.deriveConfidence(answer);
41
+ const escalate = confidence < this.minConfidence || citations.length === 0;
42
+ return {
43
+ ticketId: ticket.id,
44
+ answer: answer.answer,
45
+ confidence,
46
+ citations,
47
+ actions: [
48
+ escalate ? { type: "escalate", label: "Escalate for human review" } : { type: "respond", label: "Send automated response" }
49
+ ],
50
+ escalationReason: escalate ? "Insufficient confidence or missing knowledge references" : undefined,
51
+ knowledgeUpdates: escalate ? [ticket.body.slice(0, 200)] : undefined
52
+ };
53
+ }
54
+ deriveConfidence(answer) {
55
+ if (!answer.references.length)
56
+ return 0.3;
57
+ const topScore = answer.references[0]?.score ?? 0.4;
58
+ const normalized = Math.min(1, Math.max(0, topScore));
59
+ const tokenPenalty = answer.usage?.completionTokens ? Math.min(answer.usage.completionTokens / 1000, 0.2) : 0;
60
+ return Number((normalized - tokenPenalty).toFixed(2));
61
+ }
62
+ }
63
+ export {
64
+ TicketResolver
65
+ };
@@ -0,0 +1,33 @@
1
+ // src/spec.ts
2
+ import { defineAgent } from "@contractspec/lib.ai-agent";
3
+ function defineSupportBot(definition) {
4
+ const base = defineAgent({
5
+ ...definition.base,
6
+ policy: {
7
+ ...definition.base.policy,
8
+ confidence: {
9
+ min: definition.base.policy?.confidence?.min ?? 0.7,
10
+ default: definition.base.policy?.confidence?.default ?? 0.6
11
+ },
12
+ escalation: {
13
+ confidenceThreshold: definition.autoEscalateThreshold ?? definition.base.policy?.escalation?.confidenceThreshold ?? definition.base.policy?.confidence?.min ?? 0.7,
14
+ ...definition.base.policy?.escalation
15
+ }
16
+ },
17
+ memory: definition.base.memory ?? { maxEntries: 120, ttlMinutes: 120 },
18
+ tools: definition.tools ?? definition.base.tools,
19
+ instructions: `${definition.base.instructions}
20
+
21
+ Always cite support knowledge sources and flag compliance/billing issues for human review when unsure.`
22
+ });
23
+ return {
24
+ ...base,
25
+ thresholds: {
26
+ autoResolveMinConfidence: definition.autoEscalateThreshold ?? 0.75,
27
+ maxIterations: 6
28
+ }
29
+ };
30
+ }
31
+ export {
32
+ defineSupportBot
33
+ };
@@ -0,0 +1,156 @@
1
+ // src/tickets/classifier.ts
2
+ var CATEGORY_KEYWORDS = {
3
+ billing: ["invoice", "payout", "refund", "charge", "billing", "payment"],
4
+ technical: ["bug", "error", "crash", "issue", "failed", "timeout"],
5
+ product: ["feature", "roadmap", "idea", "request", "feedback"],
6
+ account: ["login", "password", "2fa", "account", "profile", "email change"],
7
+ compliance: ["kyc", "aml", "compliance", "regulation", "gdpr"],
8
+ other: []
9
+ };
10
+ var PRIORITY_HINTS = {
11
+ urgent: ["urgent", "asap", "immediately", "today", "right away"],
12
+ high: ["high priority", "blocking", "major", "critical"],
13
+ medium: ["soon", "next few days"],
14
+ low: ["nice to have", "when possible", "later"]
15
+ };
16
+ var SENTIMENT_HINTS = {
17
+ positive: ["love", "great", "awesome", "thank you"],
18
+ neutral: ["question", "wonder", "curious"],
19
+ negative: ["unhappy", "bad", "terrible", "awful", "angry"],
20
+ frustrated: ["furious", "frustrated", "fed up", "ridiculous"]
21
+ };
22
+
23
+ class TicketClassifier {
24
+ keywords;
25
+ llm;
26
+ llmModel;
27
+ constructor(options) {
28
+ this.keywords = {
29
+ ...CATEGORY_KEYWORDS,
30
+ ...options?.keywords ?? {}
31
+ };
32
+ this.llm = options?.llm;
33
+ this.llmModel = options?.llmModel;
34
+ }
35
+ async classify(ticket) {
36
+ const heuristics = this.heuristicClassification(ticket);
37
+ if (!this.llm)
38
+ return heuristics;
39
+ try {
40
+ const llmResult = await this.llm.chat([
41
+ {
42
+ role: "system",
43
+ content: [{ type: "text", text: "Classify the support ticket." }]
44
+ },
45
+ {
46
+ role: "user",
47
+ content: [
48
+ {
49
+ type: "text",
50
+ text: JSON.stringify({
51
+ subject: ticket.subject,
52
+ body: ticket.body,
53
+ channel: ticket.channel
54
+ })
55
+ }
56
+ ]
57
+ }
58
+ ], {
59
+ responseFormat: "json",
60
+ model: this.llmModel
61
+ });
62
+ const content = llmResult.message.content.find((part) => ("text" in part));
63
+ if (content && "text" in content) {
64
+ const parsed = JSON.parse(content.text);
65
+ return {
66
+ ...heuristics,
67
+ ...parsed,
68
+ intents: parsed.intents ?? heuristics.intents,
69
+ tags: parsed.tags ?? heuristics.tags
70
+ };
71
+ }
72
+ } catch {}
73
+ return heuristics;
74
+ }
75
+ heuristicClassification(ticket) {
76
+ const text = `${ticket.subject}
77
+ ${ticket.body}`.toLowerCase();
78
+ const category = this.detectCategory(text);
79
+ const priority = this.detectPriority(text);
80
+ const sentiment = this.detectSentiment(text);
81
+ const intents = this.extractIntents(text);
82
+ const tags = intents.slice(0, 3);
83
+ const confidence = this.estimateConfidence(category, priority, sentiment);
84
+ return {
85
+ ticketId: ticket.id,
86
+ category,
87
+ priority,
88
+ sentiment,
89
+ intents,
90
+ tags,
91
+ confidence,
92
+ escalationRequired: priority === "urgent" || category === "compliance"
93
+ };
94
+ }
95
+ detectCategory(text) {
96
+ for (const [category, keywords] of Object.entries(this.keywords)) {
97
+ if (keywords.some((keyword) => text.includes(keyword))) {
98
+ return category;
99
+ }
100
+ }
101
+ return "other";
102
+ }
103
+ detectPriority(text) {
104
+ for (const priority of [
105
+ "urgent",
106
+ "high",
107
+ "medium",
108
+ "low"
109
+ ]) {
110
+ if (PRIORITY_HINTS[priority].some((word) => text.includes(word))) {
111
+ return priority;
112
+ }
113
+ }
114
+ return "medium";
115
+ }
116
+ detectSentiment(text) {
117
+ for (const sentiment of [
118
+ "frustrated",
119
+ "negative",
120
+ "neutral",
121
+ "positive"
122
+ ]) {
123
+ if (SENTIMENT_HINTS[sentiment].some((word) => text.includes(word))) {
124
+ return sentiment;
125
+ }
126
+ }
127
+ return "neutral";
128
+ }
129
+ extractIntents(text) {
130
+ const intents = [];
131
+ if (text.includes("refund") || text.includes("chargeback"))
132
+ intents.push("refund");
133
+ if (text.includes("payout"))
134
+ intents.push("payout");
135
+ if (text.includes("login"))
136
+ intents.push("login-help");
137
+ if (text.includes("feature"))
138
+ intents.push("feature-request");
139
+ if (text.includes("bug") || text.includes("error"))
140
+ intents.push("bug-report");
141
+ return intents.length ? intents : ["general"];
142
+ }
143
+ estimateConfidence(category, priority, sentiment) {
144
+ let base = 0.6;
145
+ if (category !== "other")
146
+ base += 0.1;
147
+ if (priority === "urgent" || priority === "low")
148
+ base += 0.05;
149
+ if (sentiment === "frustrated")
150
+ base -= 0.05;
151
+ return Math.min(0.95, Math.max(0.4, Number(base.toFixed(2))));
152
+ }
153
+ }
154
+ export {
155
+ TicketClassifier
156
+ };
@@ -0,0 +1,156 @@
1
+ // src/tickets/classifier.ts
2
+ var CATEGORY_KEYWORDS = {
3
+ billing: ["invoice", "payout", "refund", "charge", "billing", "payment"],
4
+ technical: ["bug", "error", "crash", "issue", "failed", "timeout"],
5
+ product: ["feature", "roadmap", "idea", "request", "feedback"],
6
+ account: ["login", "password", "2fa", "account", "profile", "email change"],
7
+ compliance: ["kyc", "aml", "compliance", "regulation", "gdpr"],
8
+ other: []
9
+ };
10
+ var PRIORITY_HINTS = {
11
+ urgent: ["urgent", "asap", "immediately", "today", "right away"],
12
+ high: ["high priority", "blocking", "major", "critical"],
13
+ medium: ["soon", "next few days"],
14
+ low: ["nice to have", "when possible", "later"]
15
+ };
16
+ var SENTIMENT_HINTS = {
17
+ positive: ["love", "great", "awesome", "thank you"],
18
+ neutral: ["question", "wonder", "curious"],
19
+ negative: ["unhappy", "bad", "terrible", "awful", "angry"],
20
+ frustrated: ["furious", "frustrated", "fed up", "ridiculous"]
21
+ };
22
+
23
+ class TicketClassifier {
24
+ keywords;
25
+ llm;
26
+ llmModel;
27
+ constructor(options) {
28
+ this.keywords = {
29
+ ...CATEGORY_KEYWORDS,
30
+ ...options?.keywords ?? {}
31
+ };
32
+ this.llm = options?.llm;
33
+ this.llmModel = options?.llmModel;
34
+ }
35
+ async classify(ticket) {
36
+ const heuristics = this.heuristicClassification(ticket);
37
+ if (!this.llm)
38
+ return heuristics;
39
+ try {
40
+ const llmResult = await this.llm.chat([
41
+ {
42
+ role: "system",
43
+ content: [{ type: "text", text: "Classify the support ticket." }]
44
+ },
45
+ {
46
+ role: "user",
47
+ content: [
48
+ {
49
+ type: "text",
50
+ text: JSON.stringify({
51
+ subject: ticket.subject,
52
+ body: ticket.body,
53
+ channel: ticket.channel
54
+ })
55
+ }
56
+ ]
57
+ }
58
+ ], {
59
+ responseFormat: "json",
60
+ model: this.llmModel
61
+ });
62
+ const content = llmResult.message.content.find((part) => ("text" in part));
63
+ if (content && "text" in content) {
64
+ const parsed = JSON.parse(content.text);
65
+ return {
66
+ ...heuristics,
67
+ ...parsed,
68
+ intents: parsed.intents ?? heuristics.intents,
69
+ tags: parsed.tags ?? heuristics.tags
70
+ };
71
+ }
72
+ } catch {}
73
+ return heuristics;
74
+ }
75
+ heuristicClassification(ticket) {
76
+ const text = `${ticket.subject}
77
+ ${ticket.body}`.toLowerCase();
78
+ const category = this.detectCategory(text);
79
+ const priority = this.detectPriority(text);
80
+ const sentiment = this.detectSentiment(text);
81
+ const intents = this.extractIntents(text);
82
+ const tags = intents.slice(0, 3);
83
+ const confidence = this.estimateConfidence(category, priority, sentiment);
84
+ return {
85
+ ticketId: ticket.id,
86
+ category,
87
+ priority,
88
+ sentiment,
89
+ intents,
90
+ tags,
91
+ confidence,
92
+ escalationRequired: priority === "urgent" || category === "compliance"
93
+ };
94
+ }
95
+ detectCategory(text) {
96
+ for (const [category, keywords] of Object.entries(this.keywords)) {
97
+ if (keywords.some((keyword) => text.includes(keyword))) {
98
+ return category;
99
+ }
100
+ }
101
+ return "other";
102
+ }
103
+ detectPriority(text) {
104
+ for (const priority of [
105
+ "urgent",
106
+ "high",
107
+ "medium",
108
+ "low"
109
+ ]) {
110
+ if (PRIORITY_HINTS[priority].some((word) => text.includes(word))) {
111
+ return priority;
112
+ }
113
+ }
114
+ return "medium";
115
+ }
116
+ detectSentiment(text) {
117
+ for (const sentiment of [
118
+ "frustrated",
119
+ "negative",
120
+ "neutral",
121
+ "positive"
122
+ ]) {
123
+ if (SENTIMENT_HINTS[sentiment].some((word) => text.includes(word))) {
124
+ return sentiment;
125
+ }
126
+ }
127
+ return "neutral";
128
+ }
129
+ extractIntents(text) {
130
+ const intents = [];
131
+ if (text.includes("refund") || text.includes("chargeback"))
132
+ intents.push("refund");
133
+ if (text.includes("payout"))
134
+ intents.push("payout");
135
+ if (text.includes("login"))
136
+ intents.push("login-help");
137
+ if (text.includes("feature"))
138
+ intents.push("feature-request");
139
+ if (text.includes("bug") || text.includes("error"))
140
+ intents.push("bug-report");
141
+ return intents.length ? intents : ["general"];
142
+ }
143
+ estimateConfidence(category, priority, sentiment) {
144
+ let base = 0.6;
145
+ if (category !== "other")
146
+ base += 0.1;
147
+ if (priority === "urgent" || priority === "low")
148
+ base += 0.05;
149
+ if (sentiment === "frustrated")
150
+ base -= 0.05;
151
+ return Math.min(0.95, Math.max(0.4, Number(base.toFixed(2))));
152
+ }
153
+ }
154
+ export {
155
+ TicketClassifier
156
+ };
File without changes
package/dist/index.d.ts CHANGED
@@ -1,11 +1,6 @@
1
- import { ClassificationResultPayload, ResolutionResultPayload, SupportAction, SupportBotSpec, SupportCitation, SupportResolution, SupportResponseDraft, SupportTicket, TicketCategory, TicketChannel, TicketClassification, TicketPriority, TicketSentiment } from "./types.js";
2
- import { AutoResponder, AutoResponderOptions } from "./bot/auto-responder.js";
3
- import { FeedbackMetrics, SupportFeedbackLoop } from "./bot/feedback-loop.js";
4
- import { KnowledgeRetriever, TicketResolver, TicketResolverOptions } from "./rag/ticket-resolver.js";
5
- import { TicketClassifier, TicketClassifierOptions } from "./tickets/classifier.js";
6
- import { SupportToolsetOptions, createSupportTools } from "./bot/tools.js";
7
- import "./bot/index.js";
8
- import { SupportBotDefinition, defineSupportBot } from "./spec.js";
9
- import "./rag/index.js";
10
- import "./tickets/index.js";
11
- export { AutoResponder, AutoResponderOptions, ClassificationResultPayload, FeedbackMetrics, KnowledgeRetriever, ResolutionResultPayload, SupportAction, SupportBotDefinition, SupportBotSpec, SupportCitation, SupportFeedbackLoop, SupportResolution, SupportResponseDraft, SupportTicket, SupportToolsetOptions, TicketCategory, TicketChannel, TicketClassification, TicketClassifier, TicketClassifierOptions, TicketPriority, TicketResolver, TicketResolverOptions, TicketSentiment, createSupportTools, defineSupportBot };
1
+ export * from './types';
2
+ export * from './spec';
3
+ export * from './rag';
4
+ export * from './tickets';
5
+ export * from './bot';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC;AACvB,cAAc,OAAO,CAAC;AACtB,cAAc,WAAW,CAAC;AAC1B,cAAc,OAAO,CAAC"}