@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
@@ -1 +1 @@
1
- {"version":3,"file":"tools.d.ts","names":[],"sources":["../../src/bot/tools.ts"],"mappings":";;;;;;UAgGiB,qBAAA;EACf,QAAA,EAAU,cAAA;EACV,UAAA,EAAY,gBAAA;EACZ,SAAA,EAAW,aAAA;AAAA;AAAA,iBAGG,kBAAA,CAAmB,OAAA,EAAS,qBAAA,GAAwB,IAAA"}
1
+ {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../src/bot/tools.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAWtD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAmFnD,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,cAAc,CAAC;IACzB,UAAU,EAAE,gBAAgB,CAAC;IAC7B,SAAS,EAAE,aAAa,CAAC;CAC1B;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI,EAAE,CA0DzE"}
package/dist/bot/tools.js CHANGED
@@ -1,137 +1,132 @@
1
+ // @bun
2
+ // src/bot/tools.ts
1
3
  import * as z from "zod";
2
-
3
- //#region src/bot/tools.ts
4
- const ticketSchema = z.object({
5
- id: z.string(),
6
- subject: z.string(),
7
- body: z.string(),
8
- channel: z.enum([
9
- "email",
10
- "chat",
11
- "phone",
12
- "portal"
13
- ]),
14
- customerName: z.string().optional(),
15
- customerEmail: z.string().optional(),
16
- metadata: z.object().optional()
4
+ var ticketSchema = z.object({
5
+ id: z.string(),
6
+ subject: z.string(),
7
+ body: z.string(),
8
+ channel: z.enum(["email", "chat", "phone", "portal"]),
9
+ customerName: z.string().optional(),
10
+ customerEmail: z.string().optional(),
11
+ metadata: z.object().optional()
17
12
  });
18
- const supportCitationSchema = z.object({
19
- label: z.string(),
20
- url: z.string().optional(),
21
- snippet: z.string().optional(),
22
- score: z.number().optional()
13
+ var supportCitationSchema = z.object({
14
+ label: z.string(),
15
+ url: z.string().optional(),
16
+ snippet: z.string().optional(),
17
+ score: z.number().optional()
23
18
  });
24
- const supportActionSchema = z.object({
25
- type: z.enum([
26
- "respond",
27
- "escalate",
28
- "refund",
29
- "manual"
30
- ]),
31
- label: z.string(),
32
- payload: z.record(z.string(), z.string())
19
+ var supportActionSchema = z.object({
20
+ type: z.enum(["respond", "escalate", "refund", "manual"]),
21
+ label: z.string(),
22
+ payload: z.record(z.string(), z.string())
33
23
  });
34
- const supportResolutionSchema = z.object({
35
- ticketId: z.string(),
36
- answer: z.string(),
37
- confidence: z.number(),
38
- citations: supportCitationSchema.array(),
39
- actions: supportActionSchema.array(),
40
- escalationReason: z.string().optional(),
41
- knowledgeUpdates: z.array(z.string()).optional()
24
+ var supportResolutionSchema = z.object({
25
+ ticketId: z.string(),
26
+ answer: z.string(),
27
+ confidence: z.number(),
28
+ citations: supportCitationSchema.array(),
29
+ actions: supportActionSchema.array(),
30
+ escalationReason: z.string().optional(),
31
+ knowledgeUpdates: z.array(z.string()).optional()
42
32
  });
43
- const ticketClassificationSchema = z.object({
44
- ticketId: z.string(),
45
- category: z.enum([
46
- "billing",
47
- "technical",
48
- "product",
49
- "account",
50
- "compliance",
51
- "other"
52
- ]),
53
- priority: z.enum([
54
- "urgent",
55
- "high",
56
- "medium",
57
- "low"
58
- ]),
59
- sentiment: z.enum([
60
- "positive",
61
- "neutral",
62
- "negative",
63
- "frustrated"
64
- ]),
65
- intents: z.array(z.string()),
66
- tags: z.array(z.string()),
67
- confidence: z.number(),
68
- escalationRequired: z.boolean().optional()
33
+ var ticketClassificationSchema = z.object({
34
+ ticketId: z.string(),
35
+ category: z.enum([
36
+ "billing",
37
+ "technical",
38
+ "product",
39
+ "account",
40
+ "compliance",
41
+ "other"
42
+ ]),
43
+ priority: z.enum([
44
+ "urgent",
45
+ "high",
46
+ "medium",
47
+ "low"
48
+ ]),
49
+ sentiment: z.enum([
50
+ "positive",
51
+ "neutral",
52
+ "negative",
53
+ "frustrated"
54
+ ]),
55
+ intents: z.array(z.string()),
56
+ tags: z.array(z.string()),
57
+ confidence: z.number(),
58
+ escalationRequired: z.boolean().optional()
69
59
  });
70
60
  function ensureTicket(input) {
71
- if (!input || typeof input !== "object" || !("ticket" in input)) throw new Error("Input must include ticket");
72
- const ticket = input.ticket;
73
- if (!ticket?.id) throw new Error("Ticket is missing id");
74
- return ticket;
61
+ if (!input || typeof input !== "object" || !("ticket" in input)) {
62
+ throw new Error("Input must include ticket");
63
+ }
64
+ const ticket = input.ticket;
65
+ if (!ticket?.id)
66
+ throw new Error("Ticket is missing id");
67
+ return ticket;
75
68
  }
76
69
  function extractResolution(input) {
77
- if (!input || typeof input !== "object" || !("resolution" in input)) return void 0;
78
- return input.resolution;
70
+ if (!input || typeof input !== "object" || !("resolution" in input))
71
+ return;
72
+ return input.resolution;
79
73
  }
80
74
  function extractClassification(input) {
81
- if (!input || typeof input !== "object" || !("classification" in input)) return void 0;
82
- return input.classification;
75
+ if (!input || typeof input !== "object" || !("classification" in input))
76
+ return;
77
+ return input.classification;
83
78
  }
84
79
  function createSupportTools(options) {
85
- return [
86
- {
87
- title: "support_classify_ticket",
88
- description: "Classify a ticket for priority, sentiment, and category",
89
- inputSchema: z.object({ ticket: ticketSchema }),
90
- execute: async (input) => {
91
- const ticket = ensureTicket(input);
92
- const classification = await options.classifier.classify(ticket);
93
- return {
94
- content: JSON.stringify(classification),
95
- metadata: { ticketId: ticket.id }
96
- };
97
- }
98
- },
99
- {
100
- title: "support_resolve_ticket",
101
- description: "Generate a knowledge-grounded resolution for a ticket",
102
- inputSchema: z.object({ ticket: ticketSchema }),
103
- execute: async (input) => {
104
- const ticket = ensureTicket(input);
105
- const resolution = await options.resolver.resolve(ticket);
106
- return {
107
- content: JSON.stringify(resolution),
108
- metadata: { ticketId: ticket.id }
109
- };
110
- }
111
- },
112
- {
113
- title: "support_draft_response",
114
- description: "Draft a user-facing reply based on resolution + classification",
115
- inputSchema: z.object({
116
- ticket: ticketSchema,
117
- resolution: supportResolutionSchema,
118
- classification: ticketClassificationSchema
119
- }),
120
- execute: async (input) => {
121
- const ticket = ensureTicket(input);
122
- const resolution = extractResolution(input);
123
- const classification = extractClassification(input);
124
- if (!resolution || !classification) throw new Error("resolution and classification are required");
125
- const draft = await options.responder.draft(ticket, resolution, classification);
126
- return {
127
- content: JSON.stringify(draft),
128
- metadata: { ticketId: ticket.id }
129
- };
130
- }
131
- }
132
- ];
80
+ const classifyTool = {
81
+ title: "support_classify_ticket",
82
+ description: "Classify a ticket for priority, sentiment, and category",
83
+ inputSchema: z.object({ ticket: ticketSchema }),
84
+ execute: async (input) => {
85
+ const ticket = ensureTicket(input);
86
+ const classification = await options.classifier.classify(ticket);
87
+ return {
88
+ content: JSON.stringify(classification),
89
+ metadata: { ticketId: ticket.id }
90
+ };
91
+ }
92
+ };
93
+ const resolveTool = {
94
+ title: "support_resolve_ticket",
95
+ description: "Generate a knowledge-grounded resolution for a ticket",
96
+ inputSchema: z.object({ ticket: ticketSchema }),
97
+ execute: async (input) => {
98
+ const ticket = ensureTicket(input);
99
+ const resolution = await options.resolver.resolve(ticket);
100
+ return {
101
+ content: JSON.stringify(resolution),
102
+ metadata: { ticketId: ticket.id }
103
+ };
104
+ }
105
+ };
106
+ const responderTool = {
107
+ title: "support_draft_response",
108
+ description: "Draft a user-facing reply based on resolution + classification",
109
+ inputSchema: z.object({
110
+ ticket: ticketSchema,
111
+ resolution: supportResolutionSchema,
112
+ classification: ticketClassificationSchema
113
+ }),
114
+ execute: async (input) => {
115
+ const ticket = ensureTicket(input);
116
+ const resolution = extractResolution(input);
117
+ const classification = extractClassification(input);
118
+ if (!resolution || !classification) {
119
+ throw new Error("resolution and classification are required");
120
+ }
121
+ const draft = await options.responder.draft(ticket, resolution, classification);
122
+ return {
123
+ content: JSON.stringify(draft),
124
+ metadata: { ticketId: ticket.id }
125
+ };
126
+ }
127
+ };
128
+ return [classifyTool, resolveTool, responderTool];
133
129
  }
134
-
135
- //#endregion
136
- export { createSupportTools };
137
- //# sourceMappingURL=tools.js.map
130
+ export {
131
+ createSupportTools
132
+ };
@@ -0,0 +1,101 @@
1
+ // src/bot/auto-responder.ts
2
+ class AutoResponder {
3
+ llm;
4
+ model;
5
+ tone;
6
+ closing;
7
+ constructor(options) {
8
+ this.llm = options?.llm;
9
+ this.model = options?.model;
10
+ this.tone = options?.tone ?? "friendly";
11
+ this.closing = options?.closing ?? (this.tone === "friendly" ? "We remain available if you need anything else." : "Please let us know if you require additional assistance.");
12
+ }
13
+ async draft(ticket, resolution, classification) {
14
+ if (this.llm) {
15
+ return this.generateWithLLM(ticket, resolution, classification);
16
+ }
17
+ return this.generateTemplate(ticket, resolution, classification);
18
+ }
19
+ async generateWithLLM(ticket, resolution, classification) {
20
+ const prompt = `You are a ${this.tone} support agent. Draft an email response.
21
+ Ticket Subject: ${ticket.subject}
22
+ Ticket Body: ${ticket.body}
23
+ Detected Category: ${classification.category}
24
+ Detected Priority: ${classification.priority}
25
+ Resolution:
26
+ ${resolution.answer}
27
+ Citations: ${resolution.citations.map((c) => c.label).join(", ")}`;
28
+ const response = await this.llm.chat([
29
+ {
30
+ role: "system",
31
+ content: [
32
+ {
33
+ type: "text",
34
+ text: "Write empathetic, accurate support replies that cite sources when relevant."
35
+ }
36
+ ]
37
+ },
38
+ {
39
+ role: "user",
40
+ content: [{ type: "text", text: prompt }]
41
+ }
42
+ ], { model: this.model });
43
+ const body = response.message.content.map((part) => ("text" in part) ? part.text : "").join("").trim();
44
+ return this.buildDraft(ticket, resolution, classification, body);
45
+ }
46
+ generateTemplate(ticket, resolution, classification) {
47
+ const greeting = ticket.customerName ? `Hi ${ticket.customerName},` : "Hi there,";
48
+ const body = `${greeting}
49
+
50
+ Thanks for contacting us about "${ticket.subject}". ${this.renderCategoryIntro(classification)}
51
+
52
+ ${resolution.answer}
53
+
54
+ ${this.renderCitations(resolution)}
55
+ ${this.closing}
56
+
57
+ — ContractSpec Support`;
58
+ return this.buildDraft(ticket, resolution, classification, body);
59
+ }
60
+ buildDraft(ticket, resolution, classification, body) {
61
+ return {
62
+ ticketId: ticket.id,
63
+ subject: ticket.subject.startsWith("Re:") ? ticket.subject : `Re: ${ticket.subject}`,
64
+ body,
65
+ confidence: Math.min(resolution.confidence, classification.confidence),
66
+ requiresEscalation: resolution.actions.some((action) => action.type === "escalate") || Boolean(classification.escalationRequired),
67
+ citations: resolution.citations
68
+ };
69
+ }
70
+ renderCategoryIntro(classification) {
71
+ switch (classification.category) {
72
+ case "billing":
73
+ return "I understand billing issues can be stressful, so let me clarify the situation.";
74
+ case "technical":
75
+ return "I see you encountered a technical issue. Here is what happened and how to fix it.";
76
+ case "product":
77
+ return "Thanks for sharing feedback about the product. Here are the next steps.";
78
+ case "account":
79
+ return "Account access is critical, so let me walk you through the resolution.";
80
+ case "compliance":
81
+ return "Compliance questions require precision. See the policy-aligned answer below.";
82
+ default:
83
+ return "Here is what we found after reviewing your request.";
84
+ }
85
+ }
86
+ renderCitations(resolution) {
87
+ if (!resolution.citations.length)
88
+ return "";
89
+ const lines = resolution.citations.map((citation, index) => {
90
+ const label = citation.label || `Source ${index + 1}`;
91
+ const link = citation.url ? ` (${citation.url})` : "";
92
+ return `- ${label}${link}`;
93
+ });
94
+ return `References:
95
+ ${lines.join(`
96
+ `)}`;
97
+ }
98
+ }
99
+ export {
100
+ AutoResponder
101
+ };
@@ -0,0 +1,38 @@
1
+ // src/bot/feedback-loop.ts
2
+ class SupportFeedbackLoop {
3
+ history = [];
4
+ responseTimes = new Map;
5
+ recordResolution(payload, responseTimeMs) {
6
+ this.history.push(payload);
7
+ if (responseTimeMs != null) {
8
+ this.responseTimes.set(payload.ticket.id, responseTimeMs);
9
+ }
10
+ }
11
+ metrics() {
12
+ const total = this.history.length;
13
+ const autoResolved = this.history.filter((entry) => !entry.resolution.actions.some((action) => action.type === "escalate")).length;
14
+ const escalated = total - autoResolved;
15
+ const avgConfidence = total === 0 ? 0 : this.history.reduce((sum, entry) => sum + entry.resolution.confidence, 0) / total;
16
+ const avgResponseTimeMs = this.responseTimes.size === 0 ? 0 : [...this.responseTimes.values()].reduce((a, b) => a + b, 0) / this.responseTimes.size;
17
+ return {
18
+ totalTickets: total,
19
+ autoResolved,
20
+ escalated,
21
+ avgConfidence: Number(avgConfidence.toFixed(2)),
22
+ avgResponseTimeMs: Math.round(avgResponseTimeMs)
23
+ };
24
+ }
25
+ feedbackSummary(limit = 5) {
26
+ const recent = this.history.slice(-limit);
27
+ if (!recent.length)
28
+ return "No feedback recorded yet.";
29
+ return recent.map((entry) => {
30
+ const status = entry.resolution.actions.some((action) => action.type === "escalate") ? "Escalated" : "Auto-resolved";
31
+ return `${entry.ticket.subject} – ${status} (confidence: ${entry.resolution.confidence})`;
32
+ }).join(`
33
+ `);
34
+ }
35
+ }
36
+ export {
37
+ SupportFeedbackLoop
38
+ };
@@ -0,0 +1,268 @@
1
+ // src/bot/auto-responder.ts
2
+ class AutoResponder {
3
+ llm;
4
+ model;
5
+ tone;
6
+ closing;
7
+ constructor(options) {
8
+ this.llm = options?.llm;
9
+ this.model = options?.model;
10
+ this.tone = options?.tone ?? "friendly";
11
+ this.closing = options?.closing ?? (this.tone === "friendly" ? "We remain available if you need anything else." : "Please let us know if you require additional assistance.");
12
+ }
13
+ async draft(ticket, resolution, classification) {
14
+ if (this.llm) {
15
+ return this.generateWithLLM(ticket, resolution, classification);
16
+ }
17
+ return this.generateTemplate(ticket, resolution, classification);
18
+ }
19
+ async generateWithLLM(ticket, resolution, classification) {
20
+ const prompt = `You are a ${this.tone} support agent. Draft an email response.
21
+ Ticket Subject: ${ticket.subject}
22
+ Ticket Body: ${ticket.body}
23
+ Detected Category: ${classification.category}
24
+ Detected Priority: ${classification.priority}
25
+ Resolution:
26
+ ${resolution.answer}
27
+ Citations: ${resolution.citations.map((c) => c.label).join(", ")}`;
28
+ const response = await this.llm.chat([
29
+ {
30
+ role: "system",
31
+ content: [
32
+ {
33
+ type: "text",
34
+ text: "Write empathetic, accurate support replies that cite sources when relevant."
35
+ }
36
+ ]
37
+ },
38
+ {
39
+ role: "user",
40
+ content: [{ type: "text", text: prompt }]
41
+ }
42
+ ], { model: this.model });
43
+ const body = response.message.content.map((part) => ("text" in part) ? part.text : "").join("").trim();
44
+ return this.buildDraft(ticket, resolution, classification, body);
45
+ }
46
+ generateTemplate(ticket, resolution, classification) {
47
+ const greeting = ticket.customerName ? `Hi ${ticket.customerName},` : "Hi there,";
48
+ const body = `${greeting}
49
+
50
+ Thanks for contacting us about "${ticket.subject}". ${this.renderCategoryIntro(classification)}
51
+
52
+ ${resolution.answer}
53
+
54
+ ${this.renderCitations(resolution)}
55
+ ${this.closing}
56
+
57
+ — ContractSpec Support`;
58
+ return this.buildDraft(ticket, resolution, classification, body);
59
+ }
60
+ buildDraft(ticket, resolution, classification, body) {
61
+ return {
62
+ ticketId: ticket.id,
63
+ subject: ticket.subject.startsWith("Re:") ? ticket.subject : `Re: ${ticket.subject}`,
64
+ body,
65
+ confidence: Math.min(resolution.confidence, classification.confidence),
66
+ requiresEscalation: resolution.actions.some((action) => action.type === "escalate") || Boolean(classification.escalationRequired),
67
+ citations: resolution.citations
68
+ };
69
+ }
70
+ renderCategoryIntro(classification) {
71
+ switch (classification.category) {
72
+ case "billing":
73
+ return "I understand billing issues can be stressful, so let me clarify the situation.";
74
+ case "technical":
75
+ return "I see you encountered a technical issue. Here is what happened and how to fix it.";
76
+ case "product":
77
+ return "Thanks for sharing feedback about the product. Here are the next steps.";
78
+ case "account":
79
+ return "Account access is critical, so let me walk you through the resolution.";
80
+ case "compliance":
81
+ return "Compliance questions require precision. See the policy-aligned answer below.";
82
+ default:
83
+ return "Here is what we found after reviewing your request.";
84
+ }
85
+ }
86
+ renderCitations(resolution) {
87
+ if (!resolution.citations.length)
88
+ return "";
89
+ const lines = resolution.citations.map((citation, index) => {
90
+ const label = citation.label || `Source ${index + 1}`;
91
+ const link = citation.url ? ` (${citation.url})` : "";
92
+ return `- ${label}${link}`;
93
+ });
94
+ return `References:
95
+ ${lines.join(`
96
+ `)}`;
97
+ }
98
+ }
99
+
100
+ // src/bot/feedback-loop.ts
101
+ class SupportFeedbackLoop {
102
+ history = [];
103
+ responseTimes = new Map;
104
+ recordResolution(payload, responseTimeMs) {
105
+ this.history.push(payload);
106
+ if (responseTimeMs != null) {
107
+ this.responseTimes.set(payload.ticket.id, responseTimeMs);
108
+ }
109
+ }
110
+ metrics() {
111
+ const total = this.history.length;
112
+ const autoResolved = this.history.filter((entry) => !entry.resolution.actions.some((action) => action.type === "escalate")).length;
113
+ const escalated = total - autoResolved;
114
+ const avgConfidence = total === 0 ? 0 : this.history.reduce((sum, entry) => sum + entry.resolution.confidence, 0) / total;
115
+ const avgResponseTimeMs = this.responseTimes.size === 0 ? 0 : [...this.responseTimes.values()].reduce((a, b) => a + b, 0) / this.responseTimes.size;
116
+ return {
117
+ totalTickets: total,
118
+ autoResolved,
119
+ escalated,
120
+ avgConfidence: Number(avgConfidence.toFixed(2)),
121
+ avgResponseTimeMs: Math.round(avgResponseTimeMs)
122
+ };
123
+ }
124
+ feedbackSummary(limit = 5) {
125
+ const recent = this.history.slice(-limit);
126
+ if (!recent.length)
127
+ return "No feedback recorded yet.";
128
+ return recent.map((entry) => {
129
+ const status = entry.resolution.actions.some((action) => action.type === "escalate") ? "Escalated" : "Auto-resolved";
130
+ return `${entry.ticket.subject} – ${status} (confidence: ${entry.resolution.confidence})`;
131
+ }).join(`
132
+ `);
133
+ }
134
+ }
135
+
136
+ // src/bot/tools.ts
137
+ import * as z from "zod";
138
+ var ticketSchema = z.object({
139
+ id: z.string(),
140
+ subject: z.string(),
141
+ body: z.string(),
142
+ channel: z.enum(["email", "chat", "phone", "portal"]),
143
+ customerName: z.string().optional(),
144
+ customerEmail: z.string().optional(),
145
+ metadata: z.object().optional()
146
+ });
147
+ var supportCitationSchema = z.object({
148
+ label: z.string(),
149
+ url: z.string().optional(),
150
+ snippet: z.string().optional(),
151
+ score: z.number().optional()
152
+ });
153
+ var supportActionSchema = z.object({
154
+ type: z.enum(["respond", "escalate", "refund", "manual"]),
155
+ label: z.string(),
156
+ payload: z.record(z.string(), z.string())
157
+ });
158
+ var supportResolutionSchema = z.object({
159
+ ticketId: z.string(),
160
+ answer: z.string(),
161
+ confidence: z.number(),
162
+ citations: supportCitationSchema.array(),
163
+ actions: supportActionSchema.array(),
164
+ escalationReason: z.string().optional(),
165
+ knowledgeUpdates: z.array(z.string()).optional()
166
+ });
167
+ var ticketClassificationSchema = z.object({
168
+ ticketId: z.string(),
169
+ category: z.enum([
170
+ "billing",
171
+ "technical",
172
+ "product",
173
+ "account",
174
+ "compliance",
175
+ "other"
176
+ ]),
177
+ priority: z.enum([
178
+ "urgent",
179
+ "high",
180
+ "medium",
181
+ "low"
182
+ ]),
183
+ sentiment: z.enum([
184
+ "positive",
185
+ "neutral",
186
+ "negative",
187
+ "frustrated"
188
+ ]),
189
+ intents: z.array(z.string()),
190
+ tags: z.array(z.string()),
191
+ confidence: z.number(),
192
+ escalationRequired: z.boolean().optional()
193
+ });
194
+ function ensureTicket(input) {
195
+ if (!input || typeof input !== "object" || !("ticket" in input)) {
196
+ throw new Error("Input must include ticket");
197
+ }
198
+ const ticket = input.ticket;
199
+ if (!ticket?.id)
200
+ throw new Error("Ticket is missing id");
201
+ return ticket;
202
+ }
203
+ function extractResolution(input) {
204
+ if (!input || typeof input !== "object" || !("resolution" in input))
205
+ return;
206
+ return input.resolution;
207
+ }
208
+ function extractClassification(input) {
209
+ if (!input || typeof input !== "object" || !("classification" in input))
210
+ return;
211
+ return input.classification;
212
+ }
213
+ function createSupportTools(options) {
214
+ const classifyTool = {
215
+ title: "support_classify_ticket",
216
+ description: "Classify a ticket for priority, sentiment, and category",
217
+ inputSchema: z.object({ ticket: ticketSchema }),
218
+ execute: async (input) => {
219
+ const ticket = ensureTicket(input);
220
+ const classification = await options.classifier.classify(ticket);
221
+ return {
222
+ content: JSON.stringify(classification),
223
+ metadata: { ticketId: ticket.id }
224
+ };
225
+ }
226
+ };
227
+ const resolveTool = {
228
+ title: "support_resolve_ticket",
229
+ description: "Generate a knowledge-grounded resolution for a ticket",
230
+ inputSchema: z.object({ ticket: ticketSchema }),
231
+ execute: async (input) => {
232
+ const ticket = ensureTicket(input);
233
+ const resolution = await options.resolver.resolve(ticket);
234
+ return {
235
+ content: JSON.stringify(resolution),
236
+ metadata: { ticketId: ticket.id }
237
+ };
238
+ }
239
+ };
240
+ const responderTool = {
241
+ title: "support_draft_response",
242
+ description: "Draft a user-facing reply based on resolution + classification",
243
+ inputSchema: z.object({
244
+ ticket: ticketSchema,
245
+ resolution: supportResolutionSchema,
246
+ classification: ticketClassificationSchema
247
+ }),
248
+ execute: async (input) => {
249
+ const ticket = ensureTicket(input);
250
+ const resolution = extractResolution(input);
251
+ const classification = extractClassification(input);
252
+ if (!resolution || !classification) {
253
+ throw new Error("resolution and classification are required");
254
+ }
255
+ const draft = await options.responder.draft(ticket, resolution, classification);
256
+ return {
257
+ content: JSON.stringify(draft),
258
+ metadata: { ticketId: ticket.id }
259
+ };
260
+ }
261
+ };
262
+ return [classifyTool, resolveTool, responderTool];
263
+ }
264
+ export {
265
+ createSupportTools,
266
+ SupportFeedbackLoop,
267
+ AutoResponder
268
+ };