agentxjs 2.0.2 → 2.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.
@@ -0,0 +1,424 @@
1
+ /**
2
+ * CommandHandler - Handles JSON-RPC requests directly
3
+ *
4
+ * No longer uses EventBus for request/response. Instead:
5
+ * - Receives RPC requests directly
6
+ * - Returns RPC responses directly
7
+ * - EventBus is only used for stream events (notifications)
8
+ */
9
+
10
+ import type { UserContentPart } from "@agentxjs/core/agent";
11
+ import type { RpcMethod } from "@agentxjs/core/network";
12
+ import type { AgentXRuntime } from "@agentxjs/core/runtime";
13
+ import { createLogger } from "@deepracticex/logger";
14
+
15
+ const logger = createLogger("server/CommandHandler");
16
+
17
+ /**
18
+ * RPC Result type
19
+ */
20
+ export interface RpcResult<T = unknown> {
21
+ success: true;
22
+ data: T;
23
+ }
24
+
25
+ export interface RpcError {
26
+ success: false;
27
+ code: number;
28
+ message: string;
29
+ }
30
+
31
+ export type RpcResponse<T = unknown> = RpcResult<T> | RpcError;
32
+
33
+ /**
34
+ * Helper to create success result
35
+ */
36
+ function ok<T>(data: T): RpcResult<T> {
37
+ return { success: true, data };
38
+ }
39
+
40
+ /**
41
+ * Helper to create error result
42
+ */
43
+ function err(code: number, message: string): RpcError {
44
+ return { success: false, code, message };
45
+ }
46
+
47
+ /**
48
+ * CommandHandler - Processes RPC requests directly
49
+ */
50
+ export class CommandHandler {
51
+ private readonly runtime: AgentXRuntime;
52
+
53
+ constructor(runtime: AgentXRuntime) {
54
+ this.runtime = runtime;
55
+ logger.debug("CommandHandler created");
56
+ }
57
+
58
+ /**
59
+ * Handle an RPC request and return response
60
+ */
61
+ async handle(method: RpcMethod, params: unknown): Promise<RpcResponse> {
62
+ logger.debug("Handling RPC request", { method });
63
+
64
+ try {
65
+ switch (method) {
66
+ // Container
67
+ case "container.create":
68
+ return await this.handleContainerCreate(params);
69
+ case "container.get":
70
+ return await this.handleContainerGet(params);
71
+ case "container.list":
72
+ return await this.handleContainerList(params);
73
+
74
+ // Image
75
+ case "image.create":
76
+ return await this.handleImageCreate(params);
77
+ case "image.get":
78
+ return await this.handleImageGet(params);
79
+ case "image.list":
80
+ return await this.handleImageList(params);
81
+ case "image.delete":
82
+ return await this.handleImageDelete(params);
83
+ case "image.run":
84
+ return await this.handleImageRun(params);
85
+ case "image.stop":
86
+ return await this.handleImageStop(params);
87
+ case "image.update":
88
+ return await this.handleImageUpdate(params);
89
+ case "image.messages":
90
+ return await this.handleImageMessages(params);
91
+
92
+ // Agent
93
+ case "agent.get":
94
+ return await this.handleAgentGet(params);
95
+ case "agent.list":
96
+ return await this.handleAgentList(params);
97
+ case "agent.destroy":
98
+ return await this.handleAgentDestroy(params);
99
+ case "agent.destroyAll":
100
+ return await this.handleAgentDestroyAll(params);
101
+ case "agent.interrupt":
102
+ return await this.handleAgentInterrupt(params);
103
+
104
+ // Message
105
+ case "message.send":
106
+ return await this.handleMessageSend(params);
107
+
108
+ default:
109
+ return err(-32601, `Method not found: ${method}`);
110
+ }
111
+ } catch (error) {
112
+ logger.error("RPC handler error", { method, error });
113
+ return err(-32000, error instanceof Error ? error.message : String(error));
114
+ }
115
+ }
116
+
117
+ // ==================== Container Commands ====================
118
+
119
+ private async handleContainerCreate(params: unknown): Promise<RpcResponse> {
120
+ const { containerId } = params as { containerId: string };
121
+ const { getOrCreateContainer } = await import("@agentxjs/core/container");
122
+ const { containerRepository, imageRepository, sessionRepository } = this.runtime.platform;
123
+
124
+ const container = await getOrCreateContainer(containerId, {
125
+ containerRepository,
126
+ imageRepository,
127
+ sessionRepository,
128
+ });
129
+
130
+ return ok({ containerId: container.containerId });
131
+ }
132
+
133
+ private async handleContainerGet(params: unknown): Promise<RpcResponse> {
134
+ const { containerId } = params as { containerId: string };
135
+ const exists = await this.runtime.platform.containerRepository.containerExists(containerId);
136
+ return ok({ containerId, exists });
137
+ }
138
+
139
+ private async handleContainerList(_params: unknown): Promise<RpcResponse> {
140
+ const containers = await this.runtime.platform.containerRepository.findAllContainers();
141
+ return ok({ containerIds: containers.map((c) => c.containerId) });
142
+ }
143
+
144
+ // ==================== Image Commands ====================
145
+
146
+ private async handleImageCreate(params: unknown): Promise<RpcResponse> {
147
+ const { containerId, name, description, systemPrompt, mcpServers, customData } = params as {
148
+ containerId: string;
149
+ name?: string;
150
+ description?: string;
151
+ systemPrompt?: string;
152
+ mcpServers?: Record<string, unknown>;
153
+ customData?: Record<string, unknown>;
154
+ };
155
+
156
+ const { imageRepository, sessionRepository } = this.runtime.platform;
157
+ const { createImage } = await import("@agentxjs/core/image");
158
+
159
+ const image = await createImage(
160
+ { containerId, name, description, systemPrompt, mcpServers: mcpServers as any, customData },
161
+ { imageRepository, sessionRepository }
162
+ );
163
+
164
+ return ok({
165
+ record: image.toRecord(),
166
+ __subscriptions: [image.sessionId],
167
+ });
168
+ }
169
+
170
+ private async handleImageGet(params: unknown): Promise<RpcResponse> {
171
+ const { imageId } = params as { imageId: string };
172
+ const record = await this.runtime.platform.imageRepository.findImageById(imageId);
173
+ return ok({
174
+ record,
175
+ __subscriptions: record?.sessionId ? [record.sessionId] : undefined,
176
+ });
177
+ }
178
+
179
+ private async handleImageList(params: unknown): Promise<RpcResponse> {
180
+ const { containerId } = params as { containerId?: string };
181
+ const records = containerId
182
+ ? await this.runtime.platform.imageRepository.findImagesByContainerId(containerId)
183
+ : await this.runtime.platform.imageRepository.findAllImages();
184
+
185
+ return ok({
186
+ records,
187
+ __subscriptions: records.map((r) => r.sessionId),
188
+ });
189
+ }
190
+
191
+ private async handleImageDelete(params: unknown): Promise<RpcResponse> {
192
+ const { imageId } = params as { imageId: string };
193
+ const { loadImage } = await import("@agentxjs/core/image");
194
+ const { imageRepository, sessionRepository } = this.runtime.platform;
195
+
196
+ const image = await loadImage(imageId, { imageRepository, sessionRepository });
197
+ if (image) {
198
+ await image.delete();
199
+ }
200
+
201
+ return ok({ imageId });
202
+ }
203
+
204
+ private async handleImageRun(params: unknown): Promise<RpcResponse> {
205
+ const { imageId, agentId: requestedAgentId } = params as {
206
+ imageId: string;
207
+ agentId?: string;
208
+ };
209
+
210
+ // Check if already have a running agent for this image
211
+ const existingAgent = this.runtime
212
+ .getAgents()
213
+ .find((a) => a.imageId === imageId && a.lifecycle === "running");
214
+
215
+ if (existingAgent) {
216
+ logger.debug("Reusing existing agent for image", {
217
+ imageId,
218
+ agentId: existingAgent.agentId,
219
+ });
220
+ return ok({
221
+ imageId,
222
+ agentId: existingAgent.agentId,
223
+ sessionId: existingAgent.sessionId,
224
+ containerId: existingAgent.containerId,
225
+ reused: true,
226
+ });
227
+ }
228
+
229
+ // Create new agent (with optional custom agentId)
230
+ const agent = await this.runtime.createAgent({
231
+ imageId,
232
+ agentId: requestedAgentId,
233
+ });
234
+ logger.info("Created new agent for image", {
235
+ imageId,
236
+ agentId: agent.agentId,
237
+ });
238
+
239
+ return ok({
240
+ imageId,
241
+ agentId: agent.agentId,
242
+ sessionId: agent.sessionId,
243
+ containerId: agent.containerId,
244
+ reused: false,
245
+ });
246
+ }
247
+
248
+ private async handleImageStop(params: unknown): Promise<RpcResponse> {
249
+ const { imageId } = params as { imageId: string };
250
+
251
+ // Find running agent for this image
252
+ const agent = this.runtime
253
+ .getAgents()
254
+ .find((a) => a.imageId === imageId && a.lifecycle === "running");
255
+
256
+ if (agent) {
257
+ await this.runtime.stopAgent(agent.agentId);
258
+ logger.info("Stopped agent for image", { imageId, agentId: agent.agentId });
259
+ } else {
260
+ logger.debug("No running agent found for image", { imageId });
261
+ }
262
+
263
+ return ok({ imageId });
264
+ }
265
+
266
+ private async handleImageUpdate(params: unknown): Promise<RpcResponse> {
267
+ const { imageId, updates } = params as {
268
+ imageId: string;
269
+ updates: { name?: string; description?: string; customData?: Record<string, unknown> };
270
+ };
271
+
272
+ // Get existing image
273
+ const imageRecord = await this.runtime.platform.imageRepository.findImageById(imageId);
274
+ if (!imageRecord) {
275
+ return err(404, `Image not found: ${imageId}`);
276
+ }
277
+
278
+ // Update image record
279
+ const updatedRecord = {
280
+ ...imageRecord,
281
+ ...updates,
282
+ updatedAt: Date.now(),
283
+ };
284
+
285
+ await this.runtime.platform.imageRepository.saveImage(updatedRecord);
286
+
287
+ logger.info("Updated image", { imageId, updates });
288
+
289
+ return ok({ record: updatedRecord });
290
+ }
291
+
292
+ private async handleImageMessages(params: unknown): Promise<RpcResponse> {
293
+ const { imageId } = params as { imageId: string };
294
+
295
+ // Get image record to find sessionId
296
+ const imageRecord = await this.runtime.platform.imageRepository.findImageById(imageId);
297
+ if (!imageRecord) {
298
+ return err(404, `Image not found: ${imageId}`);
299
+ }
300
+
301
+ // Get messages from session
302
+ const messages = await this.runtime.platform.sessionRepository.getMessages(
303
+ imageRecord.sessionId
304
+ );
305
+
306
+ logger.debug("Got messages for image", { imageId, count: messages.length });
307
+
308
+ return ok({ imageId, messages });
309
+ }
310
+
311
+ // ==================== Agent Commands ====================
312
+
313
+ private async handleAgentGet(params: unknown): Promise<RpcResponse> {
314
+ const { agentId } = params as { agentId: string };
315
+ const agent = this.runtime.getAgent(agentId);
316
+
317
+ return ok({
318
+ agent: agent
319
+ ? {
320
+ agentId: agent.agentId,
321
+ imageId: agent.imageId,
322
+ containerId: agent.containerId,
323
+ sessionId: agent.sessionId,
324
+ lifecycle: agent.lifecycle,
325
+ }
326
+ : null,
327
+ exists: !!agent,
328
+ });
329
+ }
330
+
331
+ private async handleAgentList(params: unknown): Promise<RpcResponse> {
332
+ const { containerId } = params as { containerId?: string };
333
+ const agents = containerId
334
+ ? this.runtime.getAgentsByContainer(containerId)
335
+ : this.runtime.getAgents();
336
+
337
+ return ok({
338
+ agents: agents.map((a) => ({
339
+ agentId: a.agentId,
340
+ imageId: a.imageId,
341
+ containerId: a.containerId,
342
+ sessionId: a.sessionId,
343
+ lifecycle: a.lifecycle,
344
+ })),
345
+ });
346
+ }
347
+
348
+ private async handleAgentDestroy(params: unknown): Promise<RpcResponse> {
349
+ const { agentId } = params as { agentId: string };
350
+
351
+ // Check if agent exists first
352
+ const agent = this.runtime.getAgent(agentId);
353
+ if (!agent) {
354
+ return ok({ agentId, success: false });
355
+ }
356
+
357
+ await this.runtime.destroyAgent(agentId);
358
+ return ok({ agentId, success: true });
359
+ }
360
+
361
+ private async handleAgentDestroyAll(params: unknown): Promise<RpcResponse> {
362
+ const { containerId } = params as { containerId: string };
363
+ const agents = this.runtime.getAgentsByContainer(containerId);
364
+ for (const agent of agents) {
365
+ await this.runtime.destroyAgent(agent.agentId);
366
+ }
367
+ return ok({ containerId });
368
+ }
369
+
370
+ private async handleAgentInterrupt(params: unknown): Promise<RpcResponse> {
371
+ const { agentId } = params as { agentId: string };
372
+ this.runtime.interrupt(agentId);
373
+ return ok({ agentId });
374
+ }
375
+
376
+ // ==================== Message Commands ====================
377
+
378
+ private async handleMessageSend(params: unknown): Promise<RpcResponse> {
379
+ const { agentId, imageId, content } = params as {
380
+ agentId?: string;
381
+ imageId?: string;
382
+ content: string | UserContentPart[];
383
+ };
384
+
385
+ let targetAgentId: string;
386
+
387
+ if (agentId) {
388
+ // Direct agent reference
389
+ targetAgentId = agentId;
390
+ } else if (imageId) {
391
+ // Auto-activate image: find or create agent
392
+ const existingAgent = this.runtime
393
+ .getAgents()
394
+ .find((a) => a.imageId === imageId && a.lifecycle === "running");
395
+
396
+ if (existingAgent) {
397
+ targetAgentId = existingAgent.agentId;
398
+ logger.debug("Using existing agent for message", {
399
+ imageId,
400
+ agentId: targetAgentId,
401
+ });
402
+ } else {
403
+ // Create new agent for this image
404
+ const agent = await this.runtime.createAgent({ imageId });
405
+ targetAgentId = agent.agentId;
406
+ logger.info("Auto-created agent for message", {
407
+ imageId,
408
+ agentId: targetAgentId,
409
+ });
410
+ }
411
+ } else {
412
+ return err(-32602, "Either agentId or imageId is required");
413
+ }
414
+
415
+ await this.runtime.receive(targetAgentId, content);
416
+ return ok({ agentId: targetAgentId, imageId });
417
+ }
418
+
419
+ // ==================== Lifecycle ====================
420
+
421
+ dispose(): void {
422
+ logger.debug("CommandHandler disposed");
423
+ }
424
+ }
@@ -31,21 +31,21 @@ export class LocalClient implements AgentX {
31
31
  private readonly runtime: AgentXRuntime;
32
32
  private isDisposed = false;
33
33
 
34
- readonly containers: ContainerNamespace;
35
- readonly images: ImageNamespace;
36
- readonly agents: AgentNamespace;
37
- readonly sessions: SessionNamespace;
38
- readonly presentations: PresentationNamespace;
34
+ readonly container: ContainerNamespace;
35
+ readonly image: ImageNamespace;
36
+ readonly agent: AgentNamespace;
37
+ readonly session: SessionNamespace;
38
+ readonly presentation: PresentationNamespace;
39
39
 
40
40
  constructor(runtime: AgentXRuntime) {
41
41
  this.runtime = runtime;
42
42
  const platform = runtime.platform;
43
43
 
44
- this.containers = createLocalContainers(platform);
45
- this.images = createLocalImages(platform);
46
- this.agents = createLocalAgents(runtime);
47
- this.sessions = createLocalSessions(runtime);
48
- this.presentations = createPresentations(this);
44
+ this.container = createLocalContainers(platform);
45
+ this.image = createLocalImages(platform);
46
+ this.agent = createLocalAgents(runtime);
47
+ this.session = createLocalSessions(runtime);
48
+ this.presentation = createPresentations(this);
49
49
 
50
50
  logger.info("LocalClient initialized");
51
51
  }
@@ -17,10 +17,10 @@ import { createRemoteSessions } from "./namespaces/sessions";
17
17
  import type {
18
18
  AgentNamespace,
19
19
  AgentX,
20
- AgentXConfig,
21
20
  ContainerNamespace,
22
21
  ImageNamespace,
23
22
  PresentationNamespace,
23
+ RemoteClientConfig,
24
24
  SessionNamespace,
25
25
  } from "./types";
26
26
 
@@ -30,23 +30,23 @@ const logger = createLogger("agentx/RemoteClient");
30
30
  * RemoteClient implementation using JSON-RPC 2.0
31
31
  */
32
32
  export class RemoteClient implements AgentX {
33
- private readonly config: AgentXConfig;
33
+ private readonly config: RemoteClientConfig;
34
34
  private readonly eventBus: EventBus;
35
35
  private readonly rpcClient: RpcClient;
36
36
 
37
- readonly containers: ContainerNamespace;
38
- readonly images: ImageNamespace;
39
- readonly agents: AgentNamespace;
40
- readonly sessions: SessionNamespace;
41
- readonly presentations: PresentationNamespace;
37
+ readonly container: ContainerNamespace;
38
+ readonly image: ImageNamespace;
39
+ readonly agent: AgentNamespace;
40
+ readonly session: SessionNamespace;
41
+ readonly presentation: PresentationNamespace;
42
42
 
43
- constructor(config: AgentXConfig) {
43
+ constructor(config: RemoteClientConfig) {
44
44
  this.config = config;
45
45
  this.eventBus = new EventBusImpl();
46
46
 
47
47
  // Create RPC client (WebSocket factory from platform if available)
48
48
  this.rpcClient = new RpcClient({
49
- url: config.serverUrl!,
49
+ url: config.serverUrl,
50
50
  createWebSocket: config.customPlatform?.channelClient,
51
51
  timeout: config.timeout ?? 30000,
52
52
  autoReconnect: config.autoReconnect ?? true,
@@ -61,11 +61,11 @@ export class RemoteClient implements AgentX {
61
61
  });
62
62
 
63
63
  // Assemble namespaces
64
- this.containers = createRemoteContainers(this.rpcClient);
65
- this.images = createRemoteImages(this.rpcClient, (sessionId) => this.subscribe(sessionId));
66
- this.agents = createRemoteAgents(this.rpcClient);
67
- this.sessions = createRemoteSessions(this.rpcClient);
68
- this.presentations = createPresentations(this);
64
+ this.container = createRemoteContainers(this.rpcClient);
65
+ this.image = createRemoteImages(this.rpcClient, (sessionId) => this.subscribe(sessionId));
66
+ this.agent = createRemoteAgents(this.rpcClient);
67
+ this.session = createRemoteSessions(this.rpcClient);
68
+ this.presentation = createPresentations(this);
69
69
  }
70
70
 
71
71
  // ==================== Properties ====================