cs-agent 0.0.0-stage → 0.1.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/README.md +114 -2
- package/channels/telegram.js +63 -0
- package/channels/whatsapp.js +73 -0
- package/config.example.json +1 -0
- package/data/faq.json +1 -0
- package/data/products.json +1 -0
- package/index.js +38 -0
- package/lib/agent.js +170 -0
- package/lib/config.js +15 -0
- package/lib/faq.js +44 -0
- package/lib/handover.js +21 -0
- package/lib/llm.js +59 -0
- package/lib/memory.js +56 -0
- package/lib/orders.js +42 -0
- package/lib/telegram-api.js +68 -0
- package/package.json +1 -6
- package/test/agent.test.js +144 -0
package/README.md
CHANGED
|
@@ -1,3 +1,115 @@
|
|
|
1
|
-
#
|
|
1
|
+
# cs-agent
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Agent bisnis khusus customer service untuk **WhatsApp + Telegram**.
|
|
4
|
+
Dibangun ulang dari CodeClaw (backup `codeclaw-2026-11-25`), tapi fungsinya
|
|
5
|
+
diganti total: **bukan coding agent lagi**.
|
|
6
|
+
|
|
7
|
+
Agent ini hanya bisa:
|
|
8
|
+
- Menjawab pertanyaan pelanggan dari FAQ toko
|
|
9
|
+
- Menyebutkan daftar harga
|
|
10
|
+
- Mencatat order dan mengirim ringkasannya ke pemilik toko
|
|
11
|
+
- Meneruskan ke manusia (handover) kalau pelanggan minta admin, marah, atau komplain
|
|
12
|
+
|
|
13
|
+
Agent ini **tidak bisa** menjalankan perintah sistem, membaca/mengubah file,
|
|
14
|
+
menjalankan kode, atau browsing. Tidak ada tool berbahaya di dalam kode ini.
|
|
15
|
+
|
|
16
|
+
## Yang dipakai ulang dari CodeClaw
|
|
17
|
+
|
|
18
|
+
| Bagian | Asal | Keterangan |
|
|
19
|
+
|---|---|---|
|
|
20
|
+
| `lib/llm.js` | `lib/llm.js` CodeClaw | Client chat completions OpenAI-compatible, disederhanakan, tanpa tool calling |
|
|
21
|
+
| `lib/telegram-api.js` | `lib/telegram-api.js` CodeClaw | Wrapper Bot API Telegram, hanya method yang dipakai CS |
|
|
22
|
+
| Pola config & session | `lib/config.js`, `lib/session.js` | Dijadikan `lib/config.js` + `lib/memory.js` (JSON, bukan SQLite) |
|
|
23
|
+
|
|
24
|
+
`telegram.js` CodeClaw yang lama **tidak** dipakai ulang — file itu monolit
|
|
25
|
+
penuh tool coding (shell, edit file, git, dll).
|
|
26
|
+
|
|
27
|
+
## Instalasi
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
cd cs-agent
|
|
31
|
+
npm install
|
|
32
|
+
cp config.example.json config.json
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Isi `config.json`:
|
|
36
|
+
- `telegram.botToken` — token bot dari @BotFather
|
|
37
|
+
- `shop.ownerTelegramChatId` — chat ID Telegram pemilik (untuk notifikasi order/handover)
|
|
38
|
+
- `shop.ownerWhatsapp` — nomor WA pemilik, format `62812...` (untuk notifikasi order/handover)
|
|
39
|
+
- `llm` — **opsional**. Kalau `enabled: false` atau API key tidak diisi, agent tetap jalan dengan mode FAQ saja. Kalau diisi, agent memakai LLM hanya untuk merangkai jawaban dari konteks FAQ — LLM tidak bisa menjalankan apa pun.
|
|
40
|
+
|
|
41
|
+
Jangan pernah memasukkan token asli ke git/repo. `config.json` sudah ada di `.gitignore`.
|
|
42
|
+
|
|
43
|
+
## Menjalankan
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npm start # semua channel yang enabled
|
|
47
|
+
npm run telegram # hanya Telegram
|
|
48
|
+
npm run whatsapp # hanya WhatsApp
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Telegram
|
|
52
|
+
Bot jalan dengan long polling. Pelanggan cukup chat bot seperti biasa.
|
|
53
|
+
Perintah pemilik (kirim dari chat pemilik): `/reset <customerId>` untuk
|
|
54
|
+
mencabut status handover pelanggan, supaya agent menjawab lagi.
|
|
55
|
+
|
|
56
|
+
### WhatsApp
|
|
57
|
+
Saat pertama jalan, terminal menampilkan **QR code**. Scan dengan WhatsApp
|
|
58
|
+
di HP: *Perangkat Tertaut → Tautkan Perangkat*. Sesi tersimpan di
|
|
59
|
+
`data/wa-auth/` (jangan dibagikan ke siapa pun).
|
|
60
|
+
|
|
61
|
+
> ⚠️ **Penting — WhatsApp di sini UNOFFICIAL.** Agent memakai library
|
|
62
|
+
> `@whiskeysockets/baileys`, bukan WhatsApp Business API resmi. Risikonya:
|
|
63
|
+
> nomor bisa **diblokir Meta** kalau terdeteksi bot, terutama kalau spam
|
|
64
|
+
> atau mengirim banyak pesan sekaligus. Jangan pakai nomor utama/pribadi —
|
|
65
|
+
> pakai nomor khusus CS. Kalau butuh yang resmi dan aman, migrasikan ke
|
|
66
|
+
> WhatsApp Business API (Cloud API) nanti.
|
|
67
|
+
|
|
68
|
+
## Edit FAQ, produk, dan harga
|
|
69
|
+
|
|
70
|
+
Semua bisa diedit tanpa ubah kode:
|
|
71
|
+
|
|
72
|
+
- **FAQ:** `data/faq.json` — tambah objek `{question, keywords, answer}`.
|
|
73
|
+
`keywords` dipakai untuk pencocokan pertanyaan pelanggan.
|
|
74
|
+
- **Produk & harga:** `data/products.json` — tambah `{name, keywords, price, note}`.
|
|
75
|
+
- **Sapaan & jawaban fallback:** `config.json` bagian `cs`.
|
|
76
|
+
|
|
77
|
+
Order yang masuk tersimpan di `data/orders.json`, riwayat chat per pelanggan
|
|
78
|
+
di `data/memory.json`.
|
|
79
|
+
|
|
80
|
+
## Cara kerja agent
|
|
81
|
+
|
|
82
|
+
1. **Handover dulu:** kalau pelanggan minta manusia/admin/CS, marah, atau
|
|
83
|
+
komplain → agent berhenti menjawab, kirim pesan handover, dan memberi
|
|
84
|
+
tahu pemilik. Pesan berikutnya dari pelanggan itu hanya dibalas singkat
|
|
85
|
+
sampai pemilik mengirim `/reset <customerId>` (Telegram).
|
|
86
|
+
2. **Sapaan** → greeting toko.
|
|
87
|
+
3. **Order:** pelanggan tulis "saya mau order Token 50rb 2" → agent tanya
|
|
88
|
+
nama kalau belum tahu, lalu catat order (ID `ORD-...`), kirim ringkasan
|
|
89
|
+
ke pemilik, dan kirim info bayar QRIS ke pelanggan.
|
|
90
|
+
4. **Harga / FAQ** → jawab dari `products.json` / `faq.json`.
|
|
91
|
+
5. **LLM (kalau aktif)** → hanya untuk pertanyaan di luar FAQ, dengan
|
|
92
|
+
konteks FAQ + info toko. Kalau LLM gagal, pakai jawaban fallback.
|
|
93
|
+
6. **Tidak ada yang cocok** → jawaban fallback yang sopan + tawaran ke admin.
|
|
94
|
+
|
|
95
|
+
## Tes
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
npm test
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
11 tes simulasi pesan pelanggan, tanpa jaringan dan tanpa LLM asli:
|
|
102
|
+
tanya harga, cara bayar, cara order, lacak order, order tanpa nama lalu
|
|
103
|
+
kasih nama, order langsung, order tanpa produk jelas, minta manusia,
|
|
104
|
+
pelanggan marah, pertanyaan di luar FAQ (fallback), LLM aktif, sapaan.
|
|
105
|
+
|
|
106
|
+
## Batasan
|
|
107
|
+
|
|
108
|
+
- WhatsApp unofficial (Baileys) — risiko blokir nomor, lihat di atas.
|
|
109
|
+
- Koneksi WhatsApp/Telegram asli belum dicoba di sini — butuh QR scan
|
|
110
|
+
dan token bot asli.
|
|
111
|
+
- LLM opsional dan butuh API key sendiri (OpenAI-compatible).
|
|
112
|
+
- Order hanya dicatat; pembayaran QRIS tetap dikonfirmasi manual oleh pemilik.
|
|
113
|
+
- Agent hanya 1:1, tidak menjawab grup WhatsApp.
|
|
114
|
+
- Memori & order disimpan di file JSON lokal — cukup untuk toko kecil,
|
|
115
|
+
belum cocok untuk ribuan pelanggan per hari.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Channel Telegram — long polling Bot API.
|
|
2
|
+
// Dipakai ulang dari pola CodeClaw (lib/telegram-api.js), tapi TANPA
|
|
3
|
+
// tool, TANPA shell, TANPA eksekusi: hanya terima pesan -> agent -> balas.
|
|
4
|
+
import { TelegramAPI, escapeHtml } from "../lib/telegram-api.js";
|
|
5
|
+
|
|
6
|
+
export async function startTelegram({ agent, config }) {
|
|
7
|
+
const token = config.telegram?.botToken;
|
|
8
|
+
if (!token || /ISI_/.test(token)) {
|
|
9
|
+
console.log("[telegram] botToken belum diisi di config.json — channel Telegram dilewati.");
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
const tg = new TelegramAPI(token);
|
|
13
|
+
const me = await tg.getMe();
|
|
14
|
+
console.log(`[telegram] terhubung sebagai @${me.username} (${me.first_name})`);
|
|
15
|
+
const ownerChatId = config.shop?.ownerTelegramChatId;
|
|
16
|
+
|
|
17
|
+
let offset = 0;
|
|
18
|
+
let stopped = false;
|
|
19
|
+
|
|
20
|
+
const notifyOwner = (text) => {
|
|
21
|
+
if (ownerChatId && !/ISI_/.test(String(ownerChatId))) {
|
|
22
|
+
tg.sendMessage(ownerChatId, escapeHtml(text)).catch(() => {});
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
agent.addOwnerNotifier((text) => notifyOwner(text));
|
|
26
|
+
|
|
27
|
+
async function poll() {
|
|
28
|
+
while (!stopped) {
|
|
29
|
+
try {
|
|
30
|
+
const updates = await tg.getUpdates(offset, 30);
|
|
31
|
+
for (const u of updates) {
|
|
32
|
+
offset = u.update_id + 1;
|
|
33
|
+
const msg = u.message;
|
|
34
|
+
if (!msg?.text) continue;
|
|
35
|
+
const chatId = String(msg.chat.id);
|
|
36
|
+
const text = msg.text;
|
|
37
|
+
|
|
38
|
+
// Perintah pemilik: /reset <customerId> — cabut status handover.
|
|
39
|
+
if (ownerChatId && chatId === String(ownerChatId) && text.startsWith("/reset")) {
|
|
40
|
+
const target = text.split(/\s+/)[1];
|
|
41
|
+
if (target) {
|
|
42
|
+
agent.memory.clearHandover(target);
|
|
43
|
+
await tg.sendMessage(chatId, escapeHtml(`Handover untuk ${target} sudah dicabut. Agent akan menjawab lagi.`));
|
|
44
|
+
} else {
|
|
45
|
+
await tg.sendMessage(chatId, escapeHtml("Pakai: /reset <customerId>"));
|
|
46
|
+
}
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const from = msg.from || {};
|
|
51
|
+
const name = [from.first_name, from.last_name].filter(Boolean).join(" ") || null;
|
|
52
|
+
const result = await agent.handleMessage({ channel: "telegram", customerId: chatId, customerName: name, text });
|
|
53
|
+
await tg.sendMessage(chatId, escapeHtml(result.reply));
|
|
54
|
+
}
|
|
55
|
+
} catch (e) {
|
|
56
|
+
console.error("[telegram] poll error:", e.message);
|
|
57
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
poll();
|
|
62
|
+
return { stop() { stopped = true; } };
|
|
63
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Channel WhatsApp — unofficial, memakai @whiskeysockets/baileys.
|
|
2
|
+
// Cara kerja: scan QR yang muncul di terminal dengan WhatsApp di HP.
|
|
3
|
+
// RISIKO (baca README): ini BUKAN WhatsApp Business API resmi. Meta
|
|
4
|
+
// bisa memblokir nomor yang terdeteksi bot. Jangan pakai nomor utama;
|
|
5
|
+
// pakai nomor khusus CS, jangan spam, dan selalu ada handover ke manusia.
|
|
6
|
+
import makeWASocket, { DisconnectReason, fetchLatestBaileysVersion, useMultiFileAuthState } from "@whiskeysockets/baileys";
|
|
7
|
+
import qrcode from "qrcode-terminal";
|
|
8
|
+
import pino from "pino";
|
|
9
|
+
|
|
10
|
+
export async function startWhatsapp({ agent, config }) {
|
|
11
|
+
const authDir = config.whatsapp?.authDir || "./data/wa-auth";
|
|
12
|
+
const ownerJid = config.shop?.ownerWhatsapp
|
|
13
|
+
? `${String(config.shop.ownerWhatsapp).replace(/\D/g, "")}@s.whatsapp.net`
|
|
14
|
+
: null;
|
|
15
|
+
|
|
16
|
+
const { state, saveCreds } = await useMultiFileAuthState(authDir);
|
|
17
|
+
const { version } = await fetchLatestBaileysVersion();
|
|
18
|
+
|
|
19
|
+
const sock = makeWASocket({
|
|
20
|
+
version,
|
|
21
|
+
auth: state,
|
|
22
|
+
logger: pino({ level: "silent" }),
|
|
23
|
+
printQRInTerminal: false,
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
agent.addOwnerNotifier((text) => {
|
|
27
|
+
if (ownerJid) sock.sendMessage(ownerJid, { text }).catch(() => {});
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
sock.ev.on("creds.update", saveCreds);
|
|
31
|
+
|
|
32
|
+
sock.ev.on("connection.update", (update) => {
|
|
33
|
+
const { connection, lastDisconnect, qr } = update;
|
|
34
|
+
if (qr) {
|
|
35
|
+
console.log("[whatsapp] Scan QR ini dengan WhatsApp di HP (Perangkat Tertaut):");
|
|
36
|
+
qrcode.generate(qr, { small: true });
|
|
37
|
+
}
|
|
38
|
+
if (connection === "open") console.log("[whatsapp] terhubung.");
|
|
39
|
+
if (connection === "close") {
|
|
40
|
+
const code = lastDisconnect?.error?.output?.statusCode;
|
|
41
|
+
const loggedOut = code === DisconnectReason.loggedOut;
|
|
42
|
+
console.log(`[whatsapp] koneksi putus (kode ${code})${loggedOut ? " — sesi habis, hapus data/wa-auth lalu scan ulang." : " — mencoba sambung lagi..."}`);
|
|
43
|
+
if (!loggedOut) setTimeout(() => startWhatsapp({ agent, config }), 5000);
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
sock.ev.on("messages.upsert", async ({ messages, type }) => {
|
|
48
|
+
if (type !== "notify") return;
|
|
49
|
+
for (const m of messages) {
|
|
50
|
+
try {
|
|
51
|
+
if (!m.message || m.key.fromMe) continue;
|
|
52
|
+
const jid = m.key.remoteJid;
|
|
53
|
+
if (!jid || jid === "status@broadcast" || jid.endsWith("@g.us")) continue; // bukan grup
|
|
54
|
+
const text = m.message.conversation
|
|
55
|
+
|| m.message.extendedTextMessage?.text
|
|
56
|
+
|| m.message.imageMessage?.caption
|
|
57
|
+
|| "";
|
|
58
|
+
if (!text.trim()) continue;
|
|
59
|
+
const result = await agent.handleMessage({
|
|
60
|
+
channel: "whatsapp",
|
|
61
|
+
customerId: jid,
|
|
62
|
+
customerName: m.pushName || null,
|
|
63
|
+
text: text.trim(),
|
|
64
|
+
});
|
|
65
|
+
await sock.sendMessage(jid, { text: result.reply });
|
|
66
|
+
} catch (e) {
|
|
67
|
+
console.error("[whatsapp] gagal proses pesan:", e.message);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
return sock;
|
|
73
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"cs":{"fallbackMessage":"Maaf, saya belum bisa menjawab itu. Boleh tulis ulang dengan kata lain, atau ketik 'admin' untuk bicara dengan manusia.","greeting":"Halo! Selamat datang di Tokenobral. Ada yang bisa saya bantu? Ketik 'harga' untuk lihat daftar harga, atau langsung tulis pertanyaan Anda.","handoverMessage":"Baik, saya teruskan ke admin manusia. Mohon tunggu sebentar, admin akan segera membantu Anda."},"llm":{"apiKey":"ISI_API_KEY_LLM_JIKA_PAKAI","baseUrl":"https://api.openai.com/v1","enabled":false,"maxTokens":1024,"model":"gpt-4o-mini","temperature":0.3},"shop":{"description":"Toko token AI — beli token, bayar QRIS, token langsung aktif.","name":"Tokenobral","ownerName":"Agus","ownerTelegramChatId":"ISI_CHAT_ID_TELEGRAM_PEMILIK","ownerWhatsapp":"6281234567890","paymentInfo":"Pembayaran via QRIS. Setelah bayar, kirim bukti bayar ke admin, token langsung diaktifkan."},"telegram":{"botToken":"ISI_TOKEN_BOT_DARI_BOTFATHER","enabled":true},"whatsapp":{"authDir":"./data/wa-auth","enabled":true}}
|
package/data/faq.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
[{"answer":"Halo! Untuk order, tulis contohnya: \"saya mau order Token 50rb 1\". Setelah itu Anda akan diminta nama, lalu total dan cara bayar QRIS akan kami kirim. Setelah bayar, kirim bukti bayarnya di sini.","keywords":["cara order","cara pesan","cara beli","order","pesan","beli","gimana order"],"question":"Bagaimana cara order?"},{"answer":"Pembayaran via QRIS. Setelah Anda order, kami kirim totalnya. Silakan bayar via QRIS, lalu kirim bukti bayar di sini. Setelah bukti diterima, token langsung diaktifkan.","keywords":["cara bayar","bayar","qris","pembayaran","payment"],"question":"Bagaimana cara bayar?"},{"answer":"Untuk lacak order, kirim nomor order Anda (contoh: ORD-XXXX) atau nama Anda. Kalau sudah bayar dan kirim bukti, token biasanya aktif dalam beberapa menit. Kalau lebih dari 1 jam belum aktif, ketik 'admin' untuk dibantu manusia.","keywords":["lacak","status order","cek order","sudah bayar","kapan aktif"],"question":"Bagaimana cara lacak order?"},{"answer":"Jam layanan kami 08.00-22.00 WIB setiap hari. Di luar jam itu pesan Anda tetap kami balas secepatnya keesokan paginya.","keywords":["jam buka","jam layanan","jam operasional","buka jam"],"question":"Jam berapa toko buka?"},{"answer":"Token dipakai untuk mengakses layanan AI kami. Setelah aktif, token berlaku sesuai paket yang Anda beli dan bisa langsung dipakai.","keywords":["token itu apa","fungsi token","token buat apa"],"question":"Token itu untuk apa?"}]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
[{"keywords":["10rb","10 ribu","10k","paket kecil"],"name":"Token 10rb","note":"1.000 token","price":10000},{"keywords":["25rb","25 ribu","25k"],"name":"Token 25rb","note":"3.000 token","price":25000},{"keywords":["50rb","50 ribu","50k"],"name":"Token 50rb","note":"7.000 token","price":50000},{"keywords":["100rb","100 ribu","100k","paket besar"],"name":"Token 100rb","note":"15.000 token","price":100000}]
|
package/index.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Entry point cs-agent.
|
|
2
|
+
// node index.js -> jalanin semua channel yang enabled
|
|
3
|
+
// node index.js --telegram -> hanya Telegram
|
|
4
|
+
// node index.js --whatsapp -> hanya WhatsApp
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { loadConfig } from "./lib/config.js";
|
|
9
|
+
import { CSAgent } from "./lib/agent.js";
|
|
10
|
+
import { LLM } from "./lib/llm.js";
|
|
11
|
+
import { Memory } from "./lib/memory.js";
|
|
12
|
+
import { OrderStore } from "./lib/orders.js";
|
|
13
|
+
import { loadFaq } from "./lib/faq.js";
|
|
14
|
+
import { startTelegram } from "./channels/telegram.js";
|
|
15
|
+
import { startWhatsapp } from "./channels/whatsapp.js";
|
|
16
|
+
|
|
17
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
18
|
+
const args = process.argv.slice(2);
|
|
19
|
+
const onlyTelegram = args.includes("--telegram");
|
|
20
|
+
const onlyWhatsapp = args.includes("--whatsapp");
|
|
21
|
+
|
|
22
|
+
const config = loadConfig(__dirname);
|
|
23
|
+
const faq = loadFaq(path.join(__dirname, "data", "faq.json"));
|
|
24
|
+
const products = JSON.parse(fs.readFileSync(path.join(__dirname, "data", "products.json"), "utf8"));
|
|
25
|
+
const memory = new Memory(path.join(__dirname, "data", "memory.json"));
|
|
26
|
+
const orders = new OrderStore(path.join(__dirname, "data", "orders.json"));
|
|
27
|
+
const llm = new LLM(config.llm || {});
|
|
28
|
+
|
|
29
|
+
const agent = new CSAgent({ config, faq, products, memory, orders, llm });
|
|
30
|
+
console.log(`[cs-agent] ${config.shop?.name || "toko"} siap. LLM: ${llm.configured ? "aktif" : "nonaktif (mode FAQ saja)"}.`);
|
|
31
|
+
|
|
32
|
+
if (!onlyWhatsapp && config.telegram?.enabled) {
|
|
33
|
+
await startTelegram({ agent, config });
|
|
34
|
+
}
|
|
35
|
+
if (!onlyTelegram && config.whatsapp?.enabled) {
|
|
36
|
+
await startWhatsapp({ agent, config });
|
|
37
|
+
}
|
|
38
|
+
console.log("[cs-agent] berjalan. Tekan Ctrl+C untuk berhenti.");
|
package/lib/agent.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// Otak CS agent — SATU-SATUNYA tempat logika percakapan.
|
|
2
|
+
// TIDAK ADA tool berbahaya di sini: tidak ada shell, tidak ada baca/tulis
|
|
3
|
+
// file oleh LLM, tidak ada akses sistem. Agent hanya:
|
|
4
|
+
// 1. cek handover ke manusia
|
|
5
|
+
// 2. tangkap nama & order pelanggan
|
|
6
|
+
// 3. jawab dari FAQ / daftar harga
|
|
7
|
+
// 4. kalau LLM aktif, minta LLM merangkai jawaban dari konteks FAQ
|
|
8
|
+
// 5. kalau tidak ada yang cocok, jawab fallback yang sopan
|
|
9
|
+
import { findFaq, priceList } from "./faq.js";
|
|
10
|
+
import { needsHandover } from "./handover.js";
|
|
11
|
+
|
|
12
|
+
const GREETINGS = ["halo", "hai", "hi", "pagi", "siang", "sore", "malam", "selamat", "assalamu", "permisi", "start"];
|
|
13
|
+
const NUMBER_WORDS = { satu: 1, dua: 2, tiga: 3, empat: 4, lima: 5 };
|
|
14
|
+
|
|
15
|
+
export class CSAgent {
|
|
16
|
+
constructor({ config, faq, products, memory, orders, llm = null, onOwnerNotify = null }) {
|
|
17
|
+
this.config = config;
|
|
18
|
+
this.faq = faq;
|
|
19
|
+
this.products = products;
|
|
20
|
+
this.memory = memory;
|
|
21
|
+
this.orders = orders;
|
|
22
|
+
this.llm = llm;
|
|
23
|
+
this.ownerNotifiers = [];
|
|
24
|
+
if (onOwnerNotify) this.ownerNotifiers.push(onOwnerNotify);
|
|
25
|
+
this.shop = config.shop || {};
|
|
26
|
+
this.cs = config.cs || {};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
addOwnerNotifier(fn) {
|
|
30
|
+
if (typeof fn === "function") this.ownerNotifiers.push(fn);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
notify(ownerText) {
|
|
34
|
+
for (const fn of this.ownerNotifiers) {
|
|
35
|
+
try { fn(ownerText); } catch {}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
findProduct(text) {
|
|
40
|
+
const t = String(text || "").toLowerCase();
|
|
41
|
+
for (const p of this.products) {
|
|
42
|
+
const keys = [p.name.toLowerCase(), ...(p.keywords || []).map((k) => k.toLowerCase())];
|
|
43
|
+
if (keys.some((k) => k && t.includes(k))) return p;
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
parseQty(text) {
|
|
49
|
+
const t = String(text || "");
|
|
50
|
+
// "x2" / "2 pcs" / "2 buah" dulu, baru angka berdiri sendiri di akhir
|
|
51
|
+
// ("Token 50rb 2"). Angka harga ("50rb") JANGAN dihitung sebagai jumlah.
|
|
52
|
+
const x = t.match(/x\s*(\d+)/i);
|
|
53
|
+
if (x) return Math.max(1, parseInt(x[1], 10));
|
|
54
|
+
const unit = t.match(/(\d+)\s*(?:pcs|buah|biji)\b/i);
|
|
55
|
+
if (unit) return Math.max(1, parseInt(unit[1], 10));
|
|
56
|
+
const tail = t.trim().match(/(?:^|\s)(\d+)\s*$/);
|
|
57
|
+
if (tail) return Math.max(1, parseInt(tail[1], 10));
|
|
58
|
+
const low = t.toLowerCase();
|
|
59
|
+
for (const [w, n] of Object.entries(NUMBER_WORDS)) if (low.includes(w)) return n;
|
|
60
|
+
return 1;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async handleMessage({ channel, customerId, customerName, text }) {
|
|
64
|
+
const msg = String(text || "").trim();
|
|
65
|
+
const mem = this.memory.get(customerId);
|
|
66
|
+
if (customerName && !mem.name) this.memory.setName(customerId, customerName);
|
|
67
|
+
this.memory.addMessage(customerId, "user", msg);
|
|
68
|
+
const lower = msg.toLowerCase();
|
|
69
|
+
|
|
70
|
+
// 0. Kalau sudah di-handover, agent tidak menjawab lagi.
|
|
71
|
+
if (mem.handover) {
|
|
72
|
+
this.notify(`[Handover] ${mem.name || customerId} (${channel}) menulis lagi: "${msg.slice(0, 200)}"`);
|
|
73
|
+
return { reply: "Admin sedang menangani chat Anda, mohon tunggu sebentar ya.", notifyOwner: true };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// 1. Handover: minta manusia / marah / komplain.
|
|
77
|
+
const handoverReason = needsHandover(msg);
|
|
78
|
+
if (handoverReason) {
|
|
79
|
+
this.memory.setHandover(customerId, true);
|
|
80
|
+
this.notify(`[Handover: ${handoverReason}] ${mem.name || customerName || customerId} (${channel}): "${msg.slice(0, 200)}"`);
|
|
81
|
+
return { reply: this.cs.handoverMessage || "Baik, saya teruskan ke admin manusia. Mohon tunggu sebentar.", notifyOwner: true };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// 2. Sapaan / /start
|
|
85
|
+
if (!msg || lower === "/start" || GREETINGS.some((g) => lower === g || lower.startsWith(g + " "))) {
|
|
86
|
+
return { reply: this.cs.greeting || "Halo! Ada yang bisa saya bantu?" };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 3. Nama pelanggan: "nama saya Budi" — selesaikan order yang tertunda.
|
|
90
|
+
const nameMatch = msg.match(/nama saya\s+([A-Za-z ]{2,30})/i);
|
|
91
|
+
if (nameMatch) {
|
|
92
|
+
const name = nameMatch[1].trim();
|
|
93
|
+
this.memory.setName(customerId, name);
|
|
94
|
+
const pending = this.memory.get(customerId).pendingOrder;
|
|
95
|
+
if (pending) {
|
|
96
|
+
const product = this.products.find((p) => p.name === pending.productName);
|
|
97
|
+
if (product) {
|
|
98
|
+
const order = this.orders.add({ channel, customerId, customerName: name, product, qty: pending.qty, price: product.price });
|
|
99
|
+
this.memory.setPendingOrder(customerId, null);
|
|
100
|
+
this.notify(`[Order baru]\n${this.orders.summary(order)}`);
|
|
101
|
+
return { reply: `Terima kasih, ${name}! Order Anda sudah dicatat:\n\n${this.orders.summary(order)}\n\n${this.shop.paymentInfo || ""}\n\nSilakan bayar, lalu kirim bukti bayarnya di sini ya.`, order, notifyOwner: true };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return { reply: `Baik, terima kasih ${name}! Ada lagi yang bisa saya bantu?` };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// 4. Order dengan produk yang jelas: "saya mau order Token 50rb 2".
|
|
108
|
+
// Sengaja dicek SEBELUM FAQ supaya perintah order tidak tertangkap
|
|
109
|
+
// jawaban FAQ "cara order".
|
|
110
|
+
const isOrderIntent = /\b(order|beli|pesan|mau|ambil)\b/.test(lower);
|
|
111
|
+
const product = this.findProduct(msg);
|
|
112
|
+
if (isOrderIntent && product) {
|
|
113
|
+
const qty = this.parseQty(msg);
|
|
114
|
+
const total = product.price * qty;
|
|
115
|
+
const name = mem.name || customerName;
|
|
116
|
+
if (!name) {
|
|
117
|
+
this.memory.setPendingOrder(customerId, { productName: product.name, qty });
|
|
118
|
+
return { reply: `Siap! ${product.name} x${qty}, total Rp ${total.toLocaleString("id-ID")}. Boleh tahu nama Anda? (tulis: nama saya Budi)` };
|
|
119
|
+
}
|
|
120
|
+
const order = this.orders.add({ channel, customerId, customerName: name, product, qty, price: product.price });
|
|
121
|
+
this.notify(`[Order baru]\n${this.orders.summary(order)}`);
|
|
122
|
+
return { reply: `Terima kasih, ${name}! Order Anda sudah dicatat:\n\n${this.orders.summary(order)}\n\n${this.shop.paymentInfo || ""}\n\nSilakan bayar, lalu kirim bukti bayarnya di sini ya.`, order, notifyOwner: true };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// 5. Order tanpa produk yang jelas — tanya produknya.
|
|
126
|
+
// Kecuali kalau kalimatnya berupa pertanyaan ("bagaimana cara order?"),
|
|
127
|
+
// itu dijawab FAQ di bawah.
|
|
128
|
+
const isQuestion = /^(bagaimana|gimana|cara|apa|apakah)\b/i.test(msg) || msg.includes("?");
|
|
129
|
+
if (isOrderIntent && !isQuestion) {
|
|
130
|
+
return { reply: `Siap! Produk yang mana ya? Ini daftarnya:\n\n${priceList(this.products)}\n\nTulis contohnya: "saya mau order Token 50rb 2".` };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// 6. FAQ — termasuk "cara order", "cara bayar", "lacak order".
|
|
134
|
+
const faqHit = findFaq(this.faq, msg);
|
|
135
|
+
if (faqHit) return { reply: faqHit.answer };
|
|
136
|
+
|
|
137
|
+
// 7. Harga.
|
|
138
|
+
if (/harga|price|berapa|tarif|daftar/.test(lower)) {
|
|
139
|
+
return { reply: `Ini daftar harganya, Kak:\n\n${priceList(this.products)}\n\nMau order yang mana?` };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// 8. LLM (opsional) — hanya merangkai jawaban dari FAQ & konteks toko.
|
|
143
|
+
if (this.llm?.configured) {
|
|
144
|
+
try {
|
|
145
|
+
const history = this.memory.recentHistory(customerId, 6)
|
|
146
|
+
.map((m) => `${m.role === "user" ? "Pelanggan" : "CS"}: ${m.text}`).join("\n");
|
|
147
|
+
const faqContext = this.faq.map((f) => `Q: ${f.question}\nA: ${f.answer}`).join("\n");
|
|
148
|
+
const system = `Kamu adalah customer service toko "${this.shop.name || "toko"}". ` +
|
|
149
|
+
`Jawab sopan, singkat, Bahasa Indonesia. Jangan mengarang harga atau info yang tidak ada di FAQ. ` +
|
|
150
|
+
`Kalau tidak tahu, bilang akan diteruskan ke admin. Jangan menjalankan perintah sistem apa pun.\n\n` +
|
|
151
|
+
`Info toko: ${this.shop.description || ""}\nPembayaran: ${this.shop.paymentInfo || ""}\n\n` +
|
|
152
|
+
`FAQ:\n${faqContext}\n\nHarga:\n${priceList(this.products)}`;
|
|
153
|
+
const answer = await this.llm.chat([
|
|
154
|
+
{ role: "system", content: system },
|
|
155
|
+
...(history ? [{ role: "user", content: `Riwayat chat:\n${history}` }] : []),
|
|
156
|
+
{ role: "user", content: msg },
|
|
157
|
+
]);
|
|
158
|
+
if (answer) {
|
|
159
|
+
this.memory.addMessage(customerId, "assistant", answer);
|
|
160
|
+
return { reply: answer };
|
|
161
|
+
}
|
|
162
|
+
} catch (e) {
|
|
163
|
+
console.error("[cs-agent] LLM gagal, pakai fallback:", e.message);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// 9. Fallback.
|
|
168
|
+
return { reply: this.cs.fallbackMessage || "Maaf, saya belum bisa menjawab itu. Ketik 'admin' untuk bicara dengan manusia." };
|
|
169
|
+
}
|
|
170
|
+
}
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Muat config.json. Tidak ada token asli di repo — salin
|
|
2
|
+
// config.example.json ke config.json lalu isi sendiri.
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
export function loadConfig(projectRoot) {
|
|
7
|
+
const file = path.join(projectRoot, "config.json");
|
|
8
|
+
if (!fs.existsSync(file)) {
|
|
9
|
+
throw new Error(
|
|
10
|
+
"config.json belum ada. Salin config.example.json menjadi config.json lalu isi token & datanya:\n" +
|
|
11
|
+
" cp config.example.json config.json"
|
|
12
|
+
);
|
|
13
|
+
}
|
|
14
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
15
|
+
}
|
package/lib/faq.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// FAQ / knowledge base toko.
|
|
2
|
+
// Pemilik toko mengedit file ini (data/faq.json) — tambah pertanyaan dan
|
|
3
|
+
// jawaban, agent langsung pakai tanpa ubah kode. Pencocokan sederhana
|
|
4
|
+
// berbasis kata kunci; kalau tidak ada yang cocok, agent pakai LLM
|
|
5
|
+
// (kalau aktif) atau jawaban fallback.
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
|
|
8
|
+
function norm(s) {
|
|
9
|
+
return String(s || "").toLowerCase().replace(/[^a-z0-9\s]/g, " ").replace(/\s+/g, " ").trim();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function loadFaq(filePath) {
|
|
13
|
+
const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
14
|
+
return raw.map((f) => ({
|
|
15
|
+
...f,
|
|
16
|
+
_keywords: (f.keywords || []).map((k) => norm(k)),
|
|
17
|
+
_question: norm(f.question),
|
|
18
|
+
}));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function findFaq(faq, text) {
|
|
22
|
+
const query = norm(text);
|
|
23
|
+
if (!query) return null;
|
|
24
|
+
const words = new Set(query.split(" ").filter((w) => w.length > 2));
|
|
25
|
+
let best = null;
|
|
26
|
+
let bestScore = 0;
|
|
27
|
+
for (const item of faq) {
|
|
28
|
+
let score = 0;
|
|
29
|
+
for (const kw of item._keywords) {
|
|
30
|
+
if (query.includes(kw)) score += 3;
|
|
31
|
+
}
|
|
32
|
+
for (const w of words) {
|
|
33
|
+
if (item._question.includes(w)) score += 1;
|
|
34
|
+
}
|
|
35
|
+
if (score > bestScore) { bestScore = score; best = item; }
|
|
36
|
+
}
|
|
37
|
+
return bestScore >= 2 ? best : null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function priceList(products) {
|
|
41
|
+
return products
|
|
42
|
+
.map((p) => `- ${p.name}: Rp ${p.price.toLocaleString("id-ID")}${p.note ? ` (${p.note})` : ""}`)
|
|
43
|
+
.join("\n");
|
|
44
|
+
}
|
package/lib/handover.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Deteksi handover ke manusia.
|
|
2
|
+
// Agent berhenti menjawab sendiri dan meneruskan ke pemilik toko kalau:
|
|
3
|
+
// - pelanggan minta manusia / admin / CS / orang
|
|
4
|
+
// - pelanggan marah / komplain keras
|
|
5
|
+
// - pelanggan minta refund / komplain penipuan
|
|
6
|
+
const HUMAN_WORDS = [
|
|
7
|
+
"manusia", "admin", "cs", "customer service", "orang", "operator",
|
|
8
|
+
"bicara dengan manusia", "mau admin", "panggil admin", "tolong manusia",
|
|
9
|
+
];
|
|
10
|
+
const ANGRY_WORDS = [
|
|
11
|
+
"penipu", "bohong", "scam", "jelek", "buruk", "kecewa", "marah",
|
|
12
|
+
"parah", "refund", "kembalikan uang", "komplain", "lapor", "bodoh",
|
|
13
|
+
"tidak becus", "mengecewakan",
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
export function needsHandover(text) {
|
|
17
|
+
const t = String(text || "").toLowerCase();
|
|
18
|
+
if (HUMAN_WORDS.some((w) => t.includes(w))) return "minta manusia";
|
|
19
|
+
if (ANGRY_WORDS.some((w) => t.includes(w))) return "pelanggan marah/komplain";
|
|
20
|
+
return null;
|
|
21
|
+
}
|
package/lib/llm.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// LLM client — diadaptasi dari CodeClaw (lib/llm.js), disederhanakan.
|
|
2
|
+
// Hanya chat completions OpenAI-compatible, TANPA tool calling, TANPA
|
|
3
|
+
// eksekusi apa pun. Dipakai agent hanya untuk merangkai jawaban sopan
|
|
4
|
+
// dari konteks FAQ; kalau LLM tidak dikonfigurasi, agent tetap jalan
|
|
5
|
+
// dengan mode FAQ saja (lihat lib/agent.js).
|
|
6
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
7
|
+
|
|
8
|
+
export class LLM {
|
|
9
|
+
constructor(cfg = {}) {
|
|
10
|
+
this.baseUrl = String(cfg.baseUrl || "").replace(/\/+$/, "");
|
|
11
|
+
this.apiKey = cfg.apiKey || "";
|
|
12
|
+
this.model = cfg.model || "gpt-4o-mini";
|
|
13
|
+
this.maxTokens = cfg.maxTokens ?? 1024;
|
|
14
|
+
this.temperature = cfg.temperature ?? 0.3;
|
|
15
|
+
this.maxRetries = 2;
|
|
16
|
+
this.timeoutMs = 60_000;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
get configured() {
|
|
20
|
+
return Boolean(this.baseUrl && this.apiKey && !/ISI_/.test(this.apiKey));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async chat(messages) {
|
|
24
|
+
if (!this.configured) throw new Error("LLM belum dikonfigurasi");
|
|
25
|
+
let lastErr;
|
|
26
|
+
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
27
|
+
if (attempt > 0) await sleep(Math.min(500 * 2 ** (attempt - 1), 4000));
|
|
28
|
+
try {
|
|
29
|
+
const res = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
30
|
+
method: "POST",
|
|
31
|
+
headers: {
|
|
32
|
+
"Content-Type": "application/json",
|
|
33
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
34
|
+
},
|
|
35
|
+
body: JSON.stringify({
|
|
36
|
+
model: this.model,
|
|
37
|
+
messages,
|
|
38
|
+
max_tokens: this.maxTokens,
|
|
39
|
+
temperature: this.temperature,
|
|
40
|
+
stream: false,
|
|
41
|
+
}),
|
|
42
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
43
|
+
});
|
|
44
|
+
if (!res.ok) {
|
|
45
|
+
const text = await res.text().catch(() => "");
|
|
46
|
+
const err = new Error(`LLM HTTP ${res.status}: ${text.slice(0, 300)}`);
|
|
47
|
+
err.fatal = !(res.status === 429 || res.status >= 500);
|
|
48
|
+
throw err;
|
|
49
|
+
}
|
|
50
|
+
const json = await res.json();
|
|
51
|
+
return json.choices?.[0]?.message?.content?.trim() || "";
|
|
52
|
+
} catch (err) {
|
|
53
|
+
lastErr = err;
|
|
54
|
+
if (err.fatal) break;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
throw new Error(`LLM gagal: ${lastErr?.message || "unknown"}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
package/lib/memory.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Memori percakapan per pelanggan — disimpan di file JSON lokal.
|
|
2
|
+
// Isi: riwayat pesan singkat, nama pelanggan, status handover, dan
|
|
3
|
+
// order yang sedang diproses. Bukan database berat, cukup untuk toko kecil.
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
|
|
6
|
+
export class Memory {
|
|
7
|
+
constructor(filePath) {
|
|
8
|
+
this.filePath = filePath;
|
|
9
|
+
this.data = {};
|
|
10
|
+
try {
|
|
11
|
+
if (fs.existsSync(filePath)) this.data = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
12
|
+
} catch { this.data = {}; }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
save() {
|
|
16
|
+
try { fs.writeFileSync(this.filePath, JSON.stringify(this.data, null, 2)); } catch {}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
get(customerId) {
|
|
20
|
+
if (!this.data[customerId]) {
|
|
21
|
+
this.data[customerId] = { name: null, history: [], handover: false, pendingOrder: null };
|
|
22
|
+
}
|
|
23
|
+
return this.data[customerId];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
addMessage(customerId, role, text) {
|
|
27
|
+
const c = this.get(customerId);
|
|
28
|
+
c.history.push({ role, text: String(text).slice(0, 500), at: new Date().toISOString() });
|
|
29
|
+
if (c.history.length > 20) c.history = c.history.slice(-20);
|
|
30
|
+
this.save();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
recentHistory(customerId, n = 6) {
|
|
34
|
+
return this.get(customerId).history.slice(-n);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
setName(customerId, name) {
|
|
38
|
+
this.get(customerId).name = name;
|
|
39
|
+
this.save();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
setHandover(customerId, value) {
|
|
43
|
+
this.get(customerId).handover = value;
|
|
44
|
+
this.save();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
setPendingOrder(customerId, order) {
|
|
48
|
+
this.get(customerId).pendingOrder = order;
|
|
49
|
+
this.save();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
clearHandover(customerId) {
|
|
53
|
+
this.get(customerId).handover = false;
|
|
54
|
+
this.save();
|
|
55
|
+
}
|
|
56
|
+
}
|
package/lib/orders.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Pencatatan order — disimpan ke file JSON lokal (data/orders.json).
|
|
2
|
+
// Tidak ada database eksternal, tidak ada pengiriman uang di sini:
|
|
3
|
+
// order hanya dicatat, pembayaran tetap via QRIS dan konfirmasi manual.
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
|
|
6
|
+
export class OrderStore {
|
|
7
|
+
constructor(filePath) {
|
|
8
|
+
this.filePath = filePath;
|
|
9
|
+
this.orders = [];
|
|
10
|
+
try {
|
|
11
|
+
if (fs.existsSync(filePath)) this.orders = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
12
|
+
} catch { this.orders = []; }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
save() {
|
|
16
|
+
try { fs.writeFileSync(this.filePath, JSON.stringify(this.orders, null, 2)); } catch {}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
add({ channel, customerId, customerName, product, qty, price }) {
|
|
20
|
+
const order = {
|
|
21
|
+
id: `ORD-${Date.now().toString(36).toUpperCase()}-${String(this.orders.length + 1).padStart(3, "0")}`,
|
|
22
|
+
channel,
|
|
23
|
+
customerId,
|
|
24
|
+
customerName: customerName || "-",
|
|
25
|
+
product: product.name,
|
|
26
|
+
qty,
|
|
27
|
+
unitPrice: product.price,
|
|
28
|
+
total: product.price * qty,
|
|
29
|
+
status: "pending",
|
|
30
|
+
createdAt: new Date().toISOString(),
|
|
31
|
+
};
|
|
32
|
+
this.orders.push(order);
|
|
33
|
+
this.save();
|
|
34
|
+
return order;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
list() { return this.orders; }
|
|
38
|
+
|
|
39
|
+
summary(order) {
|
|
40
|
+
return `Order ${order.id}\nProduk: ${order.product} x${order.qty}\nTotal: Rp ${order.total.toLocaleString("id-ID")}\nPelanggan: ${order.customerName} (${order.channel})`;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Wrapper Telegram Bot API — diadaptasi dari CodeClaw (lib/telegram-api.js).
|
|
2
|
+
// Hanya method yang dibutuhkan CS agent: getMe, getUpdates, sendMessage,
|
|
3
|
+
// sendChatAction. Tidak ada download file, tidak ada edit file.
|
|
4
|
+
function splitForTelegram(text, max = 4000) {
|
|
5
|
+
const s = String(text ?? "");
|
|
6
|
+
if (s.length <= max) return [s];
|
|
7
|
+
const parts = [];
|
|
8
|
+
let rest = s;
|
|
9
|
+
while (rest.length > max) {
|
|
10
|
+
let cut = rest.lastIndexOf("\n", max);
|
|
11
|
+
if (cut < Math.floor(max * 0.5)) cut = max;
|
|
12
|
+
parts.push(rest.slice(0, cut));
|
|
13
|
+
rest = rest.slice(cut).replace(/^\n+/, "");
|
|
14
|
+
}
|
|
15
|
+
if (rest.length) parts.push(rest);
|
|
16
|
+
return parts;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class TelegramAPI {
|
|
20
|
+
constructor(token) {
|
|
21
|
+
if (!token) throw new Error("botToken kosong");
|
|
22
|
+
this.baseUrl = `https://api.telegram.org/bot${token}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async call(method, params = {}) {
|
|
26
|
+
const allowed = ["getMe", "getUpdates", "sendMessage", "sendChatAction"];
|
|
27
|
+
if (!allowed.includes(method)) throw new Error(`Telegram ${method}: method tidak diizinkan`);
|
|
28
|
+
const res = await fetch(`${this.baseUrl}/${method}`, {
|
|
29
|
+
method: "POST",
|
|
30
|
+
headers: { "Content-Type": "application/json" },
|
|
31
|
+
body: JSON.stringify(params),
|
|
32
|
+
signal: AbortSignal.timeout(35000),
|
|
33
|
+
});
|
|
34
|
+
const json = await res.json();
|
|
35
|
+
if (!json.ok) throw new Error(`Telegram ${method}: ${json.description || "unknown"}`);
|
|
36
|
+
return json.result;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
getMe() { return this.call("getMe"); }
|
|
40
|
+
|
|
41
|
+
getUpdates(offset, timeout = 30) {
|
|
42
|
+
return this.call("getUpdates", { offset, timeout, allowed_updates: ["message"] });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async sendMessage(chatId, text, opts = {}) {
|
|
46
|
+
for (const part of splitForTelegram(text)) {
|
|
47
|
+
try {
|
|
48
|
+
await this.call("sendMessage", {
|
|
49
|
+
chat_id: chatId, text: part, parse_mode: "HTML",
|
|
50
|
+
disable_web_page_preview: true, ...opts,
|
|
51
|
+
});
|
|
52
|
+
} catch {
|
|
53
|
+
await this.call("sendMessage", {
|
|
54
|
+
chat_id: chatId, text: part.replace(/<[^>]+>/g, ""),
|
|
55
|
+
disable_web_page_preview: true,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
sendChatAction(chatId, action = "typing") {
|
|
62
|
+
return this.call("sendChatAction", { chat_id: chatId, action }).catch(() => {});
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function escapeHtml(s) {
|
|
67
|
+
return String(s ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
68
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "cs-agent",
|
|
3
|
-
"version": "0.0.0-stage",
|
|
4
|
-
"stub": true,
|
|
5
|
-
"description": "Temporary package placeholder for staged publishing"
|
|
6
|
-
}
|
|
1
|
+
{"dependencies":{"@whiskeysockets/baileys":"^6.7.18","pino":"^9.0.0","qrcode-terminal":"^0.12.0"},"description":"Agent bisnis khusus customer service untuk WhatsApp dan Telegram. Hanya menjawab pelanggan, mencatat order, dan meneruskan ke manusia. Tidak bisa menjalankan perintah sistem atau mengubah file.","engines":{"node":">=22.5.0"},"license":"MIT","main":"index.js","name":"cs-agent","scripts":{"start":"node index.js","telegram":"node index.js --telegram","test":"node --test test/*.test.js","whatsapp":"node index.js --whatsapp"},"type":"module","version":"0.1.0"}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Tes otomatis cs-agent — simulasi pesan pelanggan, tanpa jaringan,
|
|
2
|
+
// tanpa LLM asli, tanpa Telegram/WhatsApp asli.
|
|
3
|
+
import test from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { CSAgent } from "../lib/agent.js";
|
|
9
|
+
import { Memory } from "../lib/memory.js";
|
|
10
|
+
import { OrderStore } from "../lib/orders.js";
|
|
11
|
+
import { loadFaq } from "../lib/faq.js";
|
|
12
|
+
|
|
13
|
+
const ROOT = path.join(import.meta.dirname, "..");
|
|
14
|
+
const FAQ = loadFaq(path.join(ROOT, "data", "faq.json"));
|
|
15
|
+
const PRODUCTS = JSON.parse(fs.readFileSync(path.join(ROOT, "data", "products.json"), "utf8"));
|
|
16
|
+
const CONFIG = {
|
|
17
|
+
shop: {
|
|
18
|
+
name: "Tokenobral",
|
|
19
|
+
description: "Toko token AI.",
|
|
20
|
+
paymentInfo: "Pembayaran via QRIS. Setelah bayar, kirim bukti bayar ke admin.",
|
|
21
|
+
},
|
|
22
|
+
cs: {
|
|
23
|
+
greeting: "Halo! Ada yang bisa saya bantu?",
|
|
24
|
+
fallbackMessage: "Maaf, saya belum bisa menjawab itu. Ketik 'admin' untuk bicara dengan manusia.",
|
|
25
|
+
handoverMessage: "Baik, saya teruskan ke admin manusia. Mohon tunggu sebentar.",
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
function makeAgent({ llm = null } = {}) {
|
|
30
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cs-agent-test-"));
|
|
31
|
+
const notified = [];
|
|
32
|
+
const agent = new CSAgent({
|
|
33
|
+
config: CONFIG,
|
|
34
|
+
faq: FAQ,
|
|
35
|
+
products: PRODUCTS,
|
|
36
|
+
memory: new Memory(path.join(dir, "memory.json")),
|
|
37
|
+
orders: new OrderStore(path.join(dir, "orders.json")),
|
|
38
|
+
llm,
|
|
39
|
+
onOwnerNotify: (t) => notified.push(t),
|
|
40
|
+
});
|
|
41
|
+
return { agent, notified, dir };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const msg = (text, extra = {}) => ({ channel: "whatsapp", customerId: "6281234567890@s.whatsapp.net", customerName: null, text, ...extra });
|
|
45
|
+
|
|
46
|
+
test("tanya harga -> daftar harga", async () => {
|
|
47
|
+
const { agent } = makeAgent();
|
|
48
|
+
const r = await agent.handleMessage(msg("berapa harga token?"));
|
|
49
|
+
assert.match(r.reply, /Token 50rb/);
|
|
50
|
+
assert.match(r.reply, /50\.000/);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("tanya cara bayar -> jawaban FAQ QRIS", async () => {
|
|
54
|
+
const { agent } = makeAgent();
|
|
55
|
+
const r = await agent.handleMessage(msg("bagaimana cara bayar?"));
|
|
56
|
+
assert.match(r.reply, /QRIS/);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("tanya cara order dan lacak order -> jawaban FAQ", async () => {
|
|
60
|
+
const { agent } = makeAgent();
|
|
61
|
+
const r1 = await agent.handleMessage(msg("bagaimana cara order?"));
|
|
62
|
+
assert.match(r1.reply, /order Token 50rb/);
|
|
63
|
+
const r2 = await agent.handleMessage(msg("bagaimana cara lacak order saya?"));
|
|
64
|
+
assert.match(r2.reply, /nomor order/);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("order tanpa nama -> tanya nama, lalu nama menyelesaikan order", async () => {
|
|
68
|
+
const { agent, notified } = makeAgent();
|
|
69
|
+
const r1 = await agent.handleMessage(msg("saya mau order Token 50rb 2"));
|
|
70
|
+
assert.match(r1.reply, /total Rp 100\.000/);
|
|
71
|
+
assert.match(r1.reply, /nama Anda/);
|
|
72
|
+
assert.equal(r1.order, undefined);
|
|
73
|
+
|
|
74
|
+
const r2 = await agent.handleMessage(msg("nama saya Budi"));
|
|
75
|
+
assert.match(r2.reply, /Budi/);
|
|
76
|
+
assert.match(r2.reply, /ORD-/);
|
|
77
|
+
assert.match(r2.reply, /100\.000/);
|
|
78
|
+
assert.ok(r2.order);
|
|
79
|
+
assert.equal(r2.order.qty, 2);
|
|
80
|
+
assert.equal(r2.order.total, 100000);
|
|
81
|
+
assert.equal(notified.length, 1);
|
|
82
|
+
assert.match(notified[0], /Order baru/);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("order langsung saat nama sudah dikenal -> order tercatat", async () => {
|
|
86
|
+
const { agent } = makeAgent();
|
|
87
|
+
await agent.handleMessage(msg("nama saya Sari"));
|
|
88
|
+
const r = await agent.handleMessage(msg("saya mau beli Token 25rb 1"));
|
|
89
|
+
assert.ok(r.order);
|
|
90
|
+
assert.equal(r.order.customerName, "Sari");
|
|
91
|
+
assert.equal(r.order.total, 25000);
|
|
92
|
+
assert.match(r.reply, /QRIS/);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test("order tanpa produk jelas -> ditanya produknya", async () => {
|
|
96
|
+
const { agent } = makeAgent();
|
|
97
|
+
const r = await agent.handleMessage(msg("saya mau order dong"));
|
|
98
|
+
assert.match(r.reply, /Produk yang mana/);
|
|
99
|
+
assert.match(r.reply, /Token 10rb/);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test("minta manusia -> handover, lalu pesan berikutnya tidak dijawab agent", async () => {
|
|
103
|
+
const { agent, notified } = makeAgent();
|
|
104
|
+
const r1 = await agent.handleMessage(msg("tolong saya mau bicara dengan manusia"));
|
|
105
|
+
assert.match(r1.reply, /admin manusia/);
|
|
106
|
+
assert.equal(notified.length, 1);
|
|
107
|
+
|
|
108
|
+
const r2 = await agent.handleMessage(msg("saya mau order Token 10rb 1"));
|
|
109
|
+
assert.match(r2.reply, /Admin sedang menangani/);
|
|
110
|
+
assert.equal(r2.order, undefined);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("pelanggan marah -> handover", async () => {
|
|
114
|
+
const { agent } = makeAgent();
|
|
115
|
+
const r = await agent.handleMessage(msg("kamu penipu! uang saya mana?"));
|
|
116
|
+
assert.match(r.reply, /admin manusia/);
|
|
117
|
+
assert.equal(agent.memory.get("6281234567890@s.whatsapp.net").handover, true);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test("pertanyaan di luar FAQ tanpa LLM -> fallback sopan", async () => {
|
|
121
|
+
const { agent } = makeAgent();
|
|
122
|
+
const r = await agent.handleMessage(msg("apakah ada diskon natal tahun ini?"));
|
|
123
|
+
assert.match(r.reply, /belum bisa menjawab/);
|
|
124
|
+
assert.match(r.reply, /admin/);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test("LLM aktif -> pertanyaan di luar FAQ dijawab LLM dari konteks", async () => {
|
|
128
|
+
const fakeLlm = {
|
|
129
|
+
configured: true,
|
|
130
|
+
chat: async (messages) => {
|
|
131
|
+
assert.ok(messages[0].content.includes("Tokenobral"));
|
|
132
|
+
return "Promo akhir tahun sedang kami siapkan, Kak. Nanti kami kabari ya.";
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
const { agent } = makeAgent({ llm: fakeLlm });
|
|
136
|
+
const r = await agent.handleMessage(msg("apakah ada promo akhir tahun?"));
|
|
137
|
+
assert.match(r.reply, /Promo akhir tahun/);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("sapaan -> greeting", async () => {
|
|
141
|
+
const { agent } = makeAgent();
|
|
142
|
+
const r = await agent.handleMessage(msg("halo"));
|
|
143
|
+
assert.match(r.reply, /Ada yang bisa saya bantu/);
|
|
144
|
+
});
|