beddel 0.1.0 → 0.2.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.
Files changed (63) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/LICENSE +21 -0
  3. package/README.md +446 -192
  4. package/dist/agents/agentRegistry.d.ts +26 -1
  5. package/dist/agents/agentRegistry.d.ts.map +1 -1
  6. package/dist/agents/agentRegistry.js +180 -1
  7. package/dist/agents/agentRegistry.js.map +1 -1
  8. package/dist/runtime/declarativeAgentRuntime.d.ts +4 -0
  9. package/dist/runtime/declarativeAgentRuntime.d.ts.map +1 -1
  10. package/dist/runtime/declarativeAgentRuntime.js +43 -0
  11. package/dist/runtime/declarativeAgentRuntime.js.map +1 -1
  12. package/dist/runtime/schemaCompiler.js +5 -4
  13. package/dist/runtime/schemaCompiler.js.map +1 -1
  14. package/package.json +6 -3
  15. package/src/agents/agentRegistry.ts +172 -2
  16. package/src/runtime/declarativeAgentRuntime.ts +71 -13
  17. package/src/runtime/schemaCompiler.ts +5 -5
  18. package/dist/agents/formatter-agent.d.ts +0 -10
  19. package/dist/agents/formatter-agent.d.ts.map +0 -1
  20. package/dist/agents/formatter-agent.js +0 -49
  21. package/dist/agents/formatter-agent.js.map +0 -1
  22. package/dist/agents/genkit-agent.d.ts +0 -12
  23. package/dist/agents/genkit-agent.d.ts.map +0 -1
  24. package/dist/agents/genkit-agent.js +0 -119
  25. package/dist/agents/genkit-agent.js.map +0 -1
  26. package/dist/agents/i18n-messages.d.ts +0 -17
  27. package/dist/agents/i18n-messages.d.ts.map +0 -1
  28. package/dist/agents/i18n-messages.js +0 -92
  29. package/dist/agents/i18n-messages.js.map +0 -1
  30. package/dist/agents/index.d.ts +0 -10
  31. package/dist/agents/index.d.ts.map +0 -1
  32. package/dist/agents/index.js +0 -26
  33. package/dist/agents/index.js.map +0 -1
  34. package/dist/agents/pipeline.d.ts +0 -15
  35. package/dist/agents/pipeline.d.ts.map +0 -1
  36. package/dist/agents/pipeline.js +0 -45
  37. package/dist/agents/pipeline.js.map +0 -1
  38. package/dist/agents/schema-factory.d.ts +0 -40
  39. package/dist/agents/schema-factory.d.ts.map +0 -1
  40. package/dist/agents/schema-factory.js +0 -121
  41. package/dist/agents/schema-factory.js.map +0 -1
  42. package/dist/agents/translation-validators.d.ts +0 -26
  43. package/dist/agents/translation-validators.d.ts.map +0 -1
  44. package/dist/agents/translation-validators.js +0 -77
  45. package/dist/agents/translation-validators.js.map +0 -1
  46. package/dist/agents/translator-agents.d.ts +0 -184
  47. package/dist/agents/translator-agents.d.ts.map +0 -1
  48. package/dist/agents/translator-agents.js +0 -613
  49. package/dist/agents/translator-agents.js.map +0 -1
  50. package/dist/agents/types/translation.types.d.ts +0 -100
  51. package/dist/agents/types/translation.types.d.ts.map +0 -1
  52. package/dist/agents/types/translation.types.js +0 -3
  53. package/dist/agents/types/translation.types.js.map +0 -1
  54. package/dist/agents/validator-agent.d.ts +0 -42
  55. package/dist/agents/validator-agent.d.ts.map +0 -1
  56. package/dist/agents/validator-agent.js +0 -122
  57. package/dist/agents/validator-agent.js.map +0 -1
  58. package/dist/security/test-security.d.ts +0 -22
  59. package/dist/security/test-security.d.ts.map +0 -1
  60. package/dist/security/test-security.js +0 -154
  61. package/dist/security/test-security.js.map +0 -1
  62. package/tools/seed.ts +0 -365
  63. package/tools/test-endpoints.ts +0 -174
package/README.md CHANGED
@@ -1,297 +1,551 @@
1
- # Beddel: Secure, Declarative, and Extensible Agent Runtimes
1
+ # Beddel
2
+
3
+ **Secure, Declarative, and Extensible Agent Runtime**
2
4
 
