@agentxjs/types 0.0.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Deepractice
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,540 @@
1
+ # @agentxjs/types
2
+
3
+ > Core type definitions for the Deepractice AgentX ecosystem
4
+
5
+ ## Overview
6
+
7
+ `agentx-types` is a **pure TypeScript type library** (140+ files, zero dependencies) that defines the complete type system for building event-driven AI agents.
8
+
9
+ **Key Characteristics:**
10
+
11
+ - **Zero runtime dependencies** - Pure TypeScript types (except type guards)
12
+ - **Platform-agnostic** - Works in Node.js, Browser, and Edge runtimes
13
+ - **Contract-first design** - Single source of truth for data structures
14
+ - **4-Layer Event Architecture** - Stream → State → Message → Turn
15
+ - **"Define Once, Run Anywhere"** - Unified agent definition across platforms
16
+ - **Well-documented** - Every type includes JSDoc comments with design decisions
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ pnpm add @agentxjs/types
22
+ ```
23
+
24
+ ---
25
+
26
+ ## Architecture Overview
27
+
28
+ ```text
29
+ ┌─────────────────────────────────────────────────────────────────────┐
30
+ │ agentx-types (140+ files) │
31
+ ├─────────────────────────────────────────────────────────────────────┤
32
+ │ │
33
+ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌───────────┐ │
34
+ │ │ agent/ │ │ event/ │ │ message/ │ │ llm/ │ │
35
+ │ │ 14 files │ │ 44 files │ │ 13 files │ │ 7 files │ │
36
+ │ │ │ │ │ │ │ │ │ │
37
+ │ │ Agent │ │ 4-Layer │ │ Message │ │ LLM │ │
38
+ │ │ Driver │ │ Events │ │ Content │ │ Config │ │
39
+ │ │ Presenter │ │ │ │ Parts │ │ Request │ │
40
+ │ │ Definition │ │ │ │ │ │ Response │ │
41
+ │ └─────────────┘ └─────────────┘ └─────────────┘ └───────────┘ │
42
+ │ │
43
+ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌───────────┐ │
44
+ │ │ agentx/ │ │ runtime/ │ │ mcp/ │ │ error/ │ │
45
+ │ │ 13 files │ │ 15+ files │ │ 7 files │ │ 7 files │ │
46
+ │ │ │ │ │ │ │ │ │ │
47
+ │ │ Platform │ │ Runtime │ │ Tool │ │ AgentError│ │
48
+ │ │ Manager │ │ Container │ │ Resource │ │ Category │ │
49
+ │ │ defineAgent │ │ Sandbox │ │ Prompt │ │ Severity │ │
50
+ │ └─────────────┘ └─────────────┘ └─────────────┘ └───────────┘ │
51
+ │ │
52
+ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
53
+ │ │ session/ │ │ logger/ │ │ guards/ │ │
54
+ │ │ 2 files │ │ 4 files │ │ 3 files │ │
55
+ │ └─────────────┘ └─────────────┘ └─────────────┘ │
56
+ │ │
57
+ └─────────────────────────────────────────────────────────────────────┘
58
+ ```
59
+
60
+ ---
61
+
62
+ ## Module Reference
63
+
64
+ ### Core Contracts (`agent/`)
65
+
66
+ Agent runtime interfaces - the core contracts for building agents.
67
+
68
+ | Type | Description |
69
+ | ------------------ | ------------------------------------------------------ |
70
+ | `Agent` | Agent instance interface (receive, on, react, destroy) |
71
+ | `AgentDriver` | Message processor contract (receive → StreamEvent) |
72
+ | `AgentPresenter` | Side-effect handler (logging, monitoring, webhooks) |
73
+ | `AgentMiddleware` | Incoming message interceptor (before driver) |
74
+ | `AgentInterceptor` | Outgoing event interceptor (after engine) |
75
+ | `AgentContext` | Runtime context (agentId, config, session) |
76
+ | `AgentDefinition` | Agent template (name, description, systemPrompt) |
77
+ | `AgentContainer` | Agent instance storage |
78
+
79
+ ```typescript
80
+ import type { Agent, AgentDriver, AgentPresenter } from "@agentxjs/types";
81
+
82
+ // Driver: Process messages, yield stream events
83
+ interface AgentDriver {
84
+ receive(message: UserMessage): AsyncIterable<StreamEventType>;
85
+ abort(): void;
86
+ destroy(): Promise<void>;
87
+ }
88
+
89
+ // Agent: High-level interface
90
+ interface Agent {
91
+ readonly id: string;
92
+ receive(input: string | UserMessage): Promise<void>;
93
+ on<T extends AgentEventType["type"]>(type: T, handler: Handler<T>): Unsubscribe;
94
+ react(handlers: EventHandlers): Unsubscribe;
95
+ destroy(): Promise<void>;
96
+ }
97
+ ```
98
+
99
+ ---
100
+
101
+ ### Event System (`event/`) - 4-Layer Architecture
102
+
103
+ The heart of AgentX - a hierarchical event system for real-time AI interactions.
104
+
105
+ ```text
106
+ ┌─────────────────────────────────────────────────────────────────────┐
107
+ │ Event Flow │
108
+ ├─────────────────────────────────────────────────────────────────────┤
109
+ │ │
110
+ │ Driver.receive() │
111
+ │ │ │
112
+ │ ▼ yields │
113
+ │ ┌─────────────────────────────────────────────────────────────┐ │
114
+ │ │ L1: Stream Layer (real-time, incremental) │ │
115
+ │ │ message_start → text_delta* → tool_call → message_stop │ │
116
+ │ └────────────────────────────┬────────────────────────────────┘ │
117
+ │ │ Mealy Machine assembles │
118
+ │ ▼ │
119
+ │ ┌─────────────────────────────────────────────────────────────┐ │
120
+ │ │ L2: State Layer (state transitions) │ │
121
+ │ │ conversation_start → thinking → responding → conversation_end│ │
122
+ │ └────────────────────────────┬────────────────────────────────┘ │
123
+ │ │ │
124
+ │ ▼ │
125
+ │ ┌─────────────────────────────────────────────────────────────┐ │
126
+ │ │ L3: Message Layer (complete messages) │ │
127
+ │ │ user_message, assistant_message, tool_call_message │ │
128
+ │ └────────────────────────────┬────────────────────────────────┘ │
129
+ │ │ │
130
+ │ ▼ │
131
+ │ ┌─────────────────────────────────────────────────────────────┐ │
132
+ │ │ L4: Turn Layer (analytics) │ │
133
+ │ │ turn_request → turn_response (duration, cost, tokens) │ │
134
+ │ └─────────────────────────────────────────────────────────────┘ │
135
+ │ │
136
+ └─────────────────────────────────────────────────────────────────────┘
137
+ ```
138
+
139
+ #### Design Decision: Why 4 Layers?
140
+
141
+ Each layer serves a different consumer:
142
+
143
+ | Layer | Consumer | Purpose |
144
+ | ----------- | --------------------------------- | ------------------------------- |
145
+ | **Stream** | UI (typewriter effect) | Real-time incremental updates |
146
+ | **State** | State machine, loading indicators | Track agent lifecycle |
147
+ | **Message** | Chat history, persistence | Complete conversation records |
148
+ | **Turn** | Analytics, billing | Usage metrics and cost tracking |
149
+
150
+ #### Stream Layer Events (L1)
151
+
152
+ Real-time incremental events during streaming response.
153
+
154
+ ```typescript
155
+ import type {
156
+ StreamEventType,
157
+ TextDeltaEvent,
158
+ ToolCallEvent,
159
+ MessageStopEvent,
160
+ } from "@agentxjs/types";
161
+
162
+ // Text streaming flow
163
+ // 1. MessageStartEvent
164
+ // 2. TextContentBlockStartEvent
165
+ // 3. TextDeltaEvent (repeated) ← append to build complete text
166
+ // 4. TextContentBlockStopEvent
167
+ // 5. MessageDeltaEvent
168
+ // 6. MessageStopEvent
169
+
170
+ // Tool use flow
171
+ // 1. MessageStartEvent
172
+ // 2. ToolUseContentBlockStartEvent
173
+ // 3. InputJsonDeltaEvent (repeated) ← concatenate to build JSON
174
+ // 4. ToolUseContentBlockStopEvent
175
+ // 5. ToolCallEvent ← complete tool call ready
176
+ // 6. ToolResultEvent ← after execution
177
+ ```
178
+
179
+ #### State Layer Events (L2)
180
+
181
+ State machine transitions for agent lifecycle.
182
+
183
+ ```typescript
184
+ import type {
185
+ StateEventType,
186
+ ConversationStartStateEvent,
187
+ ToolPlannedStateEvent,
188
+ ConversationEndStateEvent,
189
+ } from "@agentxjs/types";
190
+
191
+ // Agent lifecycle: agent_initializing → agent_ready → agent_destroyed
192
+ // Conversation: conversation_queued → conversation_start → conversation_thinking
193
+ // → conversation_responding → conversation_end
194
+ // Tool: tool_planned → tool_executing → tool_completed/tool_failed
195
+ ```
196
+
197
+ #### Message Layer Events (L3)
198
+
199
+ Complete message events for chat history.
200
+
201
+ ```typescript
202
+ import type {
203
+ MessageEventType,
204
+ UserMessageEvent,
205
+ AssistantMessageEvent,
206
+ ToolCallMessageEvent,
207
+ } from "@agentxjs/types";
208
+
209
+ // UserMessageEvent - user sent a message
210
+ // AssistantMessageEvent - AI completed a response
211
+ // ToolCallMessageEvent - AI requested tool execution
212
+ // ToolResultMessageEvent - tool execution completed
213
+ ```
214
+
215
+ #### Turn Layer Events (L4)
216
+
217
+ Analytics events for complete request-response cycles.
218
+
219
+ ```typescript
220
+ import type { TurnRequestEvent, TurnResponseEvent } from "@agentxjs/types";
221
+
222
+ interface TurnResponseEvent {
223
+ type: "turn_response";
224
+ turnId: string;
225
+ data: {
226
+ assistantMessage: AssistantMessage;
227
+ durationMs: number;
228
+ usage?: { input: number; output: number };
229
+ costUsd?: number;
230
+ };
231
+ }
232
+ ```
233
+
234
+ #### Design Decision: ErrorEvent is Independent
235
+
236
+ Error is NOT part of Message or the 4-layer hierarchy because:
237
+
238
+ 1. **Not conversation content** - Errors are system notifications
239
+ 2. **SSE transport** - Errors need special handling for transmission
240
+ 3. **UI-specific rendering** - Error display differs from messages
241
+
242
+ ```typescript
243
+ import type { ErrorEvent } from "@agentxjs/types";
244
+
245
+ // ErrorEvent travels via SSE alongside StreamEvents
246
+ // Browser receives and displays error UI
247
+ ```
248
+
249
+ ---
250
+
251
+ ### Message Types (`message/`)
252
+
253
+ Role-based message system with multi-modal content support.
254
+
255
+ ```typescript
256
+ import type {
257
+ Message,
258
+ UserMessage,
259
+ AssistantMessage,
260
+ ToolCallMessage,
261
+ ToolResultMessage,
262
+ } from "@agentxjs/types";
263
+
264
+ // Discriminated union by `subtype` field
265
+ type Message =
266
+ | UserMessage // subtype: "user"
267
+ | AssistantMessage // subtype: "assistant"
268
+ | SystemMessage // subtype: "system"
269
+ | ToolCallMessage // subtype: "tool-call"
270
+ | ToolResultMessage; // subtype: "tool-result"
271
+ ```
272
+
273
+ #### Content Parts
274
+
275
+ Multi-modal content through `ContentPart` types:
276
+
277
+ ```typescript
278
+ import type { ContentPart, TextPart, ImagePart, ToolCallPart } from "@agentxjs/types";
279
+
280
+ type ContentPart =
281
+ | TextPart // { type: "text", text: string }
282
+ | ThinkingPart // { type: "thinking", reasoning: string }
283
+ | ImagePart // { type: "image", data: string, mediaType: string }
284
+ | FilePart // { type: "file", data: string, mediaType: string }
285
+ | ToolCallPart // { type: "tool-call", id, name, input }
286
+ | ToolResultPart; // { type: "tool-result", id, name, output }
287
+ ```
288
+
289
+ ---
290
+
291
+ ### Platform API (`agentx/`)
292
+
293
+ AgentX platform contracts - the application context for agent management.
294
+
295
+ ```typescript
296
+ import type {
297
+ AgentX,
298
+ AgentXLocal,
299
+ AgentXRemote,
300
+ AgentManager,
301
+ SessionManager,
302
+ } from "@agentxjs/types";
303
+
304
+ // Two modes: Local (in-memory) and Remote (via network)
305
+ interface AgentXLocal {
306
+ readonly mode: "local";
307
+ readonly agents: AgentManager;
308
+ readonly sessions: LocalSessionManager;
309
+ readonly errors: ErrorManager;
310
+ }
311
+
312
+ interface AgentXRemote {
313
+ readonly mode: "remote";
314
+ readonly agents: AgentManager;
315
+ readonly sessions: RemoteSessionManager;
316
+ readonly platform: PlatformManager;
317
+ }
318
+ ```
319
+
320
+ #### HTTP Endpoint Contracts
321
+
322
+ Type-safe HTTP API definitions using `Endpoint` type:
323
+
324
+ ```typescript
325
+ import type { Endpoint, ListAgentsEndpoint, CreateAgentEndpoint } from "@agentxjs/types";
326
+
327
+ // Endpoint<Method, Path, Input, Output>
328
+ interface ListAgentsEndpoint extends Endpoint<"GET", "/agents", void, ListAgentsResponse> {}
329
+ interface CreateAgentEndpoint
330
+ extends Endpoint<"POST", "/agents", CreateAgentRequest, CreateAgentResponse> {}
331
+ ```
332
+
333
+ ---
334
+
335
+ ### Runtime Types (`runtime/`)
336
+
337
+ Runtime layer types for the "Define Once, Run Anywhere" architecture.
338
+
339
+ ```typescript
340
+ import type { Runtime, RuntimeDriver, Container, Sandbox } from "@agentxjs/types";
341
+
342
+ // Runtime - Complete environment encapsulation
343
+ interface Runtime {
344
+ readonly name: string;
345
+ readonly container: Container;
346
+ createSandbox(name: string): Sandbox;
347
+ createDriver(definition: AgentDefinition, context: AgentContext, sandbox: Sandbox): RuntimeDriver;
348
+ }
349
+
350
+ // Container - Agent lifecycle management
351
+ interface Container {
352
+ register(agent: Agent): void;
353
+ get(agentId: string): Agent | undefined;
354
+ remove(agentId: string): boolean;
355
+ list(): Agent[];
356
+ }
357
+
358
+ // Sandbox - Resource isolation (OS + LLM)
359
+ interface Sandbox {
360
+ readonly name: string;
361
+ readonly os: OS; // FileSystem, Process, Env, Disk
362
+ readonly llm: LLMProvider; // apiKey, baseUrl
363
+ }
364
+ ```
365
+
366
+ **Key Concepts:**
367
+
368
+ | Type | Description |
369
+ | --------------- | ------------------------------------------------------------- |
370
+ | `Runtime` | Complete environment (Container + Sandbox + Driver) |
371
+ | `RuntimeDriver` | Driver interface with sandbox access |
372
+ | `Container` | Agent lifecycle management (1:N) |
373
+ | `Sandbox` | Resource isolation per agent (OS + LLM) |
374
+ | `OS` | Operating system abstraction (FileSystem, Process, Env, Disk) |
375
+ | `LLMProvider` | LLM supply service (apiKey, baseUrl) |
376
+
377
+ ---
378
+
379
+ ### LLM Types (`llm/`)
380
+
381
+ Language model abstractions for stateless inference.
382
+
383
+ ```typescript
384
+ import type { LLMConfig, LLMRequest, LLMResponse, StopReason } from "@agentxjs/types";
385
+
386
+ interface LLMConfig {
387
+ model: string;
388
+ temperature?: number;
389
+ maxTokens?: number;
390
+ maxThinkingTokens?: number;
391
+ }
392
+
393
+ type StopReason = "end_turn" | "max_tokens" | "tool_use" | "stop_sequence" | "error";
394
+ ```
395
+
396
+ ---
397
+
398
+ ### MCP Types (`mcp/`)
399
+
400
+ Model Context Protocol - tools, resources, and prompts.
401
+
402
+ ```typescript
403
+ import type { McpTool, McpResource, McpPrompt, McpTransportConfig } from "@agentxjs/types";
404
+
405
+ interface McpTool {
406
+ name: string;
407
+ description?: string;
408
+ inputSchema: JsonSchema;
409
+ }
410
+
411
+ type McpTransportConfig =
412
+ | McpStdioTransport // Local process
413
+ | McpSseTransport // SSE connection
414
+ | McpHttpTransport // HTTP requests
415
+ | McpSdkTransport; // In-process SDK
416
+ ```
417
+
418
+ ---
419
+
420
+ ### Error Types (`error/`)
421
+
422
+ Unified error taxonomy for agent systems.
423
+
424
+ ```typescript
425
+ import type { AgentError, ErrorSeverity } from "@agentxjs/types";
426
+
427
+ interface AgentError {
428
+ category: "system" | "agent" | "llm" | "validation" | "unknown";
429
+ code: string;
430
+ message: string;
431
+ severity: ErrorSeverity;
432
+ recoverable: boolean;
433
+ details?: Record<string, unknown>;
434
+ }
435
+
436
+ type ErrorSeverity = "fatal" | "error" | "warning";
437
+ ```
438
+
439
+ ---
440
+
441
+ ## Design Decisions
442
+
443
+ ### Why Separate Types Package?
444
+
445
+ 1. **Zero Dependencies** - Can be imported anywhere without bloat
446
+ 2. **Contract-First** - Types are the single source of truth
447
+ 3. **Cross-Platform** - Same types work in Node.js, Browser, Edge
448
+ 4. **Version Control** - Type changes are explicit and versioned
449
+
450
+ ### Why Discriminated Unions?
451
+
452
+ TypeScript's type narrowing works best with discriminated unions:
453
+
454
+ ```typescript
455
+ function handleEvent(event: AgentEventType) {
456
+ switch (event.type) {
457
+ case "text_delta":
458
+ // TypeScript knows: event is TextDeltaEvent
459
+ console.log(event.data.text);
460
+ break;
461
+ case "assistant_message":
462
+ // TypeScript knows: event is AssistantMessageEvent
463
+ console.log(event.data.content);
464
+ break;
465
+ }
466
+ }
467
+ ```
468
+
469
+ ### Why `subtype` for Messages?
470
+
471
+ Messages use `subtype` instead of `type` because:
472
+
473
+ 1. `role` indicates WHO (user, assistant, tool, system)
474
+ 2. `subtype` indicates WHAT TYPE of message (user, assistant, tool-call, tool-result)
475
+ 3. This supports future message types with same role but different structure
476
+
477
+ ```typescript
478
+ // Both are role: "assistant" but different subtypes
479
+ | AssistantMessage // subtype: "assistant" - text response
480
+ | ToolCallMessage // subtype: "tool-call" - tool request
481
+ ```
482
+
483
+ ---
484
+
485
+ ## Type Guards
486
+
487
+ Runtime type checking for discriminated unions:
488
+
489
+ ```typescript
490
+ import { isTextPart, isToolCallPart, isStopReason } from "@agentxjs/types";
491
+
492
+ // Content part guards
493
+ if (isTextPart(part)) {
494
+ console.log(part.text);
495
+ }
496
+
497
+ // StopReason guard
498
+ if (isStopReason(value)) {
499
+ // value is StopReason
500
+ }
501
+ ```
502
+
503
+ ---
504
+
505
+ ## Package Dependencies
506
+
507
+ ```text
508
+ agentx-types (this package)
509
+
510
+ agentx-logger (logging facade)
511
+
512
+ agentx-engine (Mealy Machine processors)
513
+
514
+ agentx-agent (Agent runtime)
515
+
516
+ agentx (Platform API + defineAgent)
517
+
518
+ agentx-runtime (NodeRuntime + ClaudeDriver)
519
+
520
+ agentx-ui (React components)
521
+ ```
522
+
523
+ ---
524
+
525
+ ## Contributing
526
+
527
+ This package follows **strict type-only conventions**:
528
+
529
+ 1. **No runtime code** - Only TypeScript types (except type guards)
530
+ 2. **No dependencies** - Keep the package pure
531
+ 3. **One file, one primary type** - Use PascalCase filenames
532
+ 4. **Discriminated unions** - Always use `type` or `subtype` for discrimination
533
+ 5. **JSDoc comments** - Document every public type with examples
534
+ 6. **Design decisions** - Document WHY in module-level comments
535
+
536
+ ---
537
+
538
+ ## License
539
+
540
+ MIT