agentxjs 1.9.9-dev → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import { BusEvent, Unsubscribe, EventBus, BusEventHandler } from '@agentxjs/core/event';
2
+ import { CreateDriver } from '@agentxjs/core/driver';
3
+ import { AgentXPlatform } from '@agentxjs/core/runtime';
4
+ import { Message } from '@agentxjs/core/agent';
2
5
 
3
6
  /**
4
7
  * Presentation Types
@@ -43,6 +46,13 @@ interface UserConversation {
43
46
  role: "user";
44
47
  blocks: Block[];
45
48
  }
49
+ /**
50
+ * Token usage for a message (one LLM call / step)
51
+ */
52
+ interface TokenUsage {
53
+ inputTokens: number;
54
+ outputTokens: number;
55
+ }
46
56
  /**
47
57
  * Assistant conversation
48
58
  */
@@ -50,6 +60,8 @@ interface AssistantConversation {
50
60
  role: "assistant";
51
61
  blocks: Block[];
52
62
  isStreaming: boolean;
63
+ /** Accumulated token usage across all steps in this conversation */
64
+ usage?: TokenUsage;
53
65
  }
54
66
  /**
55
67
  * Error conversation
@@ -87,22 +99,40 @@ declare const initialPresentationState: PresentationState;
87
99
  /**
88
100
  * Presentation Reducer
89
101
  *
90
- * Aggregates stream events into PresentationState.
102
+ * Aggregates events into PresentationState.
91
103
  * Pure function: (state, event) => newState
104
+ *
105
+ * Event consumption strategy:
106
+ * - Stream layer: message_start, text_delta, tool_use_start, tool_use_stop, message_stop
107
+ * (for real-time streaming display)
108
+ * - Message layer: tool_result_message
109
+ * (for tool execution results — arrives after message_stop)
110
+ *
111
+ * Tool calls are stream-level blocks within the assistant turn,
112
+ * matching the mainstream API pattern (Anthropic, OpenAI).
92
113
  */
93
114
 
94
115
  /**
95
- * Reduce a stream event into presentation state
116
+ * Reduce an event into presentation state.
117
+ *
118
+ * Consumes:
119
+ * - Stream events: message_start, text_delta, tool_use_start, tool_use_stop, message_stop
120
+ * - Message events: tool_result_message
121
+ * - Error events: error
96
122
  */
97
123
  declare function presentationReducer(state: PresentationState, event: BusEvent): PresentationState;
98
- /**
99
- * Add a user conversation to state
100
- */
101
124
  declare function addUserConversation(state: PresentationState, content: string): PresentationState;
125
+ declare function createInitialState(): PresentationState;
102
126
  /**
103
- * Create initial state
127
+ * Convert persisted Messages to Presentation Conversations.
128
+ *
129
+ * Groups consecutive assistant + tool-result messages
130
+ * into a single AssistantConversation.
131
+ *
132
+ * Tool calls are now part of AssistantMessage.content (as ToolCallPart),
133
+ * so we extract them directly from the assistant message.
104
134
  */
105
- declare function createInitialState(): PresentationState;
135
+ declare function messagesToConversations(messages: Message[]): Conversation[];
106
136
 
107
137
  /**
108
138
  * Presentation Class
@@ -142,7 +172,7 @@ declare class Presentation {
142
172
  private updateHandlers;
143
173
  private errorHandlers;
144
174
  private eventUnsubscribe;
145
- constructor(agentx: AgentX, agentId: string, options?: PresentationOptions);
175
+ constructor(agentx: AgentX, agentId: string, options?: PresentationOptions, initialConversations?: Conversation[]);
146
176
  /**
147
177
  * Get current state
148
178
  */
