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