beddel 1.0.3 β†’ 1.0.4

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 (41) hide show
  1. package/README.md +39 -29
  2. package/dist/agents/assistant-bedrock.yaml +1 -2
  3. package/dist/agents/assistant-openrouter.yaml +1 -2
  4. package/dist/agents/assistant.yaml +1 -2
  5. package/dist/agents/index.d.ts +1 -1
  6. package/dist/agents/index.d.ts.map +1 -1
  7. package/dist/agents/index.js +2 -0
  8. package/dist/agents/multi-step-assistant.yaml +67 -0
  9. package/dist/agents/text-generator.yaml +27 -0
  10. package/dist/primitives/call-agent.d.ts +28 -0
  11. package/dist/primitives/call-agent.d.ts.map +1 -0
  12. package/dist/primitives/call-agent.js +79 -0
  13. package/dist/primitives/chat.d.ts +26 -0
  14. package/dist/primitives/chat.d.ts.map +1 -0
  15. package/dist/primitives/chat.js +63 -0
  16. package/dist/primitives/index.d.ts +9 -15
  17. package/dist/primitives/index.d.ts.map +1 -1
  18. package/dist/primitives/index.js +24 -34
  19. package/dist/primitives/llm-core.d.ts +45 -0
  20. package/dist/primitives/llm-core.d.ts.map +1 -0
  21. package/dist/primitives/llm-core.js +43 -0
  22. package/dist/primitives/llm.d.ts +12 -41
  23. package/dist/primitives/llm.d.ts.map +1 -1
  24. package/dist/primitives/llm.js +27 -133
  25. package/docs/architecture/api-reference.md +134 -102
  26. package/docs/architecture/components.md +130 -133
  27. package/docs/architecture/core-workflows.md +146 -129
  28. package/docs/architecture/high-level-architecture.md +19 -12
  29. package/docs/architecture/source-tree.md +60 -34
  30. package/package.json +1 -1
  31. package/src/agents/assistant-bedrock.yaml +1 -2
  32. package/src/agents/assistant-openrouter.yaml +1 -2
  33. package/src/agents/assistant.yaml +1 -2
  34. package/src/agents/index.ts +2 -0
  35. package/src/agents/multi-step-assistant.yaml +67 -0
  36. package/src/agents/text-generator.yaml +27 -0
  37. package/src/primitives/call-agent.ts +108 -0
  38. package/src/primitives/chat.ts +84 -0
  39. package/src/primitives/index.ts +25 -38
  40. package/src/primitives/llm-core.ts +77 -0
  41. package/src/primitives/llm.ts +28 -178
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Beddel Protocol
2
2
 
