@oryksa/sdk 0.1.1 → 0.1.2

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 (3) hide show
  1. package/README.md +75 -68
  2. package/package.json +1 -1
  3. package/src/index.js +325 -325
package/README.md CHANGED
@@ -1,68 +1,75 @@
1
- <p align="center"><img src="https://app.oryksa.com/static/oryksa_logo.png" width="300" alt="ORYKSA"></p>
2
-
3
- # @oryksa/sdk
4
-
5
- Official JavaScript and TypeScript SDK for **ORYKSA AI Employees**: put an AI employee that already knows the business inside your web app, Node backend or Electron desktop app. Same brain as WhatsApp and the website chat, text and voice.
6
-
7
- - Docs: https://developer.oryksa.com
8
- - API: `https://api.oryksa.com/v1`
9
-
10
- ## Install
11
-
12
- ```bash
13
- npm install @oryksa/sdk
14
- ```
15
-
16
- ## Server (secret key)
17
-
18
- ```js
19
- import { Oryksa } from "@oryksa/sdk";
20
- const oryksa = new Oryksa(process.env.ORYKSA_API_KEY); // Account > Developer
21
-
22
- const r = await oryksa.chat({ message: "Are you open on Saturday?" });
23
- console.log(r.reply, r.conversation_id);
24
-
25
- // Teach the AI employee about your app (e.g. on every release)
26
- await oryksa.learnApp({
27
- name: "FitTrack",
28
- description: "Fitness app to log workouts and follow training plans.",
29
- screens: [{ title: "Workouts", content: "Tap + to log a workout." }],
30
- faq: [{ question: "How do I cancel Premium?", answer: "Settings > Subscription > Cancel." }],
31
- });
32
- ```
33
-
34
- ## In the app (session token, never the secret key)
35
-
36
- ```js
37
- // your server
38
- app.get("/oryksa-token", requireLogin, async (req, res) => {
39
- const s = await oryksa.createSession({ conversationId: "user-" + req.user.id, customerName: req.user.firstName });
40
- res.json({ token: s.client_token });
41
- });
42
-
43
- // your web app
44
- import { OryksaClient, mountChat } from "@oryksa/sdk";
45
- const client = new OryksaClient({ getToken: async () => (await fetch("/oryksa-token").then(r => r.json())).token });
46
- mountChat({ client, lang: "en" }); // ready-made chat UI
47
- ```
48
-
49
- ## Webhooks
50
-
51
- ```js
52
- import { verifyWebhook } from "@oryksa/sdk";
53
- app.post("/oryksa-webhook", express.raw({ type: "application/json" }), async (req, res) => {
54
- const event = await verifyWebhook(req.body, req.get("ORYKSA-Signature"), process.env.ORYKSA_WEBHOOK_SECRET);
55
- if (event.type === "booking.created") { /* save it */ }
56
- res.sendStatus(200);
57
- });
58
- ```
59
-
60
- ## Errors
61
-
62
- Every failed call throws `OryksaError` with `status`, `code` (for example `interaction_limit_reached`, `rate_limited`, `plan_required`) and `message`.
63
-
64
- ## Author
65
-
66
- Created by **Weslley Harakawa** · [GitHub](https://github.com/WeslleyHarakawa) · [LinkedIn](https://www.linkedin.com/in/weslleyharakawa)
67
-
68
- MIT License · ORYKSA AI Employees · W8 Atlantic Unipessoal Lda
1
+ <p align="center"><img src="https://app.oryksa.com/static/oryksa_logo.png" width="300" alt="ORYKSA"></p>
2
+
3
+ # @oryksa/sdk
4
+
5
+ Official JavaScript and TypeScript SDK for **ORYKSA AI Employees**: put an AI employee that already knows the business inside your web app, Node backend or Electron desktop app. Same brain as WhatsApp and the website chat, text and voice.
6
+
7
+ - Docs: https://developer.oryksa.com
8
+ - API: `https://api.oryksa.com/v1`
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm install @oryksa/sdk
14
+ ```
15
+
16
+ ## Server (secret key)
17
+
18
+ ```js
19
+ import { Oryksa } from "@oryksa/sdk";
20
+ const oryksa = new Oryksa(process.env.ORYKSA_API_KEY); // developer.oryksa.com > Keys
21
+
22
+ const r = await oryksa.chat({ message: "Are you open on Saturday?" });
23
+ console.log(r.reply, r.conversation_id);
24
+
25
+ // Teach the AI employee about your app (e.g. on every release)
26
+ await oryksa.learnApp({
27
+ name: "FitTrack",
28
+ description: "Fitness app to log workouts and follow training plans.",
29
+ screens: [{ title: "Workouts", content: "Tap + to log a workout." }],
30
+ faq: [{ question: "How do I cancel Premium?", answer: "Settings > Subscription > Cancel." }],
31
+ });
32
+ ```
33
+
34
+ ## In the app (session token, never the secret key)
35
+
36
+ ```js
37
+ // your server
38
+ app.get("/oryksa-token", requireLogin, async (req, res) => {
39
+ const s = await oryksa.createSession({ conversationId: "user-" + req.user.id, customerName: req.user.firstName });
40
+ res.json({ token: s.client_token });
41
+ });
42
+
43
+ // your web app
44
+ import { OryksaClient, mountChat } from "@oryksa/sdk";
45
+ const client = new OryksaClient({ getToken: async () => (await fetch("/oryksa-token").then(r => r.json())).token });
46
+ mountChat({ client, lang: "en" }); // ready-made chat UI
47
+ ```
48
+
49
+ ## Webhooks
50
+
51
+ ```js
52
+ import { verifyWebhook } from "@oryksa/sdk";
53
+ app.post("/oryksa-webhook", express.raw({ type: "application/json" }), async (req, res) => {
54
+ const event = await verifyWebhook(req.body, req.get("ORYKSA-Signature"), process.env.ORYKSA_WEBHOOK_SECRET);
55
+ if (event.type === "booking.created") { /* save it */ }
56
+ res.sendStatus(200);
57
+ });
58
+ ```
59
+
60
+ ## Errors
61
+
62
+ Every failed call throws `OryksaError` with `status`, `code` (for example `interaction_limit_reached`, `rate_limited`, `plan_required`) and `message`.
63
+
64
+ ## About the author
65
+
66
+ **Weslley Harakawa** - Founder of ORYKSA AI and Chief Innovation Officer at Harakawa Tech. Based in Lisbon, Portugal. Specialties: artificial intelligence, web and mobile development, blockchain tokenization. Education: University of the People.
67
+
68
+ - Website: https://harakawa.tech
69
+ - LinkedIn: https://www.linkedin.com/in/weslleyharakawa/
70
+ - Instagram: https://www.instagram.com/weslley.harakawa
71
+ - ORYKSA AI Employees: https://oryksa.com (X: https://x.com/oryksa, Instagram: https://www.instagram.com/oryksaai, YouTube: https://www.youtube.com/@ORYKSAAI)
72
+
73
+ ---
74
+
75
+ MIT License · ORYKSA AI Employees · W8 Atlantic Unipessoal Lda
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oryksa/sdk",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "ORYKSA AI Employees SDK: chat API, knowledge (Brain), webhooks and an in-app chat for web, Node and Electron.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/index.js CHANGED
@@ -1,325 +1,325 @@
1
- /*!
2
- * @oryksa/sdk - ORYKSA AI Employees SDK for JavaScript and TypeScript.
3
- * Server client (secret API key), webhook verification, and an in-app chat
4
- * client that only uses short-lived session tokens (never the secret key).
5
- * Docs: https://developer.oryksa.com License: MIT
6
- */
7
-
8
- const DEFAULT_BASE = "https://api.oryksa.com/v1";
9
- export const VERSION = "0.1.0";
10
-
11
- export class OryksaError extends Error {
12
- constructor(status, code, message, extra = {}) {
13
- super(message);
14
- this.name = "OryksaError";
15
- this.status = status;
16
- this.code = code;
17
- Object.assign(this, extra);
18
- }
19
- }
20
-
21
- async function request(base, token, method, path, body, fetchImpl, timeoutMs) {
22
- const f = fetchImpl || globalThis.fetch;
23
- if (!f) throw new Error("fetch is not available: pass { fetch } in the options (Node < 18).");
24
- const ctrl = typeof AbortController !== "undefined" ? new AbortController() : null;
25
- const timer = ctrl ? setTimeout(() => ctrl.abort(), timeoutMs) : null;
26
- let res;
27
- try {
28
- res = await f(base + path, {
29
- method,
30
- headers: {
31
- Authorization: "Bearer " + token,
32
- ...(body !== undefined ? { "Content-Type": "application/json" } : {}),
33
- "X-ORYKSA-SDK": "js/" + VERSION,
34
- },
35
- body: body !== undefined ? JSON.stringify(body) : undefined,
36
- signal: ctrl ? ctrl.signal : undefined,
37
- });
38
- } finally {
39
- if (timer) clearTimeout(timer);
40
- }
41
- let data = null;
42
- try { data = await res.json(); } catch (_) { data = null; }
43
- if (!res.ok && res.status !== 202) {
44
- const e = (data && data.error) || {};
45
- const { code, message, ...extra } = e;
46
- throw new OryksaError(res.status, code || "http_" + res.status, message || "Request failed with HTTP " + res.status, extra);
47
- }
48
- return data;
49
- }
50
-
51
- /**
52
- * Server-side client. Uses the SECRET API key (oryk_live_...). Never ship it in a browser or app bundle.
53
- */
54
- export class Oryksa {
55
- constructor(apiKey, opts = {}) {
56
- if (!apiKey || !String(apiKey).startsWith("oryk_live_")) {
57
- throw new Error("An ORYKSA API key (oryk_live_...) is required. Create one in Account > Developer.");
58
- }
59
- if (typeof window !== "undefined" && typeof document !== "undefined" && !opts.dangerouslyAllowBrowser) {
60
- throw new Error("The secret API key must stay on the server. In apps use OryksaClient with a session token.");
61
- }
62
- this._key = apiKey;
63
- this._base = (opts.baseUrl || DEFAULT_BASE).replace(/\/$/, "");
64
- this._fetch = opts.fetch;
65
- this._timeout = opts.timeoutMs || 60000;
66
- }
67
-
68
- _req(method, path, body) {
69
- return request(this._base, this._key, method, path, body, this._fetch, this._timeout);
70
- }
71
-
72
- account() { return this._req("GET", "/account"); }
73
-
74
- /** Chat with the AI employee. Reuse conversationId to keep the context. */
75
- chat({ message, conversationId, customerName } = {}) {
76
- return this._req("POST", "/chat", { message, conversation_id: conversationId, customer_name: customerName });
77
- }
78
-
79
- conversations({ limit } = {}) { return this._req("GET", "/conversations" + (limit ? "?limit=" + Number(limit) : "")); }
80
- conversation(id) { return this._req("GET", "/conversations/" + encodeURIComponent(id)); }
81
-
82
- get agent() {
83
- return {
84
- update: (fields) => this._req("PATCH", "/agent", fields),
85
- appearance: (fields) => this._req("PATCH", "/agent/appearance", fields),
86
- };
87
- }
88
-
89
- get knowledge() {
90
- return {
91
- get: () => this._req("GET", "/knowledge"),
92
- setPages: ({ pages, businessSummary, siteUrl }) =>
93
- this._req("PUT", "/knowledge/pages", { pages, business_summary: businessSummary, site_url: siteUrl }),
94
- crawl: ({ url, maxPages }) => this._req("POST", "/knowledge/crawl", { url, max_pages: maxPages }),
95
- addFaq: (items) => this._req("POST", "/knowledge/faq", { items }),
96
- };
97
- }
98
-
99
- get widget() {
100
- return {
101
- snippet: ({ framework = "html", lang = "", position = "" } = {}) =>
102
- this._req("GET", `/widget?framework=${encodeURIComponent(framework)}&lang=${encodeURIComponent(lang)}&position=${encodeURIComponent(position)}`),
103
- setDomains: (domains) => this._req("PUT", "/widget/domains", { domains }),
104
- };
105
- }
106
-
107
- get webhooks() {
108
- return {
109
- list: () => this._req("GET", "/webhooks"),
110
- create: ({ url, events = ["*"] }) => this._req("POST", "/webhooks", { url, events }),
111
- delete: (id) => this._req("DELETE", "/webhooks/" + encodeURIComponent(id)),
112
- test: (id) => this._req("POST", "/webhooks/" + encodeURIComponent(id) + "/test"),
113
- };
114
- }
115
-
116
- /** Short-lived token for an app user. Send only this token to the app. */
117
- createSession({ conversationId, customerName, ttlMinutes = 60 } = {}) {
118
- return this._req("POST", "/sessions", { conversation_id: conversationId, customer_name: customerName, ttl_minutes: ttlMinutes });
119
- }
120
-
121
- /**
122
- * Teach the AI employee about an app: what it is, its screens/features and FAQs.
123
- * The agent then answers users inside the app with that knowledge.
124
- * @param {{name:string, description?:string, screens?:{title:string, content:string, url?:string}[], faq?:{question:string, answer:string}[], languages?:string[], agentName?:string, settings?:object}} app
125
- */
126
- async learnApp(app) {
127
- if (!app || !app.name) throw new Error("learnApp needs at least { name }.");
128
- const out = {};
129
- const profile = { business_name: app.name };
130
- if (app.description) profile.business_description = app.description;
131
- if (app.agentName) profile.agent_name = app.agentName;
132
- if (Array.isArray(app.languages)) profile.languages = app.languages;
133
- if (Array.isArray(app.services)) profile.services = app.services;
134
- out.agent = await this.agent.update(profile);
135
- const pages = [];
136
- if (app.description) pages.push({ title: app.name + " - overview", content: app.description });
137
- for (const s of app.screens || []) {
138
- if (s && s.content) pages.push({ title: s.title || "Screen", url: s.url, content: String(s.content) });
139
- }
140
- if (app.settings && typeof app.settings === "object") {
141
- const lines = Object.entries(app.settings).map(([k, v]) => `${k}: ${typeof v === "object" ? JSON.stringify(v) : v}`);
142
- pages.push({ title: app.name + " - configuration", content: lines.join("\n") });
143
- }
144
- if (pages.length) out.pages = await this.knowledge.setPages({ pages, siteUrl: app.url });
145
- if (Array.isArray(app.faq) && app.faq.length) out.faq = await this.knowledge.addFaq(app.faq);
146
- return out;
147
- }
148
- }
149
-
150
- /**
151
- * Verify an ORYKSA webhook signature (Node.js). Pass the RAW request body.
152
- * @returns {Promise<object>} the parsed event, or throws OryksaError(400).
153
- */
154
- export async function verifyWebhook(rawBody, signatureHeader, secret, { toleranceSeconds = 300 } = {}) {
155
- const parts = Object.fromEntries(String(signatureHeader || "").split(",").map((p) => p.split("=")));
156
- const t = Number(parts.t || 0);
157
- if (!t || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) throw new OryksaError(400, "invalid_signature", "Webhook timestamp is missing or too old.");
158
- const body = typeof rawBody === "string" ? rawBody : new TextDecoder().decode(rawBody);
159
- let expected;
160
- if (globalThis.crypto && globalThis.crypto.subtle) {
161
- const key = await globalThis.crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
162
- const sig = await globalThis.crypto.subtle.sign("HMAC", key, new TextEncoder().encode(t + "." + body));
163
- expected = [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
164
- } else {
165
- const { createHmac } = await import("node:crypto");
166
- expected = createHmac("sha256", secret).update(t + "." + body).digest("hex");
167
- }
168
- const got = String(parts.v1 || "");
169
- let diff = expected.length ^ got.length;
170
- for (let i = 0; i < Math.min(expected.length, got.length); i++) diff |= expected.charCodeAt(i) ^ got.charCodeAt(i);
171
- if (diff !== 0) throw new OryksaError(400, "invalid_signature", "Webhook signature does not match.");
172
- return JSON.parse(body);
173
- }
174
-
175
- /**
176
- * In-app client (browser, React Native, Electron). Uses a short-lived session token
177
- * created by YOUR server with Oryksa.createSession(). Pass getToken() to refresh it.
178
- */
179
- export class OryksaClient {
180
- constructor({ token, getToken, baseUrl, fetch, timeoutMs } = {}) {
181
- if (!token && !getToken) throw new Error("OryksaClient needs { token } or { getToken }.");
182
- if (token && String(token).startsWith("oryk_live_")) throw new Error("Never use the secret API key in an app. Use a session token (oryk_cs_...).");
183
- this._token = token || null;
184
- this._getToken = getToken || null;
185
- this._base = (baseUrl || DEFAULT_BASE).replace(/\/$/, "");
186
- this._fetch = fetch;
187
- this._timeout = timeoutMs || 60000;
188
- }
189
-
190
- async _tok(force) {
191
- if ((!this._token || force) && this._getToken) this._token = await this._getToken();
192
- return this._token;
193
- }
194
-
195
- async _req(method, path, body) {
196
- try {
197
- return await request(this._base, await this._tok(false), method, path, body, this._fetch, this._timeout);
198
- } catch (e) {
199
- if (e instanceof OryksaError && (e.code === "session_expired" || e.status === 401) && this._getToken) {
200
- return request(this._base, await this._tok(true), method, path, body, this._fetch, this._timeout);
201
- }
202
- throw e;
203
- }
204
- }
205
-
206
- agent() { return this._req("GET", "/client/agent"); }
207
- send(message) { return this._req("POST", "/client/chat", { message }); }
208
- messages() { return this._req("GET", "/client/messages"); }
209
- }
210
-
211
- /* ------------------------------------------------------------------ Browser chat UI */
212
- const CSS = `
213
- :host{all:initial}
214
- *{box-sizing:border-box;font-family:Manrope,Inter,system-ui,-apple-system,Segoe UI,sans-serif}
215
- .btn{position:fixed;bottom:22px;display:flex;align-items:center;gap:10px;background:var(--accent);color:#fff;border:0;border-radius:999px;padding:8px 18px 8px 8px;cursor:pointer;box-shadow:0 12px 30px rgba(22,27,61,.28);font-weight:800;font-size:13px;letter-spacing:.08em;text-transform:uppercase;z-index:2147483000}
216
- .btn img{width:42px;height:42px;border-radius:50%;object-fit:cover;border:2px solid #fff}
217
- .panel{position:fixed;bottom:92px;width:380px;max-width:calc(100vw - 24px);height:560px;max-height:calc(100vh - 120px);background:#fff;border-radius:20px;box-shadow:0 24px 60px rgba(22,27,61,.25);display:none;flex-direction:column;overflow:hidden;z-index:2147483000;color:var(--ink)}
218
- .panel.open{display:flex}
219
- .hd{display:flex;align-items:center;gap:12px;padding:14px 16px;border-bottom:1px solid #eceef6}
220
- .hd img{width:46px;height:46px;border-radius:50%;object-fit:cover}
221
- .hd b{display:block;font-size:14px;letter-spacing:.14em;text-transform:uppercase}
222
- .hd small{color:#6b7280;font-size:12px}
223
- .hd button{margin-left:auto;border:0;background:none;font-size:20px;cursor:pointer;color:#6b7280}
224
- .msgs{flex:1;overflow:auto;padding:16px;display:flex;flex-direction:column;gap:10px;background:#fff}
225
- .m{max-width:82%;padding:10px 14px;border-radius:16px;font-size:14px;line-height:1.5;white-space:pre-wrap;word-wrap:break-word}
226
- .m.a{background:var(--soft);align-self:flex-start;border-bottom-left-radius:6px}
227
- .m.u{background:var(--accent);color:#fff;align-self:flex-end;border-bottom-right-radius:6px}
228
- .m.t{opacity:.6}
229
- .sug{display:flex;flex-wrap:wrap;gap:8px;padding:0 16px 10px}
230
- .sug button{border:1px solid #dcdcf5;background:#fff;color:var(--accent);border-radius:999px;padding:7px 12px;font-size:12.5px;cursor:pointer}
231
- form{display:flex;border-top:1px solid #eceef6}
232
- input{flex:1;border:0;padding:14px 16px;font-size:14px;outline:none;color:var(--ink)}
233
- form button{border:0;background:var(--accent);color:#fff;font-weight:800;padding:0 18px;letter-spacing:.1em;cursor:pointer}
234
- .pw{text-align:center;font-size:10.5px;letter-spacing:.12em;color:#9ca3af;padding:6px 0 8px;text-transform:uppercase}
235
- .pw b{color:var(--accent)}
236
- `;
237
-
238
- const UI_TXT = {
239
- en: { talk: "Talk to", ph: "Type your question", send: "Send", err: "Sorry, something went wrong. Try again." },
240
- pt: { talk: "Falar com", ph: "Escreve a tua pergunta", send: "Enviar", err: "Desculpa, algo correu mal. Tenta de novo." },
241
- br: { talk: "Falar com", ph: "Digite sua pergunta", send: "Enviar", err: "Desculpe, algo deu errado. Tente de novo." },
242
- es: { talk: "Hablar con", ph: "Escribe tu pregunta", send: "Enviar", err: "Lo siento, algo salió mal. Inténtalo de nuevo." },
243
- };
244
-
245
- /**
246
- * Mount the ORYKSA chat inside a web app (same look as the website chat).
247
- * @param {{client: OryksaClient, lang?: 'en'|'pt'|'br'|'es', position?: 'left'|'right', accent?: string, ink?: string, soft?: string, open?: boolean}} opts
248
- */
249
- export function mountChat(opts) {
250
- if (typeof document === "undefined") throw new Error("mountChat runs in a browser. In React Native use @oryksa/react-native.");
251
- const client = opts.client;
252
- const lang = UI_TXT[opts.lang] ? opts.lang : "en";
253
- const tx = UI_TXT[lang];
254
- const host = document.createElement("div");
255
- host.id = "oryksa-sdk-chat";
256
- document.body.appendChild(host);
257
- const root = host.attachShadow({ mode: "open" });
258
- const side = opts.position === "left" ? "left:22px" : "right:22px";
259
- root.innerHTML = `<style>${CSS}
260
- :host{--accent:${opts.accent || "#5B57E0"};--ink:${opts.ink || "#161B3D"};--soft:${opts.soft || "#EEEBFB"}}
261
- .btn,.panel{${side}}</style>
262
- <button class="btn" part="button"><img alt=""><span></span></button>
263
- <div class="panel" part="panel"><div class="hd"><img alt=""><div><b></b><small></small></div><button aria-label="close">&times;</button></div>
264
- <div class="msgs"></div><div class="sug"></div>
265
- <form><input maxlength="2000"><button type="submit"></button></form><div class="pw">Powered by <b>ORYKSA</b></div></div>`;
266
- const $ = (s) => root.querySelector(s);
267
- const panel = $(".panel"), msgs = $(".msgs"), sug = $(".sug"), input = $("input");
268
- input.placeholder = tx.ph;
269
- $("form button").textContent = tx.send;
270
- const add = (role, text) => {
271
- const d = document.createElement("div");
272
- d.className = "m " + (role === "user" ? "u" : role === "typing" ? "a t" : "a");
273
- d.textContent = text;
274
- msgs.appendChild(d);
275
- msgs.scrollTop = msgs.scrollHeight;
276
- return d;
277
- };
278
- let busy = false;
279
- const send = async (text) => {
280
- text = String(text || "").trim();
281
- if (!text || busy) return;
282
- busy = true; sug.innerHTML = ""; add("user", text); input.value = "";
283
- const typing = add("typing", "...");
284
- try {
285
- let r = await client.send(text);
286
- if (r && r.status === "pending") {
287
- for (let i = 0; i < 20 && r.status === "pending"; i++) {
288
- await new Promise((ok) => setTimeout(ok, 1500));
289
- const h = await client.messages();
290
- const last = (h.messages || []).slice(-1)[0];
291
- if (last && last.role === "assistant") r = { status: "replied", reply: last.content };
292
- }
293
- }
294
- typing.remove();
295
- add("assistant", (r && r.reply) || tx.err);
296
- } catch (e) {
297
- typing.remove();
298
- add("assistant", tx.err);
299
- } finally { busy = false; }
300
- };
301
- $("form").addEventListener("submit", (e) => { e.preventDefault(); send(input.value); });
302
- $(".btn").addEventListener("click", () => { panel.classList.toggle("open"); if (panel.classList.contains("open")) input.focus(); });
303
- $(".hd button").addEventListener("click", () => panel.classList.remove("open"));
304
- client.agent().then(async (a) => {
305
- const pick = (o) => (o && (o[lang] || (lang === "br" && o.pt) || o.en || Object.values(o)[0])) || "";
306
- root.querySelectorAll("img").forEach((i) => (i.src = a.avatar));
307
- $(".btn span").textContent = tx.talk + " " + a.name;
308
- $(".hd b").textContent = a.name;
309
- $(".hd small").textContent = pick(a.subtitle) || a.business || "";
310
- const hist = await client.messages().catch(() => ({ messages: [] }));
311
- if ((hist.messages || []).length) hist.messages.forEach((m) => add(m.role, m.content));
312
- else if (pick(a.greeting)) add("assistant", pick(a.greeting));
313
- const sg = (a.suggestions && (a.suggestions[lang] || (lang === "br" && a.suggestions.pt) || a.suggestions.en)) || [];
314
- sg.slice(0, 4).forEach((s) => { const b = document.createElement("button"); b.textContent = s; b.onclick = () => send(s); sug.appendChild(b); });
315
- }).catch(() => { $(".btn span").textContent = tx.talk + " ORYKSA"; });
316
- if (opts.open) panel.classList.add("open");
317
- return {
318
- open: () => panel.classList.add("open"),
319
- close: () => panel.classList.remove("open"),
320
- send,
321
- destroy: () => host.remove(),
322
- };
323
- }
324
-
325
- export default Oryksa;
1
+ /*!
2
+ * @oryksa/sdk - ORYKSA AI Employees SDK for JavaScript and TypeScript.
3
+ * Server client (secret API key), webhook verification, and an in-app chat
4
+ * client that only uses short-lived session tokens (never the secret key).
5
+ * Docs: https://developer.oryksa.com License: MIT
6
+ */
7
+
8
+ const DEFAULT_BASE = "https://api.oryksa.com/v1";
9
+ export const VERSION = "0.1.2";
10
+
11
+ export class OryksaError extends Error {
12
+ constructor(status, code, message, extra = {}) {
13
+ super(message);
14
+ this.name = "OryksaError";
15
+ this.status = status;
16
+ this.code = code;
17
+ Object.assign(this, extra);
18
+ }
19
+ }
20
+
21
+ async function request(base, token, method, path, body, fetchImpl, timeoutMs) {
22
+ const f = fetchImpl || globalThis.fetch;
23
+ if (!f) throw new Error("fetch is not available: pass { fetch } in the options (Node < 18).");
24
+ const ctrl = typeof AbortController !== "undefined" ? new AbortController() : null;
25
+ const timer = ctrl ? setTimeout(() => ctrl.abort(), timeoutMs) : null;
26
+ let res;
27
+ try {
28
+ res = await f(base + path, {
29
+ method,
30
+ headers: {
31
+ Authorization: "Bearer " + token,
32
+ ...(body !== undefined ? { "Content-Type": "application/json" } : {}),
33
+ "X-ORYKSA-SDK": "js/" + VERSION,
34
+ },
35
+ body: body !== undefined ? JSON.stringify(body) : undefined,
36
+ signal: ctrl ? ctrl.signal : undefined,
37
+ });
38
+ } finally {
39
+ if (timer) clearTimeout(timer);
40
+ }
41
+ let data = null;
42
+ try { data = await res.json(); } catch (_) { data = null; }
43
+ if (!res.ok && res.status !== 202) {
44
+ const e = (data && data.error) || {};
45
+ const { code, message, ...extra } = e;
46
+ throw new OryksaError(res.status, code || "http_" + res.status, message || "Request failed with HTTP " + res.status, extra);
47
+ }
48
+ return data;
49
+ }
50
+
51
+ /**
52
+ * Server-side client. Uses the SECRET API key (oryk_live_...). Never ship it in a browser or app bundle.
53
+ */
54
+ export class Oryksa {
55
+ constructor(apiKey, opts = {}) {
56
+ if (!apiKey || !String(apiKey).startsWith("oryk_live_")) {
57
+ throw new Error("An ORYKSA API key (oryk_live_...) is required. Create one at developer.oryksa.com.");
58
+ }
59
+ if (typeof window !== "undefined" && typeof document !== "undefined" && !opts.dangerouslyAllowBrowser) {
60
+ throw new Error("The secret API key must stay on the server. In apps use OryksaClient with a session token.");
61
+ }
62
+ this._key = apiKey;
63
+ this._base = (opts.baseUrl || DEFAULT_BASE).replace(/\/$/, "");
64
+ this._fetch = opts.fetch;
65
+ this._timeout = opts.timeoutMs || 60000;
66
+ }
67
+
68
+ _req(method, path, body) {
69
+ return request(this._base, this._key, method, path, body, this._fetch, this._timeout);
70
+ }
71
+
72
+ account() { return this._req("GET", "/account"); }
73
+
74
+ /** Chat with the AI employee. Reuse conversationId to keep the context. */
75
+ chat({ message, conversationId, customerName } = {}) {
76
+ return this._req("POST", "/chat", { message, conversation_id: conversationId, customer_name: customerName });
77
+ }
78
+
79
+ conversations({ limit } = {}) { return this._req("GET", "/conversations" + (limit ? "?limit=" + Number(limit) : "")); }
80
+ conversation(id) { return this._req("GET", "/conversations/" + encodeURIComponent(id)); }
81
+
82
+ get agent() {
83
+ return {
84
+ update: (fields) => this._req("PATCH", "/agent", fields),
85
+ appearance: (fields) => this._req("PATCH", "/agent/appearance", fields),
86
+ };
87
+ }
88
+
89
+ get knowledge() {
90
+ return {
91
+ get: () => this._req("GET", "/knowledge"),
92
+ setPages: ({ pages, businessSummary, siteUrl }) =>
93
+ this._req("PUT", "/knowledge/pages", { pages, business_summary: businessSummary, site_url: siteUrl }),
94
+ crawl: ({ url, maxPages }) => this._req("POST", "/knowledge/crawl", { url, max_pages: maxPages }),
95
+ addFaq: (items) => this._req("POST", "/knowledge/faq", { items }),
96
+ };
97
+ }
98
+
99
+ get widget() {
100
+ return {
101
+ snippet: ({ framework = "html", lang = "", position = "" } = {}) =>
102
+ this._req("GET", `/widget?framework=${encodeURIComponent(framework)}&lang=${encodeURIComponent(lang)}&position=${encodeURIComponent(position)}`),
103
+ setDomains: (domains) => this._req("PUT", "/widget/domains", { domains }),
104
+ };
105
+ }
106
+
107
+ get webhooks() {
108
+ return {
109
+ list: () => this._req("GET", "/webhooks"),
110
+ create: ({ url, events = ["*"] }) => this._req("POST", "/webhooks", { url, events }),
111
+ delete: (id) => this._req("DELETE", "/webhooks/" + encodeURIComponent(id)),
112
+ test: (id) => this._req("POST", "/webhooks/" + encodeURIComponent(id) + "/test"),
113
+ };
114
+ }
115
+
116
+ /** Short-lived token for an app user. Send only this token to the app. */
117
+ createSession({ conversationId, customerName, ttlMinutes = 60 } = {}) {
118
+ return this._req("POST", "/sessions", { conversation_id: conversationId, customer_name: customerName, ttl_minutes: ttlMinutes });
119
+ }
120
+
121
+ /**
122
+ * Teach the AI employee about an app: what it is, its screens/features and FAQs.
123
+ * The agent then answers users inside the app with that knowledge.
124
+ * @param {{name:string, description?:string, screens?:{title:string, content:string, url?:string}[], faq?:{question:string, answer:string}[], languages?:string[], agentName?:string, settings?:object}} app
125
+ */
126
+ async learnApp(app) {
127
+ if (!app || !app.name) throw new Error("learnApp needs at least { name }.");
128
+ const out = {};
129
+ const profile = { business_name: app.name };
130
+ if (app.description) profile.business_description = app.description;
131
+ if (app.agentName) profile.agent_name = app.agentName;
132
+ if (Array.isArray(app.languages)) profile.languages = app.languages;
133
+ if (Array.isArray(app.services)) profile.services = app.services;
134
+ out.agent = await this.agent.update(profile);
135
+ const pages = [];
136
+ if (app.description) pages.push({ title: app.name + " - overview", content: app.description });
137
+ for (const s of app.screens || []) {
138
+ if (s && s.content) pages.push({ title: s.title || "Screen", url: s.url, content: String(s.content) });
139
+ }
140
+ if (app.settings && typeof app.settings === "object") {
141
+ const lines = Object.entries(app.settings).map(([k, v]) => `${k}: ${typeof v === "object" ? JSON.stringify(v) : v}`);
142
+ pages.push({ title: app.name + " - configuration", content: lines.join("\n") });
143
+ }
144
+ if (pages.length) out.pages = await this.knowledge.setPages({ pages, siteUrl: app.url });
145
+ if (Array.isArray(app.faq) && app.faq.length) out.faq = await this.knowledge.addFaq(app.faq);
146
+ return out;
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Verify an ORYKSA webhook signature (Node.js). Pass the RAW request body.
152
+ * @returns {Promise<object>} the parsed event, or throws OryksaError(400).
153
+ */
154
+ export async function verifyWebhook(rawBody, signatureHeader, secret, { toleranceSeconds = 300 } = {}) {
155
+ const parts = Object.fromEntries(String(signatureHeader || "").split(",").map((p) => p.split("=")));
156
+ const t = Number(parts.t || 0);
157
+ if (!t || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) throw new OryksaError(400, "invalid_signature", "Webhook timestamp is missing or too old.");
158
+ const body = typeof rawBody === "string" ? rawBody : new TextDecoder().decode(rawBody);
159
+ let expected;
160
+ if (globalThis.crypto && globalThis.crypto.subtle) {
161
+ const key = await globalThis.crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
162
+ const sig = await globalThis.crypto.subtle.sign("HMAC", key, new TextEncoder().encode(t + "." + body));
163
+ expected = [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
164
+ } else {
165
+ const { createHmac } = await import("node:crypto");
166
+ expected = createHmac("sha256", secret).update(t + "." + body).digest("hex");
167
+ }
168
+ const got = String(parts.v1 || "");
169
+ let diff = expected.length ^ got.length;
170
+ for (let i = 0; i < Math.min(expected.length, got.length); i++) diff |= expected.charCodeAt(i) ^ got.charCodeAt(i);
171
+ if (diff !== 0) throw new OryksaError(400, "invalid_signature", "Webhook signature does not match.");
172
+ return JSON.parse(body);
173
+ }
174
+
175
+ /**
176
+ * In-app client (browser, React Native, Electron). Uses a short-lived session token
177
+ * created by YOUR server with Oryksa.createSession(). Pass getToken() to refresh it.
178
+ */
179
+ export class OryksaClient {
180
+ constructor({ token, getToken, baseUrl, fetch, timeoutMs } = {}) {
181
+ if (!token && !getToken) throw new Error("OryksaClient needs { token } or { getToken }.");
182
+ if (token && String(token).startsWith("oryk_live_")) throw new Error("Never use the secret API key in an app. Use a session token (oryk_cs_...).");
183
+ this._token = token || null;
184
+ this._getToken = getToken || null;
185
+ this._base = (baseUrl || DEFAULT_BASE).replace(/\/$/, "");
186
+ this._fetch = fetch;
187
+ this._timeout = timeoutMs || 60000;
188
+ }
189
+
190
+ async _tok(force) {
191
+ if ((!this._token || force) && this._getToken) this._token = await this._getToken();
192
+ return this._token;
193
+ }
194
+
195
+ async _req(method, path, body) {
196
+ try {
197
+ return await request(this._base, await this._tok(false), method, path, body, this._fetch, this._timeout);
198
+ } catch (e) {
199
+ if (e instanceof OryksaError && (e.code === "session_expired" || e.status === 401) && this._getToken) {
200
+ return request(this._base, await this._tok(true), method, path, body, this._fetch, this._timeout);
201
+ }
202
+ throw e;
203
+ }
204
+ }
205
+
206
+ agent() { return this._req("GET", "/client/agent"); }
207
+ send(message) { return this._req("POST", "/client/chat", { message }); }
208
+ messages() { return this._req("GET", "/client/messages"); }
209
+ }
210
+
211
+ /* ------------------------------------------------------------------ Browser chat UI */
212
+ const CSS = `
213
+ :host{all:initial}
214
+ *{box-sizing:border-box;font-family:Manrope,Inter,system-ui,-apple-system,Segoe UI,sans-serif}
215
+ .btn{position:fixed;bottom:22px;display:flex;align-items:center;gap:10px;background:var(--accent);color:#fff;border:0;border-radius:999px;padding:8px 18px 8px 8px;cursor:pointer;box-shadow:0 12px 30px rgba(22,27,61,.28);font-weight:800;font-size:13px;letter-spacing:.08em;text-transform:uppercase;z-index:2147483000}
216
+ .btn img{width:42px;height:42px;border-radius:50%;object-fit:cover;border:2px solid #fff}
217
+ .panel{position:fixed;bottom:92px;width:380px;max-width:calc(100vw - 24px);height:560px;max-height:calc(100vh - 120px);background:#fff;border-radius:20px;box-shadow:0 24px 60px rgba(22,27,61,.25);display:none;flex-direction:column;overflow:hidden;z-index:2147483000;color:var(--ink)}
218
+ .panel.open{display:flex}
219
+ .hd{display:flex;align-items:center;gap:12px;padding:14px 16px;border-bottom:1px solid #eceef6}
220
+ .hd img{width:46px;height:46px;border-radius:50%;object-fit:cover}
221
+ .hd b{display:block;font-size:14px;letter-spacing:.14em;text-transform:uppercase}
222
+ .hd small{color:#6b7280;font-size:12px}
223
+ .hd button{margin-left:auto;border:0;background:none;font-size:20px;cursor:pointer;color:#6b7280}
224
+ .msgs{flex:1;overflow:auto;padding:16px;display:flex;flex-direction:column;gap:10px;background:#fff}
225
+ .m{max-width:82%;padding:10px 14px;border-radius:16px;font-size:14px;line-height:1.5;white-space:pre-wrap;word-wrap:break-word}
226
+ .m.a{background:var(--soft);align-self:flex-start;border-bottom-left-radius:6px}
227
+ .m.u{background:var(--accent);color:#fff;align-self:flex-end;border-bottom-right-radius:6px}
228
+ .m.t{opacity:.6}
229
+ .sug{display:flex;flex-wrap:wrap;gap:8px;padding:0 16px 10px}
230
+ .sug button{border:1px solid #dcdcf5;background:#fff;color:var(--accent);border-radius:999px;padding:7px 12px;font-size:12.5px;cursor:pointer}
231
+ form{display:flex;border-top:1px solid #eceef6}
232
+ input{flex:1;border:0;padding:14px 16px;font-size:14px;outline:none;color:var(--ink)}
233
+ form button{border:0;background:var(--accent);color:#fff;font-weight:800;padding:0 18px;letter-spacing:.1em;cursor:pointer}
234
+ .pw{text-align:center;font-size:10.5px;letter-spacing:.12em;color:#9ca3af;padding:6px 0 8px;text-transform:uppercase}
235
+ .pw b{color:var(--accent)}
236
+ `;
237
+
238
+ const UI_TXT = {
239
+ en: { talk: "Talk to", ph: "Type your question", send: "Send", err: "Sorry, something went wrong. Try again." },
240
+ pt: { talk: "Falar com", ph: "Escreve a tua pergunta", send: "Enviar", err: "Desculpa, algo correu mal. Tenta de novo." },
241
+ br: { talk: "Falar com", ph: "Digite sua pergunta", send: "Enviar", err: "Desculpe, algo deu errado. Tente de novo." },
242
+ es: { talk: "Hablar con", ph: "Escribe tu pregunta", send: "Enviar", err: "Lo siento, algo salió mal. Inténtalo de nuevo." },
243
+ };
244
+
245
+ /**
246
+ * Mount the ORYKSA chat inside a web app (same look as the website chat).
247
+ * @param {{client: OryksaClient, lang?: 'en'|'pt'|'br'|'es', position?: 'left'|'right', accent?: string, ink?: string, soft?: string, open?: boolean}} opts
248
+ */
249
+ export function mountChat(opts) {
250
+ if (typeof document === "undefined") throw new Error("mountChat runs in a browser. In React Native use @oryksa/react-native.");
251
+ const client = opts.client;
252
+ const lang = UI_TXT[opts.lang] ? opts.lang : "en";
253
+ const tx = UI_TXT[lang];
254
+ const host = document.createElement("div");
255
+ host.id = "oryksa-sdk-chat";
256
+ document.body.appendChild(host);
257
+ const root = host.attachShadow({ mode: "open" });
258
+ const side = opts.position === "left" ? "left:22px" : "right:22px";
259
+ root.innerHTML = `<style>${CSS}
260
+ :host{--accent:${opts.accent || "#5B57E0"};--ink:${opts.ink || "#161B3D"};--soft:${opts.soft || "#EEEBFB"}}
261
+ .btn,.panel{${side}}</style>
262
+ <button class="btn" part="button"><img alt=""><span></span></button>
263
+ <div class="panel" part="panel"><div class="hd"><img alt=""><div><b></b><small></small></div><button aria-label="close">&times;</button></div>
264
+ <div class="msgs"></div><div class="sug"></div>
265
+ <form><input maxlength="2000"><button type="submit"></button></form><div class="pw">Powered by <b>ORYKSA</b></div></div>`;
266
+ const $ = (s) => root.querySelector(s);
267
+ const panel = $(".panel"), msgs = $(".msgs"), sug = $(".sug"), input = $("input");
268
+ input.placeholder = tx.ph;
269
+ $("form button").textContent = tx.send;
270
+ const add = (role, text) => {
271
+ const d = document.createElement("div");
272
+ d.className = "m " + (role === "user" ? "u" : role === "typing" ? "a t" : "a");
273
+ d.textContent = text;
274
+ msgs.appendChild(d);
275
+ msgs.scrollTop = msgs.scrollHeight;
276
+ return d;
277
+ };
278
+ let busy = false;
279
+ const send = async (text) => {
280
+ text = String(text || "").trim();
281
+ if (!text || busy) return;
282
+ busy = true; sug.innerHTML = ""; add("user", text); input.value = "";
283
+ const typing = add("typing", "...");
284
+ try {
285
+ let r = await client.send(text);
286
+ if (r && r.status === "pending") {
287
+ for (let i = 0; i < 20 && r.status === "pending"; i++) {
288
+ await new Promise((ok) => setTimeout(ok, 1500));
289
+ const h = await client.messages();
290
+ const last = (h.messages || []).slice(-1)[0];
291
+ if (last && last.role === "assistant") r = { status: "replied", reply: last.content };
292
+ }
293
+ }
294
+ typing.remove();
295
+ add("assistant", (r && r.reply) || tx.err);
296
+ } catch (e) {
297
+ typing.remove();
298
+ add("assistant", tx.err);
299
+ } finally { busy = false; }
300
+ };
301
+ $("form").addEventListener("submit", (e) => { e.preventDefault(); send(input.value); });
302
+ $(".btn").addEventListener("click", () => { panel.classList.toggle("open"); if (panel.classList.contains("open")) input.focus(); });
303
+ $(".hd button").addEventListener("click", () => panel.classList.remove("open"));
304
+ client.agent().then(async (a) => {
305
+ const pick = (o) => (o && (o[lang] || (lang === "br" && o.pt) || o.en || Object.values(o)[0])) || "";
306
+ root.querySelectorAll("img").forEach((i) => (i.src = a.avatar));
307
+ $(".btn span").textContent = tx.talk + " " + a.name;
308
+ $(".hd b").textContent = a.name;
309
+ $(".hd small").textContent = pick(a.subtitle) || a.business || "";
310
+ const hist = await client.messages().catch(() => ({ messages: [] }));
311
+ if ((hist.messages || []).length) hist.messages.forEach((m) => add(m.role, m.content));
312
+ else if (pick(a.greeting)) add("assistant", pick(a.greeting));
313
+ const sg = (a.suggestions && (a.suggestions[lang] || (lang === "br" && a.suggestions.pt) || a.suggestions.en)) || [];
314
+ sg.slice(0, 4).forEach((s) => { const b = document.createElement("button"); b.textContent = s; b.onclick = () => send(s); sug.appendChild(b); });
315
+ }).catch(() => { $(".btn span").textContent = tx.talk + " ORYKSA"; });
316
+ if (opts.open) panel.classList.add("open");
317
+ return {
318
+ open: () => panel.classList.add("open"),
319
+ close: () => panel.classList.remove("open"),
320
+ send,
321
+ destroy: () => host.remove(),
322
+ };
323
+ }
324
+
325
+ export default Oryksa;