@dolfinhos/cli 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/LICENSE +21 -0
- package/README.md +12 -2
- package/dist/cli.js +205 -0
- package/package.json +39 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dolfinsis
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dolfinhos/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Comandos do Dolfinhos para aplicações NestJS.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install -D @dolfinhos/cli
|
|
7
|
+
npx dolfinhos init # cria a configuração em src/dolfinhos/
|
|
8
|
+
npx dolfinhos generate # escreve títulos e descrições das ações em dolfinhos.capabilities.json
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
O `generate` pede as descrições à própria aplicação rodando (rota `/dolfinhos/capabilities/describe`) e preserva o que você já editou à mão. Revise o arquivo e faça commit dele: é o que a IA lê.
|
|
12
|
+
|
|
13
|
+
Documentação completa no [repositório do Dolfinhos Toolkit](https://github.com/dolfinsis/dolfinhos-toolkit). Licença MIT.
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { existsSync } from "fs";
|
|
5
|
+
import { mkdir, readFile, writeFile } from "fs/promises";
|
|
6
|
+
import { dirname, resolve } from "path";
|
|
7
|
+
import { parseArgs } from "util";
|
|
8
|
+
|
|
9
|
+
// src/generate.ts
|
|
10
|
+
async function request(fetchImpl, url, token, init = {}) {
|
|
11
|
+
const res = await fetchImpl(url, { ...init, headers: { authorization: token.startsWith("Bearer ") ? token : `Bearer ${token}`, "content-type": "application/json" } });
|
|
12
|
+
const body = await res.json().catch(() => null);
|
|
13
|
+
if (!res.ok) {
|
|
14
|
+
const message = body?.error?.message ?? `HTTP ${res.status}`;
|
|
15
|
+
throw new Error(`${init.method ?? "GET"} ${url}: ${message}`);
|
|
16
|
+
}
|
|
17
|
+
return body;
|
|
18
|
+
}
|
|
19
|
+
async function generate(options) {
|
|
20
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
21
|
+
const log = options.log ?? (() => {
|
|
22
|
+
});
|
|
23
|
+
const base = options.url.replace(/\/$/, "");
|
|
24
|
+
const listed = await request(fetchImpl, `${base}/capabilities`, options.token);
|
|
25
|
+
const names = listed.map((c) => c.name);
|
|
26
|
+
const missing = options.all ? names : names.filter((n) => !options.current[n]);
|
|
27
|
+
log(`${names.length} capacidades na aplica\xE7\xE3o; ${missing.length} para descrever.`);
|
|
28
|
+
const catalog = { ...options.current };
|
|
29
|
+
const added = [];
|
|
30
|
+
for (let i = 0; i < missing.length; i += 40) {
|
|
31
|
+
const chunk = missing.slice(i, i + 40);
|
|
32
|
+
const described = await request(fetchImpl, `${base}/capabilities/describe`, options.token, { method: "POST", body: JSON.stringify({ names: chunk }) });
|
|
33
|
+
for (const [name, entry] of Object.entries(described)) {
|
|
34
|
+
catalog[name] = options.all ? { ...entry, ...pick(options.current[name], ["ignore", "tags", "kind", "risk", "entity"]) } : entry;
|
|
35
|
+
added.push(name);
|
|
36
|
+
}
|
|
37
|
+
log(` ${Math.min(i + 40, missing.length)}/${missing.length}`);
|
|
38
|
+
}
|
|
39
|
+
const sorted = Object.fromEntries(Object.entries(catalog).sort(([a], [b]) => a.localeCompare(b)));
|
|
40
|
+
return {
|
|
41
|
+
catalog: sorted,
|
|
42
|
+
added,
|
|
43
|
+
obsolete: Object.keys(options.current).filter((n) => !names.includes(n)),
|
|
44
|
+
failed: missing.filter((n) => !added.includes(n))
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function pick(entry, keys) {
|
|
48
|
+
if (!entry) return {};
|
|
49
|
+
return Object.fromEntries(keys.filter((k) => k in entry).map((k) => [k, entry[k]]));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/templates.ts
|
|
53
|
+
var NEST_CONFIG_TEMPLATE = `import { createOrchestrator, knowledgeTool, memoryPrompt, rememberTool, type FactSubjects } from '@dolfinhos/core';
|
|
54
|
+
import {
|
|
55
|
+
createPostgresAdapter,
|
|
56
|
+
createPostgresAuditStore,
|
|
57
|
+
createPostgresFactStore,
|
|
58
|
+
createPostgresKnowledgeStore,
|
|
59
|
+
createPostgresSettingsStore,
|
|
60
|
+
createPostgresUsageStore,
|
|
61
|
+
} from '@dolfinhos/db-postgres';
|
|
62
|
+
import type { DolfinhosModuleOptions } from '@dolfinhos/nestjs';
|
|
63
|
+
import { openai } from '@ai-sdk/openai'; // troque pelo provedor que voc\xEA usa
|
|
64
|
+
import pg from 'pg';
|
|
65
|
+
|
|
66
|
+
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 4 });
|
|
67
|
+
const knowledge = createPostgresKnowledgeStore({ client: pool });
|
|
68
|
+
const facts = createPostgresFactStore({ client: pool });
|
|
69
|
+
|
|
70
|
+
// Sobre quem o assistente guarda mem\xF3ria: aqui, a pr\xF3pria pessoa (prefer\xEAncias de trabalho).
|
|
71
|
+
const subjects: FactSubjects<any> = ({ ctx }) => (ctx.userId ? { eu: { type: 'user', id: String(ctx.userId) } } : {});
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Configura\xE7\xE3o do Dolfinhos. As capacidades v\xEAm das rotas da aplica\xE7\xE3o;
|
|
75
|
+
* aqui voc\xEA decide quem \xE9 o usu\xE1rio, quais agentes existem e o que a IA pode
|
|
76
|
+
* fazer sozinha, o que pergunta e o que nunca faz.
|
|
77
|
+
*/
|
|
78
|
+
export const dolfinhosConfig: DolfinhosModuleOptions = {
|
|
79
|
+
// Quem est\xE1 pedindo: leia o usu\xE1rio que o seu guard de autentica\xE7\xE3o colocou na requisi\xE7\xE3o.
|
|
80
|
+
context: (req) =>
|
|
81
|
+
req.user
|
|
82
|
+
? {
|
|
83
|
+
actor: { type: 'user', id: req.user.id, tenantId: req.user.tenantId, roles: [req.user.role] },
|
|
84
|
+
tenantId: req.user.tenantId,
|
|
85
|
+
userId: req.user.id,
|
|
86
|
+
}
|
|
87
|
+
: null,
|
|
88
|
+
|
|
89
|
+
// Quem pode editar as regras da empresa e ver a auditoria.
|
|
90
|
+
canManage: (ctx) => Boolean((ctx.actor as { roles?: string[] }).roles?.includes('ADMIN')),
|
|
91
|
+
|
|
92
|
+
// Um orquestrador: consulta direto, prop\xF5e planos e cria especialistas para executar.
|
|
93
|
+
pod: ({ capabilities }) =>
|
|
94
|
+
createOrchestrator({
|
|
95
|
+
name: 'Assistente',
|
|
96
|
+
capabilities: [
|
|
97
|
+
...capabilities,
|
|
98
|
+
knowledgeTool({ store: knowledge, audience: 'internal' }),
|
|
99
|
+
rememberTool({ store: facts, subjects }),
|
|
100
|
+
],
|
|
101
|
+
orchestratorCapabilities: [{ kinds: ['read'] }, { names: ['lembrar'] }],
|
|
102
|
+
model: openai('gpt-4.1-mini'),
|
|
103
|
+
instructions: 'Voc\xEA ajuda o usu\xE1rio a usar a aplica\xE7\xE3o. Use as ferramentas para consultar e agir; n\xE3o invente dados.',
|
|
104
|
+
systemPrompt: ({ ctx, screen }) => memoryPrompt({ store: facts, ctx, screen, subjects }),
|
|
105
|
+
}),
|
|
106
|
+
|
|
107
|
+
// Regras da aplica\xE7\xE3o. Padr\xE3o do toolkit: consultar \xE9 livre, o resto pergunta.
|
|
108
|
+
policies: [
|
|
109
|
+
{ match: { capability: 'lembrar' }, mode: 'auto', description: 'Guardar uma prefer\xEAncia n\xE3o precisa de aprova\xE7\xE3o.' },
|
|
110
|
+
// { match: { kind: 'delete', role: 'AGENT' }, mode: 'deny', final: true, reason: 'S\xF3 administradores excluem.' },
|
|
111
|
+
],
|
|
112
|
+
|
|
113
|
+
memory: createPostgresAdapter({ client: pool, table: 'dolfinhos.sessions' }),
|
|
114
|
+
settings: createPostgresSettingsStore({ client: pool }),
|
|
115
|
+
audit: createPostgresAuditStore({ client: pool }),
|
|
116
|
+
knowledge,
|
|
117
|
+
facts,
|
|
118
|
+
usage: createPostgresUsageStore({ client: pool }),
|
|
119
|
+
// Pre\xE7o por milh\xE3o de tokens, para a tela de custos e o limite mensal de cada empresa. Confira no seu provedor.
|
|
120
|
+
pricing: { currency: 'USD', models: { 'gpt-4.1-mini': { input: 0.4, output: 1.6 } } },
|
|
121
|
+
|
|
122
|
+
// Modelo usado pelo \`dolfinhos generate\` para escrever as descri\xE7\xF5es das a\xE7\xF5es.
|
|
123
|
+
describeModel: openai('gpt-4.1-mini'),
|
|
124
|
+
describeContext: 'Descreva a sua aplica\xE7\xE3o em uma frase.',
|
|
125
|
+
};
|
|
126
|
+
`;
|
|
127
|
+
|
|
128
|
+
// src/cli.ts
|
|
129
|
+
var HELP = `Dolfinhos: camada de IA para a sua aplica\xE7\xE3o.
|
|
130
|
+
|
|
131
|
+
Uso:
|
|
132
|
+
dolfinhos init [--out src/dolfinhos.config.ts]
|
|
133
|
+
Cria o arquivo de configura\xE7\xE3o (NestJS) para voc\xEA ajustar.
|
|
134
|
+
|
|
135
|
+
dolfinhos generate --url http://localhost:3000/dolfinhos --token <token de admin> [--out dolfinhos.capabilities.json] [--all]
|
|
136
|
+
Pergunta \xE0 aplica\xE7\xE3o rodando quais a\xE7\xF5es ela tem e escreve t\xEDtulos e
|
|
137
|
+
descri\xE7\xF5es para as que faltam no arquivo. Revise e versione o arquivo.
|
|
138
|
+
O token tamb\xE9m pode vir de DOLFINHOS_TOKEN.
|
|
139
|
+
`;
|
|
140
|
+
async function main(argv) {
|
|
141
|
+
const [command, ...rest] = argv[0]?.startsWith("-") ? ["help", ...argv] : argv;
|
|
142
|
+
const { values } = parseArgs({
|
|
143
|
+
args: rest,
|
|
144
|
+
options: {
|
|
145
|
+
url: { type: "string" },
|
|
146
|
+
token: { type: "string" },
|
|
147
|
+
out: { type: "string" },
|
|
148
|
+
all: { type: "boolean", default: false },
|
|
149
|
+
help: { type: "boolean", short: "h", default: false }
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
if (!command || values.help || command === "help") {
|
|
153
|
+
console.log(HELP);
|
|
154
|
+
return 0;
|
|
155
|
+
}
|
|
156
|
+
if (command === "init") {
|
|
157
|
+
const out = resolve(values.out ?? "src/dolfinhos.config.ts");
|
|
158
|
+
if (existsSync(out)) {
|
|
159
|
+
console.error(`J\xE1 existe ${out}. Nada foi alterado.`);
|
|
160
|
+
return 1;
|
|
161
|
+
}
|
|
162
|
+
await mkdir(dirname(out), { recursive: true });
|
|
163
|
+
await writeFile(out, NEST_CONFIG_TEMPLATE);
|
|
164
|
+
console.log(`Criado ${out}.
|
|
165
|
+
|
|
166
|
+
Pr\xF3ximos passos:
|
|
167
|
+
1. Instale: npm i @dolfinhos/core @dolfinhos/server @dolfinhos/nestjs @dolfinhos/db-postgres ai zod
|
|
168
|
+
e o provedor do modelo (ex.: @ai-sdk/openai, @ai-sdk/deepseek).
|
|
169
|
+
2. Ajuste o arquivo (como ler o usu\xE1rio da requisi\xE7\xE3o, modelo, pol\xEDticas).
|
|
170
|
+
3. No AppModule: imports: [DolfinhosModule.forRoot(dolfinhosConfig)].
|
|
171
|
+
4. Suba a aplica\xE7\xE3o e rode: dolfinhos generate --url http://localhost:3000/dolfinhos --token <token de admin>`);
|
|
172
|
+
return 0;
|
|
173
|
+
}
|
|
174
|
+
if (command === "generate") {
|
|
175
|
+
const url = values.url;
|
|
176
|
+
const token = values.token ?? process.env.DOLFINHOS_TOKEN;
|
|
177
|
+
if (!url || !token) {
|
|
178
|
+
console.error("Informe --url e --token (ou DOLFINHOS_TOKEN).\n");
|
|
179
|
+
console.log(HELP);
|
|
180
|
+
return 1;
|
|
181
|
+
}
|
|
182
|
+
const out = resolve(values.out ?? "dolfinhos.capabilities.json");
|
|
183
|
+
const current = existsSync(out) ? JSON.parse(await readFile(out, "utf8")) : {};
|
|
184
|
+
const result = await generate({ url, token, current, all: values.all, log: (line) => console.log(line) });
|
|
185
|
+
await writeFile(out, `${JSON.stringify(result.catalog, null, 2)}
|
|
186
|
+
`);
|
|
187
|
+
console.log(`
|
|
188
|
+
${result.added.length} descritas, gravado em ${out}.`);
|
|
189
|
+
if (result.failed.length) console.log(`Sem descri\xE7\xE3o (rode de novo): ${result.failed.join(", ")}`);
|
|
190
|
+
if (result.obsolete.length) console.log(`No arquivo, mas n\xE3o existem mais na aplica\xE7\xE3o: ${result.obsolete.join(", ")}`);
|
|
191
|
+
console.log('Revise o arquivo: ajuste t\xEDtulos, tipos e riscos, ou use "ignore": true para esconder uma a\xE7\xE3o da IA.');
|
|
192
|
+
return 0;
|
|
193
|
+
}
|
|
194
|
+
console.error(`Comando desconhecido: ${command}
|
|
195
|
+
`);
|
|
196
|
+
console.log(HELP);
|
|
197
|
+
return 1;
|
|
198
|
+
}
|
|
199
|
+
main(process.argv.slice(2)).then(
|
|
200
|
+
(code) => process.exit(code),
|
|
201
|
+
(error) => {
|
|
202
|
+
console.error(error instanceof Error ? error.message : error);
|
|
203
|
+
process.exit(1);
|
|
204
|
+
}
|
|
205
|
+
);
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dolfinhos/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "CLI do Dolfinhos: dolfinhos init e dolfinhos generate.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"dolfinhos",
|
|
8
|
+
"cli",
|
|
9
|
+
"ai",
|
|
10
|
+
"agents",
|
|
11
|
+
"codegen"
|
|
12
|
+
],
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/dolfinsis/dolfinhos-toolkit.git",
|
|
16
|
+
"directory": "packages/cli"
|
|
17
|
+
},
|
|
18
|
+
"homepage": "https://github.com/dolfinsis/dolfinhos-toolkit/tree/main/packages/cli#readme",
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/dolfinsis/dolfinhos-toolkit/issues"
|
|
21
|
+
},
|
|
22
|
+
"type": "module",
|
|
23
|
+
"bin": {
|
|
24
|
+
"dolfinhos": "./dist/cli.js"
|
|
25
|
+
},
|
|
26
|
+
"main": "./dist/cli.js",
|
|
27
|
+
"files": [
|
|
28
|
+
"dist"
|
|
29
|
+
],
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=20"
|
|
32
|
+
},
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsup",
|
|
38
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
39
|
+
"test": "vitest run",
|
|
40
|
+
"clean": "rm -rf dist .turbo"
|
|
41
|
+
}
|
|
6
42
|
}
|