3
5
  [![NPM Version](https://img.shields.io/npm/v/beddel.svg)](https://www.npmjs.com/package/beddel)
4
6
  [![License](https://img.shields.io/npm/l/beddel.svg)](https://github.com/botanarede/beddel-alpha/blob/main/LICENSE)
5
7
 
6
- **Repos:** código-fonte em `https://github.com/botanarede/beddel-alpha` e app de exemplo Next.js em `https://github.com/botanarede/beddel-alpha-example`.
7
-
8
- ## Usage Exemplo
8
+ Beddel is a security-first toolkit for building and running declarative YAML agents with enterprise-grade isolation, automatic schema validation, and extensible architecture.
9
9
 
10
- > Declaração YAML + interpretação segura para que quem visita o perfil do pacote no npm entenda o fluxo em poucos segundos.
10
+ ## Quick Start
11
11
 
12
12
  ```yaml
13
- # joker-agent.yaml
13
+ # agents/my-agent.yaml
14
14
  agent:
15
- id: joker
15
+ id: my-agent
16
+ version: 1.0.0
16
17
  protocol: beddel-declarative-protocol/v2.0
18
+
17
19
  metadata:
18
- name: Joker Agent
20
+ name: "My Custom Agent"
21
+ description: "A simple custom agent"
22
+ route: "/agents/my-agent"
23
+
19
24
  schema:
20
25
  input:
21
26
  type: "object"
22
- properties: {}
23
- required: []
27
+ properties:
28
+ message:
29
+ type: "string"
30
+ required: ["message"]
24
31
  output:
25
32
  type: "object"
26
33
  properties:
27
34
  response:
28
35
  type: "string"
29
36
  required: ["response"]
37
+
30
38
  logic:
31
39
  workflow:
32
- - name: generate-joke
33
- type: genkit-joke
40
+ - name: "process"
41
+ type: "genkit-joke"
34
42
  action:
35
- type: joke
36
- prompt: "Conte uma piada curta e original que funcione para qualquer público."
37
- result: jokerResult
43
+ type: "joke"
44
+ prompt: "{{message}}"
45
+ result: "result"
38
46
 
39
- - name: deliver-response
40
- type: output-generator
41
- action:
42
- type: generate
43
- output:
44
- response: "$jokerResult.texto"
47
+ output:
48
+ schema:
49
+ response: "$result.texto"
45
50
  ```
46
51
 
47
52
  ```typescript
48
- import {
49
- SecureYamlParser,
50
- DeclarativeAgentInterpreter,
51
- SecureYamlRuntime,
52
- IsolatedRuntimeManager,
53
- type ExecutionContext,
54
- } from "beddel";
55
- import { readFileSync } from "node:fs";
56
-
57
- const yamlManifest = readFileSync("joker-agent.yaml", "utf8");
58
-
59
- const parser = new SecureYamlParser({ filename: "joker-agent.yaml" });
60
- const manifest = parser.parseSecure(yamlManifest); // FAILSAFE_SCHEMA + depth/size limits
61
-
62
- const context: ExecutionContext = {
63
- logs: [],
64
- status: "running",
65
- output: null,
66
- log: console.log,
67
- setOutput: (output) => (context.output = output),
68
- setError: (err) => console.error(err),
69
- };
53
+ import { agentRegistry } from "beddel";
54
+
55
+ // Execute the agent
56
+ const result = await agentRegistry.executeAgent(
57
+ "my-agent.execute",
58
+ { message: "Hello world" },
59
+ { gemini_api_key: process.env.GEMINI_API_KEY },
60
+ context
61
+ );
62
+ ```
70
63
 
71
- const interpreter = new DeclarativeAgentInterpreter();
72
- const agentResult = await interpreter.interpret({
73
- yamlContent: yamlManifest,
74
- input: {},
75
- props: {
76
- gemini_api_key: process.env.GEMINI_API_KEY ?? "",
77
- },
78
- context,
79
- });
64
+ ## Installation
80
65
 
81
- const secureRuntime = new SecureYamlRuntime(new IsolatedRuntimeManager());
82
- const execution = await secureRuntime.parseYamlSecureRuntime(yamlManifest, {
83
- tenantId: "tenant-42",
84
- securityProfile: "tenant-isolated",
85
- validateSecurity: true,
86
- });
66
+ ```bash
67
+ npm install beddel
87
68
  ```
88
69
 
89
- - `SecureYamlParser` garante o parsing estritamente FAILSAFE com validação de profundidade, tamanho e UTF-8.
90
- - `DeclarativeAgentInterpreter` executa apenas steps declarativos (`output-generator`, `genkit-joke`, `genkit-translation`, `genkit-image`) e mantém toda a validação em Zod (sem `eval`/`Function`).
91
- - `SecureYamlRuntime` conecta parser, scanner e `isolated-vm` para entregar auditoria, limites de tempo/memória e perfis multi-tenant.
70
+ Requires Node.js 18+.
71
+
72
+ ---
73
+
74
+ ## Architecture Overview
92
75
 
93
- Beddel is a security-first toolkit that combines:
76
+ ```
77
+ ┌─────────────────────────────────────────────────────────────────────┐
78
+ │ Beddel Runtime │
79
+ │ │
80
+ │ ┌──────────────────────────────────────────────────────────────┐ │
81
+ │ │ Agent Registry │ │
82
+ │ │ │ │
83
+ │ │ ┌─────────────────┐ ┌────────────────────────────────┐ │ │
84
+ │ │ │ Built-in │ │ Custom Agents │ │ │
85
+ │ │ │ Agents │ │ /agents/*.yaml │ │ │
86
+ │ │ │ │ │ │ │ │
87
+ │ │ │ • joker │ │ Automatically discovered │ │ │
88
+ │ │ │ • translator │ │ and registered at startup │ │ │
89
+ │ │ │ • image │ │ │ │ │
90
+ │ │ └─────────────────┘ └────────────────────────────────┘ │ │
91
+ │ │ │ │
92
+ │ │ Priority: Custom Agents > Built-in Agents │ │
93
+ │ └──────────────────────────────────────────────────────────────┘ │
94
+ │ │ │
95
+ │ ▼ │
96
+ │ ┌──────────────────────────────────────────────────────────────┐ │
97
+ │ │ Declarative Agent Interpreter │ │
98
+ │ │ │ │
99
+ │ │ • YAML Parsing (FAILSAFE schema) │ │
100
+ │ │ • Schema Validation (Zod) │ │
101
+ │ │ • Workflow Execution │ │
102
+ │ │ • Genkit Integration (Gemini Flash) │ │
103
+ │ └──────────────────────────────────────────────────────────────┘ │
104
+ │ │ │
105
+ │ ▼ │
106
+ │ ┌──────────────────────────────────────────────────────────────┐ │
107
+ │ │ Secure Runtime (isolated-vm) │ │
108
+ │ │ │ │
109
+ │ │ • Memory limits • V8 isolate │ │
110
+ │ │ • Execution timeouts • No Node.js access │ │
111
+ │ │ • Audit logging • Multi-tenant isolation │ │
112
+ │ └──────────────────────────────────────────────────────────────┘ │
113
+ └─────────────────────────────────────────────────────────────────────┘
114
+ ```
94
115
 
95
- - A hardened YAML parser that only exposes the YAML FAILSAFE schema.
96
- - Multiple execution strategies powered by `isolated-vm`.
97
- - Declarative agent utilities, compliance helpers, performance monitors, and Firebase multi-tenant orchestration.
116
+ ---
98
117
 
99
- ### Declarative agents shipped with Gemini Flash helpers
118
+ ## Custom Agents
100
119
 
101
- The declarative runtime now exposes three Genkit-based helpers—`callGeminiFlashText`, `callGeminiFlashTranslation`, and `callGeminiFlashImage`—which proxy `generateText`/`generateImage` calls to `google("models/gemini-flash-latest")`. Each helper validates the presence of `props.gemini_api_key`, builds friendly prompts, and returns consistent metadata (`modelo_utilizado`, `tempo_processamento`, etc.).
120
+ Beddel supports custom agents that you define in your application's `/agents` directory. Custom agents are automatically discovered and registered at startup.
102
121
 
103
- | Agent | Method | Description | Inputs | Outputs | Required props |
104
- | --- | --- | --- | --- | --- | --- |
105
- | Joker Agent | `joker.execute` | Gera uma piada curta e original usando Gemini Flash. | — | `response` | `gemini_api_key` |
106
- | Translator Agent | `translator.execute` | Traduz textos via Gemini Flash com Genkit. | `texto`, `idioma_origem`, `idioma_destino` | `texto_traduzido`, `metadados` | `gemini_api_key` |
107
- | Image Generator Agent | `image.generate` | Cria imagens nos estilos `watercolor`, `neon` ou `sketch`. | `descricao`, `estilo`, `resolucao` | `image_url`, `image_base64`, `media_type`, `prompt_utilizado`, `metadados` | `gemini_api_key` |
122
+ ### Directory Structure
108
123
 
109
- > ⚠️ Todos os agentes embutidos dependem da prop `gemini_api_key`. Sem ela o runtime aborta a execução com uma mensagem amigável.
124
+ ```
125
+ your-app/
126
+ ├── agents/ # Custom agents directory
127
+ │ ├── my-agent.yaml # Simple YAML-only agent
128
+ │ ├── my-chat.yaml # Agent with TypeScript code-behind
129
+ │ ├── my-chat.ts # TypeScript implementation
130
+ │ ├── calculator/
131
+ │ │ └── calculator.yaml # Agent in subdirectory
132
+ │ └── translator-custom/
133
+ │ └── translator-custom.yaml # Override built-in
134
+
135
+ └── packages/beddel/src/agents/ # Built-in agents (package)
136
+ ├── joker-agent.yaml
137
+ ├── translator-agent.yaml
138
+ └── image-agent.yaml
139
+ ```
110
140
 
111
- The code that backs this README lives under `packages/beddel/src` and is what the npm package exposes.
141
+ ### Agent Loading Flow
112
142
 
113
- ## Package map
143
+ ```
144
+ ┌─────────────────────────────────────────────────────────────┐
145
+ │ Agent Loading Sequence │
146
+ │ │
147
+ │ 1. AgentRegistry constructor() │
148
+ │ │ │
149
+ │ ├──▶ 2. registerBuiltinAgents() │
150
+ │ │ ├── joker.execute │
151
+ │ │ ├── translator.execute │
152
+ │ │ └── image.generate │
153
+ │ │ │
154
+ │ └──▶ 3. loadCustomAgents() │
155
+ │ │ │
156
+ │ ├── Recursively scans /agents/**/*.yaml │
157
+ │ │ └── Registers each agent │
158
+ │ │ └── Custom agents override built-ins │
159
+ │ │ │
160
+ │ └── Scans /agents/**/*.ts │
161
+ │ └── Dynamically imports TypeScript modules │
162
+ │ └── Registers exported functions │
163
+ │ │
164
+ │ Priority: Custom Agents > Built-in Agents │
165
+ └─────────────────────────────────────────────────────────────┘
166
+ ```
114
167
 
115
- | Capability | Entry point / module | Notes |
116
- | --- | --- | --- |
117
- | Secure YAML parsing | `SecureYamlParser` (`src/parser/secure-yaml-parser.ts`) | FAILSAFE schema, depth/size limits, UTF-8 validation, sync + async helpers. |
118
- | Sandboxed execution | `IsolatedRuntimeManager`, `SimpleIsolatedRuntimeManager` (`src/runtime`) | Uses `isolated-vm` with configurable security profiles, pool management, metrics. |
119
- | Declarative YAML interpretation | `DeclarativeAgentInterpreter`, `AgentRegistry` (`src/runtime/declarativeAgentRuntime.ts`, `src/agents/agentRegistry.ts`) | Executes YAML agents with variables plus `output-generator`, `genkit-joke`, `genkit-translation` e `genkit-image` steps (Gemini Flash). |
120
- | Security posture | `SecurityScanner`, `ThreatDetectionEngine`, validation utilities (`src/security`) | Static scanning, scoring, and threat inference the rest of the package consumes. |
121
- | Compliance & audit | `GDPRCompliance`, `LGPDCompliance`, `AuditTrail`, `AuditService` (`src/compliance`, `src/audit`, `src/runtime/audit.ts`) | Hash-based logging, anonymization helpers, compliance verification. |
122
- | Performance & autoscaling | `PerformanceMonitor`, `AutoScaler`, benchmarking helpers (`src/performance`) | Track execution time/memory, raise violations, recommend scaling actions. |
123
- | Firebase multi-tenancy | `MultiTenantFirebaseManager` (`src/firebase/tenantManager.ts`) | Per-tenant app bootstrap, isolation policies, audit logging hooks. |
168
+ ### Creating a Custom Agent
124
169
 
125
- Everything is re-exported via `src/index.ts`, so you can import from `beddel` directly.
170
+ 1. **Create the YAML file** in `/agents`:
126
171
 
127
- ## Installation
172
+ ```yaml
173
+ # agents/greeting.yaml
174
+ agent:
175
+ id: greeting
176
+ version: 1.0.0
177
+ protocol: beddel-declarative-protocol/v2.0
128
178
 
129
- ```bash
130
- npm install beddel
179
+ metadata:
180
+ name: "Greeting Agent"
181
+ description: "Generates personalized greetings"
182
+ category: "utility"
183
+ route: "/agents/greeting"
184
+
185
+ schema:
186
+ input:
187
+ type: "object"
188
+ properties:
189
+ name:
190
+ type: "string"
191
+ minLength: 1
192
+ maxLength: 100
193
+ required: ["name"]
194
+
195
+ output:
196
+ type: "object"
197
+ properties:
198
+ greeting:
199
+ type: "string"
200
+ required: ["greeting"]
201
+
202
+ logic:
203
+ workflow:
204
+ - name: "generate-greeting"
205
+ type: "genkit-joke"
206
+ action:
207
+ type: "joke"
208
+ prompt: "Create a warm, friendly greeting for {{name}}"
209
+ result: "greetingResult"
210
+
211
+ output:
212
+ schema:
213
+ greeting: "$greetingResult.texto"
131
214
  ```
132
215
 
133
- Ensure Node.js 18+ (per `package.json`) and install optional peer dependencies you plan to use (e.g., `firebase-admin` is already included).
216
+ 2. **The agent is automatically registered** when your application starts.
134
217
 
135
- ## Project-agnostic guarantees
218
+ 3. **Execute via GraphQL or directly**:
136
219
 
137
- - No upstream app files are required—the npm tarball only ships `dist/` and the audited TypeScript sources exported through `beddel`.
138
- - `ExecutionContext` and every runtime type live inside the package, de-coupling consumers from any upstream monorepo or example app internals.
139
- - No secrets, API tokens, or environment-specific constants are embedded in the code or build output; everything is configured via your own runtime props.
140
- - Optional tools (Firebase, Upstash, benchmarking scripts) are defensive helpers; you decide which ones to instantiate depending on project size.
220
+ ```graphql
221
+ mutation {
222
+ executeMethod(
223
+ methodName: "greeting.execute"
224
+ params: { name: "Alice" }
225
+ props: { gemini_api_key: "your-api-key" }
226
+ ) {
227
+ success
228
+ data
229
+ }
230
+ }
231
+ ```
232
+
233
+ ### Custom Agents with TypeScript Code-Behind
141
234
 
142
- ## Usage examples
235
+ For more complex logic, create custom agents with TypeScript implementations:
143
236
 
144
- ### Parse YAML with strict fail-safes
237
+ #### 1. Create the TypeScript implementation:
145
238
 
146
239
  ```typescript
147
- import { SecureYamlParser } from "beddel";
240
+ // agents/my-chat.ts
241
+ export const chatHandler = async ({ input, variables, context }) => {
242
+ // Full TypeScript power available here
243
+ context.log("Processing chat message with custom TypeScript logic");
244
+
245
+ const message = input.message || "";
246
+ const history = input.messages || [];
247
+
248
+ // Add user message to history
249
+ history.push({ role: "user", content: message });
250
+
251
+ // Your custom logic here - call external APIs, use Beddel helpers, etc.
252
+ const response = `Processed: "${message}"`;
253
+
254
+ history.push({ role: "assistant", content: response });
255
+
256
+ return {
257
+ response,
258
+ history,
259
+ timestamp: new Date().toISOString()
260
+ };
261
+ };
262
+ ```
148
263
 
149
- const parser = new SecureYamlParser({
150
- maxDepth: 200,
151
- filename: "agent-manifest",
152
- });
264
+ #### 2. Create the YAML configuration:
153
265
 
154
- const manifest = parser.parseSecure(`
266
+ ```yaml
267
+ # agents/my-chat.yaml
155
268
  agent:
156
- id: joker
269
+ id: my-chat
270
+ version: 1.0.0
271
+ protocol: beddel-declarative-protocol/v2.0
272
+
273
+ metadata:
274
+ name: "Custom Chat Agent"
275
+ description: "Chat agent with TypeScript code-behind"
276
+ route: "/agents/my-chat"
277
+
157
278
  schema:
158
- input: {}
159
- output: {}
279
+ input:
280
+ type: "object"
281
+ properties:
282
+ message:
283
+ type: "string"
284
+ minLength: 1
285
+ required: ["message"]
286
+
287
+ output:
288
+ type: "object"
289
+ properties:
290
+ response:
291
+ type: "string"
292
+ required: ["response"]
293
+
160
294
  logic:
161
295
  workflow:
162
- - name: noop
163
- type: output-generator
296
+ - name: process
297
+ type: custom-action
164
298
  action:
165
- type: generate
166
- output:
167
- response: "lol"
168
- `);
299
+ function: "my-chat/chatHandler" # Format: filename/exportedFunctionName
300
+ result: response
169
301
 
170
- console.log(manifest.agent.id); // joker
302
+ output:
303
+ schema:
304
+ response: "$response.response"
171
305
  ```
172
306
 
173
- Behind the scenes, `SecureYamlParser` enforces depth, size, UTF-8, and allowed primitive types before returning the parsed object.
307
+ #### 3. Function Arguments
174
308
 
175
- ### Execute JavaScript in an isolate
309
+ Custom functions receive a standardized arguments object:
176
310
 
177
311
  ```typescript
178
- import { IsolatedRuntimeManager } from "beddel";
312
+ {
313
+ input: Record<string, any>, // Validated input from the request
314
+ variables: Record<string, any>, // Current workflow variables
315
+ action: Record<string, any>, // Action configuration from YAML
316
+ context: ExecutionContext // Logging and error handling
317
+ }
318
+ ```
179
319
 
180
- const runtimeManager = new IsolatedRuntimeManager();
320
+ ### Overriding Built-in Agents
181
321
 
182
- const result = await runtimeManager.execute({
183
- code: `
184
- const secret = "sandboxed";
185
- ({ success: true, value: secret.length });
186
- `,
187
- securityProfile: "ultra-secure",
188
- timeout: 2000,
189
- });
322
+ Create a custom agent with the same route to override a built-in:
190
323
 
191
- if (!result.success) {
192
- throw result.error;
193
- }
324
+ ```yaml
325
+ # agents/joker-custom.yaml
326
+ agent:
327
+ id: joker
328
+ protocol: beddel-declarative-protocol/v2.0
194
329
 
195
- console.log(result.result); // { success: true, value: 9 }
330
+ metadata:
331
+ route: "/agents/joker" # Same route overrides built-in
332
+ # ... your custom implementation
196
333
  ```
197
334
 
198
- The manager bootstraps `isolated-vm` contexts, strips dangerous globals (`require`, `eval`, timers), enforces memory/time limits, records metrics, and can emit audit/security signals.
335
+ ---
336
+
337
+ ## Built-in Agents
199
338
 
200
- ### Interpret a declarative YAML agent
339
+ | Agent | Method | Description | Required Props |
340
+ |-------|--------|-------------|----------------|
341
+ | **Joker** | `joker.execute` | Generates short, original jokes | `gemini_api_key` |
342
+ | **Translator** | `translator.execute` | Translates text between languages | `gemini_api_key` |
343
+ | **Image Generator** | `image.generate` | Creates images (watercolor, neon, sketch) | `gemini_api_key` |
344
+
345
+ ### Joker Agent
201
346
 
202
347
  ```typescript
203
- import { DeclarativeAgentInterpreter } from "beddel";
204
- import { readFileSync } from "node:fs";
205
- import { join } from "node:path";
206
-
207
- const interpreter = new DeclarativeAgentInterpreter();
208
- const yamlContent = readFileSync(join(process.cwd(), "joker-agent.yaml"), "utf8");
209
-
210
- const result = await interpreter.interpret({
211
- yamlContent,
212
- input: {},
213
- props: {},
214
- context: {
215
- log: console.log,
216
- setError: console.error,
348
+ const result = await agentRegistry.executeAgent(
349
+ "joker.execute",
350
+ {},
351
+ { gemini_api_key: "..." },
352
+ context
353
+ );
354
+ // Returns: { response: "Why did the..." }
355
+ ```
356
+
357
+ ### Translator Agent
358
+
359
+ ```typescript
360
+ const result = await agentRegistry.executeAgent(
361
+ "translator.execute",
362
+ {
363
+ texto: "Hello, world!",
364
+ idioma_origem: "en",
365
+ idioma_destino: "pt"
217
366
  },
218
- });
367
+ { gemini_api_key: "..." },
368
+ context
369
+ );
370
+ // Returns: { texto_traduzido: "Olá, mundo!", metadados: {...} }
371
+ ```
372
+
373
+ ### Image Generator Agent
219
374
 
220
- console.log(result.response); // lol
375
+ ```typescript
376
+ const result = await agentRegistry.executeAgent(
377
+ "image.generate",
378
+ {
379
+ descricao: "A sunset over mountains",
380
+ estilo: "watercolor",
381
+ resolucao: "1024x1024"
382
+ },
383
+ { gemini_api_key: "..." },
384
+ context
385
+ );
386
+ // Returns: { image_url, image_base64, media_type, ... }
221
387
  ```
222
388
 
223
- Current interpreter capabilities:
389
+ ---
224
390
 
225
- - Validates protocol (`beddel-declarative-protocol/v2.0`), schema presence, workflow size.
226
- - Supports string/number/boolean/object variables and literal/variable references.
227
- - Executes `output-generator` workflow steps that map variables to response objects.
391
+ ## Core Components
228
392
 
229
- For projects that want auto-registration, instantiate `AgentRegistry` (bundled with the `joker` agent) and call `executeAgent("joker.execute", …)`.
393
+ ### Package Map
230
394
 
231
- ### Automatic schema validation
395
+ | Capability | Module | Description |
396
+ |------------|--------|-------------|
397
+ | **YAML Parsing** | `SecureYamlParser` | FAILSAFE schema, depth/size limits, UTF-8 validation |
398
+ | **Sandboxed Execution** | `IsolatedRuntimeManager` | `isolated-vm` with security profiles |
399
+ | **Agent Interpretation** | `DeclarativeAgentInterpreter` | Executes YAML agents with Genkit |
400
+ | **Agent Registry** | `AgentRegistry` | Manages built-in and custom agents |
401
+ | **Security** | `SecurityScanner`, `ThreatDetectionEngine` | Static scanning, scoring |
402
+ | **Compliance** | `GDPRCompliance`, `LGPDCompliance` | Audit, anonymization |
403
+ | **Performance** | `PerformanceMonitor`, `AutoScaler` | Metrics, scaling |
404
+ | **Multi-tenancy** | `MultiTenantFirebaseManager` | Firebase tenant isolation |
232
405
 
233
- Every declarative agent must now declare `schema.input` and `schema.output` blocks that map directly to Zod primitives (`string`, `number`, `boolean`), objects (with `properties` + `required` arrays), and arrays (via `items`). The runtime compiles those YAML definitions into Zod schemas through the `DeclarativeSchemaCompiler`, caches the result per manifest, and runs validation twice per execution:
406
+ ### Secure YAML Parsing
234
407
 
235
- - **Before workflow execution** – payloads that are missing required fields, contain unexpected properties (objects are `strict` by default), or provide the wrong primitive types raise a `DeclarativeSchemaValidationError` and call `ExecutionContext.setError`.
236
- - **Before returning output** the workflow result must match `schema.output`; mismatches are rejected, the error propagates through the same structured exception, and oversize payloads (>1 MB) are blocked.
408
+ ```typescript
409
+ import { SecureYamlParser } from "beddel";
237
410
 
238
- Authors can opt into arrays by adding `type: "array"` + an `items` definition, mark optional fields by omitting them from `required`, and set `additionalProperties: true` only when extra keys should be allowed. Errors surface in GraphQL responses (and logs) as `Input validation failed: …` or `Output validation failed: …`, making it obvious which path failed.
411
+ const parser = new SecureYamlParser({
412
+ maxDepth: 200,
413
+ filename: "agent-manifest",
414
+ });
239
415
 
240
- ### Parse + execute inside the secure runtime
416
+ const manifest = parser.parseSecure(yamlContent);
417
+ ```
241
418
 
242
- Combine the parser, security scanner, and isolate manager through `SecureYamlRuntime`:
419
+ ### Sandboxed Execution
243
420
 
244
421
  ```typescript
245
- import { SecureYamlRuntime, IsolatedRuntimeManager } from "beddel";
422
+ import { IsolatedRuntimeManager } from "beddel";
423
+
424
+ const runtime = new IsolatedRuntimeManager();
246
425
 
247
- const runtime = new SecureYamlRuntime(new IsolatedRuntimeManager());
248
- const { success, result } = await runtime.parseYamlSecureRuntime(someYamlString, {
249
- tenantId: "tenant-123",
250
- securityProfile: "tenant-isolated",
251
- validateSecurity: true,
426
+ const result = await runtime.execute({
427
+ code: `({ value: 42 })`,
428
+ securityProfile: "ultra-secure",
429
+ timeout: 2000,
252
430
  });
253
431
  ```
254
432
 
255
- The helper performs pre-scan checks, runs within the requested profile, enforces performance targets, and produces audit hashes you can persist.
433
+ ### Agent Registry API
256
434
 
257
- ## Architectural reference
435
+ ```typescript
436
+ import { agentRegistry } from "beddel";
258
437
 
259
- - `src/parser`: Secure YAML parsing primitives.
260
- - `src/runtime`: `IsolatedRuntimeManager`, `SimpleIsolatedRuntimeManager`, auditing utilities, declarative interpreter, monitoring, and security hooks.
261
- - `src/security`: Validation, scoring, threat detection, dashboards.
262
- - `src/compliance`: GDPR/LGPD tooling, anonymization, export helpers.
263
- - `src/performance`: Monitoring, autoscaling, streaming metrics.
264
- - `src/firebase`: Tenant isolation via Firebase Admin SDK.
265
- - `src/agents`: Registry helpers and sample `joker-agent.yaml`.
266
- - `src/integration`: Glue code that wires parsing + runtime + scanner.
438
+ // Get all registered agents
439
+ const agents = agentRegistry.getAllAgents();
267
440
 
268
- Every module is documented inline with TypeScript types to make IDE discovery straightforward.
441
+ // Get a specific agent
442
+ const agent = agentRegistry.getAgent("joker.execute");
269
443
 
270
- ## Development workflow
444
+ // Execute an agent
445
+ const result = await agentRegistry.executeAgent(
446
+ "joker.execute",
447
+ input,
448
+ props,
449
+ context
450
+ );
271
451
 
272
- ```bash
273
- # Build the package
274
- pnpm --filter beddel build
452
+ // Load custom agents from a specific path
453
+ agentRegistry.loadCustomAgents("/path/to/custom/agents");
454
+ ```
275
455
 
276
- # Lint and test
277
- pnpm --filter beddel lint
278
- pnpm --filter beddel test
456
+ ---
457
+
458
+ ## Schema Validation
459
+
460
+ All agents must declare `schema.input` and `schema.output` blocks. The runtime compiles these into Zod schemas and validates:
461
+
462
+ - **Before execution**: Input must match `schema.input`
463
+ - **After execution**: Output must match `schema.output`
464
+
465
+ ```yaml
466
+ schema:
467
+ input:
468
+ type: "object"
469
+ properties:
470
+ name:
471
+ type: "string"
472
+ minLength: 1
473
+ maxLength: 100
474
+ age:
475
+ type: "number"
476
+ required: ["name"]
477
+
478
+ output:
479
+ type: "object"
480
+ properties:
481
+ greeting:
482
+ type: "string"
483
+ required: ["greeting"]
484
+ ```
485
+
486
+ Supported types: `string`, `number`, `boolean`, `object`, `array`
487
+
488
+ ---
489
+
490
+ ## Security
491
+
492
+ ### Multi-Layer Security Model
493
+
494
+ 1. **Parser Layer**: FAILSAFE schema, size limits, sanitization
495
+ 2. **Runtime Layer**: V8 isolate, memory limits, timeouts
496
+ 3. **Application Layer**: Authentication, rate limiting, tenant isolation
497
+
498
+ ### Security Profiles
499
+
500
+ ```typescript
501
+ const result = await runtime.execute({
502
+ code: userCode,
503
+ securityProfile: "tenant-isolated", // ultra-secure | tenant-isolated
504
+ timeout: 5000,
505
+ memoryLimit: 128,
506
+ });
279
507
  ```
280
508
 
281
- When contributing, keep README + `AGENTS.md` synchronized with any new exports or behavioral changes in `src`.
509
+ ---
282
510
 
283
- ## Docs/beddel roadmap coverage
511
+ ## Project Structure
284
512
 
285
- The product briefs under `docs/beddel` describe a richer future-state language/runtime. The current package intentionally ships a smaller, auditable subset. Notable gaps you will still find only in documentation:
513
+ ```
514
+ src/
515
+ ├── agents/ # Agent registry and built-in agents
516
+ │ ├── agentRegistry.ts # Agent management
517
+ │ ├── joker-agent.yaml # Built-in: Joker
518
+ │ ├── translator-agent.yaml
519
+ │ └── image-agent.yaml
520
+ ├── parser/ # Secure YAML parsing
521
+ ├── runtime/ # Execution environments
522
+ │ ├── isolatedRuntime.ts
523
+ │ ├── declarativeAgentRuntime.ts
524
+ │ └── schemaCompiler.ts
525
+ ├── security/ # Scanning and threat detection
526
+ ├── compliance/ # GDPR/LGPD utilities
527
+ ├── performance/ # Monitoring and autoscaling
528
+ ├── firebase/ # Multi-tenant management
529
+ └── index.ts # Public exports
530
+ ```
286
531
 
287
- - **Advanced declarative language constructs** (`map-filter-reduce` pipelines, state machines, rule engines, temporal conditions, and loop semantics) are not implemented yet—the interpreter only supports literal variables and `output-generator` steps.
288
- - **Behavior marketplace & registry extensibility** (behaviors with versions, capabilities, restrictions, and monetization hooks) are not available. Only the bundled `joker` agent is registered by default.
289
- - **Automatic behavioral integrations and external API pipelines** (`integrations`, `decisions`, `behaviors` blocks described in `docs/beddel/brief.md`) have no runtime support.
290
- - **Marketplace/compliance automation flows** mentioned in the PRD (pre-built business behaviors, Firebase deployment recipes, global consent orchestration) are still roadmap items, even though compliance helpers exist as standalone utilities.
291
- - **High-level orchestration features** like parallel execution controls, resource policies (per-step concurrency, retry semantics), and auto-generated documentation have not been wired into the runtime.
532
+ ---
533
+
534
+ ## Development
535
+
536
+ ```bash
537
+ # Build
538
+ pnpm --filter beddel build
539
+
540
+ # Test
541
+ pnpm --filter beddel test
542
+
543
+ # Lint
544
+ pnpm --filter beddel lint
545
+ ```
292
546
 
293
- Use this section as a living checklist whenever you pull features from `docs/beddel` into the actual codebase.
547
+ ---
294
548
 
295
549
  ## License
296
550
 
297
- This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
551
+ MIT License. See [LICENSE](LICENSE) for details.