@@ -185,34 +215,83 @@ declare class Presentation {
185
215
  */
186
216
  type MaybeAsync<T> = T | (() => T) | (() => Promise<T>);
187
217
  /**
188
- * AgentX client configuration
218
+ * LLM provider identifier
219
+ */
220
+ type LLMProvider = "anthropic" | "openai" | "google" | "xai" | "deepseek" | "mistral";
221
+ /**
222
+ * AgentX unified configuration
223
+ *
224
+ * Supports two modes:
225
+ * - **Local mode**: `apiKey` present → embedded Runtime + MonoDriver
226
+ * - **Remote mode**: `serverUrl` present → WebSocket client
189
227
  */
190
228
  interface AgentXConfig {
191
229
  /**
192
- * WebSocket server URL
230
+ * API key for LLM provider (local mode)
231
+ * If present, enables local mode with embedded Runtime
232
+ */
233
+ apiKey?: string;
234
+ /**
235
+ * LLM provider (local mode)
236
+ * @default "anthropic"
193
237
  */
194
- serverUrl: string;
238
+ provider?: LLMProvider;
195
239
  /**
196
- * Headers for authentication (static or dynamic)
240
+ * Model ID (local mode)
241
+ */
242
+ model?: string;
243
+ /**
244
+ * Base URL for API endpoint (local mode, for proxy/private deployments)
245
+ */
246
+ baseUrl?: string;
247
+ /**
248
+ * Data storage path (local mode)
249
+ * @default ":memory:" (in-memory storage)
250
+ */
251
+ dataPath?: string;
252
+ /**
253
+ * Custom CreateDriver factory (local mode, advanced)
254
+ * If provided, overrides the default MonoDriver
255
+ */
256
+ createDriver?: CreateDriver;
257
+ /**
258
+ * Custom AgentXPlatform (local mode, advanced)
259
+ * If provided, overrides the default NodePlatform
260
+ */
261
+ customPlatform?: AgentXPlatform;
262
+ /**
263
+ * WebSocket server URL (remote mode)
264
+ * If present, enables remote mode
265
+ */
266
+ serverUrl?: string;
267
+ /**
268
+ * Headers for authentication (remote mode, static or dynamic)
197
269
  * In Node.js: sent during WebSocket handshake
198
270
  * In browsers: sent as first auth message (WebSocket API limitation)
199
271
  */
200
272
  headers?: MaybeAsync<Record<string, string>>;
201
273
  /**
202
- * Business context injected into all requests
274
+ * Business context injected into all requests (remote mode)
203
275
  * Useful for passing userId, tenantId, permissions, etc.
204
276
  */
205
277
  context?: MaybeAsync<Record<string, unknown>>;
278
+ /**
279
+ * Log level for AgentX runtime
280
+ * Controls verbosity of console/file logging.
281
+ * @default "info"
282
+ */
283
+ logLevel?: "debug" | "info" | "warn" | "error" | "silent";
206
284
  /**
207
285
  * Request timeout in milliseconds (default: 30000)
208
286
  */
209
287
  timeout?: number;
210
288
  /**
211
289
  * Enable debug logging
290
+ * @deprecated Use `logLevel: "debug"` instead
212
291
  */
213
292
  debug?: boolean;
214
293
  /**
215
- * Auto reconnect on connection loss (default: true)
294
+ * Auto reconnect on connection loss (default: true, remote mode only)
216
295
  */
217
296
  autoReconnect?: boolean;
218
297
  }
@@ -236,6 +315,7 @@ interface ImageRecord {
236
315
  name?: string;
237
316
  description?: string;
238
317
  systemPrompt?: string;
318
+ customData?: Record<string, unknown>;
239
319
  createdAt: number;
240
320
  updatedAt: number;
241
321
  }
@@ -295,6 +375,12 @@ interface ImageListResponse extends BaseResponse {
295
375
  records: ImageRecord[];
296
376
  __subscriptions?: string[];
297
377
  }
378
+ /**
379
+ * Image update response
380
+ */
381
+ interface ImageUpdateResponse extends BaseResponse {
382
+ record: ImageRecord;
383
+ }
298
384
  /**
299
385
  * Container create response
300
386
  */
@@ -321,78 +407,151 @@ interface MessageSendResponse extends BaseResponse {
321
407
  agentId: string;
322
408
  }
323
409
  /**
324
- * AgentX Client SDK
410
+ * Container operations namespace
325
411
  */
326
- interface AgentX {
412
+ interface ContainerNamespace {
327
413
  /**
328
- * Check if connected to server
414
+ * Create or get container
329
415
  */
330
- readonly connected: boolean;
416
+ create(containerId: string): Promise<ContainerCreateResponse>;
331
417
  /**
332
- * Event bus for subscribing to events
418
+ * Get container
333
419
  */
334
- readonly events: EventBus;
420
+ get(containerId: string): Promise<ContainerGetResponse>;
421
+ /**
422
+ * List containers
423
+ */
424
+ list(): Promise<ContainerListResponse>;
425
+ }
426
+ /**
427
+ * Image operations namespace
428
+ */
429
+ interface ImageNamespace {
430
+ /**
431
+ * Create a new image
432
+ */
433
+ create(params: {
434
+ containerId: string;
435
+ name?: string;
436
+ description?: string;
437
+ systemPrompt?: string;
438
+ mcpServers?: Record<string, unknown>;
439
+ customData?: Record<string, unknown>;
440
+ }): Promise<ImageCreateResponse>;
441
+ /**
442
+ * Get image by ID
443
+ */
444
+ get(imageId: string): Promise<ImageGetResponse>;
445
+ /**
446
+ * List images
447
+ */
448
+ list(containerId?: string): Promise<ImageListResponse>;
449
+ /**
450
+ * Update image
451
+ */
452
+ update(imageId: string, updates: {
453
+ name?: string;
454
+ description?: string;
455
+ customData?: Record<string, unknown>;
456
+ }): Promise<ImageUpdateResponse>;
457
+ /**
458
+ * Delete image
459
+ */
460
+ delete(imageId: string): Promise<BaseResponse>;
461
+ }
462
+ /**
463
+ * Agent operations namespace
464
+ */
465
+ interface AgentNamespace {
335
466
  /**
336
467
  * Create a new agent
337
468
  */
338
- createAgent(params: {
469
+ create(params: {
339
470
  imageId: string;
340
471
  agentId?: string;
341
472
  }): Promise<AgentCreateResponse>;
342
473
  /**
343
474
  * Get agent by ID
344
475
  */
345
- getAgent(agentId: string): Promise<AgentGetResponse>;
476
+ get(agentId: string): Promise<AgentGetResponse>;
346
477
  /**
347
478
  * List agents
348
479
  */
349
- listAgents(containerId?: string): Promise<AgentListResponse>;
480
+ list(containerId?: string): Promise<AgentListResponse>;
350
481
  /**
351
482
  * Destroy an agent
352
483
  */
353
- destroyAgent(agentId: string): Promise<BaseResponse>;
484
+ destroy(agentId: string): Promise<BaseResponse>;
485
+ }
486
+ /**
487
+ * Session operations namespace (messaging)
488
+ */
489
+ interface SessionNamespace {
354
490
  /**
355
491
  * Send message to agent
356
492
  */
357
- sendMessage(agentId: string, content: string | unknown[]): Promise<MessageSendResponse>;
493
+ send(agentId: string, content: string | unknown[]): Promise<MessageSendResponse>;
358
494
  /**
359
495
  * Interrupt agent
360
496
  */
361
497
  interrupt(agentId: string): Promise<BaseResponse>;
362
498
  /**
363
- * Create a new image
499
+ * Get message history for an agent's session
364
500
  */
365
- createImage(params: {
366
- containerId: string;
367
- name?: string;
368
- description?: string;
369
- systemPrompt?: string;
370
- mcpServers?: Record<string, unknown>;
371
- }): Promise<ImageCreateResponse>;
501
+ getMessages(agentId: string): Promise<Message[]>;
502
+ }
503
+ /**
504
+ * Presentation operations namespace
505
+ */
506
+ interface PresentationNamespace {
372
507
  /**
373
- * Get image by ID
508
+ * Create a presentation for UI integration
509
+ *
510
+ * @example
511
+ * ```typescript
512
+ * const pres = agentx.presentations.create(agentId, {
513
+ * onUpdate: (state) => renderUI(state),
514
+ * onError: (error) => console.error(error),
515
+ * });
516
+ *
517
+ * await pres.send("Hello!");
518
+ * pres.dispose();
519
+ * ```
520
+ */
521
+ create(agentId: string, options?: PresentationOptions): Promise<Presentation>;
522
+ }
523
+ /**
524
+ * AgentX Client SDK
525
+ */
526
+ interface AgentX {
527
+ /**
528
+ * Check if connected to server
374
529
  */
375
- getImage(imageId: string): Promise<ImageGetResponse>;
530
+ readonly connected: boolean;
376
531
  /**
377
- * List images
532
+ * Event bus for subscribing to events
378
533
  */
379
- listImages(containerId?: string): Promise<ImageListResponse>;
534
+ readonly events: EventBus;
380
535
  /**
381
- * Delete image
536
+ * Container operations
382
537
  */
383
- deleteImage(imageId: string): Promise<BaseResponse>;
538
+ readonly containers: ContainerNamespace;
384
539
  /**
385
- * Create or get container
540
+ * Image operations
386
541
  */
387
- createContainer(containerId: string): Promise<ContainerCreateResponse>;
542
+ readonly images: ImageNamespace;
388
543
  /**
389
- * Get container
544
+ * Agent operations
390
545
  */
391
- getContainer(containerId: string): Promise<ContainerGetResponse>;
546
+ readonly agents: AgentNamespace;
392
547
  /**
393
- * List containers
548
+ * Session operations (messaging)
549
+ */
550
+ readonly sessions: SessionNamespace;
551
+ /**
552
+ * Presentation operations (UI integration)
394
553
  */
395
- listContainers(): Promise<ContainerListResponse>;
554
+ readonly presentations: PresentationNamespace;
396
555
  /**
397
556
  * Subscribe to specific event type
398
557
  */
@@ -407,21 +566,6 @@ interface AgentX {
407
566
  * Subscribe to session events
408
567
  */
409
568
  subscribe(sessionId: string): void;
410
- /**
411
- * Create a presentation for UI integration
412
- *
413
- * @example
414
- * ```typescript
415
- * const presentation = agentx.presentation(agentId);
416
- *
417
- * presentation.onUpdate((state) => {
418
- * render(state.conversations);
419
- * });
420
- *
421
- * await presentation.send("Hello!");
422
- * ```
423
- */
424
- presentation(agentId: string, options?: PresentationOptions): Presentation;
425
569
  /**
426
570
  * Disconnect from server
427
571
  */
@@ -435,55 +579,34 @@ interface AgentX {
435
579
  /**
436
580
  * agentxjs - AgentX Client SDK
437
581
  *
438
- * Connect to AgentX servers from Node.js and browsers.
582
+ * Unified entry point supporting local and remote modes.
439
583
  *
440
- * @example
584
+ * @example Local mode (embedded runtime)
441
585
  * ```typescript
442
586
  * import { createAgentX } from "agentxjs";
443
587
  *
444
- * // Connect to server
445
588
  * const agentx = await createAgentX({
446
- * serverUrl: "ws://localhost:5200",
447
- * headers: { Authorization: "Bearer sk-xxx" },
448
- * context: { userId: "123", tenantId: "abc" },
449
- * });
450
- *
451
- * // Create container and image
452
- * await agentx.createContainer("my-container");
453
- * const { record: image } = await agentx.createImage({
454
- * containerId: "my-container",
455
- * name: "Assistant",
456
- * systemPrompt: "You are a helpful assistant",
457
- * });
458
- *
459
- * // Create agent and send message
460
- * const { agentId } = await agentx.createAgent({ imageId: image.imageId });
461
- *
462
- * // Subscribe to events
463
- * agentx.on("text_delta", (event) => {
464
- * process.stdout.write(event.data.text);
589
+ * apiKey: process.env.ANTHROPIC_API_KEY,
590
+ * provider: "anthropic",
465
591
  * });
466
592
  *
467
- * agentx.on("assistant_message", (event) => {
468
- * console.log("Complete:", event.data.content);
593
+ * await agentx.containers.create("my-app");
594
+ * const { record: image } = await agentx.images.create({
595
+ * containerId: "my-app",
596
+ * systemPrompt: "You are helpful",
469
597
  * });
598
+ * const { agentId } = await agentx.agents.create({ imageId: image.imageId });
470
599
  *
471
- * // Send message
472
- * await agentx.sendMessage(agentId, "Hello!");
473
- *
474
- * // Cleanup
475
- * await agentx.dispose();
600
+ * agentx.on("text_delta", (e) => process.stdout.write(e.data.text));
601
+ * await agentx.sessions.send(agentId, "Hello!");
476
602
  * ```
477
603
  *
478
- * @example Dynamic headers and context
604
+ * @example Remote mode (WebSocket client)
479
605
  * ```typescript
606
+ * import { createAgentX } from "agentxjs";
607
+ *
480
608
  * const agentx = await createAgentX({
481
609
  * serverUrl: "ws://localhost:5200",
482
- * headers: () => ({ Authorization: `Bearer ${getToken()}` }),
483
- * context: async () => ({
484
- * userId: await getUserId(),
485
- * permissions: await getPermissions(),
486
- * }),
487
610
  * });
488
611
  * ```
489
612
  */
@@ -491,9 +614,13 @@ interface AgentX {
491
614
  /**
492
615
  * Create an AgentX client
493
616
  *
617
+ * Mode detection:
618
+ * - `serverUrl` present → **Remote mode** (WebSocket client)
619
+ * - `apiKey` present → **Local mode** (embedded Runtime + MonoDriver)
620
+ *
494
621
  * @param config - Client configuration
495
622
  * @returns Connected AgentX client
496
623
  */
497
624
  declare function createAgentX(config: AgentXConfig): Promise<AgentX>;
498
625
 
499
- export { type AgentCreateResponse, type AgentGetResponse, type AgentInfo, type AgentListResponse, type AgentX, type AgentXConfig, type AssistantConversation, type BaseResponse, type Block, type ContainerCreateResponse, type ContainerGetResponse, type ContainerInfo, type ContainerListResponse, type Conversation, type ErrorConversation, type ImageBlock, type ImageCreateResponse, type ImageGetResponse, type ImageListResponse, type ImageRecord, type MaybeAsync, type MessageSendResponse, Presentation, type PresentationErrorHandler, type PresentationOptions, type PresentationState, type PresentationUpdateHandler, type TextBlock, type ToolBlock, type UserConversation, addUserConversation, createAgentX, createInitialState, initialPresentationState, presentationReducer };
626
+ export { type AgentCreateResponse, type AgentGetResponse, type AgentInfo, type AgentListResponse, type AgentNamespace, type AgentX, type AgentXConfig, type AssistantConversation, type BaseResponse, type Block, type ContainerCreateResponse, type ContainerGetResponse, type ContainerInfo, type ContainerListResponse, type ContainerNamespace, type Conversation, type ErrorConversation, type ImageBlock, type ImageCreateResponse, type ImageGetResponse, type ImageListResponse, type ImageNamespace, type ImageRecord, type LLMProvider, type MaybeAsync, type MessageSendResponse, Presentation, type PresentationErrorHandler, type PresentationNamespace, type PresentationOptions, type PresentationState, type PresentationUpdateHandler, type SessionNamespace, type TextBlock, type ToolBlock, type UserConversation, addUserConversation, createAgentX, createInitialState, initialPresentationState, messagesToConversations, presentationReducer };