@dolfinhos/studio 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/dist/index.cjs ADDED
@@ -0,0 +1,1144 @@
1
+ 'use client';
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.tsx
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ ApprovalsInbox: () => ApprovalsInbox,
25
+ AuditLog: () => AuditLog,
26
+ AutomationsEditor: () => AutomationsEditor,
27
+ BehaviorSettings: () => BehaviorSettings,
28
+ DolfinhosStudio: () => DolfinhosStudio,
29
+ KnowledgeBase: () => KnowledgeBase,
30
+ MemoryBrowser: () => MemoryBrowser,
31
+ MyMemory: () => MyMemory,
32
+ StudioError: () => StudioError,
33
+ StudioProvider: () => StudioProvider,
34
+ UsageReport: () => UsageReport,
35
+ createStudioClient: () => createStudioClient,
36
+ useStudio: () => useStudio
37
+ });
38
+ module.exports = __toCommonJS(index_exports);
39
+ var import_react11 = require("react");
40
+
41
+ // src/api.ts
42
+ var import_react = require("react");
43
+ var StudioError = class extends Error {
44
+ constructor(message, status) {
45
+ super(message);
46
+ this.status = status;
47
+ this.name = "StudioError";
48
+ }
49
+ status;
50
+ };
51
+ function createStudioClient(options = {}) {
52
+ const endpoint = (options.endpoint ?? "/dolfinhos").replace(/\/$/, "");
53
+ const doFetch = options.fetch ?? ((...args) => fetch(...args));
54
+ async function request(method, path, body) {
55
+ let res;
56
+ try {
57
+ res = await doFetch(endpoint + path, {
58
+ method,
59
+ headers: { ...body !== void 0 ? { "content-type": "application/json" } : {}, ...await options.headers?.() },
60
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
61
+ });
62
+ } catch {
63
+ throw new StudioError("N\xE3o foi poss\xEDvel falar com o servidor. Confira a conex\xE3o e tente de novo.", 0);
64
+ }
65
+ const data = await res.json().catch(() => null);
66
+ if (!res.ok) {
67
+ const message = data?.error?.message ?? data?.message;
68
+ throw new StudioError(
69
+ typeof message === "string" ? message : res.status === 403 ? "Voc\xEA n\xE3o tem permiss\xE3o para isso." : `O servidor respondeu com erro ${res.status}.`,
70
+ res.status
71
+ );
72
+ }
73
+ return data;
74
+ }
75
+ const q = (params) => {
76
+ const s = new URLSearchParams(Object.entries(params).filter((e) => !!e[1])).toString();
77
+ return s ? `?${s}` : "";
78
+ };
79
+ return {
80
+ settings: () => request("GET", "/settings"),
81
+ saveSettings: (settings) => {
82
+ const { updatedAt: _a, updatedBy: _b, ...rest } = settings;
83
+ return request("PUT", "/settings", rest);
84
+ },
85
+ capabilities: () => request("GET", "/capabilities"),
86
+ events: () => request("GET", "/events"),
87
+ approvals: () => request("GET", "/approvals"),
88
+ decide: (item, approved, reason) => request("POST", `/approvals/${encodeURIComponent(item.sessionId)}`, {
89
+ executionId: item.pendingApproval.executionId,
90
+ approved,
91
+ ...reason ? { reason } : {}
92
+ }),
93
+ audit: (params = {}) => request("GET", `/audit${q({ before: params.before, limit: params.limit?.toString(), sessionId: params.sessionId })}`),
94
+ usage: (params = {}) => request("GET", `/usage${q(params)}`),
95
+ knowledge: () => request("GET", "/knowledge"),
96
+ saveKnowledge: (doc) => request("POST", "/knowledge", doc),
97
+ removeKnowledge: (id) => request("DELETE", `/knowledge/${encodeURIComponent(id)}`),
98
+ searchKnowledge: (query, audience) => request("GET", `/knowledge/search${q({ q: query, audience })}`),
99
+ factSubjects: (type) => request("GET", `/facts${q({ type })}`),
100
+ facts: (subject) => request("GET", `/facts${q({ type: subject.type, id: subject.id })}`),
101
+ forget: (id) => request("DELETE", `/facts/${encodeURIComponent(id)}`)
102
+ };
103
+ }
104
+ var StudioContext = (0, import_react.createContext)(null);
105
+ var StudioContextProvider = StudioContext.Provider;
106
+ function useStudio() {
107
+ const value = (0, import_react.useContext)(StudioContext);
108
+ if (!value) throw new Error("Use os componentes do Dolfinhos Studio dentro de <StudioProvider>.");
109
+ return value;
110
+ }
111
+ function useResource(load, deps) {
112
+ const [state, setState] = (0, import_react.useState)({ data: null, error: null, loading: true });
113
+ const seq = (0, import_react.useRef)(0);
114
+ const run = (0, import_react.useCallback)(load, deps);
115
+ const reload = (0, import_react.useCallback)(async () => {
116
+ const id = ++seq.current;
117
+ setState((s) => ({ ...s, loading: true, error: null }));
118
+ try {
119
+ const data = await run();
120
+ if (id === seq.current) setState({ data, error: null, loading: false });
121
+ } catch (e) {
122
+ if (id === seq.current) setState((s) => ({ ...s, error: e instanceof Error ? e.message : String(e), loading: false }));
123
+ }
124
+ }, [run]);
125
+ (0, import_react.useEffect)(() => {
126
+ void reload();
127
+ }, [reload]);
128
+ return { ...state, reload, setData: (data) => setState((s) => ({ ...s, data })) };
129
+ }
130
+
131
+ // src/Approvals.tsx
132
+ var import_react3 = require("react");
133
+
134
+ // src/ui.tsx
135
+ var import_react2 = require("react");
136
+ var import_jsx_runtime = require("react/jsx-runtime");
137
+ var cx = (...c) => c.filter(Boolean).join(" ");
138
+ function Button({ variant = "secondary", loading, className, children, disabled, ...props }) {
139
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { type: "button", ...props, disabled: disabled || loading, "aria-busy": loading || void 0, className: cx("dlf-button", `dlf-button--${variant}`, className), children: [
140
+ loading && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "dlf-spinner", "aria-hidden": true }),
141
+ children
142
+ ] });
143
+ }
144
+ function Field({ label, hint, error, children, htmlFor }) {
145
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "dlf-field", children: [
146
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("label", { className: "dlf-label", htmlFor, children: label }),
147
+ children,
148
+ hint && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "dlf-hint", children: hint }),
149
+ error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "dlf-error-text", role: "alert", children: error })
150
+ ] });
151
+ }
152
+ function Notice({ tone = "info", children }) {
153
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: cx("dlf-notice", `dlf-notice--${tone}`), role: tone === "error" ? "alert" : "status", children });
154
+ }
155
+ function Empty({ title, children }) {
156
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "dlf-empty", children: [
157
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "dlf-empty-title", children: title }),
158
+ children && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "dlf-muted", children })
159
+ ] });
160
+ }
161
+ function Section({ title, description, actions, children, id }) {
162
+ const generated = (0, import_react2.useId)();
163
+ const headingId = `${id ?? generated}-titulo`;
164
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", { className: "dlf-section", "aria-labelledby": headingId, children: [
165
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "dlf-section-head", children: [
166
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [
167
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h2", { id: headingId, className: "dlf-h2", children: title }),
168
+ description && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "dlf-muted dlf-measure", children: description })
169
+ ] }),
170
+ actions && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "dlf-actions", children: actions })
171
+ ] }),
172
+ children
173
+ ] });
174
+ }
175
+ function Badge({ tone = "neutral", children }) {
176
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: cx("dlf-badge", `dlf-badge--${tone}`), children });
177
+ }
178
+ function Loading({ label = "Carregando\u2026" }) {
179
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "dlf-muted dlf-loading", role: "status", children: [
180
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "dlf-spinner", "aria-hidden": true }),
181
+ " ",
182
+ label
183
+ ] });
184
+ }
185
+ function Tabs({ tabs, value, onChange, label }) {
186
+ const refs = (0, import_react2.useRef)([]);
187
+ (0, import_react2.useEffect)(() => {
188
+ refs.current[tabs.findIndex((t) => t.id === value)]?.scrollIntoView?.({ block: "nearest", inline: "nearest" });
189
+ }, [value, tabs]);
190
+ const onKeyDown = (e, index) => {
191
+ const last = tabs.length - 1;
192
+ const next = e.key === "ArrowRight" ? index === last ? 0 : index + 1 : e.key === "ArrowLeft" ? index === 0 ? last : index - 1 : e.key === "Home" ? 0 : e.key === "End" ? last : -1;
193
+ if (next < 0) return;
194
+ e.preventDefault();
195
+ refs.current[next]?.focus();
196
+ onChange(tabs[next].id);
197
+ };
198
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "dlf-tabs", role: "tablist", "aria-label": label, children: tabs.map((tab, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
199
+ "button",
200
+ {
201
+ ref: (el) => {
202
+ refs.current[i] = el;
203
+ },
204
+ type: "button",
205
+ role: "tab",
206
+ id: `dlf-tab-${tab.id}`,
207
+ "aria-selected": tab.id === value,
208
+ "aria-controls": `dlf-panel-${tab.id}`,
209
+ tabIndex: tab.id === value ? 0 : -1,
210
+ className: "dlf-tab",
211
+ onClick: () => onChange(tab.id),
212
+ onKeyDown: (e) => onKeyDown(e, i),
213
+ children: [
214
+ tab.label,
215
+ !!tab.count && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "dlf-tab-count", children: [
216
+ tab.count,
217
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "dlf-sr-only", children: " pendentes" })
218
+ ] })
219
+ ]
220
+ },
221
+ tab.id
222
+ )) });
223
+ }
224
+ var formatDateTime = (iso, locale) => new Intl.DateTimeFormat(locale, { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(iso));
225
+ var formatNumber = (n, locale) => new Intl.NumberFormat(locale).format(n);
226
+ var formatMoney = (n, currency, locale) => currency ? new Intl.NumberFormat(locale, { style: "currency", currency, minimumFractionDigits: 2, maximumFractionDigits: n > 0 && n < 1 ? 4 : 2 }).format(n) : new Intl.NumberFormat(locale, { maximumFractionDigits: 4 }).format(n);
227
+ var showValue = (v) => typeof v === "string" ? v : v === null || v === void 0 ? "\u2014" : JSON.stringify(v);
228
+
229
+ // src/Approvals.tsx
230
+ var import_jsx_runtime2 = require("react/jsx-runtime");
231
+ function ApprovalsInbox({ refreshMs = 3e4, onDecided, onCount }) {
232
+ const { client, labels, locale, navigate } = useStudio();
233
+ const list = useResource(() => client.approvals(), [client]);
234
+ const [busy, setBusy] = (0, import_react3.useState)(null);
235
+ const [message, setMessage] = (0, import_react3.useState)(null);
236
+ (0, import_react3.useEffect)(() => {
237
+ if (!refreshMs) return;
238
+ const timer = setInterval(() => void list.reload(), refreshMs);
239
+ return () => clearInterval(timer);
240
+ }, [refreshMs, list.reload]);
241
+ (0, import_react3.useEffect)(() => {
242
+ if (list.data) onCount?.(list.data.length);
243
+ }, [list.data, onCount]);
244
+ const origin = (item) => {
245
+ const meta = item.meta ?? {};
246
+ const channel = labels.channels?.[item.channel ?? ""] ?? (item.channel === "bot" ? "Bot" : "Automa\xE7\xE3o");
247
+ const who = typeof meta.contato === "string" ? `, conversando com ${meta.contato}` : "";
248
+ const what = typeof meta.automation === "string" ? ` \u201C${meta.automation}\u201D` : "";
249
+ return `${channel}${what}${who}`;
250
+ };
251
+ async function decide(item, approved) {
252
+ const key = `${item.sessionId}:${item.pendingApproval.executionId}`;
253
+ setBusy({ key, approved });
254
+ setMessage(null);
255
+ try {
256
+ const result = await client.decide(item, approved);
257
+ const reply = result.text?.trim() ?? "";
258
+ setMessage({ tone: "success", text: `${approved ? "Aprovado e feito." : "Recusado."}${reply && item.channel === "bot" ? ` Resposta enviada ao cliente: \u201C${reply}\u201D` : ""}` });
259
+ onDecided?.({ item, approved, reply });
260
+ } catch (e) {
261
+ const status = e.status;
262
+ setMessage({ tone: "error", text: status === 404 ? "Algu\xE9m da equipe j\xE1 decidiu este pedido." : e instanceof Error ? e.message : String(e) });
263
+ } finally {
264
+ setBusy(null);
265
+ await list.reload();
266
+ }
267
+ }
268
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(Section, { title: "Aprova\xE7\xF5es", description: "O que o bot e as automa\xE7\xF5es de IA pediram para fazer. Nada acontece at\xE9 algu\xE9m da equipe aprovar.", children: [
269
+ message && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Notice, { tone: message.tone, children: message.text }),
270
+ list.error && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Notice, { tone: "error", children: list.error }),
271
+ list.loading && !list.data && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Loading, {}),
272
+ list.data && !list.data.length && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Empty, { title: "Nenhum pedido esperando", children: "Quando o bot ou uma automa\xE7\xE3o quiser fazer algo que pede aprova\xE7\xE3o, o pedido aparece aqui." }),
273
+ !!list.data?.length && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("ul", { className: "dlf-list", "aria-label": "Pedidos esperando aprova\xE7\xE3o", children: list.data.map((item) => {
274
+ const p = item.pendingApproval;
275
+ const key = `${item.sessionId}:${p.executionId}`;
276
+ const args = p.args && typeof p.args === "object" ? Object.entries(p.args) : [];
277
+ const link = labels.approvalLink?.(item);
278
+ const mine = busy?.key === key;
279
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("li", { className: "dlf-item", children: [
280
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { children: [
281
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("p", { className: "dlf-item-title", children: p.summary ?? p.title ?? p.toolName }),
282
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("p", { className: "dlf-item-meta", children: [
283
+ p.summary && p.title ? `${p.title} \xB7 ` : "",
284
+ origin(item),
285
+ " \xB7 ",
286
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("time", { dateTime: item.updatedAt, children: formatDateTime(item.updatedAt, locale) })
287
+ ] })
288
+ ] }),
289
+ args.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("details", { className: "dlf-details", children: [
290
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("summary", { children: "Ver os dados do pedido" }),
291
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("dl", { className: "dlf-dl", children: args.map(([k, v]) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: { display: "contents" }, children: [
292
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("dt", { children: k }),
293
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("dd", { children: showValue(v) })
294
+ ] }, k)) })
295
+ ] }),
296
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "dlf-item-row", children: [
297
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "dlf-actions", children: [
298
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Button, { variant: "primary", loading: mine && busy.approved, disabled: !!busy, onClick: () => decide(item, true), children: "Aprovar" }),
299
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Button, { loading: mine && !busy.approved, disabled: !!busy, onClick: () => decide(item, false), children: "Recusar" })
300
+ ] }),
301
+ link && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
302
+ "a",
303
+ {
304
+ className: "dlf-link",
305
+ href: link.href,
306
+ onClick: (e) => {
307
+ if (!navigate || e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
308
+ e.preventDefault();
309
+ navigate(link.href);
310
+ },
311
+ children: link.label
312
+ }
313
+ )
314
+ ] })
315
+ ] }, key);
316
+ }) })
317
+ ] });
318
+ }
319
+
320
+ // src/Audit.tsx
321
+ var import_react4 = require("react");
322
+ var import_jsx_runtime3 = require("react/jsx-runtime");
323
+ var DECISIONS = {
324
+ auto: { label: "Sozinho", tone: "neutral" },
325
+ approved: { label: "Aprovado", tone: "success" },
326
+ rejected: { label: "Recusado", tone: "warning" },
327
+ denied: { label: "Bloqueado", tone: "danger" },
328
+ failed: { label: "Falhou", tone: "danger" }
329
+ };
330
+ var PAGE = 50;
331
+ var humanize = (name) => {
332
+ const text = name.replace(/_/g, " ").trim();
333
+ return text.charAt(0).toUpperCase() + text.slice(1);
334
+ };
335
+ function AuditLog() {
336
+ const { client, labels, locale } = useStudio();
337
+ const [records, setRecords] = (0, import_react4.useState)(null);
338
+ const [error, setError] = (0, import_react4.useState)(null);
339
+ const [loading, setLoading] = (0, import_react4.useState)(false);
340
+ const [done, setDone] = (0, import_react4.useState)(false);
341
+ const capabilities = useResource(() => client.capabilities().catch(() => []), [client]);
342
+ const titles = new Map((capabilities.data ?? []).map((c) => [c.name, c.title]));
343
+ async function load(before) {
344
+ setLoading(true);
345
+ setError(null);
346
+ try {
347
+ const page = await client.audit({ limit: PAGE, ...before ? { before } : {} });
348
+ setRecords((current) => before ? [...current ?? [], ...page] : page);
349
+ setDone(page.length < PAGE);
350
+ } catch (e) {
351
+ setError(e instanceof Error ? e.message : String(e));
352
+ } finally {
353
+ setLoading(false);
354
+ }
355
+ }
356
+ (0, import_react4.useEffect)(() => {
357
+ void load();
358
+ }, [client]);
359
+ const who = (r) => {
360
+ const name = r.actor?.name ?? (r.actor?.type === "service" ? "Assistente" : r.actor?.id ?? "\u2014");
361
+ const channel = r.channel ? labels.channels?.[r.channel] ?? r.channel : null;
362
+ return channel && r.channel !== "app" ? `${name} \xB7 ${channel}` : name;
363
+ };
364
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(Section, { title: "Auditoria", description: "Cada a\xE7\xE3o que muda dados ou fala com algu\xE9m: o que foi pedido, por quem, e quem aprovou.", children: [
365
+ error && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Notice, { tone: "error", children: error }),
366
+ !records && loading && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Loading, {}),
367
+ records && !records.length && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Empty, { title: "Nada registrado ainda" }),
368
+ !!records?.length && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "dlf-table-wrap", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("table", { className: "dlf-table", children: [
369
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("thead", { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("tr", { children: [
370
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("th", { scope: "col", children: "Quando" }),
371
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("th", { scope: "col", children: "Quem" }),
372
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("th", { scope: "col", children: "O qu\xEA" }),
373
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("th", { scope: "col", children: "Decis\xE3o" })
374
+ ] }) }),
375
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("tbody", { children: records.map((r) => /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("tr", { children: [
376
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("td", { style: { whiteSpace: "nowrap" }, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("time", { dateTime: r.at, children: formatDateTime(r.at, locale) }) }),
377
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("td", { children: who(r) }),
378
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("td", { style: { minWidth: "14rem" }, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("details", { className: "dlf-details", children: [
379
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("summary", { style: { color: "inherit", fontSize: "inherit" }, children: titles.get(r.capability) ?? humanize(r.capability) }),
380
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("dl", { className: "dlf-dl", children: [
381
+ r.input && typeof r.input === "object" ? Object.entries(r.input).map(([k, v]) => /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: { display: "contents" }, children: [
382
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dt", { children: k }),
383
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dd", { children: showValue(v) })
384
+ ] }, k)) : null,
385
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dt", { children: "A\xE7\xE3o" }),
386
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dd", { children: r.capability }),
387
+ r.rule && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
388
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dt", { children: "Regra" }),
389
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dd", { children: r.rule })
390
+ ] }),
391
+ r.error && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
392
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dt", { children: "Erro" }),
393
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dd", { children: r.error })
394
+ ] })
395
+ ] })
396
+ ] }) }),
397
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("td", { children: [
398
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Badge, { tone: DECISIONS[r.decision].tone, children: DECISIONS[r.decision].label }),
399
+ r.decidedBy && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("p", { className: "dlf-item-meta", children: [
400
+ "por ",
401
+ r.decidedBy.name ?? r.decidedBy.id
402
+ ] })
403
+ ] })
404
+ ] }, r.id)) })
405
+ ] }) }),
406
+ !!records?.length && !done && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Button, { loading, onClick: () => load(records.at(-1).at), children: "Carregar mais" }) })
407
+ ] });
408
+ }
409
+
410
+ // src/Automations.tsx
411
+ var import_react5 = require("react");
412
+ var import_jsx_runtime4 = require("react/jsx-runtime");
413
+ var idFrom = (text) => text.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 50) || "automacao";
414
+ function AutomationsEditor() {
415
+ const { client } = useStudio();
416
+ const ids = (0, import_react5.useId)();
417
+ const settings = useResource(() => client.settings(), [client]);
418
+ const events = useResource(() => client.events(), [client]);
419
+ const [draft, setDraft] = (0, import_react5.useState)(null);
420
+ const [saving, setSaving] = (0, import_react5.useState)(null);
421
+ const [message, setMessage] = (0, import_react5.useState)(null);
422
+ const eventName = (name) => events.data?.find((e) => e.name === name)?.description ?? name;
423
+ async function write(change, key, done) {
424
+ setSaving(key);
425
+ setMessage(null);
426
+ try {
427
+ const fresh = await client.settings();
428
+ const saved = await client.saveSettings({ ...fresh, automations: change(fresh.automations ?? []) });
429
+ settings.setData(saved);
430
+ setMessage({ tone: "success", text: done });
431
+ return true;
432
+ } catch (e) {
433
+ setMessage({ tone: "error", text: e instanceof Error ? e.message : String(e) });
434
+ return false;
435
+ } finally {
436
+ setSaving(null);
437
+ }
438
+ }
439
+ async function submit() {
440
+ if (!draft) return;
441
+ const taken = new Set((settings.data?.automations ?? []).map((a) => a.id).filter((id2) => id2 !== draft.originalId));
442
+ let id = draft.originalId ?? idFrom(draft.description || draft.instruction);
443
+ for (let n = 2; taken.has(id); n++) id = `${idFrom(draft.description || draft.instruction).slice(0, 46)}-${n}`;
444
+ const automation = {
445
+ id,
446
+ event: draft.event,
447
+ instruction: draft.instruction.trim(),
448
+ enabled: draft.enabled,
449
+ ...draft.description.trim() ? { description: draft.description.trim() } : {}
450
+ };
451
+ const ok = await write(
452
+ (list2) => draft.originalId ? list2.map((a) => a.id === draft.originalId ? automation : a) : [...list2, automation],
453
+ "form",
454
+ draft.originalId ? "Automa\xE7\xE3o atualizada." : "Automa\xE7\xE3o criada. Ela roda na pr\xF3xima vez que o evento acontecer."
455
+ );
456
+ if (ok) setDraft(null);
457
+ }
458
+ const list = settings.data?.automations ?? [];
459
+ const firstEvent = events.data?.[0];
460
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
461
+ Section,
462
+ {
463
+ title: "Automa\xE7\xF5es",
464
+ description: "Quando algo acontecer, o assistente faz o que voc\xEA escrever. Ele age com as mesmas regras: o que pede aprova\xE7\xE3o espera na caixa de aprova\xE7\xF5es.",
465
+ actions: !draft && !!firstEvent && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { onClick: () => setDraft({ originalId: null, description: "", event: firstEvent.name, instruction: "", enabled: true }), disabled: !!saving, children: "Nova automa\xE7\xE3o" }),
466
+ children: [
467
+ message && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Notice, { tone: message.tone, children: message.text }),
468
+ (settings.error || events.error) && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Notice, { tone: "error", children: settings.error ?? events.error }),
469
+ (settings.loading || events.loading) && !settings.data && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Loading, {}),
470
+ events.data && !events.data.length && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Empty, { title: "A aplica\xE7\xE3o n\xE3o declarou eventos", children: "Sem eventos, n\xE3o h\xE1 quando disparar automa\xE7\xF5es." }),
471
+ settings.data && !!events.data?.length && !list.length && !draft && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Empty, { title: "Nenhuma automa\xE7\xE3o", children: "Ex.: quando um neg\xF3cio entrar em Proposta, anotar o prazo de envio." }),
472
+ !!list.length && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("ul", { className: "dlf-list", children: list.map((a) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("li", { className: "dlf-item", children: [
473
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "dlf-item-row", children: [
474
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { minWidth: 0 }, children: [
475
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { className: "dlf-item-title", children: a.description ?? a.instruction.slice(0, 80) }),
476
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("p", { className: "dlf-item-meta", children: [
477
+ "Quando: ",
478
+ eventName(a.event)
479
+ ] })
480
+ ] }),
481
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "dlf-actions", children: [
482
+ a.enabled === false ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Badge, { children: "Pausada" }) : /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Badge, { tone: "success", children: "Ativa" }),
483
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
484
+ Button,
485
+ {
486
+ variant: "ghost",
487
+ loading: saving === `toggle:${a.id}`,
488
+ disabled: !!saving,
489
+ onClick: () => write((all) => all.map((x) => x.id === a.id ? { ...x, enabled: x.enabled === false } : x), `toggle:${a.id}`, a.enabled === false ? "Automa\xE7\xE3o ativada." : "Automa\xE7\xE3o pausada."),
490
+ children: a.enabled === false ? "Ativar" : "Pausar"
491
+ }
492
+ ),
493
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { variant: "ghost", disabled: !!saving, onClick: () => setDraft({ originalId: a.id, description: a.description ?? "", event: a.event, instruction: a.instruction, enabled: a.enabled !== false }), children: "Editar" }),
494
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
495
+ Button,
496
+ {
497
+ variant: "ghost",
498
+ loading: saving === `remove:${a.id}`,
499
+ disabled: !!saving,
500
+ onClick: () => {
501
+ if (window.confirm(`Excluir a automa\xE7\xE3o \u201C${a.description ?? a.id}\u201D?`)) void write((all) => all.filter((x) => x.id !== a.id), `remove:${a.id}`, "Automa\xE7\xE3o exclu\xEDda.");
502
+ },
503
+ children: "Excluir"
504
+ }
505
+ )
506
+ ] })
507
+ ] }),
508
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { className: "dlf-item-meta dlf-measure", children: a.instruction })
509
+ ] }, a.id)) }),
510
+ draft && events.data && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
511
+ "form",
512
+ {
513
+ className: "dlf-form",
514
+ "aria-label": draft.originalId ? "Editar automa\xE7\xE3o" : "Nova automa\xE7\xE3o",
515
+ onSubmit: (e) => {
516
+ e.preventDefault();
517
+ void submit();
518
+ },
519
+ children: [
520
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "dlf-row", children: [
521
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Field, { label: "Nome", htmlFor: `${ids}-nome`, hint: "Para achar na lista.", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("input", { id: `${ids}-nome`, className: "dlf-input", maxLength: 200, autoComplete: "off", placeholder: "Ex.: Prazo da proposta\u2026", value: draft.description, onChange: (e) => setDraft({ ...draft, description: e.target.value }) }) }),
522
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Field, { label: "Quando", htmlFor: `${ids}-evento`, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("select", { id: `${ids}-evento`, className: "dlf-select", value: draft.event, onChange: (e) => setDraft({ ...draft, event: e.target.value }), children: events.data.map((ev) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("option", { value: ev.name, children: ev.description }, ev.name)) }) })
523
+ ] }),
524
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Field, { label: "O que fazer", htmlFor: `${ids}-instr`, hint: "Escreva como pediria a algu\xE9m da equipe. O assistente recebe os dados do evento (n\xFAmero, fase, processo).", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
525
+ "textarea",
526
+ {
527
+ id: `${ids}-instr`,
528
+ className: "dlf-textarea",
529
+ rows: 4,
530
+ required: true,
531
+ minLength: 5,
532
+ maxLength: 2e3,
533
+ placeholder: "Ex.: Se a fase for Proposta, anote no neg\xF3cio: enviar a proposta em at\xE9 24h\u2026",
534
+ value: draft.instruction,
535
+ onChange: (e) => setDraft({ ...draft, instruction: e.target.value })
536
+ }
537
+ ) }),
538
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { className: "dlf-choice", children: [
539
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("input", { type: "checkbox", checked: draft.enabled, onChange: (e) => setDraft({ ...draft, enabled: e.target.checked }) }),
540
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { children: "Ativa" })
541
+ ] }),
542
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "dlf-actions", children: [
543
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { type: "submit", variant: "primary", loading: saving === "form", disabled: draft.instruction.trim().length < 5, children: draft.originalId ? "Salvar automa\xE7\xE3o" : "Criar automa\xE7\xE3o" }),
544
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Button, { variant: "ghost", onClick: () => setDraft(null), children: "Cancelar" })
545
+ ] })
546
+ ]
547
+ }
548
+ )
549
+ ]
550
+ }
551
+ );
552
+ }
553
+
554
+ // src/Behavior.tsx
555
+ var import_react6 = require("react");
556
+ var import_jsx_runtime5 = require("react/jsx-runtime");
557
+ var MODES = {
558
+ auto: { label: "Faz sozinho", tone: "success" },
559
+ ask: { label: "Pergunta antes", tone: "warning" },
560
+ deny: { label: "Nunca faz", tone: "danger" }
561
+ };
562
+ var KIND_LABELS = {
563
+ read: "Consultar",
564
+ create: "Criar",
565
+ update: "Alterar",
566
+ delete: "Excluir",
567
+ action: "A\xE7\xF5es (mover, arquivar\u2026)",
568
+ send: "Enviar mensagens"
569
+ };
570
+ var asList = (v) => v === void 0 ? [] : Array.isArray(v) ? v : [v];
571
+ function describeRule(rule, capabilities) {
572
+ const m = rule.match ?? {};
573
+ const parts = [];
574
+ if (m.actorType) parts.push(m.actorType === "service" ? "Bots e automa\xE7\xF5es" : "Pessoas da equipe");
575
+ if (m.channel) parts.push(`no canal ${asList(m.channel).join(", ")}`);
576
+ if (m.role) parts.push(`papel ${asList(m.role).join(", ")}`);
577
+ const what = [
578
+ ...asList(m.capability).map((c) => capabilities.get(c)?.title ?? c),
579
+ ...asList(m.kind).map((k) => KIND_LABELS[k] ?? k),
580
+ ...asList(m.entity).map((e) => `\xE1rea ${e}`),
581
+ ...asList(m.tag).map((t) => `tema ${t}`),
582
+ ...asList(m.risk).map((r) => `risco ${r === "high" ? "alto" : r === "medium" ? "m\xE9dio" : "baixo"}`)
583
+ ];
584
+ parts.push(what.length ? what.join(", ") : "Qualquer a\xE7\xE3o");
585
+ return parts.join(" \xB7 ");
586
+ }
587
+ var emptyDraft = { target: "kind:create", actorType: "", mode: "ask", description: "" };
588
+ function BehaviorSettings({ currency }) {
589
+ const { client } = useStudio();
590
+ const ids = (0, import_react6.useId)();
591
+ const settings = useResource(() => client.settings(), [client]);
592
+ const capabilities = useResource(() => client.capabilities().catch(() => []), [client]);
593
+ const [form, setForm] = (0, import_react6.useState)(null);
594
+ const [draft, setDraft] = (0, import_react6.useState)(null);
595
+ const [saving, setSaving] = (0, import_react6.useState)(false);
596
+ const [message, setMessage] = (0, import_react6.useState)(null);
597
+ (0, import_react6.useEffect)(() => {
598
+ if (settings.data) setForm(settings.data);
599
+ }, [settings.data]);
600
+ const caps = new Map((capabilities.data ?? []).map((c) => [c.name, c]));
601
+ const dirty = !!form && !!settings.data && JSON.stringify(form) !== JSON.stringify(settings.data);
602
+ async function save(next) {
603
+ setSaving(true);
604
+ setMessage(null);
605
+ try {
606
+ const fresh = await client.settings();
607
+ const saved = await client.saveSettings({
608
+ rules: next.rules,
609
+ ...next.instructions?.trim() ? { instructions: next.instructions } : {},
610
+ automations: fresh.automations ?? [],
611
+ ...next.budget ? { budget: next.budget } : {}
612
+ });
613
+ settings.setData(saved);
614
+ setForm(saved);
615
+ setMessage({ tone: "success", text: "Salvo. As pr\xF3ximas conversas j\xE1 seguem estas regras." });
616
+ } catch (e) {
617
+ setMessage({ tone: "error", text: e instanceof Error ? e.message : String(e) });
618
+ } finally {
619
+ setSaving(false);
620
+ }
621
+ }
622
+ function addRule() {
623
+ if (!draft || !form) return;
624
+ const [type, value] = draft.target.split(/:(.*)/s);
625
+ const rule = {
626
+ mode: draft.mode,
627
+ match: { ...type === "cap" ? { capability: value } : { kind: value }, ...draft.actorType ? { actorType: draft.actorType } : {} },
628
+ ...draft.description.trim() ? { description: draft.description.trim() } : {}
629
+ };
630
+ setForm({ ...form, rules: [...form.rules, rule] });
631
+ setDraft(null);
632
+ }
633
+ if (settings.error && !form) return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Notice, { tone: "error", children: settings.error });
634
+ if (!form) return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Loading, {});
635
+ const budgetValue = form.budget?.monthly;
636
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "dlf-stack", children: [
637
+ message && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Notice, { tone: message.tone, children: message.text }),
638
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
639
+ Section,
640
+ {
641
+ title: "Regras",
642
+ description: "O que o assistente faz sozinho, o que pergunta antes e o que nunca faz nesta empresa. Regras fixas da aplica\xE7\xE3o continuam valendo: aqui voc\xEA pode deixar mais restrito, e afrouxar s\xF3 o que a aplica\xE7\xE3o permite.",
643
+ actions: !draft && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Button, { onClick: () => setDraft(emptyDraft), disabled: saving, children: "Nova regra" }),
644
+ children: [
645
+ !form.rules.length && !draft && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Empty, { title: "Sem regras pr\xF3prias", children: "Valem as regras da aplica\xE7\xE3o: consultar \xE9 livre e o que muda dados pergunta antes." }),
646
+ !!form.rules.length && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("ul", { className: "dlf-list", children: form.rules.map((rule, i) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("li", { className: "dlf-item", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "dlf-item-row", children: [
647
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { style: { minWidth: 0 }, children: [
648
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "dlf-item-title", children: describeRule(rule, caps) }),
649
+ rule.description && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "dlf-item-meta", children: rule.description })
650
+ ] }),
651
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "dlf-actions", children: [
652
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Badge, { tone: MODES[rule.mode].tone, children: MODES[rule.mode].label }),
653
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Button, { variant: "ghost", onClick: () => setForm({ ...form, rules: form.rules.filter((_, j) => j !== i) }), "aria-label": `Remover a regra: ${describeRule(rule, caps)}`, children: "Remover" })
654
+ ] })
655
+ ] }) }, i)) }),
656
+ draft && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "dlf-form", role: "group", "aria-label": "Nova regra", children: [
657
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "dlf-row", children: [
658
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Field, { label: "Para qu\xEA", htmlFor: `${ids}-alvo`, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("select", { id: `${ids}-alvo`, className: "dlf-select", value: draft.target, onChange: (e) => setDraft({ ...draft, target: e.target.value }), children: [
659
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("optgroup", { label: "Tipo de a\xE7\xE3o", children: Object.keys(KIND_LABELS).map((k) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: `kind:${k}`, children: KIND_LABELS[k] }, k)) }),
660
+ !!capabilities.data?.length && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("optgroup", { label: "Uma a\xE7\xE3o espec\xEDfica", children: [...capabilities.data].sort((a, b) => (a.title ?? a.name).localeCompare(b.title ?? b.name)).map((c) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: `cap:${c.name}`, children: c.title ?? c.name }, c.name)) })
661
+ ] }) }),
662
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Field, { label: "Quem", htmlFor: `${ids}-quem`, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("select", { id: `${ids}-quem`, className: "dlf-select", value: draft.actorType, onChange: (e) => setDraft({ ...draft, actorType: e.target.value }), children: [
663
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "", children: "Todos" }),
664
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "user", children: "Pessoas da equipe (painel)" }),
665
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: "service", children: "Bots e automa\xE7\xF5es" })
666
+ ] }) }),
667
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Field, { label: "Decis\xE3o", htmlFor: `${ids}-modo`, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("select", { id: `${ids}-modo`, className: "dlf-select", value: draft.mode, onChange: (e) => setDraft({ ...draft, mode: e.target.value }), children: Object.keys(MODES).map((m) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("option", { value: m, children: MODES[m].label }, m)) }) })
668
+ ] }),
669
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Field, { label: "Por qu\xEA (opcional)", htmlFor: `${ids}-desc`, hint: "Aparece na auditoria e para o assistente explicar quando n\xE3o puder fazer algo.", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("input", { id: `${ids}-desc`, className: "dlf-input", maxLength: 500, autoComplete: "off", placeholder: "Ex.: exclus\xF5es s\xF3 pela equipe\u2026", value: draft.description, onChange: (e) => setDraft({ ...draft, description: e.target.value }) }) }),
670
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "dlf-actions", children: [
671
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Button, { variant: "primary", onClick: addRule, children: "Adicionar regra" }),
672
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Button, { variant: "ghost", onClick: () => setDraft(null), children: "Cancelar" })
673
+ ] })
674
+ ] })
675
+ ]
676
+ }
677
+ ),
678
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Section, { title: "Prefer\xEAncias", description: "Como o assistente da equipe deve trabalhar aqui: tom, vocabul\xE1rio, o que priorizar. O bot de atendimento usa as instru\xE7\xF5es do pr\xF3prio produto.", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Field, { label: "Instru\xE7\xF5es para o assistente", htmlFor: `${ids}-instr`, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
679
+ "textarea",
680
+ {
681
+ id: `${ids}-instr`,
682
+ className: "dlf-textarea",
683
+ rows: 5,
684
+ maxLength: 1e4,
685
+ placeholder: "Ex.: Chame neg\xF3cios de oportunidades. Sempre informe valores com centavos\u2026",
686
+ value: form.instructions ?? "",
687
+ onChange: (e) => setForm({ ...form, instructions: e.target.value })
688
+ }
689
+ ) }) }),
690
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Section, { title: "Limite de gasto", description: "Ao chegar no limite do m\xEAs, o assistente e o bot param de responder at\xE9 o m\xEAs virar ou algu\xE9m aumentar o limite. Em branco: sem limite.", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Field, { label: `Limite mensal${currency ? ` (${currency})` : ""}`, htmlFor: `${ids}-budget`, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
691
+ "input",
692
+ {
693
+ id: `${ids}-budget`,
694
+ className: "dlf-input",
695
+ style: { maxWidth: "12rem" },
696
+ type: "number",
697
+ inputMode: "decimal",
698
+ min: 0,
699
+ step: "0.01",
700
+ autoComplete: "off",
701
+ value: budgetValue ?? "",
702
+ onChange: (e) => {
703
+ const n = Number(e.target.value);
704
+ const { budget: _b, ...rest } = form;
705
+ setForm(e.target.value === "" || !(n > 0) ? rest : { ...rest, budget: { monthly: n } });
706
+ }
707
+ }
708
+ ) }) }),
709
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "dlf-actions", children: [
710
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Button, { variant: "primary", loading: saving, disabled: !dirty, onClick: () => save(form), children: "Salvar altera\xE7\xF5es" }),
711
+ dirty && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Button, { variant: "ghost", disabled: saving, onClick: () => setForm(settings.data), children: "Descartar" })
712
+ ] })
713
+ ] });
714
+ }
715
+
716
+ // src/Knowledge.tsx
717
+ var import_react7 = require("react");
718
+ var import_jsx_runtime6 = require("react/jsx-runtime");
719
+ function KnowledgeBase() {
720
+ const { client, locale } = useStudio();
721
+ const ids = (0, import_react7.useId)();
722
+ const docs = useResource(() => client.knowledge(), [client]);
723
+ const [draft, setDraft] = (0, import_react7.useState)(null);
724
+ const [saving, setSaving] = (0, import_react7.useState)(null);
725
+ const [message, setMessage] = (0, import_react7.useState)(null);
726
+ const [query, setQuery] = (0, import_react7.useState)("");
727
+ const [queryAudience, setQueryAudience] = (0, import_react7.useState)("all");
728
+ const [hits, setHits] = (0, import_react7.useState)(null);
729
+ const [searching, setSearching] = (0, import_react7.useState)(false);
730
+ async function save() {
731
+ if (!draft) return;
732
+ setSaving("form");
733
+ setMessage(null);
734
+ try {
735
+ await client.saveKnowledge({ ...draft.id ? { id: draft.id } : {}, title: draft.title.trim(), content: draft.content.trim(), audience: draft.audience, tags: draft.tags });
736
+ setDraft(null);
737
+ setMessage({ tone: "success", text: "Documento salvo. O assistente j\xE1 consulta a vers\xE3o nova." });
738
+ await docs.reload();
739
+ } catch (e) {
740
+ setMessage({ tone: "error", text: e instanceof Error ? e.message : String(e) });
741
+ } finally {
742
+ setSaving(null);
743
+ }
744
+ }
745
+ async function remove(doc) {
746
+ if (!window.confirm(`Excluir o documento \u201C${doc.title}\u201D? O assistente deixa de consult\xE1-lo.`)) return;
747
+ setSaving(doc.id);
748
+ setMessage(null);
749
+ try {
750
+ await client.removeKnowledge(doc.id);
751
+ setMessage({ tone: "success", text: "Documento exclu\xEDdo." });
752
+ await docs.reload();
753
+ } catch (e) {
754
+ setMessage({ tone: "error", text: e instanceof Error ? e.message : String(e) });
755
+ } finally {
756
+ setSaving(null);
757
+ }
758
+ }
759
+ async function search() {
760
+ if (!query.trim()) return;
761
+ setSearching(true);
762
+ try {
763
+ setHits(await client.searchKnowledge(query.trim(), queryAudience));
764
+ } catch (e) {
765
+ setMessage({ tone: "error", text: e instanceof Error ? e.message : String(e) });
766
+ } finally {
767
+ setSearching(false);
768
+ }
769
+ }
770
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "dlf-stack", children: [
771
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
772
+ Section,
773
+ {
774
+ title: "Base de conhecimento",
775
+ description: "O que o assistente e o bot consultam antes de responder: perguntas frequentes, pol\xEDticas, explica\xE7\xF5es de produtos. Documentos internos nunca chegam ao bot de atendimento.",
776
+ actions: !draft && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Button, { onClick: () => setDraft({ title: "", content: "", audience: "internal", tags: [] }), disabled: !!saving, children: "Novo documento" }),
777
+ children: [
778
+ message && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Notice, { tone: message.tone, children: message.text }),
779
+ docs.error && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Notice, { tone: "error", children: docs.error }),
780
+ docs.loading && !docs.data && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Loading, {}),
781
+ docs.data && !docs.data.length && !draft && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Empty, { title: "Nenhum documento", children: "Comece pelas perguntas que os clientes mais fazem e pela pol\xEDtica de trocas e pagamentos." }),
782
+ !!docs.data?.length && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("ul", { className: "dlf-list", children: docs.data.map((doc) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("li", { className: "dlf-item", children: /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "dlf-item-row", children: [
783
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { style: { minWidth: 0 }, children: [
784
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "dlf-item-title", children: doc.title }),
785
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("p", { className: "dlf-item-meta", children: [
786
+ doc.content.length.toLocaleString(locale),
787
+ " caracteres \xB7 atualizado em ",
788
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("time", { dateTime: doc.updatedAt, children: formatDateTime(doc.updatedAt, locale) })
789
+ ] })
790
+ ] }),
791
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "dlf-actions", children: [
792
+ doc.audience === "all" ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Badge, { tone: "accent", children: "Equipe e clientes" }) : /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Badge, { children: "S\xF3 a equipe" }),
793
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Button, { variant: "ghost", disabled: !!saving, onClick: () => setDraft({ id: doc.id, title: doc.title, content: doc.content, audience: doc.audience, tags: doc.tags }), children: "Editar" }),
794
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Button, { variant: "ghost", loading: saving === doc.id, disabled: !!saving, onClick: () => remove(doc), children: "Excluir" })
795
+ ] })
796
+ ] }) }, doc.id)) }),
797
+ draft && /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
798
+ "form",
799
+ {
800
+ className: "dlf-form",
801
+ "aria-label": draft.id ? "Editar documento" : "Novo documento",
802
+ onSubmit: (e) => {
803
+ e.preventDefault();
804
+ void save();
805
+ },
806
+ children: [
807
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Field, { label: "T\xEDtulo", htmlFor: `${ids}-titulo`, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("input", { id: `${ids}-titulo`, className: "dlf-input", required: true, maxLength: 200, autoComplete: "off", placeholder: "Ex.: Pol\xEDtica de trocas\u2026", value: draft.title, onChange: (e) => setDraft({ ...draft, title: e.target.value }) }) }),
808
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Field, { label: "Conte\xFAdo", htmlFor: `${ids}-conteudo`, hint: "Texto simples. Separe assuntos em par\xE1grafos: a busca devolve o trecho mais relevante.", children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("textarea", { id: `${ids}-conteudo`, className: "dlf-textarea", required: true, rows: 12, maxLength: 1e5, value: draft.content, onChange: (e) => setDraft({ ...draft, content: e.target.value }) }) }),
809
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("fieldset", { className: "dlf-field", style: { border: 0, padding: 0, margin: 0 }, children: [
810
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("legend", { className: "dlf-label", children: "Quem pode ler" }),
811
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("label", { className: "dlf-choice", children: [
812
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("input", { type: "radio", name: `${ids}-publico`, checked: draft.audience === "internal", onChange: () => setDraft({ ...draft, audience: "internal" }) }),
813
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("span", { children: [
814
+ "S\xF3 a equipe ",
815
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "dlf-muted", children: "(o assistente do painel)" })
816
+ ] })
817
+ ] }),
818
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("label", { className: "dlf-choice", children: [
819
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("input", { type: "radio", name: `${ids}-publico`, checked: draft.audience === "all", onChange: () => setDraft({ ...draft, audience: "all" }) }),
820
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("span", { children: [
821
+ "Equipe e clientes ",
822
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "dlf-muted", children: "(o bot de atendimento tamb\xE9m usa nas respostas)" })
823
+ ] })
824
+ ] })
825
+ ] }),
826
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "dlf-actions", children: [
827
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Button, { type: "submit", variant: "primary", loading: saving === "form", disabled: !draft.title.trim() || !draft.content.trim(), children: "Salvar documento" }),
828
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Button, { variant: "ghost", onClick: () => setDraft(null), children: "Cancelar" })
829
+ ] })
830
+ ]
831
+ }
832
+ )
833
+ ]
834
+ }
835
+ ),
836
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Section, { title: "Testar a busca", description: "Veja o que o assistente encontra para uma pergunta.", children: [
837
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
838
+ "form",
839
+ {
840
+ className: "dlf-row",
841
+ style: { alignItems: "end" },
842
+ onSubmit: (e) => {
843
+ e.preventDefault();
844
+ void search();
845
+ },
846
+ children: [
847
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Field, { label: "Pergunta", htmlFor: `${ids}-busca`, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("input", { id: `${ids}-busca`, className: "dlf-input", type: "search", autoComplete: "off", maxLength: 300, placeholder: "Ex.: qual o prazo para trocar?\u2026", value: query, onChange: (e) => setQuery(e.target.value) }) }),
848
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Field, { label: "Como", htmlFor: `${ids}-como`, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("select", { id: `${ids}-como`, className: "dlf-select", value: queryAudience, onChange: (e) => setQueryAudience(e.target.value), children: [
849
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("option", { value: "all", children: "O bot de atendimento veria" }),
850
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("option", { value: "internal", children: "O assistente da equipe veria" })
851
+ ] }) }),
852
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Button, { type: "submit", loading: searching, disabled: !query.trim(), children: "Buscar" }) })
853
+ ]
854
+ }
855
+ ),
856
+ hits && !hits.length && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Empty, { title: "Nada encontrado", children: "Nesse caso o assistente diz que vai verificar, em vez de inventar." }),
857
+ !!hits?.length && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("ul", { className: "dlf-list", "aria-live": "polite", children: hits.map((h) => /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("li", { className: "dlf-item", children: [
858
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "dlf-item-title", children: h.title }),
859
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "dlf-item-meta dlf-measure", style: { whiteSpace: "pre-line" }, children: h.excerpt.length > 600 ? `${h.excerpt.slice(0, 600)}\u2026` : h.excerpt })
860
+ ] }, h.docId)) })
861
+ ] })
862
+ ] });
863
+ }
864
+
865
+ // src/Memory.tsx
866
+ var import_react8 = require("react");
867
+ var import_jsx_runtime7 = require("react/jsx-runtime");
868
+ function FactList({ subject, emptyText }) {
869
+ const { client, locale } = useStudio();
870
+ const facts = useResource(() => client.facts(subject), [client, subject.type, subject.id]);
871
+ const [removing, setRemoving] = (0, import_react8.useState)(null);
872
+ const [error, setError] = (0, import_react8.useState)(null);
873
+ async function forget(fact) {
874
+ if (!window.confirm(`Esquecer \u201C${fact.text}\u201D? O assistente deixa de usar isso nas pr\xF3ximas conversas.`)) return;
875
+ setRemoving(fact.id);
876
+ setError(null);
877
+ try {
878
+ await client.forget(fact.id);
879
+ await facts.reload();
880
+ } catch (e) {
881
+ setError(e instanceof Error ? e.message : String(e));
882
+ } finally {
883
+ setRemoving(null);
884
+ }
885
+ }
886
+ if (facts.error) return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Notice, { tone: "error", children: facts.error });
887
+ if (!facts.data) return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Loading, {});
888
+ if (!facts.data.length) return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Empty, { title: "Nada guardado", children: emptyText });
889
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_jsx_runtime7.Fragment, { children: [
890
+ error && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Notice, { tone: "error", children: error }),
891
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("ul", { className: "dlf-list", children: facts.data.map((f) => /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("li", { className: "dlf-item", children: /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "dlf-item-row", children: [
892
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { style: { minWidth: 0 }, children: [
893
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("p", { className: "dlf-item-title", style: { fontWeight: 400 }, children: f.text }),
894
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("p", { className: "dlf-item-meta", children: [
895
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("time", { dateTime: f.createdAt, children: formatDateTime(f.createdAt, locale) }),
896
+ f.createdBy?.name ? ` \xB7 por ${f.createdBy.name}` : f.createdBy?.type === "service" ? " \xB7 pelo bot" : ""
897
+ ] })
898
+ ] }),
899
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Button, { variant: "ghost", loading: removing === f.id, disabled: !!removing, onClick: () => forget(f), "aria-label": `Esquecer: ${f.text}`, children: "Esquecer" })
900
+ ] }) }, f.id)) })
901
+ ] });
902
+ }
903
+ function MemoryBrowser() {
904
+ const { client, labels, locale } = useStudio();
905
+ const subjects = useResource(() => client.factSubjects(), [client]);
906
+ const [open, setOpen] = (0, import_react8.useState)(null);
907
+ const typeLabel = (type) => labels.subjects?.[type] ?? type;
908
+ if (open) {
909
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
910
+ Section,
911
+ {
912
+ title: open.label ?? open.id,
913
+ description: `${typeLabel(open.type)}. O que o assistente lembra nas pr\xF3ximas conversas. Esque\xE7a o que estiver errado ou n\xE3o deveria ser guardado.`,
914
+ actions: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
915
+ Button,
916
+ {
917
+ variant: "ghost",
918
+ onClick: () => {
919
+ setOpen(null);
920
+ void subjects.reload();
921
+ },
922
+ children: "Voltar para a lista"
923
+ }
924
+ ),
925
+ children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(FactList, { subject: open, emptyText: "Tudo foi esquecido." })
926
+ }
927
+ );
928
+ }
929
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Section, { title: "Mem\xF3ria", description: "O que o assistente e o bot guardaram sobre clientes e pessoas da equipe, de conversas anteriores.", children: [
930
+ subjects.error && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Notice, { tone: "error", children: subjects.error }),
931
+ subjects.loading && !subjects.data && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Loading, {}),
932
+ subjects.data && !subjects.data.length && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Empty, { title: "Nada guardado ainda", children: "O bot guarda o que o cliente conta (prefer\xEAncias, contexto) e o assistente guarda como cada pessoa gosta de trabalhar." }),
933
+ !!subjects.data?.length && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { className: "dlf-table-wrap", children: /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("table", { className: "dlf-table", children: [
934
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("thead", { children: /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("tr", { children: [
935
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("th", { scope: "col", children: "Sobre" }),
936
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("th", { scope: "col", children: "Tipo" }),
937
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("th", { scope: "col", className: "dlf-num", children: "Fatos" }),
938
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("th", { scope: "col", children: "\xDAltimo" })
939
+ ] }) }),
940
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("tbody", { children: subjects.data.map((s) => /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("tr", { children: [
941
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("td", { children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("button", { type: "button", className: "dlf-link-button", onClick: () => setOpen(s), children: s.label ?? s.id }) }),
942
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("td", { children: typeLabel(s.type) }),
943
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("td", { className: "dlf-num", children: s.count }),
944
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("td", { children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("time", { dateTime: s.lastAt, children: formatDateTime(s.lastAt, locale) }) })
945
+ ] }, `${s.type}:${s.id}`)) })
946
+ ] }) })
947
+ ] });
948
+ }
949
+ function MyMemory({ subject }) {
950
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Section, { title: "O que o assistente lembra de voc\xEA", description: "Prefer\xEAncias que voc\xEA pediu para ele guardar. Esque\xE7a o que n\xE3o valer mais.", children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(FactList, { subject, emptyText: 'Pe\xE7a ao assistente, por exemplo: "lembre que prefiro respostas curtas".' }) });
951
+ }
952
+
953
+ // src/Studio.tsx
954
+ var import_react10 = require("react");
955
+
956
+ // src/Usage.tsx
957
+ var import_react9 = require("react");
958
+ var import_jsx_runtime8 = require("react/jsx-runtime");
959
+ var periodRange = (period) => {
960
+ const now = /* @__PURE__ */ new Date();
961
+ const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
962
+ if (period === "month") return { from: monthStart.toISOString(), to: new Date(now.getTime() + 6e4).toISOString() };
963
+ if (period === "last-month") return { from: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 1, 1)).toISOString(), to: monthStart.toISOString() };
964
+ return { from: new Date(now.getTime() - 7 * 864e5).toISOString(), to: new Date(now.getTime() + 6e4).toISOString() };
965
+ };
966
+ function UsageReport() {
967
+ const { client, labels, locale } = useStudio();
968
+ const ids = (0, import_react9.useId)();
969
+ const [period, setPeriod] = (0, import_react9.useState)("month");
970
+ const usage = useResource(() => client.usage(periodRange(period)), [client, period]);
971
+ const data = usage.data;
972
+ const money = (n) => formatMoney(n, data?.currency ?? null, locale);
973
+ const tokens = (t) => formatNumber(t.inputTokens + t.outputTokens, locale);
974
+ const channelLabel = (c) => labels.channels?.[c] ?? c;
975
+ const maxDay = Math.max(...data?.byDay.map((d) => data.currency ? d.cost : d.inputTokens + d.outputTokens) ?? [0], 0);
976
+ const used = data?.budget && period === "month" ? data.total.cost / data.budget.monthly : null;
977
+ return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
978
+ Section,
979
+ {
980
+ title: "Uso e custos",
981
+ description: "Quanto o assistente, o bot e as automa\xE7\xF5es gastaram com IA.",
982
+ actions: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Field, { label: "Per\xEDodo", htmlFor: `${ids}-periodo`, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("select", { id: `${ids}-periodo`, className: "dlf-select", value: period, onChange: (e) => setPeriod(e.target.value), children: [
983
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("option", { value: "month", children: "Este m\xEAs" }),
984
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("option", { value: "last-month", children: "M\xEAs passado" }),
985
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("option", { value: "7d", children: "\xDAltimos 7 dias" })
986
+ ] }) }),
987
+ children: [
988
+ usage.error && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Notice, { tone: "error", children: usage.error }),
989
+ usage.loading && !data && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Loading, {}),
990
+ data && /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(import_jsx_runtime8.Fragment, { children: [
991
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("dl", { className: "dlf-stats", children: [
992
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "dlf-stat", children: [
993
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("dt", { children: "Custo" }),
994
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("dd", { children: data.currency ? money(data.total.cost) : "\u2014" })
995
+ ] }),
996
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "dlf-stat", children: [
997
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("dt", { children: "Conversas e tarefas" }),
998
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("dd", { children: formatNumber(data.total.runs, locale) })
999
+ ] }),
1000
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "dlf-stat", children: [
1001
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("dt", { children: "Tokens" }),
1002
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("dd", { children: tokens(data.total) })
1003
+ ] })
1004
+ ] }),
1005
+ !data.currency && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("p", { className: "dlf-muted", children: "Sem tabela de pre\xE7os configurada na aplica\xE7\xE3o: s\xF3 os tokens aparecem." }),
1006
+ data.total.unpricedCalls > 0 && data.currency && /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("p", { className: "dlf-muted", children: [
1007
+ formatNumber(data.total.unpricedCalls, locale),
1008
+ " chamadas usaram modelos sem pre\xE7o configurado e n\xE3o entram no custo."
1009
+ ] }),
1010
+ used !== null && data.budget && /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { className: "dlf-field", children: [
1011
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("p", { className: "dlf-muted", id: `${ids}-limite`, children: [
1012
+ money(data.total.cost),
1013
+ " de ",
1014
+ money(data.budget.monthly),
1015
+ " do limite do m\xEAs (",
1016
+ Math.round(used * 100),
1017
+ "%)",
1018
+ used >= 1 ? ". Limite atingido: o assistente est\xE1 parado at\xE9 o m\xEAs virar ou o limite subir." : ""
1019
+ ] }),
1020
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
1021
+ "div",
1022
+ {
1023
+ className: used >= 1 ? "dlf-meter dlf-meter--over" : "dlf-meter",
1024
+ role: "meter",
1025
+ "aria-labelledby": `${ids}-limite`,
1026
+ "aria-valuemin": 0,
1027
+ "aria-valuemax": 100,
1028
+ "aria-valuenow": Math.min(100, Math.round(used * 100)),
1029
+ children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { style: { width: `${Math.min(100, used * 100)}%` } })
1030
+ }
1031
+ )
1032
+ ] }),
1033
+ !data.byDay.length ? /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Empty, { title: "Nenhum uso no per\xEDodo" }) : /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(import_jsx_runtime8.Fragment, { children: [
1034
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { children: [
1035
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("h3", { className: "dlf-h3", style: { marginBottom: "0.5rem" }, children: "Por dia" }),
1036
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { className: "dlf-bars", children: data.byDay.map((d) => {
1037
+ const value = data.currency ? d.cost : d.inputTokens + d.outputTokens;
1038
+ return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("div", { style: { display: "contents" }, children: [
1039
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "dlf-muted", children: new Intl.DateTimeFormat(locale, { day: "2-digit", month: "2-digit", timeZone: "UTC" }).format(/* @__PURE__ */ new Date(`${d.day}T00:00:00Z`)) }),
1040
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "dlf-bar", style: { width: `${maxDay ? value / maxDay * 100 : 0}%` }, "aria-hidden": true }),
1041
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("span", { className: "dlf-num", children: data.currency ? money(d.cost) : tokens(d) })
1042
+ ] }, d.day);
1043
+ }) })
1044
+ ] }),
1045
+ [
1046
+ ["Por canal", data.byChannel.map((c) => ({ key: c.channel, label: channelLabel(c.channel), t: c }))],
1047
+ ["Por modelo", data.byModel.map((m) => ({ key: m.model, label: m.model.slice(m.model.indexOf(":") + 1), t: m }))]
1048
+ ].map(([title, rows]) => /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("div", { className: "dlf-table-wrap", children: /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("table", { className: "dlf-table", children: [
1049
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("caption", { className: "dlf-sr-only", children: title }),
1050
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("thead", { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("tr", { children: [
1051
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("th", { scope: "col", children: title }),
1052
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("th", { scope: "col", className: "dlf-num", children: "Execu\xE7\xF5es" }),
1053
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("th", { scope: "col", className: "dlf-num", children: "Tokens" }),
1054
+ data.currency && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("th", { scope: "col", className: "dlf-num", children: "Custo" })
1055
+ ] }) }),
1056
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("tbody", { children: rows.map((r) => /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)("tr", { children: [
1057
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("td", { children: r.label }),
1058
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("td", { className: "dlf-num", children: formatNumber(r.t.runs, locale) }),
1059
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("td", { className: "dlf-num", children: tokens(r.t) }),
1060
+ data.currency && /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("td", { className: "dlf-num", children: money(r.t.cost) })
1061
+ ] }, r.key)) })
1062
+ ] }) }, title))
1063
+ ] })
1064
+ ] })
1065
+ ]
1066
+ }
1067
+ );
1068
+ }
1069
+
1070
+ // src/Studio.tsx
1071
+ var import_jsx_runtime9 = require("react/jsx-runtime");
1072
+ var LABELS = {
1073
+ approvals: "Aprova\xE7\xF5es",
1074
+ behavior: "Regras",
1075
+ automations: "Automa\xE7\xF5es",
1076
+ knowledge: "Conhecimento",
1077
+ memory: "Mem\xF3ria",
1078
+ usage: "Custos",
1079
+ audit: "Auditoria"
1080
+ };
1081
+ function DolfinhosStudio({ sections, section, defaultSection, onSectionChange, currency, pendingApprovals, onPendingApprovalsChange }) {
1082
+ const visible = sections ?? Object.keys(LABELS);
1083
+ const [own, setOwn] = (0, import_react10.useState)(defaultSection ?? visible[0]);
1084
+ const [pending, setPending] = (0, import_react10.useState)(pendingApprovals);
1085
+ const current = section ?? own;
1086
+ const select = (s) => {
1087
+ setOwn(s);
1088
+ onSectionChange?.(s);
1089
+ };
1090
+ const onCount = (n) => {
1091
+ setPending(n);
1092
+ onPendingApprovalsChange?.(n);
1093
+ };
1094
+ const panels = {
1095
+ approvals: () => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(ApprovalsInbox, { onCount }),
1096
+ behavior: () => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(BehaviorSettings, { currency: currency ?? null }),
1097
+ automations: () => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(AutomationsEditor, {}),
1098
+ knowledge: () => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(KnowledgeBase, {}),
1099
+ memory: () => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(MemoryBrowser, {}),
1100
+ usage: () => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(UsageReport, {}),
1101
+ audit: () => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(AuditLog, {})
1102
+ };
1103
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("div", { className: "dlf dlf-studio", children: [
1104
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
1105
+ Tabs,
1106
+ {
1107
+ label: "\xC1reas do assistente de IA",
1108
+ value: current,
1109
+ onChange: select,
1110
+ tabs: visible.map((id) => ({ id, label: LABELS[id], ...id === "approvals" ? { count: pendingApprovals ?? pending ?? 0 } : {} }))
1111
+ }
1112
+ ),
1113
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { role: "tabpanel", id: `dlf-panel-${current}`, "aria-labelledby": `dlf-tab-${current}`, tabIndex: 0, style: { outlineOffset: 4 }, children: panels[current]() })
1114
+ ] });
1115
+ }
1116
+
1117
+ // src/index.tsx
1118
+ var import_jsx_runtime10 = require("react/jsx-runtime");
1119
+ function StudioProvider({ children, endpoint, headers, fetch: fetch2, labels, locale = "pt-BR", navigate }) {
1120
+ const client = (0, import_react11.useMemo)(
1121
+ () => createStudioClient({ ...endpoint ? { endpoint } : {}, ...headers ? { headers } : {}, ...fetch2 ? { fetch: fetch2 } : {} }),
1122
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1123
+ [endpoint]
1124
+ );
1125
+ const value = (0, import_react11.useMemo)(() => ({ client, labels: labels ?? {}, locale, ...navigate ? { navigate } : {} }), [client, labels, locale, navigate]);
1126
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(StudioContextProvider, { value, children });
1127
+ }
1128
+ // Annotate the CommonJS export names for ESM import in node:
1129
+ 0 && (module.exports = {
1130
+ ApprovalsInbox,
1131
+ AuditLog,
1132
+ AutomationsEditor,
1133
+ BehaviorSettings,
1134
+ DolfinhosStudio,
1135
+ KnowledgeBase,
1136
+ MemoryBrowser,
1137
+ MyMemory,
1138
+ StudioError,
1139
+ StudioProvider,
1140
+ UsageReport,
1141
+ createStudioClient,
1142
+ useStudio
1143
+ });
1144
+ //# sourceMappingURL=index.cjs.map