3
3
  [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
4
- [![npm version](https://img.shields.io/badge/npm-1.0.0-brightgreen.svg)](https://www.npmjs.com/package/beddel)
4
+ [![npm version](https://img.shields.io/badge/npm-1.0.4-brightgreen.svg)](https://www.npmjs.com/package/beddel)
5
5
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue.svg)](https://www.typescriptlang.org/)
6
6
  [![AI SDK](https://img.shields.io/badge/AI%20SDK-v6-purple.svg)](https://sdk.vercel.ai/)
7
7
 
@@ -10,11 +10,12 @@
10
10
  ## Features
11
11
 
12
12
  - πŸ”„ **Sequential Pipeline Execution** β€” Define workflows as YAML, execute steps in order
13
- - 🌊 **Native Streaming** β€” First-class `streamText` support with `useChat` compatibility
13
+ - 🌊 **Native Streaming** β€” First-class `streamText` support via `chat` primitive with `useChat` compatibility
14
14
  - πŸ”Œ **Extensible Primitives** β€” Register custom step types, tools, and callbacks
15
15
  - πŸ”’ **Security First** β€” YAML parsing with `FAILSAFE_SCHEMA` prevents code execution
16
16
  - πŸ“¦ **Bundle Separation** β€” Three entry points for server, client, and full API access
17
17
  - 🌐 **Multi-Provider** β€” Built-in support for Google Gemini, Amazon Bedrock, and OpenRouter (400+ models)
18
+ - πŸ”€ **Semantic Primitives** β€” `chat` for streaming frontend, `llm` for blocking workflows
18
19
 
19
20
  ## Installation
20
21
 
@@ -51,11 +52,10 @@ metadata:
51
52
 
52
53
  workflow:
53
54
  - id: "chat-interaction"
54
- type: "llm"
55
+ type: "chat"
55
56
  config:
56
57
  provider: "google"
57
58
  model: "gemini-2.0-flash-exp"
58
- stream: true
59
59
  system: "You are a helpful assistant."
60
60
  messages: "$input.messages"
61
61
  ```
@@ -71,17 +71,34 @@ metadata:
71
71
 
72
72
  workflow:
73
73
  - id: "chat"
74
- type: "llm"
74
+ type: "chat"
75
75
  config:
76
76
  provider: "bedrock"
77
77
  model: "us.meta.llama3-2-1b-instruct-v1:0"
78
- stream: true
79
78
  system: |
80
79
  You are a helpful, friendly assistant. Be concise and direct.
81
80
  Answer in the same language the user writes to you.
82
81
  messages: "$input.messages"
83
82
  ```
84
83
 
84
+ #### Example 3: OpenRouter (400+ Models)
85
+
86
+ ```yaml
87
+ # src/agents/assistant-openrouter.yaml
88
+ metadata:
89
+ name: "OpenRouter Assistant"
90
+ version: "1.0.0"
91
+
92
+ workflow:
93
+ - id: "chat"
94
+ type: "chat"
95
+ config:
96
+ provider: "openrouter"
97
+ model: "qwen/qwen3-14b:free" # or any model from openrouter.ai/models
98
+ system: "You are a helpful assistant."
99
+ messages: "$input.messages"
100
+ ```
101
+
85
102
  ### 3. Set Environment Variables
86
103
 
87
104
  ```bash
@@ -94,6 +111,9 @@ AWS_BEARER_TOKEN_BEDROCK=your_bedrock_api_key
94
111
  # Or use standard AWS credentials:
95
112
  # AWS_ACCESS_KEY_ID=your_access_key
96
113
  # AWS_SECRET_ACCESS_KEY=your_secret_key
114
+
115
+ # For OpenRouter
116
+ OPENROUTER_API_KEY=your_openrouter_api_key
97
117
  ```
98
118
 
99
119
  ### 4. Use with React (useChat)
@@ -132,25 +152,6 @@ export default function Chat() {
132
152
 
133
153
  > **Note:** The Bedrock provider requires `AWS_REGION` to be set (defaults to `us-east-1` if not provided).
134
154
 
135
- ### Example: OpenRouter (400+ Models)
136
-
137
- ```yaml
138
- # src/agents/assistant-openrouter.yaml
139
- metadata:
140
- name: "OpenRouter Assistant"
141
- version: "1.0.0"
142
-
143
- workflow:
144
- - id: "chat"
145
- type: "llm"
146
- config:
147
- provider: "openrouter"
148
- model: "qwen/qwen3-14b:free" # or any model from openrouter.ai/models
149
- stream: true
150
- system: "You are a helpful assistant."
151
- messages: "$input.messages"
152
- ```
153
-
154
155
  ## Entry Points
155
156
 
156
157
  | Import Path | Purpose | Environment |
@@ -208,10 +209,9 @@ metadata:
208
209
 
209
210
  workflow:
210
211
  - id: "step-1"
211
- type: "llm"
212
+ type: "chat" # or "llm" for non-streaming workflows
212
213
  config:
213
214
  model: "gemini-2.0-flash-exp"
214
- stream: true
215
215
  system: "System prompt"
216
216
  messages: "$input.messages"
217
217
  tools:
@@ -220,6 +220,15 @@ workflow:
220
220
  result: "stepOutput"
221
221
  ```
222
222
 
223
+ ### Primitive Types
224
+
225
+ | Type | Behavior | Use Case |
226
+ |------|----------|----------|
227
+ | `chat` | Always streaming, converts UIMessage | Frontend chat interfaces (`useChat`) |
228
+ | `llm` | Never streaming, returns complete result | Multi-step workflows, variable passing |
229
+ | `call-agent` | Invokes another agent | Sub-agent orchestration |
230
+ | `output-generator` | JSON template transform | Structured output generation |
231
+
223
232
  ### Variable Resolution
224
233
 
225
234
  | Pattern | Description | Example |
@@ -240,8 +249,9 @@ Beddel is fully compatible with Vercel AI SDK v6:
240
249
 
241
250
  - **Frontend:** `useChat` sends `UIMessage[]` with `{ parts: [...] }` format
242
251
  - **Backend:** `streamText`/`generateText` expects `ModelMessage[]` with `{ content: ... }`
243
- - **Automatic Conversion:** `convertToModelMessages()` bridges the gap
244
- - **Streaming:** `toUIMessageStreamResponse()` returns the correct format for `useChat`
252
+ - **Automatic Conversion:** `chat` primitive uses `convertToModelMessages()` to bridge the gap
253
+ - **Streaming:** `chat` primitive returns `toUIMessageStreamResponse()` for `useChat`
254
+ - **Blocking:** `llm` primitive uses `generateText()` for workflow steps
245
255
 
246
256
  ## Technology Stack
247
257
 
@@ -9,11 +9,10 @@ metadata:
9
9
 
10
10
  workflow:
11
11
  - id: "chat"
12
- type: "llm"
12
+ type: "chat"
13
13
  config:
14
14
  provider: "bedrock"
15
15
  model: "us.meta.llama3-2-1b-instruct-v1:0"
16
- stream: true
17
16
  system: |
18
17
  You are a helpful, friendly assistant. Be concise and direct.
19
18
  Answer in the same language the user writes to you.
@@ -8,10 +8,9 @@ metadata:
8
8
 
9
9
  workflow:
10
10
  - id: "chat-interaction"
11
- type: "llm"
11
+ type: "chat"
12
12
  config:
13
13
  provider: "openrouter"
14
14
  model: "qwen/qwen3-coder:free"
15
- stream: true
16
15
  system: "You are a helpful assistant."
17
16
  messages: "$input.messages"
@@ -8,10 +8,9 @@ metadata:
8
8
 
9
9
  workflow:
10
10
  - id: "chat-interaction"
11
- type: "llm"
11
+ type: "chat"
12
12
  config:
13
13
  provider: "google"
14
14
  model: "gemini-2.0-flash-exp"
15
- stream: true
16
15
  system: "You are a helpful assistant."
17
16
  messages: "$input.messages"
@@ -7,7 +7,7 @@
7
7
  /**
8
8
  * List of built-in agent IDs available in the package
9
9
  */
10
- export declare const BUILTIN_AGENTS: readonly ["assistant", "assistant-bedrock", "assistant-openrouter"];
10
+ export declare const BUILTIN_AGENTS: readonly ["assistant", "assistant-bedrock", "assistant-openrouter", "text-generator", "multi-step-assistant"];
11
11
  export type BuiltinAgentId = typeof BUILTIN_AGENTS[number];
12
12
  /**
13
13
  * Get the absolute path to the built-in agents directory
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/agents/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AASH;;GAEG;AACH,eAAO,MAAM,cAAc,qEAIjB,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG,OAAO,cAAc,CAAC,MAAM,CAAC,CAAC;AAE3D;;GAEG;AACH,wBAAgB,oBAAoB,IAAI,MAAM,CAE7C;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,IAAI,cAAc,CAEzE;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,cAAc,GAAG,MAAM,CAEnE"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/agents/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AASH;;GAEG;AACH,eAAO,MAAM,cAAc,+GAMjB,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG,OAAO,cAAc,CAAC,MAAM,CAAC,CAAC;AAE3D;;GAEG;AACH,wBAAgB,oBAAoB,IAAI,MAAM,CAE7C;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,IAAI,cAAc,CAEzE;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,cAAc,GAAG,MAAM,CAEnE"}
@@ -16,6 +16,8 @@ export const BUILTIN_AGENTS = [
16
16
  'assistant',
17
17
  'assistant-bedrock',
18
18
  'assistant-openrouter',
19
+ 'text-generator',
20
+ 'multi-step-assistant',
19
21
  ];
20
22
  /**
21
23
  * Get the absolute path to the built-in agents directory
@@ -0,0 +1,67 @@
1
+ # Multi-Step Text Analyzer
2
+ # Pipeline: Generate Text β†’ Extract Entities β†’ Classify Sentiment β†’ Structured Summary
3
+
4
+ metadata:
5
+ name: "Multi-Step Text Analyzer"
6
+ version: "1.0.0"
7
+ builtin: true
8
+ description: "4-step pipeline demonstrating variable passing between steps"
9
+
10
+ workflow:
11
+ # Step 1: Generate sample text using text-generator agent
12
+ # Input: { messages: [{ role: "user", content: "Generate 200 chars about space exploration" }] }
13
+ - id: "generate-text"
14
+ type: "call-agent"
15
+ config:
16
+ agentId: "text-generator"
17
+ input:
18
+ messages: "$input.messages"
19
+ result: "generatedText"
20
+
21
+ # Step 2: Extract entities and topics from the generated text
22
+ - id: "extract-entities"
23
+ type: "llm"
24
+ config:
25
+ provider: "google"
26
+ model: "gemini-2.0-flash-exp"
27
+ system: |
28
+ You are an entity extraction specialist. Analyze the given text and extract:
29
+ - Named entities (people, places, organizations, dates)
30
+ - Main topics/themes
31
+ - Key concepts
32
+
33
+ Output ONLY valid JSON (no markdown, no explanation):
34
+ {"entities":{"people":[],"places":[],"organizations":[],"dates":[]},"topics":[],"concepts":[]}
35
+ messages:
36
+ - role: "user"
37
+ content: "$stepResult.generatedText.generatedText.text"
38
+ result: "entities"
39
+
40
+ # Step 3: Classify sentiment of the text
41
+ - id: "classify-sentiment"
42
+ type: "llm"
43
+ config:
44
+ provider: "google"
45
+ model: "gemini-2.0-flash-exp"
46
+ system: |
47
+ You are a sentiment analysis expert. Analyze the emotional tone of the text.
48
+
49
+ Output ONLY valid JSON (no markdown, no explanation):
50
+ {"overall":"positive|negative|neutral|mixed","confidence":0.8,"emotions":["joy"],"tone":"formal"}
51
+ messages:
52
+ - role: "user"
53
+ content: "$stepResult.generatedText.generatedText.text"
54
+ result: "sentiment"
55
+
56
+ # Step 4: Generate structured summary combining all analysis
57
+ - id: "final-summary"
58
+ type: "output-generator"
59
+ config:
60
+ template:
61
+ originalText: "$stepResult.generatedText.generatedText.text"
62
+ entities: "$stepResult.entities.text"
63
+ sentiment: "$stepResult.sentiment.text"
64
+ pipeline:
65
+ steps: 4
66
+ status: "completed"
67
+ result: "finalReport"
@@ -0,0 +1,27 @@
1
+ # Text Generator Agent
2
+ # Generates text based on length and subject parameters
3
+ # Uses lightweight model for efficiency
4
+
5
+ metadata:
6
+ name: "Text Generator"
7
+ version: "1.0.0"
8
+ builtin: true
9
+ description: "Generates text with specified length and subject"
10
+
11
+ workflow:
12
+ - id: "generate-text"
13
+ type: "llm"
14
+ config:
15
+ provider: "google"
16
+ model: "gemini-2.0-flash-exp"
17
+ system: |
18
+ You are a text generator. Generate creative, coherent text based on the given parameters.
19
+
20
+ RULES:
21
+ - Generate approximately the requested number of characters (can vary Β±20%)
22
+ - Stay focused on the given subject/theme
23
+ - Write in a natural, engaging style
24
+ - Output ONLY the generated text, no explanations or meta-commentary
25
+ - Do not use markdown formatting unless specifically requested
26
+ messages: "$input.messages"
27
+ result: "generatedText"
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Beddel Protocol - Call Agent Primitive
3
+ *
4
+ * Enables recursive workflow execution by calling other agents.
5
+ * This primitive loads and executes another agent's workflow,
6
+ * passing input and returning the result.
7
+ *
8
+ * Server-only: Uses loadYaml and WorkflowExecutor.
9
+ */
10
+ import type { PrimitiveHandler } from '../types';
11
+ /**
12
+ * Call Agent Primitive Handler
13
+ *
14
+ * Loads another agent's YAML and executes its workflow.
15
+ *
16
+ * IMPORTANT: If the called agent returns a Response (streaming),
17
+ * this primitive will return that Response, causing the parent
18
+ * workflow to also return immediately.
19
+ *
20
+ * For multi-step workflows, ensure called agents use stream: false
21
+ * so their results can be captured and passed to subsequent steps.
22
+ *
23
+ * @param config - Step configuration (agentId, input)
24
+ * @param context - Execution context with input and variables
25
+ * @returns Result from called agent (Response or Record)
26
+ */
27
+ export declare const callAgentPrimitive: PrimitiveHandler;
28
+ //# sourceMappingURL=call-agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"call-agent.d.ts","sourceRoot":"","sources":["../../src/primitives/call-agent.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAgC,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAwD/E;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,kBAAkB,EAAE,gBAyBhC,CAAC"}
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Beddel Protocol - Call Agent Primitive
3
+ *
4
+ * Enables recursive workflow execution by calling other agents.
5
+ * This primitive loads and executes another agent's workflow,
6
+ * passing input and returning the result.
7
+ *
8
+ * Server-only: Uses loadYaml and WorkflowExecutor.
9
+ */
10
+ import { loadYaml } from '../core/parser';
11
+ import { WorkflowExecutor } from '../core/workflow';
12
+ import { resolveVariables } from '../core/variable-resolver';
13
+ import { join } from 'path';
14
+ import { access } from 'fs/promises';
15
+ import { getBuiltinAgentsPath } from '../agents';
16
+ /**
17
+ * Check if a file exists at the given path
18
+ */
19
+ async function fileExists(path) {
20
+ try {
21
+ await access(path);
22
+ return true;
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ /**
29
+ * Resolve agent path with fallback chain:
30
+ * 1. User agents (agentsPath) - allows override
31
+ * 2. Built-in agents (package) - fallback
32
+ */
33
+ async function resolveAgentPath(agentId, agentsPath) {
34
+ // 1. First: try user agents
35
+ const userPath = join(process.cwd(), agentsPath, `${agentId}.yaml`);
36
+ if (await fileExists(userPath)) {
37
+ return userPath;
38
+ }
39
+ // 2. Fallback: built-in agents from package
40
+ const builtinPath = join(getBuiltinAgentsPath(), `${agentId}.yaml`);
41
+ if (await fileExists(builtinPath)) {
42
+ return builtinPath;
43
+ }
44
+ throw new Error(`[Beddel] Agent not found: ${agentId}`);
45
+ }
46
+ /**
47
+ * Call Agent Primitive Handler
48
+ *
49
+ * Loads another agent's YAML and executes its workflow.
50
+ *
51
+ * IMPORTANT: If the called agent returns a Response (streaming),
52
+ * this primitive will return that Response, causing the parent
53
+ * workflow to also return immediately.
54
+ *
55
+ * For multi-step workflows, ensure called agents use stream: false
56
+ * so their results can be captured and passed to subsequent steps.
57
+ *
58
+ * @param config - Step configuration (agentId, input)
59
+ * @param context - Execution context with input and variables
60
+ * @returns Result from called agent (Response or Record)
61
+ */
62
+ export const callAgentPrimitive = async (config, context) => {
63
+ const callConfig = config;
64
+ if (!callConfig.agentId) {
65
+ throw new Error('[Beddel] call-agent requires agentId in config');
66
+ }
67
+ // Resolve the input to pass to the agent
68
+ const agentInput = callConfig.input
69
+ ? resolveVariables(callConfig.input, context)
70
+ : context.input;
71
+ // Resolve agent path
72
+ const agentsPath = callConfig.agentsPath || 'src/agents';
73
+ const agentPath = await resolveAgentPath(callConfig.agentId, agentsPath);
74
+ // Load and execute the agent
75
+ const yaml = await loadYaml(agentPath);
76
+ const executor = new WorkflowExecutor(yaml);
77
+ const result = await executor.execute(agentInput);
78
+ return result;
79
+ };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Beddel Protocol - Chat Primitive
3
+ *
4
+ * Primitive for frontend chat interfaces using useChat hook.
5
+ * ALWAYS streams responses for responsive UX.
6
+ * Expects UIMessage format (with 'parts' array) and converts to ModelMessage.
7
+ *
8
+ * Use this primitive when:
9
+ * - Input comes from useChat frontend hook
10
+ * - You need streaming responses to the client
11
+ *
12
+ * Server-only: Uses Vercel AI SDK Core.
13
+ */
14
+ import type { PrimitiveHandler } from '../types';
15
+ /**
16
+ * Chat Primitive Handler
17
+ *
18
+ * Converts UIMessage[] (from useChat) to ModelMessage[] and streams response.
19
+ * Always uses streaming mode for responsive frontend UX.
20
+ *
21
+ * @param config - Step configuration from YAML
22
+ * @param context - Execution context with input and variables
23
+ * @returns Response (always streaming)
24
+ */
25
+ export declare const chatPrimitive: PrimitiveHandler;
26
+ //# sourceMappingURL=chat.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chat.d.ts","sourceRoot":"","sources":["../../src/primitives/chat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAQH,OAAO,KAAK,EAAgC,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAK/E;;;;;;;;;GASG;AACH,eAAO,MAAM,aAAa,EAAE,gBA2C3B,CAAC"}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Beddel Protocol - Chat Primitive
3
+ *
4
+ * Primitive for frontend chat interfaces using useChat hook.
5
+ * ALWAYS streams responses for responsive UX.
6
+ * Expects UIMessage format (with 'parts' array) and converts to ModelMessage.
7
+ *
8
+ * Use this primitive when:
9
+ * - Input comes from useChat frontend hook
10
+ * - You need streaming responses to the client
11
+ *
12
+ * Server-only: Uses Vercel AI SDK Core.
13
+ */
14
+ import { streamText, convertToModelMessages, stepCountIs, } from 'ai';
15
+ import { resolveVariables } from '../core/variable-resolver';
16
+ import { createModel } from '../providers';
17
+ import { mapTools, callbackRegistry } from './llm-core';
18
+ /**
19
+ * Chat Primitive Handler
20
+ *
21
+ * Converts UIMessage[] (from useChat) to ModelMessage[] and streams response.
22
+ * Always uses streaming mode for responsive frontend UX.
23
+ *
24
+ * @param config - Step configuration from YAML
25
+ * @param context - Execution context with input and variables
26
+ * @returns Response (always streaming)
27
+ */
28
+ export const chatPrimitive = async (config, context) => {
29
+ const llmConfig = config;
30
+ const model = createModel(llmConfig.provider || 'google', {
31
+ model: llmConfig.model || 'gemini-1.5-flash',
32
+ });
33
+ // Resolve and convert UIMessage to ModelMessage
34
+ const uiMessages = resolveVariables(llmConfig.messages, context);
35
+ const messages = await convertToModelMessages(uiMessages);
36
+ const hasTools = llmConfig.tools && llmConfig.tools.length > 0;
37
+ const tools = hasTools ? mapTools(llmConfig.tools) : undefined;
38
+ const result = streamText({
39
+ model,
40
+ messages,
41
+ system: llmConfig.system,
42
+ stopWhen: hasTools ? stepCountIs(5) : undefined,
43
+ tools,
44
+ onFinish: async ({ text, finishReason, usage, totalUsage, steps, response }) => {
45
+ if (llmConfig.onFinish) {
46
+ const callback = callbackRegistry[llmConfig.onFinish];
47
+ if (callback) {
48
+ await callback({ text, finishReason, usage, totalUsage, steps, response });
49
+ }
50
+ }
51
+ },
52
+ onError: ({ error }) => {
53
+ if (llmConfig.onError) {
54
+ const callback = callbackRegistry[llmConfig.onError];
55
+ if (callback) {
56
+ callback({ error });
57
+ }
58
+ }
59
+ console.error('[Beddel] Stream error:', error);
60
+ },
61
+ });
62
+ return result.toUIMessageStreamResponse();
63
+ };
@@ -3,35 +3,29 @@
3
3
  *
4
4
  * This registry maps step types to their handler implementations.
5
5
  * Following Expansion Pack Pattern from BMAD-METHODβ„’ for extensibility.
6
- * See: https://github.com/bmadcode/bmad-method
7
6
  *
8
7
  * Server-only: Handlers may use Node.js APIs and external services.
9
8
  */
10
9
  import type { PrimitiveHandler } from '../types';
11
- export { llmPrimitive, registerCallback, callbackRegistry } from './llm';
10
+ export { registerCallback, callbackRegistry } from './llm-core';
11
+ export { chatPrimitive } from './chat';
12
+ export { llmPrimitive } from './llm';
13
+ export { callAgentPrimitive } from './call-agent';
12
14
  /**
13
15
  * Registry of primitive handlers keyed by step type.
14
16
  *
15
- * MVP Primitives:
16
- * - 'llm': Wrapper for streamText/generateText (Task 2.2)
17
- * - 'output-generator': Deterministic variable mapping (Task 2.3)
18
- * - 'call-agent': Sub-agent invocation (future)
17
+ * Primitives:
18
+ * - 'chat': Frontend chat interface (UIMessage with 'parts' β†’ converts to ModelMessage)
19
+ * - 'llm': Workflow/API calls (ModelMessage with 'content' β†’ direct use)
20
+ * - 'output-generator': Deterministic variable mapping
21
+ * - 'call-agent': Sub-agent invocation
19
22
  */
20
23
  export declare const handlerRegistry: Record<string, PrimitiveHandler>;
21
24
  /**
22
25
  * Register a custom primitive handler in the registry.
23
- * Allows consumers to extend Beddel with domain-specific primitives.
24
26
  *
25
27
  * @param type - Step type identifier (e.g., 'my-custom-primitive')
26
28
  * @param handler - PrimitiveHandler function
27
- *
28
- * @example
29
- * import { registerPrimitive } from 'beddel';
30
- *
31
- * registerPrimitive('http-fetch', async (config, context) => {
32
- * const response = await fetch(config.url);
33
- * return { data: await response.json() };
34
- * });
35
29
  */
36
30
  export declare function registerPrimitive(type: string, handler: PrimitiveHandler): void;
37
31
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/primitives/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAgC,MAAM,UAAU,CAAC;AAK/E,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,OAAO,CAAC;AAmBzE;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAkB5D,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAK/E"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/primitives/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAgC,MAAM,UAAU,CAAC;AAO/E,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAChE,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AACrC,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAElD;;;;;;;;GAQG;AACH,eAAO,MAAM,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CA0B5D,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAK/E"}
@@ -3,39 +3,38 @@
3
3
  *
4
4
  * This registry maps step types to their handler implementations.
5
5
  * Following Expansion Pack Pattern from BMAD-METHODβ„’ for extensibility.
6
- * See: https://github.com/bmadcode/bmad-method
7
6
  *
8
7
  * Server-only: Handlers may use Node.js APIs and external services.
9
8
  */
9
+ import { chatPrimitive } from './chat';
10
10
  import { llmPrimitive } from './llm';
11
11
  import { outputPrimitive } from './output';
12
- // Re-export llm exports for consumer access
13
- export { llmPrimitive, registerCallback, callbackRegistry } from './llm';
14
- /**
15
- * Placeholder handler for primitives not yet implemented.
16
- * Returns config and context for debugging purposes.
17
- */
18
- const placeholderHandler = async (config, context) => {
19
- console.warn('[Beddel] Placeholder handler invoked. Implement the actual primitive.');
20
- return {
21
- _placeholder: true,
22
- config,
23
- input: context.input,
24
- variableCount: context.variables.size,
25
- };
26
- };
12
+ import { callAgentPrimitive } from './call-agent';
13
+ // Re-export from llm-core for consumer access
14
+ export { registerCallback, callbackRegistry } from './llm-core';
15
+ export { chatPrimitive } from './chat';
16
+ export { llmPrimitive } from './llm';
17
+ export { callAgentPrimitive } from './call-agent';
27
18
  /**
28
19
  * Registry of primitive handlers keyed by step type.
29
20
  *
30
- * MVP Primitives:
31
- * - 'llm': Wrapper for streamText/generateText (Task 2.2)
32
- * - 'output-generator': Deterministic variable mapping (Task 2.3)
33
- * - 'call-agent': Sub-agent invocation (future)
21
+ * Primitives:
22
+ * - 'chat': Frontend chat interface (UIMessage with 'parts' β†’ converts to ModelMessage)
23
+ * - 'llm': Workflow/API calls (ModelMessage with 'content' β†’ direct use)
24
+ * - 'output-generator': Deterministic variable mapping
25
+ * - 'call-agent': Sub-agent invocation
34
26
  */
35
27
  export const handlerRegistry = {
36
28
  /**
37
- * LLM Primitive - Dual-mode AI text generation.
38
- * Supports streaming (streamText) and blocking (generateText) modes.
29
+ * Chat Primitive - Frontend chat interface.
30
+ * Converts UIMessage (from useChat) to ModelMessage.
31
+ * Use for: API routes serving useChat frontend hooks.
32
+ */
33
+ 'chat': chatPrimitive,
34
+ /**
35
+ * LLM Primitive - Direct LLM calls for workflows.
36
+ * Uses ModelMessage format directly without conversion.
37
+ * Use for: Internal workflows, call-agent, API calls.
39
38
  */
40
39
  'llm': llmPrimitive,
41
40
  /**
@@ -44,25 +43,16 @@ export const handlerRegistry = {
44
43
  */
45
44
  'output-generator': outputPrimitive,
46
45
  /**
47
- * Call Agent Primitive - Placeholder
48
- * Enables recursive workflow execution via sub-agents.
46
+ * Call Agent Primitive - Sub-agent invocation.
47
+ * Loads and executes another agent's workflow.
49
48
  */
50
- 'call-agent': placeholderHandler,
49
+ 'call-agent': callAgentPrimitive,
51
50
  };
52
51
  /**
53
52
  * Register a custom primitive handler in the registry.
54
- * Allows consumers to extend Beddel with domain-specific primitives.
55
53
  *
56
54
  * @param type - Step type identifier (e.g., 'my-custom-primitive')
57
55
  * @param handler - PrimitiveHandler function
58
- *
59
- * @example
60
- * import { registerPrimitive } from 'beddel';
61
- *
62
- * registerPrimitive('http-fetch', async (config, context) => {
63
- * const response = await fetch(config.url);
64
- * return { data: await response.json() };
65
- * });
66
56
  */
67
57
  export function registerPrimitive(type, handler) {
68
58
  if (handlerRegistry[type]) {