llmz 0.3.0 → 0.4.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.
@@ -1,8 +1,40 @@
1
1
  export declare namespace Transcript {
2
+ /**
3
+ * A file attached to a transcript message.
4
+ *
5
+ * - `image`: a picture the model can see.
6
+ * - `audio`: a voice message — spoken audio of what the user said. Messages
7
+ * carrying an audio attachment are presented to the model as spoken turns
8
+ * (tagged `modality="voice"` in the prompt) and the audio is sent as model
9
+ * input: audio-capable models hear it directly, others receive a
10
+ * transcription (see `@botpress/cognitive`'s `transcriptionModel` option).
11
+ *
12
+ * `url` supports http(s) URLs and base64 `data:` URIs.
13
+ *
14
+ * `id` is an optional stable identifier for referencing the attachment from
15
+ * the message content (e.g. `screenshot-A` in a screen-share event log). It
16
+ * is used as the attachment's reference in the prompt; without it, a
17
+ * positional letter (A, B, C...) is auto-assigned.
18
+ *
19
+ * `alt` is an optional human-readable description shown to the model next to
20
+ * the attachment (e.g. "Screenshot of the checkout error page").
21
+ */
2
22
  type Attachment = {
3
- type: 'image';
23
+ type: 'image' | 'audio';
4
24
  url: string;
25
+ id?: string;
26
+ alt?: string;
5
27
  };
28
+ /**
29
+ * How the user delivered a message. Defaults to `'text'`.
30
+ *
31
+ * Set to `'voice'` when the user spoke the message out loud. Use it when the
32
+ * speech was already transcribed upstream and no audio is attached — the
33
+ * message `content` is then treated as a transcript of what the user said.
34
+ * Messages with an `audio` attachment are always treated as voice; setting
35
+ * this field is not required for them.
36
+ */
37
+ type Modality = 'text' | 'voice';
6
38
  type AssistantMessage = {
7
39
  role: 'assistant';
8
40
  name?: string;
@@ -14,6 +46,8 @@ export declare namespace Transcript {
14
46
  createdAt?: string;
15
47
  name?: string;
16
48
  content: string;
49
+ /** How the user delivered this message. Defaults to 'text'. See {@link Modality}. */
50
+ modality?: Modality;
17
51
  attachments?: Array<Attachment>;
18
52
  };
19
53
  type EventMessage = {
@@ -30,6 +64,8 @@ export declare namespace Transcript {
30
64
  };
31
65
  type Message = AssistantMessage | UserMessage | EventMessage | SummaryMessage;
32
66
  }
67
+ /** Whether the message is a spoken turn: explicit voice modality or an audio attachment. */
68
+ export declare function isVoiceMessage(message: Transcript.Message): boolean;
33
69
  export declare class TranscriptArray extends Array<Transcript.Message> {
34
70
  constructor(items?: Transcript.Message[]);
35
71
  toString(): string;
package/package.json CHANGED
@@ -2,7 +2,11 @@
2
2
  "name": "llmz",
3
3
  "type": "module",
4
4
  "description": "LLMz - An LLM-native Typescript VM built on top of Zui",
5
- "version": "0.3.0",
5
+ "version": "0.4.0",
6
+ "files": [
7
+ "dist",
8
+ "DOCS.md"
9
+ ],
6
10
  "types": "./dist/index.d.ts",
7
11
  "main": "./dist/index.cjs",
8
12
  "module": "./dist/index.js",
@@ -64,8 +68,8 @@
64
68
  "tsx": "^4.19.2"
65
69
  },
66
70
  "peerDependencies": {
67
- "@botpress/client": "1.49.0",
68
- "@botpress/cognitive": "1.0.0",
71
+ "@botpress/client": "2.0.0",
72
+ "@botpress/cognitive": "1.0.2",
69
73
  "@bpinternal/thicktoken": "^3.1.0",
70
74
  "@bpinternal/zui": "^2.4.0"
71
75
  },
package/CLAUDE.md DELETED
@@ -1,362 +0,0 @@
1
- # CLAUDE.md
2
-
3
- This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
-
5
- ## What is LLMz?
6
-
7
- LLMz is a revolutionary TypeScript AI agent framework that fundamentally changes how AI agents work. Like other agent frameworks, LLMz calls LLM models in a loop to achieve desired outcomes with access to tools and memory. However, LLMz is **code-first** – meaning it generates and runs TypeScript code in a sandbox rather than using traditional JSON tool calling.
8
-
9
- **Core Philosophy**: Stop chaining tools. Start generating real code.
10
-
11
- ### Why Code Generation Works Better
12
-
13
- Traditional agent frameworks rely on JSON tool calling, which has significant limitations:
14
-
15
- - Hard-to-parse JSON schemas for LLMs
16
- - Incapable of complex logic, loops, and conditionals
17
- - Multiple expensive roundtrips for each tool call
18
- - Unreliable beyond simple scenarios
19
-
20
- LLMz leverages the fact that models have been trained extensively on millions of TypeScript codebases, making them incredibly reliable at generating working code. This enables:
21
-
22
- - Complex logic and multi-tool orchestration in **one call**
23
- - Native LLM thinking via comments and code structure
24
- - Complete type safety and predictable schemas
25
- - Seamless scaling in production environments
26
-
27
- ## Core Concepts
28
-
29
- ### Execution Loop
30
-
31
- LLMz exposes a single method (`execute`) that runs in a loop until one of these conditions:
32
-
33
- 1. **An Exit is returned** - Agent completes with structured result
34
- 2. **Agent waits for user input** (Chat Mode) - Returns control to user
35
- 3. **Maximum iterations reached** - Safety limit to prevent infinite loops
36
-
37
- The loop automatically handles:
38
-
39
- - Tool calling and result processing
40
- - Thinking about outputs and context
41
- - Error recovery and retry logic
42
- - Variable state persistence across iterations
43
-
44
- ### Generated Code Structure
45
-
46
- Every LLMz code block follows a predictable structure:
47
-
48
- **Return Statement (Required)**:
49
-
50
- ```tsx
51
- // Chat mode - give turn back to user
52
- return { action: 'listen' }
53
-
54
- // Worker mode - complete with result
55
- return { action: 'done', result: calculatedValue }
56
- ```
57
-
58
- **Tool Calls with Logic**:
59
-
60
- ```tsx
61
- // Complex logic impossible with JSON tool calling
62
- const price = await getTicketPrice({ from: 'quebec', to: 'new york' })
63
-
64
- if (price > 500) {
65
- throw new Error('Price too high')
66
- } else {
67
- const ticketId = await buyTicket({ from: 'quebec', to: 'new york' })
68
- return { action: 'done', result: ticketId }
69
- }
70
- ```
71
-
72
- **Comments for Planning**:
73
-
74
- ```tsx
75
- // Comments help LLM think step-by-step and plan ahead
76
- // Check user's budget first before proceeding with purchase
77
- const budget = await getUserBudget()
78
- ```
79
-
80
- ### Execution Modes
81
-
82
- **Chat Mode**: Interactive conversational agents
83
-
84
- - Enabled when `chat` is provided to `execute()`
85
- - Agents can `yield` React components to user
86
- - Special `ListenExit` automatically available for user interaction
87
- - Transcript management for conversation history
88
-
89
- **Worker Mode**: Automated execution environments
90
-
91
- - Enabled when `chat` is omitted from `execute()`
92
- - Focus on computational tasks and data processing
93
- - Uses `DefaultExit` if no custom exits provided
94
- - Sandboxed execution with security isolation
95
-
96
- ### Chat Components (Chat Mode Only)
97
-
98
- Agents can yield React components for rich user interaction:
99
-
100
- ```tsx
101
- // Multi-line text support
102
- yield <Text>
103
- Hello, world!
104
- This is a second line.
105
- </Text>
106
-
107
- // Composed/nested components
108
- yield <Message>
109
- <Text>What do you prefer?</Text>
110
- <Button>Cats</Button>
111
- <Button>Dogs</Button>
112
- </Message>
113
-
114
- return { action: 'listen' }
115
- ```
116
-
117
- Components map to communication channels (Webchat, SMS, etc.) and can be completely custom.
118
-
119
- ### Tools and Objects
120
-
121
- **Tools**: Type-safe functions with Zod/Zui schemas
122
-
123
- - Input/output validation and TypeScript inference
124
- - Synchronous and asynchronous support
125
- - Retry logic and error handling
126
- - Tool aliases for multiple names
127
-
128
- **Objects**: Namespaced containers for related tools and variables
129
-
130
- - Group related functionality together
131
- - Support both readonly and writable variables
132
- - Variable type validation with schemas
133
- - Mutation tracking across iterations
134
-
135
- ### Advanced Features
136
-
137
- **Snapshots**: Pausable/resumable execution
138
-
139
- - Throw `SnapshotSignal` to halt and serialize execution state
140
- - Resume later from exact same point
141
- - Useful for long-running workflows and async operations
142
-
143
- **Thinking**: Agent reflection and variable inspection
144
-
145
- - Agent-initiated: `return { action: 'think' }`
146
- - Tool-initiated: Throw `ThinkSignal` to force reflection
147
- - Helps agents avoid rushed decisions and process complex information
148
-
149
- **Hooks**: Custom logic at execution points
150
-
151
- - `onTrace`: Non-blocking monitoring and logging
152
- - `onExit`: Validate exits and implement guardrails
153
- - `onBeforeExecution`: Code mutation and security checks
154
- - `onIterationEnd`: State augmentation between iterations
155
-
156
- ## Project Overview
157
-
158
- LLMz operates as an LLM-native TypeScript VM built on top of Zui (Botpress's internal schema library), battle-tested in production powering millions of AI agents worldwide.
159
-
160
- ## Architecture
161
-
162
- LLMz operates as an LLM-native TypeScript VM built on top of Zui (Botpress's internal schema library). The framework includes two primary execution modes:
163
-
164
- LLMz operates in two primary modes:
165
-
166
- - **Chat Mode**: Interactive conversational agents with tools and user interaction. Chat mode is enabled when `chat` is provided to `execute()`
167
- - **Worker Mode**: Automated execution environments with sandboxing and security. Worker mode is enabled when `chat` is omitted from `execute()`.
168
-
169
- ### Core Components
170
-
171
- **Main Framework** (`src/`):
172
-
173
- - `llmz.ts`: Core execution engine and context management
174
- - `vm.ts`: Virtual machine with isolated-vm and Node.js execution environments
175
- - `compiler/`: TypeScript compilation pipeline with AST transformations
176
- - `chat.ts`: Chat interface and message handling
177
- - `tool.ts`: Tool definition and execution system
178
- - `component.ts`: UI component system for interactive elements
179
-
180
- **Execution Pipeline**:
181
-
182
- - `prompts/`: Dual-mode prompt system (chat-mode/, worker-mode/)
183
- - `transcript.ts`: Conversation history and context management
184
- - `context.ts`: Execution context and iteration tracking
185
- - `result.ts`: Execution result types and error handling
186
-
187
- **Safety & Security**:
188
-
189
- - `errors.ts`: Comprehensive error handling and signals
190
- - `stack-traces.ts`: Stack trace sanitization
191
- - `snapshots.ts`: Execution state snapshots
192
- - `truncator.ts`: Content truncation for token limits
193
-
194
- ## Development Commands
195
-
196
- ### Building and Testing
197
-
198
- ```bash
199
- # Build the package (TypeScript compilation + bundling)
200
- pnpm build
201
-
202
- # Type checking without emitting files
203
- pnpm check:type
204
-
205
- # Development mode with hot reloading
206
- pnpm watch
207
-
208
- # Run test suite
209
- pnpm test
210
-
211
- # Run tests in watch mode
212
- pnpm test:watch
213
-
214
- # Update test snapshots
215
- pnpm test:update
216
-
217
- # Generate prompt files (.md.ts) files after changing them
218
- pnpm generate
219
- ```
220
-
221
- ### Testing Configuration
222
-
223
- - Tests use Vitest with custom configuration for LLM testing
224
- - Retry mechanism (2 retries) due to LLM non-determinism
225
- - Extended timeout (60s) for LLM response times
226
- - Custom snapshot serializers for stack traces
227
- - Markdown and text file loaders for prompt testing
228
-
229
- ## Key Dependencies
230
-
231
- **Core Runtime**:
232
-
233
- - `isolated-vm`: Secure JavaScript execution environment
234
- - `@babel/*`: TypeScript/JSX compilation pipeline
235
- - `@botpress/client`: Botpress API integration
236
- - `@bpinternal/zui`: Schema validation and TypeScript generation
237
-
238
- **Development**:
239
-
240
- - `tsup`: Fast TypeScript bundler (ESM + CJS output)
241
- - `vitest`: Modern test framework with TypeScript support
242
- - `prettier`: Code formatting
243
-
244
- ## Code Architecture Patterns
245
-
246
- ### Execution Flow
247
-
248
- 1. **Prompt Generation**: Dual-mode prompts based on execution type
249
- 2. **Code Generation**: LLM generates TypeScript code with embedded tools
250
- 3. **Compilation**: Babel-based AST transformation with custom plugins
251
- 4. **Execution**: Isolated VM or Node.js execution with monitoring
252
- 5. **Result Processing**: Type-safe result handling and error recovery
253
-
254
- ### Key Plugins (`src/compiler/plugins/`):
255
-
256
- - `track-tool-calls.ts`: Instrument tool calls for monitoring
257
- - `variable-extraction.ts`: Extract and track variable usage
258
- - `line-tracking.ts`: Source map generation and error tracking
259
- - `jsx-preserve-newlines.ts`: Maintain formatting in JSX components
260
-
261
- ### VM Execution Strategy
262
-
263
- - **Production**: Uses `isolated-vm` for security isolation
264
- - **CI/Development**: Falls back to Node.js VM for compatibility
265
- - **Browser**: Uses standard JavaScript execution
266
-
267
- ## Tool System
268
-
269
- Tools are defined using Zui schemas and can be:
270
-
271
- - **Synchronous/Asynchronous**: Both execution types supported
272
- - **Type-Safe**: Full TypeScript inference and validation
273
- - **Retryable**: Built-in retry logic with exponential backoff
274
- - **Traceable**: Comprehensive execution monitoring
275
-
276
- Example tool definition:
277
-
278
- ```typescript
279
- const tool = new Tool({
280
- name: 'exampleTool',
281
- description: 'Tool description',
282
- input: z.object({ param: z.string() }),
283
- output: z.object({ result: z.string() }),
284
- handler: async ({ param }) => ({ result: `Processed: ${param}` }),
285
- })
286
- ```
287
-
288
- ## Component System
289
-
290
- LLMz includes a React-like component system for building interactive UIs:
291
-
292
- - **JSX Support**: Full JSX compilation and rendering
293
- - **Type Safety**: Components are fully typed with Zui schemas
294
- - **Rendering**: Server-side rendering to various output formats
295
-
296
- ## Security Considerations
297
-
298
- - **Isolated Execution**: VM isolation prevents access to host system
299
- - **Stack Trace Cleaning**: Removes internal framework details from errors
300
- - **Tool Access Control**: Granular permissions for tool execution
301
- - **Content Truncation**: Automatic handling of token limits
302
- - **Error Recovery**: Graceful handling of execution failures
303
-
304
- ## File Structure Conventions
305
-
306
- - Tests co-located with source files (`.test.ts` suffix)
307
- - Markdown prompts compiled to TypeScript modules
308
- - Source maps preserved for debugging
309
- - TypeScript declaration files generated for exports
310
-
311
- ## Environment Variables
312
-
313
- - `VM_DRIVER`: Choose VM execution environment ('isolated-vm' | 'node')
314
- - `CI`: Automatically detected, affects VM driver selection
315
-
316
- ## Performance Considerations
317
-
318
- - Code splitting with dynamic imports for faster startup
319
- - LRU caching for compiled code and results
320
- - Lazy loading of heavy dependencies
321
- - Bundle size optimization with tsup configuration
322
-
323
- ## Exit System
324
-
325
- LLMz uses a sophisticated exit system for controlling agent termination:
326
-
327
- - **Built-in Exits**: `ThinkExit`, `ListenExit`, `DefaultExit` for common patterns
328
- - **Custom Exits**: Domain-specific exits with typed schemas using Zod/Zui
329
- - **Type Safety**: `result.is(exit)` for compile-time type checking
330
- - **Agent Usage**: Agents call `return { action: 'exit_name', ...data }` to exit
331
-
332
- ## Prompt System Architecture
333
-
334
- The dual-mode prompt system (`src/prompts/`) generates different prompts based on execution mode:
335
-
336
- - **Chat Mode**: Uses prompts from `chat-mode/` for interactive conversations
337
- - **Worker Mode**: Uses prompts from `worker-mode/` for automated execution
338
- - **Markdown Templates**: Prompts are written in Markdown and compiled to TypeScript
339
- - **Dynamic Content**: Tool definitions, schemas, and context injected at runtime
340
-
341
- ## Compiler Pipeline
342
-
343
- The Babel-based compilation system transforms generated code:
344
-
345
- 1. **AST Parsing**: TypeScript/JSX code parsed into Abstract Syntax Tree
346
- 2. **Plugin Transformation**: Custom plugins modify the AST for execution
347
- 3. **Code Generation**: Modified AST compiled back to executable JavaScript
348
- 4. **Source Maps**: Generated for debugging and error tracking
349
-
350
- Key transformations:
351
-
352
- - Tool call instrumentation for monitoring
353
- - Variable extraction and tracking
354
- - JSX component handling
355
- - Line number preservation for stack traces
356
-
357
- # important-instruction-reminders
358
-
359
- Do what has been asked; nothing more, nothing less.
360
- NEVER create files unless they're absolutely necessary for achieving your goal.
361
- ALWAYS prefer editing an existing file to creating a new one.
362
- NEVER proactively create documentation files (\*.md) or README files. Only create documentation files if explicitly requested by the User.