@thenajs/tools 0.9.0 → 0.12.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/dist/index.d.ts +1 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/parallel.tool.d.ts +21 -0
- package/dist/parallel.tool.d.ts.map +1 -0
- package/dist/parallel.tool.js +93 -0
- package/dist/parallel.tool.js.map +1 -0
- package/package.json +3 -3
- package/dist/shell.tool.d.ts +0 -55
- package/dist/shell.tool.d.ts.map +0 -1
- package/dist/shell.tool.js +0 -114
- package/dist/shell.tool.js.map +0 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 castroneto
|
|
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 DEALING IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.d.ts
CHANGED
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { ParallelTool } from "./parallel.tool.js";
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ToolOutput, ToolType } from "@thenajs/core";
|
|
2
|
+
/**
|
|
3
|
+
* Executa várias tools do próprio agente numa única chamada ao modelo.
|
|
4
|
+
*
|
|
5
|
+
* O ganho é **round-trip**: ler três arquivos custa uma ida ao modelo em vez de
|
|
6
|
+
* três.
|
|
7
|
+
*
|
|
8
|
+
* Ela não recebe tool nenhuma — o `@tools()` entrega as irmãs **já embrulhadas**
|
|
9
|
+
* na cadeia de middleware. É isso que faz cada chamada interna continuar abrindo
|
|
10
|
+
* o próprio nó no report e passando pelos hooks, pela autorização, pelo
|
|
11
|
+
* orçamento e pela política de erro.
|
|
12
|
+
*/
|
|
13
|
+
export declare class ParallelTool {
|
|
14
|
+
execute({ calls }: {
|
|
15
|
+
calls: {
|
|
16
|
+
tool: string;
|
|
17
|
+
args: Record<string, unknown>;
|
|
18
|
+
}[];
|
|
19
|
+
}, siblings: ToolType[]): Promise<ToolOutput>;
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=parallel.tool.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parallel.tool.d.ts","sourceRoot":"","sources":["../src/parallel.tool.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAG1D;;;;;;;;;;GAUG;AACH,qBAoBa,YAAY;IACjB,OAAO,CACF,EAAE,KAAK,EAAE,EAAE;QAAE,KAAK,EAAE;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;SAAE,EAAE,CAAA;KAAE,EACvE,QAAQ,EAAE,QAAQ,EAAE,GAC5B,OAAO,CAAC,UAAU,CAAC;CA4CvB"}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
import { Tool, input, toToolOutput, tools } from "@thenajs/core";
|
|
14
|
+
import { z } from "zod";
|
|
15
|
+
/**
|
|
16
|
+
* Executa várias tools do próprio agente numa única chamada ao modelo.
|
|
17
|
+
*
|
|
18
|
+
* O ganho é **round-trip**: ler três arquivos custa uma ida ao modelo em vez de
|
|
19
|
+
* três.
|
|
20
|
+
*
|
|
21
|
+
* Ela não recebe tool nenhuma — o `@tools()` entrega as irmãs **já embrulhadas**
|
|
22
|
+
* na cadeia de middleware. É isso que faz cada chamada interna continuar abrindo
|
|
23
|
+
* o próprio nó no report e passando pelos hooks, pela autorização, pelo
|
|
24
|
+
* orçamento e pela política de erro.
|
|
25
|
+
*/
|
|
26
|
+
let ParallelTool = class ParallelTool {
|
|
27
|
+
async execute({ calls }, siblings) {
|
|
28
|
+
// Sem a si mesma: `parallel` dentro de `parallel` só aninharia lote em lote.
|
|
29
|
+
const available = siblings.filter((t) => t.name !== "parallel");
|
|
30
|
+
const results = await Promise.all(calls.map(async (call) => {
|
|
31
|
+
const target = available.find((t) => t.name === call.tool);
|
|
32
|
+
if (!target) {
|
|
33
|
+
const names = available.map((t) => t.name).join(", ");
|
|
34
|
+
return {
|
|
35
|
+
content: `unknown tool. Available: ${names}`,
|
|
36
|
+
isError: true,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
// O schema da irmã é obrigatório aqui: no caminho normal quem valida
|
|
41
|
+
// os argumentos é o provider, e o `buildToolStep` embrulha o `execute`
|
|
42
|
+
// sem validar. Sem este `parse`, a tool receberia lixo tipado errado.
|
|
43
|
+
const args = target.schema.parse(call.args);
|
|
44
|
+
return toToolOutput(await target.execute(args));
|
|
45
|
+
}
|
|
46
|
+
catch (err) {
|
|
47
|
+
// Falha de uma chamada não pode derrubar o lote: as irmãs já custaram
|
|
48
|
+
// trabalho, e o modelo consegue corrigir só a que errou.
|
|
49
|
+
return { content: err.message, isError: true };
|
|
50
|
+
}
|
|
51
|
+
}));
|
|
52
|
+
return {
|
|
53
|
+
content: results
|
|
54
|
+
.map((r, i) => {
|
|
55
|
+
const status = r.isError ? "error" : "ok";
|
|
56
|
+
return `[${i + 1}] ${calls[i].tool} → ${status}\n${r.content}`;
|
|
57
|
+
})
|
|
58
|
+
.join("\n\n"),
|
|
59
|
+
// Erro só quando **tudo** falhou: um lote parcialmente bom não é um turno
|
|
60
|
+
// perdido, e marcá-lo como erro faria o `maxFails` do loop contar uma
|
|
61
|
+
// falha que não houve.
|
|
62
|
+
isError: results.every((r) => r.isError),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
__decorate([
|
|
67
|
+
__param(0, input()),
|
|
68
|
+
__param(1, tools()),
|
|
69
|
+
__metadata("design:type", Function),
|
|
70
|
+
__metadata("design:paramtypes", [Object, Array]),
|
|
71
|
+
__metadata("design:returntype", Promise)
|
|
72
|
+
], ParallelTool.prototype, "execute", null);
|
|
73
|
+
ParallelTool = __decorate([
|
|
74
|
+
Tool({
|
|
75
|
+
name: "parallel",
|
|
76
|
+
description: "Run several of the other available tools at once and return every result. " +
|
|
77
|
+
"Use it when you need two or more calls that do not depend on each other. " +
|
|
78
|
+
"If one call needs another's result, make them in separate turns.",
|
|
79
|
+
schema: z.object({
|
|
80
|
+
calls: z
|
|
81
|
+
.array(z.object({
|
|
82
|
+
tool: z.string().describe("the name of one of the other available tools"),
|
|
83
|
+
args: z
|
|
84
|
+
.record(z.string(), z.unknown())
|
|
85
|
+
.describe("that tool's arguments, in the shape it declares"),
|
|
86
|
+
}))
|
|
87
|
+
.min(2, "use this tool only for two or more calls")
|
|
88
|
+
.max(8),
|
|
89
|
+
}),
|
|
90
|
+
})
|
|
91
|
+
], ParallelTool);
|
|
92
|
+
export { ParallelTool };
|
|
93
|
+
//# sourceMappingURL=parallel.tool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version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AQ,CAAC,iDAAiD,CAAC;aAC/D,CAAC,CACH;iBACA,GAAG,CAAC,CAAC,EAAE,0CAA0C,CAAC;iBAClD,GAAG,CAAC,CAAC,CAAC;SACV,CAAC;KACH,CAAC;GACW,YAAY,CAgDxB"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@thenajs/tools",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Tools prontas para agentes ThenaJS (ex.:
|
|
3
|
+
"version": "0.12.0",
|
|
4
|
+
"description": "Tools prontas para agentes ThenaJS (ex.: ParallelTool).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "castroneto",
|
|
7
7
|
"repository": {
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"node": ">=20.19"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@thenajs/core": "^0.
|
|
29
|
+
"@thenajs/core": "^0.12.0"
|
|
30
30
|
},
|
|
31
31
|
"peerDependencies": {
|
|
32
32
|
"zod": "^4.0.0"
|
package/dist/shell.tool.d.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import type { ToolType } from "@thenajs/core";
|
|
2
|
-
export interface ShellToolOptions {
|
|
3
|
-
/** Teto de tempo do comando, em ms. Default: 30s. */
|
|
4
|
-
timeoutMs?: number;
|
|
5
|
-
/** Diretório de trabalho. Default: o do processo. */
|
|
6
|
-
cwd?: string;
|
|
7
|
-
/**
|
|
8
|
-
* Só executa comandos cujo **primeiro token** esteja nesta lista.
|
|
9
|
-
*
|
|
10
|
-
* É a única proteção real contra prompt injection nesta tool. Sem allowlist,
|
|
11
|
-
* qualquer coisa que o modelo escrever é executada com as permissões do
|
|
12
|
-
* processo.
|
|
13
|
-
*
|
|
14
|
-
* ```ts
|
|
15
|
-
* shellTool({ allow: ["ls", "cat", "grep", "git"] })
|
|
16
|
-
* ```
|
|
17
|
-
*/
|
|
18
|
-
allow?: string[];
|
|
19
|
-
/** Teto de caracteres devolvidos ao modelo. Default: 8000. */
|
|
20
|
-
maxChars?: number;
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* Executa um comando shell.
|
|
24
|
-
*
|
|
25
|
-
* ## ⚠️ Leia antes de usar
|
|
26
|
-
*
|
|
27
|
-
* Esta tool dá ao modelo **execução arbitrária de comando** com as permissões
|
|
28
|
-
* do seu processo. Um agente que leia conteúdo de terceiro — um README, uma
|
|
29
|
-
* issue, um arquivo do repositório — pode ser induzido a executar o que
|
|
30
|
-
* estiver escrito lá. O framework não tem defesa contra prompt injection.
|
|
31
|
-
*
|
|
32
|
-
* Use `allow` sempre que o agente puder ver entrada não confiável:
|
|
33
|
-
*
|
|
34
|
-
* ```ts
|
|
35
|
-
* @Agent({ provider, prompt: "./a.agent.md", tools: [shellTool({ allow: ["git", "ls"] })] })
|
|
36
|
-
* ```
|
|
37
|
-
*
|
|
38
|
-
* Sem `allow`, restrinja o uso a ambiente controlado — sua máquina, um
|
|
39
|
-
* container descartável — e nunca a um serviço exposto.
|
|
40
|
-
*/
|
|
41
|
-
export declare function shellTool(options?: ShellToolOptions): ToolType;
|
|
42
|
-
/**
|
|
43
|
-
* Versão sem configuração, para uso rápido em ambiente controlado.
|
|
44
|
-
*
|
|
45
|
-
* ⚠️ **Sem allowlist** — o modelo executa qualquer comando. Leia o aviso de
|
|
46
|
-
* `shellTool` antes de usar; para agente que vê entrada não confiável, prefira
|
|
47
|
-
* `shellTool({ allow: [...] })`.
|
|
48
|
-
*/
|
|
49
|
-
export declare class ShellTool {
|
|
50
|
-
private readonly impl;
|
|
51
|
-
execute(args: {
|
|
52
|
-
command: string;
|
|
53
|
-
}): Promise<string | import("@thenajs/core").ToolOutput>;
|
|
54
|
-
}
|
|
55
|
-
//# sourceMappingURL=shell.tool.d.ts.map
|
package/dist/shell.tool.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"shell.tool.d.ts","sourceRoot":"","sources":["../src/shell.tool.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAa9C,MAAM,WAAW,gBAAgB;IAC/B,qDAAqD;IACrD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,qDAAqD;IACrD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;;;;;;;OAUG;IACH,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,GAAG,QAAQ,CA4DlE;AAED;;;;;;GAMG;AACH,qBAKa,SAAS;IACpB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAe;IAEpC,OAAO,CAAC,IAAI,EAAE;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE;CAGlC"}
|
package/dist/shell.tool.js
DELETED
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
-
};
|
|
7
|
-
import { exec } from "node:child_process";
|
|
8
|
-
import { promisify } from "node:util";
|
|
9
|
-
import { Tool } from "@thenajs/core";
|
|
10
|
-
import { z } from "zod";
|
|
11
|
-
const run = promisify(exec);
|
|
12
|
-
const schema = z.object({ command: z.string() });
|
|
13
|
-
/** Teto de tempo padrão. Sem ele, um comando pendurado trava a run para sempre. */
|
|
14
|
-
const DEFAULT_TIMEOUT = 30_000;
|
|
15
|
-
/** Teto de saída devolvida ao modelo, para não entupir a janela de contexto. */
|
|
16
|
-
const MAX_CHARS = 8_000;
|
|
17
|
-
/**
|
|
18
|
-
* Executa um comando shell.
|
|
19
|
-
*
|
|
20
|
-
* ## ⚠️ Leia antes de usar
|
|
21
|
-
*
|
|
22
|
-
* Esta tool dá ao modelo **execução arbitrária de comando** com as permissões
|
|
23
|
-
* do seu processo. Um agente que leia conteúdo de terceiro — um README, uma
|
|
24
|
-
* issue, um arquivo do repositório — pode ser induzido a executar o que
|
|
25
|
-
* estiver escrito lá. O framework não tem defesa contra prompt injection.
|
|
26
|
-
*
|
|
27
|
-
* Use `allow` sempre que o agente puder ver entrada não confiável:
|
|
28
|
-
*
|
|
29
|
-
* ```ts
|
|
30
|
-
* @Agent({ provider, prompt: "./a.agent.md", tools: [shellTool({ allow: ["git", "ls"] })] })
|
|
31
|
-
* ```
|
|
32
|
-
*
|
|
33
|
-
* Sem `allow`, restrinja o uso a ambiente controlado — sua máquina, um
|
|
34
|
-
* container descartável — e nunca a um serviço exposto.
|
|
35
|
-
*/
|
|
36
|
-
export function shellTool(options = {}) {
|
|
37
|
-
const timeout = options.timeoutMs ?? DEFAULT_TIMEOUT;
|
|
38
|
-
const maxChars = options.maxChars ?? MAX_CHARS;
|
|
39
|
-
const allow = options.allow?.map((c) => c.trim()).filter(Boolean);
|
|
40
|
-
return {
|
|
41
|
-
name: "shell",
|
|
42
|
-
description: allow
|
|
43
|
-
? `Executa um comando shell. Permitidos: ${allow.join(", ")}.`
|
|
44
|
-
: "Executa um comando shell e retorna a saída.",
|
|
45
|
-
schema,
|
|
46
|
-
async execute({ command }) {
|
|
47
|
-
if (allow) {
|
|
48
|
-
// O primeiro token decide. Não tenta interpretar a linha inteira: um
|
|
49
|
-
// parser de shell parcial dá falsa sensação de segurança, e `;`, `&&`,
|
|
50
|
-
// `$(…)` e pipes contornariam qualquer coisa mais esperta que isto.
|
|
51
|
-
const programa = command.trim().split(/\s+/)[0] ?? "";
|
|
52
|
-
if (!allow.includes(programa)) {
|
|
53
|
-
return {
|
|
54
|
-
content: `Comando "${programa}" não permitido. ` +
|
|
55
|
-
`Disponíveis: ${allow.join(", ")}.`,
|
|
56
|
-
isError: true,
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
if (/[;&|`$><]/.test(command)) {
|
|
60
|
-
// Com allowlist ligada, encadeamento anularia a lista.
|
|
61
|
-
return {
|
|
62
|
-
content: "Encadeamento e redirecionamento não são permitidos " +
|
|
63
|
-
"(`;`, `&&`, `|`, `$(…)`, `>`). Rode um comando por vez.",
|
|
64
|
-
isError: true,
|
|
65
|
-
};
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
try {
|
|
69
|
-
const { stdout, stderr } = await run(command, {
|
|
70
|
-
timeout,
|
|
71
|
-
cwd: options.cwd,
|
|
72
|
-
maxBuffer: 10 * 1024 * 1024,
|
|
73
|
-
});
|
|
74
|
-
const saida = stdout || stderr || "(sem saída)";
|
|
75
|
-
return saida.length > maxChars
|
|
76
|
-
? `${saida.slice(0, maxChars)}\n… [truncado]`
|
|
77
|
-
: saida;
|
|
78
|
-
}
|
|
79
|
-
catch (err) {
|
|
80
|
-
const e = err;
|
|
81
|
-
if (e.killed) {
|
|
82
|
-
return {
|
|
83
|
-
content: `O comando excedeu ${timeout}ms e foi encerrado.`,
|
|
84
|
-
isError: true,
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
// Erro vira observação: o modelo lê e tenta outra coisa.
|
|
88
|
-
return { content: e.stderr || e.message, isError: true };
|
|
89
|
-
}
|
|
90
|
-
},
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
/**
|
|
94
|
-
* Versão sem configuração, para uso rápido em ambiente controlado.
|
|
95
|
-
*
|
|
96
|
-
* ⚠️ **Sem allowlist** — o modelo executa qualquer comando. Leia o aviso de
|
|
97
|
-
* `shellTool` antes de usar; para agente que vê entrada não confiável, prefira
|
|
98
|
-
* `shellTool({ allow: [...] })`.
|
|
99
|
-
*/
|
|
100
|
-
let ShellTool = class ShellTool {
|
|
101
|
-
impl = shellTool();
|
|
102
|
-
execute(args) {
|
|
103
|
-
return this.impl.execute(args);
|
|
104
|
-
}
|
|
105
|
-
};
|
|
106
|
-
ShellTool = __decorate([
|
|
107
|
-
Tool({
|
|
108
|
-
name: "shell",
|
|
109
|
-
description: "Executa um comando shell e retorna a saída.",
|
|
110
|
-
schema,
|
|
111
|
-
})
|
|
112
|
-
], ShellTool);
|
|
113
|
-
export { ShellTool };
|
|
114
|
-
//# sourceMappingURL=shell.tool.js.map
|
package/dist/shell.tool.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"shell.tool.js","sourceRoot":"","sources":["../src/shell.tool.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAErC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,MAAM,GAAG,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;AAE5B,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AAEjD,mFAAmF;AACnF,MAAM,eAAe,GAAG,MAAM,CAAC;AAE/B,gFAAgF;AAChF,MAAM,SAAS,GAAG,KAAK,CAAC;AAuBxB;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,SAAS,CAAC,UAA4B,EAAE;IACtD,MAAM,OAAO,GAAG,OAAO,CAAC,SAAS,IAAI,eAAe,CAAC;IACrD,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,SAAS,CAAC;IAC/C,MAAM,K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