@majapisoftwares/agent-engine 0.1.0 → 0.1.1

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.
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+ // Shared conversation engine for the WhatsApp agents (the landing SDR and the
3
+ // Beskow customer service). Each agent adds only its own role prompt; how
4
+ // messages are written, split and delivered lives here, in one place.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CONVERSATION_STYLE_RULES = exports.CONVERSATION_MAX_BUBBLES = void 0;
7
+ exports.normalizeConversationReplies = normalizeConversationReplies;
8
+ exports.CONVERSATION_MAX_BUBBLES = 6;
9
+ // Communication rules every agent follows, written as prompt lines.
10
+ exports.CONVERSATION_STYLE_RULES = [
11
+ "Retorne replies como um array de mensagens (no máximo 4 por turno), cada uma uma bolha de WhatsApp. Prefira uma única mensagem curta; use outras bolhas somente quando houver conteúdo distinto que realmente justifique a separação. Não acrescente uma bolha só para acolher, confirmar ou preencher silêncio.",
12
+ "Cada item de replies é uma mensagem separada e já sai como bolha própria no WhatsApp. Nunca junte duas ideias em um mesmo item separando-as por linha em branco: coloque cada uma em seu próprio item.",
13
+ "Um link vai sozinho em uma bolha própria, só com a URL exata, sem texto antes nem depois, para o WhatsApp mostrar o botão do link. Explique em uma bolha anterior o que é o link e o que a pessoa deve informar nele.",
14
+ "Use somente texto simples. Nunca use Markdown, listas formatadas, blocos de código, negrito, itálico, links formatados, travessão ou meia-risca (— ou –).",
15
+ "Faça no máximo uma pergunta em todo o turno, normalmente na última bolha de replies.",
16
+ "Cumprimente e use o nome da pessoa só uma vez. Se o histórico já mostra uma saudação ou o nome dela, não repita 'Oi, Fulano!' nem reabra a conversa a cada resposta: vá direto ao conteúdo. Se a sua mensagem anterior já usou o nome da pessoa (por exemplo 'Perfeito, Ítalo.'), a resposta seguinte não pode começar com o nome nem com outro vocativo ('Claro, Ítalo.'): comece pelo conteúdo.",
17
+ "Nunca encerre a conversa no mesmo turno em que faz uma pergunta que espera resposta. Perguntas de fechamento como 'ficou tudo certo?', 'posso ajudar em mais algo?' e despedidas só entram quando o assunto realmente acabou e não há pergunta pendente para a pessoa; nesse caso a confirmação é a única pergunta do turno.",
18
+ ];
19
+ function isUrlToken(token) {
20
+ return token.startsWith("https://") || token.startsWith("http://");
21
+ }
22
+ const URL_TRAILING_PUNCTUATION = [".", ",", ";", ":", "!", "?", ")"];
23
+ // Splits a block into text pieces and standalone URLs, keeping order.
24
+ function separateUrls(block) {
25
+ const pieces = [];
26
+ let lines = [];
27
+ let tokens = [];
28
+ const flushText = () => {
29
+ if (tokens.length > 0)
30
+ lines.push(tokens.join(" "));
31
+ const joined = lines.join("\n").trim();
32
+ if (joined)
33
+ pieces.push(joined);
34
+ lines = [];
35
+ tokens = [];
36
+ };
37
+ for (const line of block.split("\n")) {
38
+ for (const token of line.split(" ").filter(Boolean)) {
39
+ if (!isUrlToken(token)) {
40
+ tokens.push(token);
41
+ continue;
42
+ }
43
+ let url = token;
44
+ while (url.length > 1 &&
45
+ URL_TRAILING_PUNCTUATION.includes(url[url.length - 1])) {
46
+ url = url.slice(0, -1);
47
+ }
48
+ flushText();
49
+ pieces.push(url);
50
+ }
51
+ if (tokens.length > 0)
52
+ lines.push(tokens.join(" "));
53
+ tokens = [];
54
+ }
55
+ flushText();
56
+ return pieces;
57
+ }
58
+ // Turns the model's replies into the final WhatsApp bubbles: each block
59
+ // separated by a blank line becomes its own message and every link goes alone.
60
+ function normalizeConversationReplies(replies) {
61
+ const bubbles = [];
62
+ for (const reply of replies) {
63
+ const withLinks = convertLeadAgentMarkdownLinks(reply);
64
+ for (const block of withLinks.split(/\n\s*\n/)) {
65
+ for (const piece of separateUrls(block)) {
66
+ if (isUrlToken(piece)) {
67
+ bubbles.push(piece);
68
+ continue;
69
+ }
70
+ const plain = toPlainText(piece);
71
+ if (plain)
72
+ bubbles.push(plain);
73
+ }
74
+ }
75
+ }
76
+ return bubbles.slice(0, exports.CONVERSATION_MAX_BUBBLES);
77
+ }
78
+ function unwrapPairedMarker(text, marker) {
79
+ let result = "";
80
+ let cursor = 0;
81
+ while (cursor < text.length) {
82
+ const openingIndex = text.indexOf(marker, cursor);
83
+ if (openingIndex === -1) {
84
+ result += text.slice(cursor);
85
+ break;
86
+ }
87
+ const contentStart = openingIndex + marker.length;
88
+ const closingIndex = text.indexOf(marker, contentStart);
89
+ if (closingIndex === -1) {
90
+ result += text.slice(cursor);
91
+ break;
92
+ }
93
+ result += text.slice(cursor, openingIndex);
94
+ result += text.slice(contentStart, closingIndex);
95
+ cursor = closingIndex + marker.length;
96
+ }
97
+ return result;
98
+ }
99
+ function convertLeadAgentMarkdownLinks(text) {
100
+ let result = "";
101
+ let cursor = 0;
102
+ while (cursor < text.length) {
103
+ const openingIndex = text.indexOf("[", cursor);
104
+ if (openingIndex === -1) {
105
+ result += text.slice(cursor);
106
+ break;
107
+ }
108
+ const separatorIndex = text.indexOf("](", openingIndex + 1);
109
+ const closingIndex = separatorIndex === -1 ? -1 : text.indexOf(")", separatorIndex + 2);
110
+ if (separatorIndex === -1 || closingIndex === -1) {
111
+ result += text.slice(cursor);
112
+ break;
113
+ }
114
+ const label = text.slice(openingIndex + 1, separatorIndex).trim();
115
+ const url = text.slice(separatorIndex + 2, closingIndex).trim();
116
+ const imageMarkerIndex = openingIndex - 1;
117
+ const contentEnd = imageMarkerIndex >= cursor && text[imageMarkerIndex] === "!"
118
+ ? imageMarkerIndex
119
+ : openingIndex;
120
+ result += text.slice(cursor, contentEnd);
121
+ result += url ? `${label} (${url})` : label;
122
+ cursor = closingIndex + 1;
123
+ }
124
+ return result;
125
+ }
126
+ function stripLeadAgentMarkdownLinePrefix(line) {
127
+ const trimmed = line.trimStart();
128
+ if (!trimmed) {
129
+ return "";
130
+ }
131
+ if (trimmed.length >= 3 &&
132
+ ["-", "*", "_"].includes(trimmed[0]) &&
133
+ Array.from(trimmed).every((character) => character === trimmed[0])) {
134
+ return "";
135
+ }
136
+ let headingLength = 0;
137
+ while (trimmed[headingLength] === "#" && headingLength < 6) {
138
+ headingLength += 1;
139
+ }
140
+ if (headingLength > 0 && trimmed[headingLength] === " ") {
141
+ return trimmed.slice(headingLength + 1);
142
+ }
143
+ if (trimmed.startsWith("> ")) {
144
+ return trimmed.slice(2);
145
+ }
146
+ if (["- ", "* ", "+ "].some((marker) => trimmed.startsWith(marker))) {
147
+ return trimmed.slice(2);
148
+ }
149
+ let digitCount = 0;
150
+ while (digitCount < trimmed.length &&
151
+ trimmed[digitCount] >= "0" &&
152
+ trimmed[digitCount] <= "9") {
153
+ digitCount += 1;
154
+ }
155
+ if (digitCount > 0 &&
156
+ [".", ")"].includes(trimmed[digitCount]) &&
157
+ trimmed[digitCount + 1] === " ") {
158
+ return trimmed.slice(digitCount + 2);
159
+ }
160
+ return line;
161
+ }
162
+ function toPlainText(reply) {
163
+ let plainReply = convertLeadAgentMarkdownLinks(reply)
164
+ .split("\n")
165
+ .map(stripLeadAgentMarkdownLinePrefix)
166
+ .join("\n");
167
+ for (const marker of ["```", "**", "__", "~~", "`", "*", "_"]) {
168
+ plainReply = unwrapPairedMarker(plainReply, marker);
169
+ }
170
+ plainReply = plainReply
171
+ .replaceAll(" — ", ", ")
172
+ .replaceAll(" – ", ", ")
173
+ .replaceAll("—", ",")
174
+ .replaceAll("–", ",")
175
+ .replaceAll(" ,", ",")
176
+ .replaceAll(", .", ".")
177
+ .replaceAll(", !", "!")
178
+ .replaceAll(", ?", "?")
179
+ .trim();
180
+ while (plainReply.includes("\n\n\n")) {
181
+ plainReply = plainReply.replaceAll("\n\n\n", "\n\n");
182
+ }
183
+ return plainReply;
184
+ }
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeConversationReplies = exports.CONVERSATION_STYLE_RULES = exports.CONVERSATION_MAX_BUBBLES = void 0;
4
+ var conversation_engine_js_1 = require("./conversation-engine.js");
5
+ Object.defineProperty(exports, "CONVERSATION_MAX_BUBBLES", { enumerable: true, get: function () { return conversation_engine_js_1.CONVERSATION_MAX_BUBBLES; } });
6
+ Object.defineProperty(exports, "CONVERSATION_STYLE_RULES", { enumerable: true, get: function () { return conversation_engine_js_1.CONVERSATION_STYLE_RULES; } });
7
+ Object.defineProperty(exports, "normalizeConversationReplies", { enumerable: true, get: function () { return conversation_engine_js_1.normalizeConversationReplies; } });
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@majapisoftwares/agent-engine",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Shared base of the WhatsApp agents: style rules and reply normalization (bubbles, lone links, plain text).",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -12,7 +12,9 @@
12
12
  "exports": {
13
13
  ".": {
14
14
  "types": "./dist/index.d.ts",
15
- "import": "./dist/index.js"
15
+ "import": "./dist/index.js",
16
+ "require": "./dist/cjs/index.js",
17
+ "default": "./dist/index.js"
16
18
  }
17
19
  },
18
20
  "main": "./dist/index.js",
@@ -27,7 +29,7 @@
27
29
  "access": "public"
28
30
  },
29
31
  "scripts": {
30
- "build": "rm -rf dist && tsc -p tsconfig.build.json",
32
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && tsc -p tsconfig.cjs.json && node ../../scripts/mark-cjs.mjs dist/cjs",
31
33
  "typecheck": "tsc --noEmit"
32
34
  }
33
35
  }