@dolfinhos/nestjs 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,910 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __decorateClass = (decorators, target, key, kind) => {
20
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
21
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
22
+ if (decorator = decorators[i])
23
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
24
+ if (kind && result) __defProp(target, key, result);
25
+ return result;
26
+ };
27
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
28
+
29
+ // src/index.ts
30
+ var index_exports = {};
31
+ __export(index_exports, {
32
+ AiCapability: () => AiCapability,
33
+ AiIgnore: () => AiIgnore,
34
+ DOLFINHOS_OPTIONS: () => DOLFINHOS_OPTIONS,
35
+ DolfinhosModule: () => DolfinhosModule,
36
+ DolfinhosService: () => DolfinhosService,
37
+ areaOf: () => areaOf,
38
+ buildCapabilities: () => buildCapabilities,
39
+ compact: () => compact,
40
+ createApiCaller: () => createApiCaller,
41
+ describeCapabilities: () => describeCapabilities,
42
+ discoverRoutes: () => discoverRoutes,
43
+ inferKind: () => inferKind,
44
+ inputSchemaOf: () => inputSchemaOf,
45
+ joinPath: () => joinPath,
46
+ loadCapabilitiesFile: () => loadCapabilitiesFile,
47
+ pathParams: () => pathParams,
48
+ requestOf: () => requestOf,
49
+ safeName: () => safeName
50
+ });
51
+ module.exports = __toCommonJS(index_exports);
52
+
53
+ // src/module.ts
54
+ var import_promises = require("fs/promises");
55
+ var import_node_path = require("path");
56
+ var import_server = require("@dolfinhos/server");
57
+ var import_common2 = require("@nestjs/common");
58
+ var import_core3 = require("@nestjs/core");
59
+
60
+ // src/capabilities.ts
61
+ var import_core = require("@dolfinhos/core");
62
+ var import_zod = require("zod");
63
+ var snake = (text) => text.replace(/Controller$/, "").replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^a-zA-Z0-9]+/g, "_").toLowerCase().replace(/^_|_$/g, "");
64
+ var segments = (path) => path.split("/").filter(Boolean);
65
+ function inferKind(route) {
66
+ if (route.method === "GET") return "read";
67
+ if (route.method === "DELETE") return "delete";
68
+ if (route.method === "PUT" || route.method === "PATCH") return "update";
69
+ const parts = segments(route.path);
70
+ const last = parts.at(-1) ?? "";
71
+ return last.startsWith(":") || parts.some((p) => p.startsWith(":")) ? "action" : "create";
72
+ }
73
+ var areaOf = (path) => segments(path).find((p) => !p.startsWith(":")) ?? "root";
74
+ var isZod = (schema) => Boolean(schema && typeof schema === "object" && "_zod" in schema);
75
+ var asZod = (schema, fallback) => isZod(schema) ? schema : fallback;
76
+ var pathParams = (path) => [...path.matchAll(/:(\w+)/g)].map((m) => m[1]);
77
+ var DOT_SEGMENT = /^\.{1,2}$/;
78
+ var notDotSegment = (schema) => schema.refine((value) => typeof value !== "string" || !DOT_SEGMENT.test(value), { message: "Valor inv\xE1lido para um par\xE2metro de caminho." });
79
+ function inputSchemaOf(route) {
80
+ const shape = {};
81
+ for (const name of pathParams(route.path)) {
82
+ shape[name] = notDotSegment(asZod(route.params[name], import_zod.z.string().min(1))).describe(`Par\xE2metro "${name}" do caminho`);
83
+ }
84
+ if (route.querySchema && isZod(route.querySchema) && route.querySchema instanceof import_zod.z.ZodObject) {
85
+ for (const [key, value] of Object.entries(route.querySchema.shape)) shape[key] ??= value.optional();
86
+ }
87
+ for (const [key, schema] of Object.entries(route.queryFields)) shape[key] ??= asZod(schema, import_zod.z.string()).optional();
88
+ if (route.bodySchema !== void 0) {
89
+ shape.dados = route.bodySchema === null ? import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).describe("Corpo JSON da requisi\xE7\xE3o") : asZod(route.bodySchema, import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()));
90
+ }
91
+ return import_zod.z.object(shape);
92
+ }
93
+ function requestOf(route, input) {
94
+ const scalar = (key) => String(input[key]);
95
+ const path = route.path.replace(/:(\w+)/g, (_, key) => {
96
+ const value = scalar(key);
97
+ if (DOT_SEGMENT.test(value)) throw new Error(`Valor inv\xE1lido para o par\xE2metro "${key}".`);
98
+ return encodeURIComponent(value);
99
+ });
100
+ if (new URL(path, "http://dolfinhos.local").pathname.split("/").length !== route.path.split("/").length) {
101
+ throw new Error("Caminho inv\xE1lido para esta a\xE7\xE3o.");
102
+ }
103
+ const queryKeys = [
104
+ ...Object.keys(route.queryFields),
105
+ ...route.querySchema && isZod(route.querySchema) && route.querySchema instanceof import_zod.z.ZodObject ? Object.keys(route.querySchema.shape) : []
106
+ ];
107
+ const query = new URLSearchParams();
108
+ for (const key of new Set(queryKeys)) {
109
+ const value = input[key];
110
+ if (value === void 0 || value === null) continue;
111
+ for (const item of Array.isArray(value) ? value : [value]) {
112
+ query.append(key, item instanceof Date ? item.toISOString() : typeof item === "object" ? JSON.stringify(item) : String(item));
113
+ }
114
+ }
115
+ return query.size ? `${path}?${query}` : path;
116
+ }
117
+ function compact(value, depth = 0) {
118
+ if (Array.isArray(value)) {
119
+ const items = value.slice(0, 30).map((v) => compact(v, depth + 1));
120
+ return value.length > 30 ? [...items, { restantes: value.length - 30 }] : items;
121
+ }
122
+ if (value && typeof value === "object" && !(value instanceof Date) && depth < 8) {
123
+ const out = {};
124
+ for (const [k, v] of Object.entries(value)) if (v !== null && v !== void 0) out[k] = compact(v, depth + 1);
125
+ return out;
126
+ }
127
+ return value;
128
+ }
129
+ var nameOf = (record) => {
130
+ const r = record;
131
+ const nested = r?.contact ?? r?.user;
132
+ const label = r?.name ?? r?.title ?? r?.label ?? nested?.name;
133
+ if (typeof label !== "string") return void 0;
134
+ return typeof r?.number === "number" ? `#${r.number} ${label}` : label;
135
+ };
136
+ var describeValue = (value) => {
137
+ const text = typeof value === "string" ? value : JSON.stringify(value);
138
+ return text.length > 80 ? `${text.slice(0, 80)}\u2026` : text;
139
+ };
140
+ function findLookup(route, reads) {
141
+ if (route.method === "GET") return void 0;
142
+ const parts = segments(route.path);
143
+ for (let end = parts.length; end > 0; end--) {
144
+ const candidate = `/${parts.slice(0, end).join("/")}`;
145
+ if (!candidate.split("/").at(-1)?.startsWith(":")) continue;
146
+ const read = reads.find((r) => r.path === candidate);
147
+ if (read) return read;
148
+ }
149
+ return void 0;
150
+ }
151
+ var MAX_NAME = 64;
152
+ var RESERVED_PREFIX = "transfer_to_";
153
+ function safeName(raw) {
154
+ let name = raw.replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "acao";
155
+ if (name.startsWith(RESERVED_PREFIX)) name = `op_${name}`;
156
+ if (name.length > MAX_NAME) {
157
+ let hash = 0;
158
+ for (const char of raw) hash = Math.imul(hash, 31) + char.charCodeAt(0) | 0;
159
+ const suffix = `_${(hash >>> 0).toString(36)}`;
160
+ name = name.slice(0, MAX_NAME - suffix.length) + suffix;
161
+ }
162
+ return name;
163
+ }
164
+ function coherentKind(route, declared, warn, name) {
165
+ const inferred = inferKind(route);
166
+ if (!declared) return inferred;
167
+ if (route.method === "DELETE" && declared !== "delete") {
168
+ warn?.(`${name}: DELETE \xE9 sempre "delete" (ignorado "${declared}").`);
169
+ return "delete";
170
+ }
171
+ if (route.method !== "GET" && declared === "read") {
172
+ warn?.(`${name}: ${route.method} n\xE3o pode ser "read" (usado "${inferred}").`);
173
+ return inferred;
174
+ }
175
+ return declared;
176
+ }
177
+ function buildCapabilities(routes, options) {
178
+ const used = /* @__PURE__ */ new Map();
179
+ const named = routes.map((route) => {
180
+ let name = safeName(route.meta.name ?? `${snake(route.controller)}_${snake(route.handler)}`);
181
+ const count = used.get(name) ?? 0;
182
+ used.set(name, count + 1);
183
+ if (count > 0) name = safeName(`${name}_${count + 1}`);
184
+ return { name, route };
185
+ });
186
+ const reads = routes.filter((r) => r.method === "GET");
187
+ const result = [];
188
+ for (const { name, route } of named) {
189
+ const fromFile = options.fileOverrides?.[name] ?? {};
190
+ const fromConfig = options.overrides?.[name] ?? {};
191
+ if (fromFile.ignore || fromConfig.ignore) continue;
192
+ const meta = { ...fromFile, ...route.meta, ...fromConfig };
193
+ const kind = coherentKind(route, meta.kind, options.warn, name);
194
+ const area = areaOf(route.path);
195
+ const lookup = findLookup(route, reads);
196
+ const title = meta.title ?? route.handler.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/^./, (c) => c.toUpperCase());
197
+ let tool;
198
+ try {
199
+ tool = (0, import_core.defineTool)({
200
+ name,
201
+ title,
202
+ description: meta.description ?? `${title} (${route.method} ${route.path}).`,
203
+ kind,
204
+ ...meta.risk ? { risk: meta.risk } : {},
205
+ tags: [.../* @__PURE__ */ new Set([area, ...meta.tags ?? []])],
206
+ entity: meta.entity ?? area,
207
+ parameters: inputSchemaOf(route),
208
+ approvalSummary: async (input, ctx) => {
209
+ const target = lookup ? nameOf(await options.call(ctx, "GET", requestOf(lookup, input)).catch(() => null)) : void 0;
210
+ const data = input.dados ?? {};
211
+ const changes = Object.entries(data).filter(([, v]) => v !== void 0 && !(Array.isArray(v) && v.length === 0) && !(v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).length === 0)).slice(0, 5).map(([k, v]) => `${k}: ${describeValue(v)}`);
212
+ return [title + (target ? ` "${target}"` : ""), changes.join(" \xB7 ")].filter(Boolean).join(" \u2014 ");
213
+ },
214
+ execute: async (input, ctx) => compact(await options.call(ctx, route.method, requestOf(route, input), route.bodySchema !== void 0 ? input.dados : void 0))
215
+ });
216
+ } catch (error) {
217
+ options.warn?.(`${name} (${route.method} ${route.path}) ficou de fora: ${error instanceof Error ? error.message : String(error)}`);
218
+ continue;
219
+ }
220
+ result.push({ name, route, tool });
221
+ }
222
+ return result;
223
+ }
224
+ function createApiCaller(baseUrl) {
225
+ return async (ctx, method, path, body) => {
226
+ const res = await fetch(baseUrl() + path, {
227
+ method,
228
+ headers: { ...ctx.credentials, ...body !== void 0 && { "content-type": "application/json" } },
229
+ body: body === void 0 ? void 0 : JSON.stringify(body),
230
+ signal: AbortSignal.timeout(3e4)
231
+ });
232
+ if (res.status === 204) return { ok: true };
233
+ const data = await res.json().catch(() => null);
234
+ if (!res.ok) {
235
+ const raw = data?.message;
236
+ const message = Array.isArray(raw) ? raw.join(" ") : typeof raw === "string" ? raw : `Erro ${res.status}`;
237
+ const missing = Array.isArray(data?.missing) ? ` Faltam: ${data.missing.join(", ")}.` : "";
238
+ throw new Error(`${message}${missing}`);
239
+ }
240
+ return data;
241
+ };
242
+ }
243
+
244
+ // src/decorators.ts
245
+ var import_common = require("@nestjs/common");
246
+ var AI_CAPABILITY = "dolfinhos:capability";
247
+ var AI_IGNORE = "dolfinhos:ignore";
248
+ var AiCapability = (options) => (0, import_common.SetMetadata)(AI_CAPABILITY, options);
249
+ var AiIgnore = () => (0, import_common.SetMetadata)(AI_IGNORE, true);
250
+
251
+ // src/describe.ts
252
+ var import_core2 = require("@dolfinhos/core");
253
+ var import_ai = require("ai");
254
+ var import_zod2 = require("zod");
255
+ var entrySchema = import_zod2.z.object({
256
+ name: import_zod2.z.string(),
257
+ title: import_zod2.z.string().min(1).max(80),
258
+ description: import_zod2.z.string().min(1).max(400),
259
+ kind: import_zod2.z.enum(["read", "create", "update", "delete", "action", "send"]),
260
+ risk: import_zod2.z.enum(["low", "medium", "high"]),
261
+ entity: import_zod2.z.string().max(40).optional()
262
+ });
263
+ async function describeCapabilities(capabilities, model, options = {}) {
264
+ const language = options.language ?? "portugu\xEAs do Brasil";
265
+ const out = {};
266
+ const batchSize = options.batchSize ?? 15;
267
+ for (let i = 0; i < capabilities.length; i += batchSize) {
268
+ const batch = await Promise.all(
269
+ capabilities.slice(i, i + batchSize).map(async ({ name, route, tool }) => ({
270
+ name,
271
+ http: `${route.method} ${route.path}`,
272
+ handler: `${route.controller}.${route.handler}`,
273
+ currentKind: tool.kind,
274
+ input: await (0, import_ai.asSchema)((0, import_core2.modelInputSchema)(tool.parameters)).jsonSchema
275
+ }))
276
+ );
277
+ const { text } = await (0, import_ai.generateText)({
278
+ model,
279
+ system: `Voc\xEA documenta as a\xE7\xF5es de uma aplica\xE7\xE3o web para um assistente de IA que vai us\xE1-las em nome do usu\xE1rio. Escreva em ${language}, com o vocabul\xE1rio do usu\xE1rio final (n\xE3o do programador).` + (options.context ? `
280
+ Sobre a aplica\xE7\xE3o: ${options.context}` : ""),
281
+ prompt: 'Para cada rota abaixo, devolva um objeto com: name (igual ao recebido), title (at\xE9 5 palavras, verbo no infinitivo: "Mover neg\xF3cio"), description (uma ou duas frases: o que faz e quando usar; cite efeitos colaterais importantes), kind (read: s\xF3 consulta; create; update; delete; action: executa algo sobre um registro existente; send: envia mensagem ou e-mail para algu\xE9m de fora), risk (low: consulta ou ajuste trivial; medium: altera dados; high: exclui, envia para clientes ou mexe em configura\xE7\xE3o/permiss\xF5es) e entity (a coisa afetada, no singular, em uma palavra).\nResponda SOMENTE com um array JSON, sem texto em volta.\n\n' + JSON.stringify(batch, null, 1)
282
+ });
283
+ const json2 = text.slice(text.indexOf("["), text.lastIndexOf("]") + 1);
284
+ let items = [];
285
+ try {
286
+ items = JSON.parse(json2);
287
+ } catch {
288
+ continue;
289
+ }
290
+ for (const item of items) {
291
+ const parsed = entrySchema.safeParse(item);
292
+ if (!parsed.success || !batch.some((b) => b.name === parsed.data.name)) continue;
293
+ const { name, ...entry } = parsed.data;
294
+ out[name] = entry;
295
+ }
296
+ }
297
+ return out;
298
+ }
299
+
300
+ // src/discovery.ts
301
+ var import_reflect_metadata = require("reflect-metadata");
302
+ var PATH_METADATA = "path";
303
+ var METHOD_METADATA = "method";
304
+ var ROUTE_ARGS_METADATA = "__routeArguments__";
305
+ var SSE_METADATA = "__sse__";
306
+ var VERSION_METADATA = "__version__";
307
+ var METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH", "ALL", "OPTIONS", "HEAD", "SEARCH"];
308
+ var ParamType = { BODY: 3, QUERY: 4, PARAM: 5, FILE: 8, FILES: 9, RAW_BODY: 12 };
309
+ var defaultIsPublic = (keys) => keys.some((key) => {
310
+ const name = typeof key === "symbol" ? key.description ?? "" : String(key);
311
+ return /(^|[:_-])public$/i.test(name) || /^is_?public$/i.test(name);
312
+ });
313
+ var asArray = (value) => Array.isArray(value) ? value : value === void 0 ? [""] : [String(value)];
314
+ function versionSegment(handler, metatype, versioning) {
315
+ if (!versioning) return "";
316
+ const raw = Reflect.getMetadata(VERSION_METADATA, handler) ?? Reflect.getMetadata(VERSION_METADATA, metatype) ?? versioning.defaultVersion;
317
+ const version = Array.isArray(raw) ? raw[0] : raw;
318
+ return typeof version === "string" || typeof version === "number" ? `${versioning.prefix ?? "v"}${version}` : "";
319
+ }
320
+ function joinPath(...parts) {
321
+ const joined = parts.flatMap((p) => p.split("/")).filter(Boolean).join("/");
322
+ return `/${joined}`;
323
+ }
324
+ function discoverRoutes(discovery, scanner, options = {}) {
325
+ const isPublic = options.isPublic ?? defaultIsPublic;
326
+ const routes = [];
327
+ for (const wrapper of discovery.getControllers()) {
328
+ const metatype = wrapper.metatype;
329
+ if (!metatype || options.skip?.includes(metatype)) continue;
330
+ if (Reflect.getMetadata(AI_IGNORE, metatype)) continue;
331
+ const classPublic = isPublic(Reflect.getMetadataKeys(metatype));
332
+ for (const handlerName of scanner.getAllMethodNames(metatype.prototype)) {
333
+ const handler = metatype.prototype[handlerName];
334
+ const methodIndex = Reflect.getMetadata(METHOD_METADATA, handler);
335
+ if (methodIndex === void 0) continue;
336
+ const method = METHODS[methodIndex];
337
+ if (method !== "GET" && method !== "POST" && method !== "PUT" && method !== "PATCH" && method !== "DELETE") continue;
338
+ if (Reflect.getMetadata(SSE_METADATA, handler)) continue;
339
+ if (Reflect.getMetadata(AI_IGNORE, handler)) continue;
340
+ if (classPublic || isPublic(Reflect.getMetadataKeys(handler))) continue;
341
+ const args = Reflect.getMetadata(ROUTE_ARGS_METADATA, metatype, handlerName) ?? {};
342
+ const params = {};
343
+ const queryFields = {};
344
+ let querySchema;
345
+ let bodySchema;
346
+ let unsupported = false;
347
+ for (const [key, arg] of Object.entries(args)) {
348
+ const type = Number(key.split(":")[0]);
349
+ if (type === ParamType.FILE || type === ParamType.FILES || type === ParamType.RAW_BODY) unsupported = true;
350
+ if (type === ParamType.BODY) bodySchema = arg.schema ?? (bodySchema === void 0 ? null : bodySchema);
351
+ if (type === ParamType.PARAM && typeof arg.data === "string") params[arg.data] = arg.schema;
352
+ if (type === ParamType.QUERY) {
353
+ if (typeof arg.data === "string") queryFields[arg.data] = arg.schema;
354
+ else if (arg.schema) querySchema = arg.schema;
355
+ }
356
+ }
357
+ if (unsupported) continue;
358
+ const meta = { ...Reflect.getMetadata(AI_CAPABILITY, handler) };
359
+ const version = versionSegment(handler, metatype, options.uriVersioning);
360
+ for (const classPath of asArray(Reflect.getMetadata(PATH_METADATA, metatype))) {
361
+ for (const methodPath of asArray(Reflect.getMetadata(PATH_METADATA, handler))) {
362
+ const path = joinPath(options.globalPrefix ?? "", version, classPath, methodPath);
363
+ if (/[*?(]/.test(path)) {
364
+ options.warn?.(`${metatype.name}.${handlerName} (${method} ${path}) ficou de fora: caminho com curinga ou par\xE2metro opcional.`);
365
+ continue;
366
+ }
367
+ if (querySchema && !(querySchema && typeof querySchema === "object" && "shape" in querySchema)) {
368
+ options.warn?.(`${metatype.name}.${handlerName}: o schema da query n\xE3o \xE9 um objeto Zod; os filtros dessa rota n\xE3o ficam dispon\xEDveis para a IA.`);
369
+ }
370
+ const route = {
371
+ controller: metatype.name,
372
+ handler: handlerName,
373
+ method,
374
+ path,
375
+ params,
376
+ queryFields,
377
+ ...querySchema ? { querySchema } : {},
378
+ ...bodySchema !== void 0 ? { bodySchema } : {},
379
+ meta
380
+ };
381
+ if (options.include && !options.include(route)) continue;
382
+ routes.push(route);
383
+ }
384
+ }
385
+ }
386
+ }
387
+ return routes;
388
+ }
389
+
390
+ // src/module.ts
391
+ var import_zod3 = require("zod");
392
+ var DOLFINHOS_OPTIONS = /* @__PURE__ */ Symbol("DOLFINHOS_OPTIONS");
393
+ var DolfinhosService = class {
394
+ constructor(options, discovery, scanner, moduleRef) {
395
+ this.options = options;
396
+ this.discovery = discovery;
397
+ this.scanner = scanner;
398
+ this.moduleRef = moduleRef;
399
+ this.call = createApiCaller(() => options.apiUrl ?? `http://127.0.0.1:${process.env.PORT ?? 3e3}`);
400
+ }
401
+ options;
402
+ discovery;
403
+ scanner;
404
+ moduleRef;
405
+ dolfinhos;
406
+ /** Capacidades descobertas na inicialização. */
407
+ capabilities = [];
408
+ /** Chama a própria API como o ator do contexto (útil para montar contexto de tela, por exemplo). */
409
+ call;
410
+ async onApplicationBootstrap() {
411
+ const options = this.options;
412
+ const warn = (message) => console.warn(`[dolfinhos] ${message}`);
413
+ const fromFile = await loadCapabilitiesFile(options.capabilitiesFile, warn);
414
+ const routes = discoverRoutes(this.discovery, this.scanner, {
415
+ ...options.globalPrefix ? { globalPrefix: options.globalPrefix } : {},
416
+ ...options.isPublic ? { isPublic: options.isPublic } : {},
417
+ ...options.include ? { include: options.include } : {},
418
+ ...options.uriVersioning ? { uriVersioning: options.uriVersioning } : {},
419
+ warn
420
+ });
421
+ this.capabilities = buildCapabilities(routes, { call: this.call, fileOverrides: fromFile, ...options.overrides ? { overrides: options.overrides } : {}, warn });
422
+ const factoryArgs = { capabilities: this.capabilities.map((c) => c.tool), call: this.call, moduleRef: this.moduleRef };
423
+ const pod = options.pod(factoryArgs);
424
+ const pods = options.pods?.(factoryArgs);
425
+ const known = new Set(this.capabilities.map((c) => c.name));
426
+ for (const p of [pod, ...Object.values(pods ?? {})]) for (const agent of p.agents.values()) for (const t of agent.tools ?? []) known.add(t.name);
427
+ warnUnknownCapabilities(options.policies ?? [], known);
428
+ const moduleRef = this.moduleRef;
429
+ const { serviceContext, onRunFinished } = options;
430
+ this.dolfinhos = (0, import_server.createDolfinhos)({
431
+ pod,
432
+ ...pods ? { pods } : {},
433
+ ...serviceContext ? {
434
+ // Bots e automações chamam a API com as credenciais que a aplicação dá ao ator de serviço.
435
+ serviceContext: async (args) => ({
436
+ channel: args.channel,
437
+ ...await serviceContext({ ...args, moduleRef })
438
+ })
439
+ } : {},
440
+ ...onRunFinished ? { onRunFinished: (info) => onRunFinished({ ...info, moduleRef }) } : {},
441
+ ...options.events ? { events: options.events } : {},
442
+ ...options.triggers ? { triggers: options.triggers } : {},
443
+ memory: options.memory,
444
+ ...options.settings ? { settings: options.settings } : {},
445
+ ...options.audit ? { audit: options.audit } : {},
446
+ ...options.usage ? { usage: options.usage } : {},
447
+ ...options.knowledge ? { knowledge: options.knowledge } : {},
448
+ ...options.facts ? { facts: options.facts } : {},
449
+ ...options.pricing ? { pricing: options.pricing } : {},
450
+ ...options.policies ? { policies: options.policies } : {},
451
+ ...options.auditReads ? { auditReads: true } : {},
452
+ ...options.owner ? { owner: options.owner } : {},
453
+ ...options.allowAnonymousSessions ? { allowAnonymousSessions: true } : {},
454
+ ...options.onError ? { onError: options.onError } : {}
455
+ });
456
+ if (options.migrate !== false) {
457
+ for (const store of [options.memory, options.settings, options.audit, options.usage, options.knowledge, options.facts]) {
458
+ const migrate = store?.migrate;
459
+ if (migrate) await migrate.call(store).catch((e) => options.onError?.(e));
460
+ }
461
+ }
462
+ }
463
+ /** O cliente do Dolfinhos (chat, approve, task, settings, audit...). */
464
+ get client() {
465
+ if (!this.dolfinhos) throw new Error("Dolfinhos ainda n\xE3o iniciou: use depois do bootstrap da aplica\xE7\xE3o.");
466
+ return this.dolfinhos;
467
+ }
468
+ /** Contexto seguro de uma requisição HTTP autenticada, com as credenciais para agir como o usuário. */
469
+ async contextFromRequest(request) {
470
+ const ctx = await this.options.context(request);
471
+ if (!ctx) return null;
472
+ const credentials = {};
473
+ for (const name of this.options.forwardHeaders ?? ["authorization", "cookie"]) {
474
+ const value = request.headers[name];
475
+ if (typeof value === "string") credentials[name] = value;
476
+ }
477
+ return { channel: "app", ...ctx, credentials: { ...credentials, ...ctx.credentials } };
478
+ }
479
+ canManage(ctx) {
480
+ return this.options.canManage?.(ctx) ?? false;
481
+ }
482
+ /** A própria pessoa como assunto da memória (preferências dela). */
483
+ selfSubject(ctx) {
484
+ if (this.options.selfSubject) return this.options.selfSubject(ctx);
485
+ const actor = ctx.actor;
486
+ return actor?.type === "user" ? { type: "user", id: actor.id } : null;
487
+ }
488
+ canApprove(ctx) {
489
+ return this.options.canApprove ? this.options.canApprove(ctx) : this.canManage(ctx);
490
+ }
491
+ /**
492
+ * Avisa que um evento aconteceu e segue sem esperar: os gatilhos e as
493
+ * automações rodam em segundo plano, e erros vão para `onError`.
494
+ */
495
+ emit(event, args) {
496
+ void Promise.resolve().then(() => this.client.emit(event, args)).catch((error) => {
497
+ if (this.options.onError) this.options.onError(error);
498
+ else console.error("[dolfinhos] evento", event, error);
499
+ });
500
+ }
501
+ canDescribe(ctx) {
502
+ if (this.options.canDescribe) return this.options.canDescribe(ctx);
503
+ return process.env.NODE_ENV !== "production" && this.canManage(ctx);
504
+ }
505
+ /** Títulos e descrições propostos pelo modelo (usado pelo `dolfinhos generate`). */
506
+ async describe(names) {
507
+ if (!this.options.describeModel) throw new Error("Configure `describeModel` no DolfinhosModule para gerar descri\xE7\xF5es.");
508
+ const selected = names?.length ? this.capabilities.filter((c) => names.includes(c.name)) : this.capabilities;
509
+ return describeCapabilities(selected, this.options.describeModel, {
510
+ ...this.options.describeContext ? { context: this.options.describeContext } : {}
511
+ });
512
+ }
513
+ };
514
+ DolfinhosService = __decorateClass([
515
+ (0, import_common2.Injectable)(),
516
+ __decorateParam(0, (0, import_common2.Inject)(DOLFINHOS_OPTIONS)),
517
+ __decorateParam(1, (0, import_common2.Inject)(import_core3.DiscoveryService)),
518
+ __decorateParam(2, (0, import_common2.Inject)(import_core3.MetadataScanner)),
519
+ __decorateParam(3, (0, import_common2.Inject)(import_core3.ModuleRef))
520
+ ], DolfinhosService);
521
+ function warnUnknownCapabilities(policies, known) {
522
+ const unknown = /* @__PURE__ */ new Set();
523
+ for (const rule of policies) {
524
+ const names = rule.match?.capability;
525
+ for (const name of Array.isArray(names) ? names : names ? [names] : []) {
526
+ if (!name.endsWith("*") && !known.has(name)) unknown.add(name);
527
+ }
528
+ }
529
+ if (unknown.size) console.warn(`[dolfinhos] Pol\xEDticas citam capacidades que n\xE3o existem: ${[...unknown].join(", ")}`);
530
+ }
531
+ var overrideSchema = import_zod3.z.object({
532
+ title: import_zod3.z.string().max(120).optional(),
533
+ description: import_zod3.z.string().max(2e3).optional(),
534
+ kind: import_zod3.z.enum(["read", "create", "update", "delete", "action", "send"]).optional(),
535
+ risk: import_zod3.z.enum(["low", "medium", "high"]).optional(),
536
+ tags: import_zod3.z.array(import_zod3.z.string().max(60)).max(20).optional(),
537
+ entity: import_zod3.z.string().max(60).optional(),
538
+ ignore: import_zod3.z.boolean().optional()
539
+ }).strict();
540
+ var fileSchema = import_zod3.z.record(import_zod3.z.string(), overrideSchema);
541
+ async function loadCapabilitiesFile(file, warn) {
542
+ if (file === false) return {};
543
+ const path = (0, import_node_path.resolve)(file ?? "dolfinhos.capabilities.json");
544
+ let text;
545
+ try {
546
+ text = await (0, import_promises.readFile)(path, "utf8");
547
+ } catch (error) {
548
+ if (file === void 0 && error.code === "ENOENT") {
549
+ warn(`Sem ${path}: rode "dolfinhos generate" para t\xEDtulos e descri\xE7\xF5es leg\xEDveis.`);
550
+ return {};
551
+ }
552
+ throw new Error(`Dolfinhos: n\xE3o consegui ler ${path}: ${error.message}`);
553
+ }
554
+ const parsed = fileSchema.safeParse(JSON.parse(text));
555
+ if (!parsed.success) throw new Error(`Dolfinhos: ${path} inv\xE1lido: ${parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`);
556
+ return parsed.data;
557
+ }
558
+ var nodeResponse = (res) => res.raw ?? res;
559
+ function json(res, status, body) {
560
+ const out = nodeResponse(res);
561
+ out.writeHead(status, { "content-type": "application/json; charset=utf-8" });
562
+ out.end(JSON.stringify(body));
563
+ }
564
+ var UNAUTHORIZED = { error: { code: "unauthorized", message: "N\xE3o autenticado." } };
565
+ var FORBIDDEN = { error: { code: "forbidden", message: "S\xF3 quem administra a empresa pode fazer isso." } };
566
+ function createController(path, guards) {
567
+ let DolfinhosController = class {
568
+ constructor(service) {
569
+ this.service = service;
570
+ }
571
+ service;
572
+ async chat(req, res, body) {
573
+ const ctx = await this.service.contextFromRequest(req);
574
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
575
+ await (0, import_server.sendNodeResponse)(nodeResponse(res), await this.service.client.handle({ body, ctx }));
576
+ }
577
+ async history(req, res, sessionId) {
578
+ const ctx = await this.service.contextFromRequest(req);
579
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
580
+ if (!sessionId) return json(res, 400, { error: { code: "bad_request", message: "Informe sessionId." } });
581
+ await (0, import_server.sendNodeResponse)(nodeResponse(res), await this.service.client.history({ sessionId, ctx }));
582
+ }
583
+ async capabilities(req, res) {
584
+ const ctx = await this.service.contextFromRequest(req);
585
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
586
+ if (!this.service.canManage(ctx)) return json(res, 403, FORBIDDEN);
587
+ const info = new Map(this.service.client.capabilities().map((c) => [c.name, c]));
588
+ json(
589
+ res,
590
+ 200,
591
+ this.service.capabilities.map(({ name, route }) => ({ ...info.get(name), http: `${route.method} ${route.path}`, handler: `${route.controller}.${route.handler}` }))
592
+ );
593
+ }
594
+ async describe(req, res, body) {
595
+ const ctx = await this.service.contextFromRequest(req);
596
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
597
+ if (!this.service.canDescribe(ctx)) return json(res, 403, FORBIDDEN);
598
+ try {
599
+ json(res, 200, await this.service.describe(Array.isArray(body?.names) ? body.names : void 0));
600
+ } catch (error) {
601
+ json(res, 400, { error: { code: "bad_request", message: error instanceof Error ? error.message : String(error) } });
602
+ }
603
+ }
604
+ async getSettings(req, res) {
605
+ const ctx = await this.service.contextFromRequest(req);
606
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
607
+ if (!this.service.canManage(ctx)) return json(res, 403, FORBIDDEN);
608
+ json(res, 200, await this.service.client.settings.get(this.service.client.tenantOf(ctx)));
609
+ }
610
+ async putSettings(req, res, body) {
611
+ const ctx = await this.service.contextFromRequest(req);
612
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
613
+ if (!this.service.canManage(ctx)) return json(res, 403, FORBIDDEN);
614
+ try {
615
+ json(res, 200, await this.service.client.settings.set(this.service.client.tenantOf(ctx), body, actorId(ctx)));
616
+ } catch (error) {
617
+ if (error instanceof import_server.SettingsValidationError) return json(res, 400, { error: { code: "bad_request", message: error.message } });
618
+ throw error;
619
+ }
620
+ }
621
+ async approvals(req, res) {
622
+ const ctx = await this.service.contextFromRequest(req);
623
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
624
+ if (!this.service.canApprove(ctx)) return json(res, 403, FORBIDDEN);
625
+ json(res, 200, await this.service.client.approvals.list({ tenantId: this.service.client.tenantOf(ctx) }));
626
+ }
627
+ async decide(req, res, sessionId, body) {
628
+ const ctx = await this.service.contextFromRequest(req);
629
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
630
+ if (!this.service.canApprove(ctx) || !ctx.actor) return json(res, 403, FORBIDDEN);
631
+ const parsed = decisionSchema.safeParse(body);
632
+ if (!parsed.success || !sessionId || sessionId.length > 200) {
633
+ return json(res, 400, { error: { code: "bad_request", message: "Envie executionId e approved." } });
634
+ }
635
+ const result = await this.service.client.approvals.decide({
636
+ tenantId: this.service.client.tenantOf(ctx),
637
+ sessionId,
638
+ executionId: parsed.data.executionId,
639
+ approved: parsed.data.approved,
640
+ ...parsed.data.reason ? { reason: parsed.data.reason } : {},
641
+ decidedBy: ctx.actor
642
+ });
643
+ const { events: _events, ...summary } = result;
644
+ if (result.error?.code === "approval_not_found") return json(res, 404, { error: result.error });
645
+ if (result.error?.code === "conflict") return json(res, 409, { error: result.error });
646
+ if (result.error?.code === "session_not_found") return json(res, 410, { error: result.error });
647
+ json(res, 200, summary);
648
+ }
649
+ async events(req, res) {
650
+ const ctx = await this.service.contextFromRequest(req);
651
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
652
+ if (!this.service.canManage(ctx)) return json(res, 403, FORBIDDEN);
653
+ json(res, 200, this.service.client.events());
654
+ }
655
+ async knowledgeList(req, res) {
656
+ const ctx = await this.service.contextFromRequest(req);
657
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
658
+ if (!this.service.canManage(ctx)) return json(res, 403, FORBIDDEN);
659
+ json(res, 200, await this.service.client.knowledge.list(this.service.client.tenantOf(ctx)));
660
+ }
661
+ async knowledgeSearch(req, res, q, audience) {
662
+ const ctx = await this.service.contextFromRequest(req);
663
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
664
+ if (!this.service.canManage(ctx)) return json(res, 403, FORBIDDEN);
665
+ if (!q?.trim()) return json(res, 400, { error: { code: "bad_request", message: "Informe q." } });
666
+ json(res, 200, await this.service.client.knowledge.search(this.service.client.tenantOf(ctx), q, audience === "all" ? "all" : "internal"));
667
+ }
668
+ async knowledgeSave(req, res, body) {
669
+ const ctx = await this.service.contextFromRequest(req);
670
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
671
+ if (!this.service.canManage(ctx)) return json(res, 403, FORBIDDEN);
672
+ try {
673
+ json(res, 200, await this.service.client.knowledge.save(this.service.client.tenantOf(ctx), body, actorId(ctx)));
674
+ } catch (error) {
675
+ if (error instanceof import_server.SettingsValidationError) return json(res, 400, { error: { code: "bad_request", message: error.message } });
676
+ throw error;
677
+ }
678
+ }
679
+ async knowledgeRemove(req, res, id) {
680
+ const ctx = await this.service.contextFromRequest(req);
681
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
682
+ if (!this.service.canManage(ctx)) return json(res, 403, FORBIDDEN);
683
+ await this.service.client.knowledge.remove(this.service.client.tenantOf(ctx), id);
684
+ json(res, 200, { ok: true });
685
+ }
686
+ async facts(req, res, type, id) {
687
+ const ctx = await this.service.contextFromRequest(req);
688
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
689
+ const tenantId = this.service.client.tenantOf(ctx);
690
+ const self = this.service.selfSubject(ctx);
691
+ if (type && id) {
692
+ const subject = { type: type.slice(0, 40), id: id.slice(0, 200) };
693
+ const own = !!self && self.type === subject.type && self.id === subject.id;
694
+ if (!own && !this.service.canManage(ctx)) return json(res, 403, FORBIDDEN);
695
+ return json(res, 200, await this.service.client.facts.list({ tenantId, subject }));
696
+ }
697
+ if (!this.service.canManage(ctx)) return json(res, 403, FORBIDDEN);
698
+ json(res, 200, await this.service.client.facts.subjects({ tenantId, ...type ? { type: type.slice(0, 40) } : {} }));
699
+ }
700
+ async forget(req, res, id) {
701
+ const ctx = await this.service.contextFromRequest(req);
702
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
703
+ const tenantId = this.service.client.tenantOf(ctx);
704
+ const fact = await this.service.client.facts.get(tenantId, id);
705
+ if (!fact) return json(res, 404, { error: { code: "not_found", message: "Este fato n\xE3o existe mais." } });
706
+ const self = this.service.selfSubject(ctx);
707
+ const own = !!self && fact.subject.type === self.type && fact.subject.id === self.id;
708
+ if (!own && !this.service.canManage(ctx)) return json(res, 403, FORBIDDEN);
709
+ await this.service.client.facts.remove(tenantId, id);
710
+ json(res, 200, { ok: true });
711
+ }
712
+ async usage(req, res, from, to) {
713
+ const ctx = await this.service.contextFromRequest(req);
714
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
715
+ if (!this.service.canManage(ctx)) return json(res, 403, FORBIDDEN);
716
+ const query = usageQuerySchema.safeParse({ from, to });
717
+ if (!query.success) return json(res, 400, { error: { code: "bad_request", message: "Use from e to como datas ISO." } });
718
+ const now = /* @__PURE__ */ new Date();
719
+ json(
720
+ res,
721
+ 200,
722
+ await this.service.client.usage.summary({
723
+ tenantId: this.service.client.tenantOf(ctx),
724
+ from: query.data.from ?? new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString(),
725
+ to: query.data.to ?? new Date(now.getTime() + 6e4).toISOString()
726
+ })
727
+ );
728
+ }
729
+ async audit(req, res, before, limit, sessionId) {
730
+ const ctx = await this.service.contextFromRequest(req);
731
+ if (!ctx) return json(res, 401, UNAUTHORIZED);
732
+ if (!this.service.canManage(ctx)) return json(res, 403, FORBIDDEN);
733
+ const query = auditQuerySchema.safeParse({ before, limit, sessionId });
734
+ if (!query.success) return json(res, 400, { error: { code: "bad_request", message: "Use limit entre 1 e 500 e before como data ISO." } });
735
+ json(
736
+ res,
737
+ 200,
738
+ await this.service.client.audit.list({
739
+ tenantId: this.service.client.tenantOf(ctx),
740
+ ...query.data.before ? { before: query.data.before } : {},
741
+ ...query.data.sessionId ? { sessionId: query.data.sessionId } : {},
742
+ ...query.data.limit ? { limit: query.data.limit } : {}
743
+ })
744
+ );
745
+ }
746
+ };
747
+ __decorateClass([
748
+ (0, import_common2.Post)(),
749
+ __decorateParam(0, (0, import_common2.Req)()),
750
+ __decorateParam(1, (0, import_common2.Res)()),
751
+ __decorateParam(2, (0, import_common2.Body)())
752
+ ], DolfinhosController.prototype, "chat", 1);
753
+ __decorateClass([
754
+ (0, import_common2.Get)(),
755
+ __decorateParam(0, (0, import_common2.Req)()),
756
+ __decorateParam(1, (0, import_common2.Res)()),
757
+ __decorateParam(2, (0, import_common2.Query)("sessionId"))
758
+ ], DolfinhosController.prototype, "history", 1);
759
+ __decorateClass([
760
+ (0, import_common2.Get)("capabilities"),
761
+ __decorateParam(0, (0, import_common2.Req)()),
762
+ __decorateParam(1, (0, import_common2.Res)())
763
+ ], DolfinhosController.prototype, "capabilities", 1);
764
+ __decorateClass([
765
+ (0, import_common2.Post)("capabilities/describe"),
766
+ __decorateParam(0, (0, import_common2.Req)()),
767
+ __decorateParam(1, (0, import_common2.Res)()),
768
+ __decorateParam(2, (0, import_common2.Body)())
769
+ ], DolfinhosController.prototype, "describe", 1);
770
+ __decorateClass([
771
+ (0, import_common2.Get)("settings"),
772
+ __decorateParam(0, (0, import_common2.Req)()),
773
+ __decorateParam(1, (0, import_common2.Res)())
774
+ ], DolfinhosController.prototype, "getSettings", 1);
775
+ __decorateClass([
776
+ (0, import_common2.Put)("settings"),
777
+ __decorateParam(0, (0, import_common2.Req)()),
778
+ __decorateParam(1, (0, import_common2.Res)()),
779
+ __decorateParam(2, (0, import_common2.Body)())
780
+ ], DolfinhosController.prototype, "putSettings", 1);
781
+ __decorateClass([
782
+ (0, import_common2.Get)("approvals"),
783
+ __decorateParam(0, (0, import_common2.Req)()),
784
+ __decorateParam(1, (0, import_common2.Res)())
785
+ ], DolfinhosController.prototype, "approvals", 1);
786
+ __decorateClass([
787
+ (0, import_common2.Post)("approvals/:sessionId"),
788
+ __decorateParam(0, (0, import_common2.Req)()),
789
+ __decorateParam(1, (0, import_common2.Res)()),
790
+ __decorateParam(2, (0, import_common2.Param)("sessionId")),
791
+ __decorateParam(3, (0, import_common2.Body)())
792
+ ], DolfinhosController.prototype, "decide", 1);
793
+ __decorateClass([
794
+ (0, import_common2.Get)("events"),
795
+ __decorateParam(0, (0, import_common2.Req)()),
796
+ __decorateParam(1, (0, import_common2.Res)())
797
+ ], DolfinhosController.prototype, "events", 1);
798
+ __decorateClass([
799
+ (0, import_common2.Get)("knowledge"),
800
+ __decorateParam(0, (0, import_common2.Req)()),
801
+ __decorateParam(1, (0, import_common2.Res)())
802
+ ], DolfinhosController.prototype, "knowledgeList", 1);
803
+ __decorateClass([
804
+ (0, import_common2.Get)("knowledge/search"),
805
+ __decorateParam(0, (0, import_common2.Req)()),
806
+ __decorateParam(1, (0, import_common2.Res)()),
807
+ __decorateParam(2, (0, import_common2.Query)("q")),
808
+ __decorateParam(3, (0, import_common2.Query)("audience"))
809
+ ], DolfinhosController.prototype, "knowledgeSearch", 1);
810
+ __decorateClass([
811
+ (0, import_common2.Post)("knowledge"),
812
+ __decorateParam(0, (0, import_common2.Req)()),
813
+ __decorateParam(1, (0, import_common2.Res)()),
814
+ __decorateParam(2, (0, import_common2.Body)())
815
+ ], DolfinhosController.prototype, "knowledgeSave", 1);
816
+ __decorateClass([
817
+ (0, import_common2.Delete)("knowledge/:id"),
818
+ __decorateParam(0, (0, import_common2.Req)()),
819
+ __decorateParam(1, (0, import_common2.Res)()),
820
+ __decorateParam(2, (0, import_common2.Param)("id"))
821
+ ], DolfinhosController.prototype, "knowledgeRemove", 1);
822
+ __decorateClass([
823
+ (0, import_common2.Get)("facts"),
824
+ __decorateParam(0, (0, import_common2.Req)()),
825
+ __decorateParam(1, (0, import_common2.Res)()),
826
+ __decorateParam(2, (0, import_common2.Query)("type")),
827
+ __decorateParam(3, (0, import_common2.Query)("id"))
828
+ ], DolfinhosController.prototype, "facts", 1);
829
+ __decorateClass([
830
+ (0, import_common2.Delete)("facts/:id"),
831
+ __decorateParam(0, (0, import_common2.Req)()),
832
+ __decorateParam(1, (0, import_common2.Res)()),
833
+ __decorateParam(2, (0, import_common2.Param)("id"))
834
+ ], DolfinhosController.prototype, "forget", 1);
835
+ __decorateClass([
836
+ (0, import_common2.Get)("usage"),
837
+ __decorateParam(0, (0, import_common2.Req)()),
838
+ __decorateParam(1, (0, import_common2.Res)()),
839
+ __decorateParam(2, (0, import_common2.Query)("from")),
840
+ __decorateParam(3, (0, import_common2.Query)("to"))
841
+ ], DolfinhosController.prototype, "usage", 1);
842
+ __decorateClass([
843
+ (0, import_common2.Get)("audit"),
844
+ __decorateParam(0, (0, import_common2.Req)()),
845
+ __decorateParam(1, (0, import_common2.Res)()),
846
+ __decorateParam(2, (0, import_common2.Query)("before")),
847
+ __decorateParam(3, (0, import_common2.Query)("limit")),
848
+ __decorateParam(4, (0, import_common2.Query)("sessionId"))
849
+ ], DolfinhosController.prototype, "audit", 1);
850
+ DolfinhosController = __decorateClass([
851
+ AiIgnore(),
852
+ (0, import_common2.Controller)(path),
853
+ (0, import_common2.UseGuards)(...guards),
854
+ __decorateParam(0, (0, import_common2.Inject)(DolfinhosService))
855
+ ], DolfinhosController);
856
+ return DolfinhosController;
857
+ }
858
+ var usageQuerySchema = import_zod3.z.object({
859
+ from: import_zod3.z.iso.datetime({ offset: true }).optional(),
860
+ to: import_zod3.z.iso.datetime({ offset: true }).optional()
861
+ });
862
+ var decisionSchema = import_zod3.z.object({
863
+ executionId: import_zod3.z.string().min(1).max(128),
864
+ approved: import_zod3.z.boolean(),
865
+ reason: import_zod3.z.string().max(500).optional()
866
+ });
867
+ var auditQuerySchema = import_zod3.z.object({
868
+ before: import_zod3.z.iso.datetime({ offset: true }).optional(),
869
+ limit: import_zod3.z.coerce.number().int().min(1).max(500).optional(),
870
+ sessionId: import_zod3.z.string().max(128).optional()
871
+ });
872
+ var actorId = (ctx) => ctx.actor?.id;
873
+ var DolfinhosModule = class {
874
+ /** Registra o Dolfinhos na aplicação: descobre as rotas e expõe o serviço e as rotas do painel. */
875
+ static forRoot(options) {
876
+ return {
877
+ module: DolfinhosModule,
878
+ global: true,
879
+ imports: [import_core3.DiscoveryModule],
880
+ providers: [{ provide: DOLFINHOS_OPTIONS, useValue: options }, DolfinhosService],
881
+ exports: [DolfinhosService],
882
+ controllers: options.path === false ? [] : [createController(options.path ?? "dolfinhos", options.guards ?? [])]
883
+ };
884
+ }
885
+ };
886
+ DolfinhosModule = __decorateClass([
887
+ (0, import_common2.Module)({})
888
+ ], DolfinhosModule);
889
+ // Annotate the CommonJS export names for ESM import in node:
890
+ 0 && (module.exports = {
891
+ AiCapability,
892
+ AiIgnore,
893
+ DOLFINHOS_OPTIONS,
894
+ DolfinhosModule,
895
+ DolfinhosService,
896
+ areaOf,
897
+ buildCapabilities,
898
+ compact,
899
+ createApiCaller,
900
+ describeCapabilities,
901
+ discoverRoutes,
902
+ inferKind,
903
+ inputSchemaOf,
904
+ joinPath,
905
+ loadCapabilitiesFile,
906
+ pathParams,
907
+ requestOf,
908
+ safeName
909
+ });
910
+ //# sourceMappingURL=index.cjs.map