@agentxjs/core 1.9.10-dev → 2.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.
Files changed (142) hide show
  1. package/README.md +342 -0
  2. package/dist/{Processor-DT0N1qI6.d.ts → Processor-CeMyXtsX.d.ts} +1 -1
  3. package/dist/RpcClient-CMdhJxjS.d.ts +304 -0
  4. package/dist/agent/engine/internal/index.d.ts +22 -18
  5. package/dist/agent/engine/internal/index.js +1 -2
  6. package/dist/agent/engine/mealy/index.d.ts +4 -4
  7. package/dist/agent/engine/mealy/index.js +1 -2
  8. package/dist/agent/index.d.ts +92 -92
  9. package/dist/agent/index.js +16 -16
  10. package/dist/agent/types/index.d.ts +4 -4
  11. package/dist/agent/types/index.js +1 -2
  12. package/dist/bash/index.d.ts +29 -0
  13. package/dist/bash/index.js +7 -0
  14. package/dist/{bus-uF1DM2ox.d.ts → bus-C9FLWIu8.d.ts} +3 -1
  15. package/dist/{chunk-E5FPOAPO.js → chunk-22NTRYNO.js} +60 -60
  16. package/dist/chunk-22NTRYNO.js.map +1 -0
  17. package/dist/{chunk-7ZDX3O6I.js → chunk-AAFPAF67.js} +2 -2
  18. package/dist/{chunk-7ZDX3O6I.js.map → chunk-AAFPAF67.js.map} +1 -1
  19. package/dist/{chunk-EKHT54KN.js → chunk-APCBNCOW.js} +1 -1
  20. package/dist/{chunk-EKHT54KN.js.map → chunk-APCBNCOW.js.map} +1 -1
  21. package/dist/chunk-BHOD5PKR.js +55 -0
  22. package/dist/chunk-BHOD5PKR.js.map +1 -0
  23. package/dist/chunk-FI7WQFGV.js +37 -0
  24. package/dist/chunk-FI7WQFGV.js.map +1 -0
  25. package/dist/{chunk-AT5P47YA.js → chunk-RWIYC65R.js} +115 -115
  26. package/dist/chunk-RWIYC65R.js.map +1 -0
  27. package/dist/chunk-SKS7S2RY.js +1 -0
  28. package/dist/{chunk-I7GYR3MN.js → chunk-TUFZ2YH6.js} +77 -91
  29. package/dist/chunk-TUFZ2YH6.js.map +1 -0
  30. package/dist/{chunk-K6WXQ2RW.js → chunk-YSZG6XIM.js} +1 -2
  31. package/dist/chunk-YSZG6XIM.js.map +1 -0
  32. package/dist/{combinators-nEa5dD0T.d.ts → combinators-Dy-7lxKV.d.ts} +50 -50
  33. package/dist/common/logger/index.js +14 -16
  34. package/dist/common/logger/index.js.map +1 -1
  35. package/dist/container/index.d.ts +3 -4
  36. package/dist/container/index.js +0 -2
  37. package/dist/container/index.js.map +1 -1
  38. package/dist/driver/index.d.ts +2 -310
  39. package/dist/event/index.d.ts +4 -4
  40. package/dist/event/index.js +2 -3
  41. package/dist/event/types/index.d.ts +202 -208
  42. package/dist/event/types/index.js +1 -2
  43. package/dist/{event-CDuTzs__.d.ts → event-DNsF9EkO.d.ts} +5 -8
  44. package/dist/image/index.d.ts +9 -5
  45. package/dist/image/index.js +5 -2
  46. package/dist/image/index.js.map +1 -1
  47. package/dist/index--gxNpY5W.d.ts +609 -0
  48. package/dist/index.d.ts +4 -4
  49. package/dist/index.js +17 -17
  50. package/dist/{message-BMrMm1pq.d.ts → message-Dn-I2vr0.d.ts} +10 -33
  51. package/dist/mq/index.d.ts +25 -25
  52. package/dist/mq/index.js +1 -3
  53. package/dist/mq/index.js.map +1 -1
  54. package/dist/network/index.d.ts +59 -347
  55. package/dist/network/index.js +30 -41
  56. package/dist/network/index.js.map +1 -1
  57. package/dist/persistence/index.d.ts +2 -155
  58. package/dist/platform/index.d.ts +76 -0
  59. package/dist/platform/index.js.map +1 -0
  60. package/dist/runtime/index.d.ts +26 -59
  61. package/dist/runtime/index.js +117 -33
  62. package/dist/runtime/index.js.map +1 -1
  63. package/dist/session/index.d.ts +4 -52
  64. package/dist/session/index.js +4 -51
  65. package/dist/session/index.js.map +1 -1
  66. package/dist/types-Cb8tKM6Y.d.ts +90 -0
  67. package/package.json +10 -5
  68. package/src/agent/AgentStateMachine.ts +2 -2
  69. package/src/agent/__tests__/AgentStateMachine.test.ts +2 -2
  70. package/src/agent/__tests__/createAgent.test.ts +4 -4
  71. package/src/agent/__tests__/engine/internal/messageAssemblerProcessor.test.ts +301 -97
  72. package/src/agent/__tests__/engine/internal/stateEventProcessor.test.ts +6 -6
  73. package/src/agent/__tests__/engine/internal/turnTrackerProcessor.test.ts +59 -78
  74. package/src/agent/__tests__/engine/mealy/Mealy.test.ts +3 -3
  75. package/src/agent/__tests__/engine/mealy/Store.test.ts +1 -1
  76. package/src/agent/__tests__/engine/mealy/combinators.test.ts +4 -4
  77. package/src/agent/createAgent.ts +15 -15
  78. package/src/agent/engine/AgentProcessor.ts +7 -7
  79. package/src/agent/engine/MealyMachine.ts +4 -4
  80. package/src/agent/engine/internal/index.ts +11 -11
  81. package/src/agent/engine/internal/messageAssemblerProcessor.ts +113 -128
  82. package/src/agent/engine/internal/stateEventProcessor.ts +13 -15
  83. package/src/agent/engine/internal/turnTrackerProcessor.ts +27 -31
  84. package/src/agent/engine/mealy/Mealy.ts +2 -2
  85. package/src/agent/engine/mealy/combinators.ts +10 -10
  86. package/src/agent/engine/mealy/index.ts +9 -11
  87. package/src/agent/index.ts +30 -32
  88. package/src/agent/types/engine.ts +3 -3
  89. package/src/agent/types/event.ts +4 -12
  90. package/src/agent/types/index.ts +86 -88
  91. package/src/agent/types/message.ts +9 -43
  92. package/src/bash/index.ts +21 -0
  93. package/src/bash/tool.ts +57 -0
  94. package/src/bash/types.ts +108 -0
  95. package/src/common/logger/ConsoleLogger.ts +1 -1
  96. package/src/common/logger/LoggerFactoryImpl.ts +14 -14
  97. package/src/common/logger/index.ts +3 -3
  98. package/src/container/index.ts +4 -5
  99. package/src/container/types.ts +1 -1
  100. package/src/driver/index.ts +15 -16
  101. package/src/driver/types.ts +201 -73
  102. package/src/event/EventBus.ts +10 -10
  103. package/src/event/__tests__/EventBus.test.ts +2 -2
  104. package/src/event/index.ts +2 -3
  105. package/src/event/types/agent.ts +186 -191
  106. package/src/event/types/bus.ts +1 -1
  107. package/src/event/types/command.ts +293 -264
  108. package/src/event/types/container.ts +207 -222
  109. package/src/event/types/driver.ts +153 -155
  110. package/src/event/types/index.ts +6 -12
  111. package/src/event/types/session.ts +117 -130
  112. package/src/image/Image.ts +12 -2
  113. package/src/image/index.ts +4 -5
  114. package/src/image/types.ts +8 -2
  115. package/src/mq/OffsetGenerator.ts +1 -1
  116. package/src/mq/__tests__/OffsetGenerator.test.ts +1 -1
  117. package/src/mq/index.ts +4 -5
  118. package/src/network/RpcClient.ts +26 -25
  119. package/src/network/index.ts +41 -44
  120. package/src/network/jsonrpc.ts +5 -5
  121. package/src/persistence/index.ts +5 -5
  122. package/src/persistence/types.ts +5 -2
  123. package/src/platform/index.ts +21 -0
  124. package/src/platform/types.ts +84 -0
  125. package/src/runtime/AgentXRuntime.ts +188 -61
  126. package/src/runtime/__tests__/AgentXRuntime.test.ts +343 -0
  127. package/src/runtime/index.ts +12 -25
  128. package/src/runtime/types.ts +10 -62
  129. package/src/session/index.ts +2 -3
  130. package/dist/chunk-7D4SUZUM.js +0 -38
  131. package/dist/chunk-AT5P47YA.js.map +0 -1
  132. package/dist/chunk-E5FPOAPO.js.map +0 -1
  133. package/dist/chunk-I7GYR3MN.js.map +0 -1
  134. package/dist/chunk-K6WXQ2RW.js.map +0 -1
  135. package/dist/workspace/index.d.ts +0 -111
  136. package/dist/wrapper-Y3UTVU2E.js +0 -3635
  137. package/dist/wrapper-Y3UTVU2E.js.map +0 -1
  138. package/src/workspace/index.ts +0 -27
  139. package/src/workspace/types.ts +0 -131
  140. /package/dist/{workspace → bash}/index.js.map +0 -0
  141. /package/dist/{chunk-7D4SUZUM.js.map → chunk-SKS7S2RY.js.map} +0 -0
  142. /package/dist/{workspace → platform}/index.js +0 -0
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * This file defines:
5
5
  * - Content Parts: TextPart, ThinkingPart, ImagePart, FilePart, ToolCallPart, ToolResultPart
6
- * - Message Types: UserMessage, AssistantMessage, ToolCallMessage, ToolResultMessage, ErrorMessage
6
+ * - Message Types: UserMessage, AssistantMessage, ToolResultMessage, ErrorMessage
7
7
  * - Message Role and Subtype discriminators
8
8
  *
9
9
  * @packageDocumentation
@@ -170,7 +170,7 @@ type MessageRole = "user" | "assistant" | "tool" | "system" | "error";
170
170
  * Represents the specific type/category of the message.
171
171
  * Used together with role for serialization and type discrimination.
172
172
  */
173
- type MessageSubtype = "user" | "assistant" | "tool-call" | "tool-result" | "error";
173
+ type MessageSubtype = "user" | "assistant" | "tool-result" | "error";
174
174
  /**
175
175
  * Token usage information
176
176
  */
@@ -203,9 +203,9 @@ interface UserMessage {
203
203
  * Assistant Message
204
204
  *
205
205
  * Message generated by the AI assistant.
206
- * Contains text, thinking process, or files.
207
- *
208
- * Note: Tool calls are separate - use ToolCallMessage for tool invocations.
206
+ * Contains text, thinking process, files, and tool calls.
207
+ * Tool calls are content blocks within the assistant message,
208
+ * matching the mainstream API pattern (Anthropic, OpenAI).
209
209
  */
210
210
  interface AssistantMessage {
211
211
  /** Unique identifier */
@@ -214,8 +214,8 @@ interface AssistantMessage {
214
214
  role: "assistant";
215
215
  /** Message subtype for serialization */
216
216
  subtype: "assistant";
217
- /** Message content - can be simple string or array of parts */
218
- content: string | Array<TextPart | ThinkingPart | FilePart>;
217
+ /** Message content - can be simple string or array of parts (including tool calls) */
218
+ content: string | Array<TextPart | ThinkingPart | FilePart | ToolCallPart>;
219
219
  /** When this message was created (Unix timestamp in milliseconds) */
220
220
  timestamp: number;
221
221
  /** Parent message ID for threading (optional) */
@@ -223,29 +223,6 @@ interface AssistantMessage {
223
223
  /** Token usage for this AI response (optional) */
224
224
  usage?: TokenUsage;
225
225
  }
226
- /**
227
- * Tool Call Message
228
- *
229
- * Represents AI's request to invoke a tool.
230
- * Emitted when tool call parameters are fully assembled.
231
- *
232
- * Subject: Assistant (AI decided to call a tool)
233
- * Timing: At tool_use_content_block_stop
234
- */
235
- interface ToolCallMessage {
236
- /** Unique message identifier */
237
- id: string;
238
- /** Message role - assistant initiates tool calls */
239
- role: "assistant";
240
- /** Message subtype for serialization */
241
- subtype: "tool-call";
242
- /** Tool call details */
243
- toolCall: ToolCallPart;
244
- /** When this message was created (Unix timestamp in milliseconds) */
245
- timestamp: number;
246
- /** Parent message ID (the assistant message that triggered this) */
247
- parentId?: string;
248
- }
249
226
  /**
250
227
  * Tool Result Message
251
228
  *
@@ -298,8 +275,8 @@ interface ErrorMessage {
298
275
  * Use `subtype` field for precise type discrimination.
299
276
  *
300
277
  * Role: Who sent it (user, assistant, tool, system, error)
301
- * Subtype: What type of message (user, assistant, tool-call, tool-result, error)
278
+ * Subtype: What type of message (user, assistant, tool-result, error)
302
279
  */
303
- type Message = UserMessage | AssistantMessage | ToolCallMessage | ToolResultMessage | ErrorMessage;
280
+ type Message = UserMessage | AssistantMessage | ToolResultMessage | ErrorMessage;
304
281
 
305
- export type { AssistantMessage as A, ContentPart as C, ErrorMessage as E, FilePart as F, ImagePart as I, Message as M, ToolCallMessage as T, UserMessage as U, ToolResultMessage as a, TokenUsage as b, UserContentPart as c, TextPart as d, ThinkingPart as e, ToolCallPart as f, ToolResultOutput as g, ToolResultPart as h, MessageRole as i, MessageSubtype as j };
282
+ export type { AssistantMessage as A, ContentPart as C, ErrorMessage as E, FilePart as F, ImagePart as I, Message as M, ToolResultMessage as T, UserMessage as U, TokenUsage as a, UserContentPart as b, MessageRole as c, MessageSubtype as d, TextPart as e, ThinkingPart as f, ToolCallPart as g, ToolResultOutput as h, ToolResultPart as i };
@@ -1,3 +1,28 @@
1
+ /**
2
+ * OffsetGenerator - Generates monotonically increasing offsets
3
+ *
4
+ * Format: "{timestamp_base36}-{sequence_padded}"
5
+ * Example: "lq5x4g2-0001"
6
+ *
7
+ * This format ensures:
8
+ * - Lexicographic ordering matches temporal ordering
9
+ * - Multiple events in same millisecond get unique offsets
10
+ * - Human-readable and compact
11
+ */
12
+ declare class OffsetGenerator {
13
+ private lastTimestamp;
14
+ private sequence;
15
+ /**
16
+ * Generate a new offset
17
+ */
18
+ generate(): string;
19
+ /**
20
+ * Compare two offsets
21
+ * @returns negative if a < b, 0 if a == b, positive if a > b
22
+ */
23
+ static compare(a: string, b: string): number;
24
+ }
25
+
1
26
  /**
2
27
  * MessageQueue - Reliable message delivery with persistence guarantee
3
28
  *
@@ -137,29 +162,4 @@ interface MessageQueueProvider {
137
162
  createQueue(config?: QueueConfig): Promise<MessageQueue>;
138
163
  }
139
164
 
140
- /**
141
- * OffsetGenerator - Generates monotonically increasing offsets
142
- *
143
- * Format: "{timestamp_base36}-{sequence_padded}"
144
- * Example: "lq5x4g2-0001"
145
- *
146
- * This format ensures:
147
- * - Lexicographic ordering matches temporal ordering
148
- * - Multiple events in same millisecond get unique offsets
149
- * - Human-readable and compact
150
- */
151
- declare class OffsetGenerator {
152
- private lastTimestamp;
153
- private sequence;
154
- /**
155
- * Generate a new offset
156
- */
157
- generate(): string;
158
- /**
159
- * Compare two offsets
160
- * @returns negative if a < b, 0 if a == b, positive if a > b
161
- */
162
- static compare(a: string, b: string): number;
163
- }
164
-
165
165
  export { type MessageQueue, type MessageQueueProvider, OffsetGenerator, type QueueConfig, type QueueEntry, type Unsubscribe };
package/dist/mq/index.js CHANGED
@@ -1,5 +1,3 @@
1
- import "../chunk-7D4SUZUM.js";
2
-
3
1
  // src/mq/OffsetGenerator.ts
4
2
  var OffsetGenerator = class {
5
3
  lastTimestamp = 0;
@@ -28,7 +26,7 @@ var OffsetGenerator = class {
28
26
  const [bTime, bSeq] = b.split("-");
29
27
  const timeDiff = parseInt(aTime, 36) - parseInt(bTime, 36);
30
28
  if (timeDiff !== 0) return timeDiff;
31
- return parseInt(aSeq) - parseInt(bSeq);
29
+ return parseInt(aSeq, 10) - parseInt(bSeq, 10);
32
30
  }
33
31
  };
34
32
  export {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mq/OffsetGenerator.ts"],"sourcesContent":["/**\n * OffsetGenerator - Generates monotonically increasing offsets\n *\n * Format: \"{timestamp_base36}-{sequence_padded}\"\n * Example: \"lq5x4g2-0001\"\n *\n * This format ensures:\n * - Lexicographic ordering matches temporal ordering\n * - Multiple events in same millisecond get unique offsets\n * - Human-readable and compact\n */\nexport class OffsetGenerator {\n private lastTimestamp = 0;\n private sequence = 0;\n\n /**\n * Generate a new offset\n */\n generate(): string {\n const now = Date.now();\n\n if (now === this.lastTimestamp) {\n this.sequence++;\n } else {\n this.lastTimestamp = now;\n this.sequence = 0;\n }\n\n const timestampPart = now.toString(36);\n const sequencePart = this.sequence.toString().padStart(4, \"0\");\n\n return `${timestampPart}-${sequencePart}`;\n }\n\n /**\n * Compare two offsets\n * @returns negative if a < b, 0 if a == b, positive if a > b\n */\n static compare(a: string, b: string): number {\n const [aTime, aSeq] = a.split(\"-\");\n const [bTime, bSeq] = b.split(\"-\");\n\n const timeDiff = parseInt(aTime, 36) - parseInt(bTime, 36);\n if (timeDiff !== 0) return timeDiff;\n\n return parseInt(aSeq) - parseInt(bSeq);\n }\n}\n"],"mappings":";;;AAWO,IAAM,kBAAN,MAAsB;AAAA,EACnB,gBAAgB;AAAA,EAChB,WAAW;AAAA;AAAA;AAAA;AAAA,EAKnB,WAAmB;AACjB,UAAM,MAAM,KAAK,IAAI;AAErB,QAAI,QAAQ,KAAK,eAAe;AAC9B,WAAK;AAAA,IACP,OAAO;AACL,WAAK,gBAAgB;AACrB,WAAK,WAAW;AAAA,IAClB;AAEA,UAAM,gBAAgB,IAAI,SAAS,EAAE;AACrC,UAAM,eAAe,KAAK,SAAS,SAAS,EAAE,SAAS,GAAG,GAAG;AAE7D,WAAO,GAAG,aAAa,IAAI,YAAY;AAAA,EACzC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAO,QAAQ,GAAW,GAAmB;AAC3C,UAAM,CAAC,OAAO,IAAI,IAAI,EAAE,MAAM,GAAG;AACjC,UAAM,CAAC,OAAO,IAAI,IAAI,EAAE,MAAM,GAAG;AAEjC,UAAM,WAAW,SAAS,OAAO,EAAE,IAAI,SAAS,OAAO,EAAE;AACzD,QAAI,aAAa,EAAG,QAAO;AAE3B,WAAO,SAAS,IAAI,IAAI,SAAS,IAAI;AAAA,EACvC;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/mq/OffsetGenerator.ts"],"sourcesContent":["/**\n * OffsetGenerator - Generates monotonically increasing offsets\n *\n * Format: \"{timestamp_base36}-{sequence_padded}\"\n * Example: \"lq5x4g2-0001\"\n *\n * This format ensures:\n * - Lexicographic ordering matches temporal ordering\n * - Multiple events in same millisecond get unique offsets\n * - Human-readable and compact\n */\nexport class OffsetGenerator {\n private lastTimestamp = 0;\n private sequence = 0;\n\n /**\n * Generate a new offset\n */\n generate(): string {\n const now = Date.now();\n\n if (now === this.lastTimestamp) {\n this.sequence++;\n } else {\n this.lastTimestamp = now;\n this.sequence = 0;\n }\n\n const timestampPart = now.toString(36);\n const sequencePart = this.sequence.toString().padStart(4, \"0\");\n\n return `${timestampPart}-${sequencePart}`;\n }\n\n /**\n * Compare two offsets\n * @returns negative if a < b, 0 if a == b, positive if a > b\n */\n static compare(a: string, b: string): number {\n const [aTime, aSeq] = a.split(\"-\");\n const [bTime, bSeq] = b.split(\"-\");\n\n const timeDiff = parseInt(aTime, 36) - parseInt(bTime, 36);\n if (timeDiff !== 0) return timeDiff;\n\n return parseInt(aSeq, 10) - parseInt(bSeq, 10);\n }\n}\n"],"mappings":";AAWO,IAAM,kBAAN,MAAsB;AAAA,EACnB,gBAAgB;AAAA,EAChB,WAAW;AAAA;AAAA;AAAA;AAAA,EAKnB,WAAmB;AACjB,UAAM,MAAM,KAAK,IAAI;AAErB,QAAI,QAAQ,KAAK,eAAe;AAC9B,WAAK;AAAA,IACP,OAAO;AACL,WAAK,gBAAgB;AACrB,WAAK,WAAW;AAAA,IAClB;AAEA,UAAM,gBAAgB,IAAI,SAAS,EAAE;AACrC,UAAM,eAAe,KAAK,SAAS,SAAS,EAAE,SAAS,GAAG,GAAG;AAE7D,WAAO,GAAG,aAAa,IAAI,YAAY;AAAA,EACzC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAO,QAAQ,GAAW,GAAmB;AAC3C,UAAM,CAAC,OAAO,IAAI,IAAI,EAAE,MAAM,GAAG;AACjC,UAAM,CAAC,OAAO,IAAI,IAAI,EAAE,MAAM,GAAG;AAEjC,UAAM,WAAW,SAAS,OAAO,EAAE,IAAI,SAAS,OAAO,EAAE;AACzD,QAAI,aAAa,EAAG,QAAO;AAE3B,WAAO,SAAS,MAAM,EAAE,IAAI,SAAS,MAAM,EAAE;AAAA,EAC/C;AACF;","names":[]}
@@ -1,6 +1,62 @@
1
- import { JsonRpc, IParsedObject } from 'jsonrpc-lite';
1
+ export { C as ControlAckParams, N as NotificationMethod, y as RpcClient, w as RpcClientConfig, x as RpcClientState, u as RpcErrorCodes, R as RpcErrorResponse, a as RpcMethod, b as RpcNotification, c as RpcRequest, d as RpcSuccessResponse, S as StreamEventParams, W as WebSocketFactory, e as createAckNotification, f as createErrorResponse, g as createNotification, h as createRequest, i as createStreamEvent, j as createSuccessResponse, k as eventTypeToRpcMethod, l as isControlAck, m as isErrorResponse, n as isInvalid, o as isNotification, p as isRequest, q as isStreamEvent, r as isSuccessResponse, s as parseMessage, t as parseMessageObject, v as rpcMethodToResponseType } from '../RpcClient-CMdhJxjS.js';
2
2
  export { JsonRpcError } from 'jsonrpc-lite';
3
- import { S as SystemEvent } from '../base-m40r3Qgu.js';
3
+ import '../base-m40r3Qgu.js';
4
+
5
+ /**
6
+ * Reliable Message Protocol
7
+ *
8
+ * Internal protocol for message acknowledgment between server and client.
9
+ * This is transparent to the application layer.
10
+ *
11
+ * Flow:
12
+ * 1. Server sends: { __msgId: "xxx", __payload: "actual message" }
13
+ * 2. Client receives, extracts payload, sends: { __ack: "xxx" }
14
+ * 3. Server receives ACK, triggers onAck callback
15
+ */
16
+ /**
17
+ * ReliableWrapper - Wrapper for reliable messages (server → client)
18
+ *
19
+ * Contains the original message payload with a unique ID for tracking.
20
+ */
21
+ interface ReliableWrapper {
22
+ /** Unique message ID for tracking */
23
+ __msgId: string;
24
+ /** Original message payload */
25
+ __payload: string;
26
+ }
27
+ /**
28
+ * AckMessage - Acknowledgment message (client → server)
29
+ *
30
+ * Sent automatically by client when receiving a reliable message.
31
+ */
32
+ interface AckMessage {
33
+ /** Message ID being acknowledged */
34
+ __ack: string;
35
+ }
36
+ /**
37
+ * Check if data is a ReliableWrapper
38
+ */
39
+ declare function isReliableWrapper(data: unknown): data is ReliableWrapper;
40
+ /**
41
+ * Check if data is an AckMessage
42
+ */
43
+ declare function isAckMessage(data: unknown): data is AckMessage;
44
+ /**
45
+ * Wrap a message for reliable delivery
46
+ */
47
+ declare function wrapMessage(msgId: string, payload: string): ReliableWrapper;
48
+ /**
49
+ * Create an ACK message
50
+ */
51
+ declare function createAck(msgId: string): AckMessage;
52
+ /**
53
+ * Unwrap a reliable message, returning the original payload
54
+ */
55
+ declare function unwrapMessage(wrapper: ReliableWrapper): string;
56
+ /**
57
+ * Generate a unique message ID
58
+ */
59
+ declare function generateMessageId(): string;
4
60
 
5
61
  /**
6
62
  * Network Types - Channel interfaces for client-server communication
@@ -220,348 +276,4 @@ interface ChannelClientProvider {
220
276
  createClient(options: ChannelClientOptions): ChannelClient;
221
277
  }
222
278
 
223
- /**
224
- * Reliable Message Protocol
225
- *
226
- * Internal protocol for message acknowledgment between server and client.
227
- * This is transparent to the application layer.
228
- *
229
- * Flow:
230
- * 1. Server sends: { __msgId: "xxx", __payload: "actual message" }
231
- * 2. Client receives, extracts payload, sends: { __ack: "xxx" }
232
- * 3. Server receives ACK, triggers onAck callback
233
- */
234
- /**
235
- * ReliableWrapper - Wrapper for reliable messages (server → client)
236
- *
237
- * Contains the original message payload with a unique ID for tracking.
238
- */
239
- interface ReliableWrapper {
240
- /** Unique message ID for tracking */
241
- __msgId: string;
242
- /** Original message payload */
243
- __payload: string;
244
- }
245
- /**
246
- * AckMessage - Acknowledgment message (client → server)
247
- *
248
- * Sent automatically by client when receiving a reliable message.
249
- */
250
- interface AckMessage {
251
- /** Message ID being acknowledged */
252
- __ack: string;
253
- }
254
- /**
255
- * Check if data is a ReliableWrapper
256
- */
257
- declare function isReliableWrapper(data: unknown): data is ReliableWrapper;
258
- /**
259
- * Check if data is an AckMessage
260
- */
261
- declare function isAckMessage(data: unknown): data is AckMessage;
262
- /**
263
- * Wrap a message for reliable delivery
264
- */
265
- declare function wrapMessage(msgId: string, payload: string): ReliableWrapper;
266
- /**
267
- * Create an ACK message
268
- */
269
- declare function createAck(msgId: string): AckMessage;
270
- /**
271
- * Unwrap a reliable message, returning the original payload
272
- */
273
- declare function unwrapMessage(wrapper: ReliableWrapper): string;
274
- /**
275
- * Generate a unique message ID
276
- */
277
- declare function generateMessageId(): string;
278
-
279
- /**
280
- * JSON-RPC 2.0 Protocol for AgentX Network Communication
281
- *
282
- * Uses jsonrpc-lite for message parsing/serialization.
283
- *
284
- * Message Types:
285
- * - Request: Client → Server (has id, expects response)
286
- * - Response: Server → Client (success or error)
287
- * - Notification: Server → Client (no id, stream events)
288
- *
289
- * @see https://www.jsonrpc.org/specification
290
- */
291
-
292
- /**
293
- * All RPC method names supported by AgentX
294
- */
295
- type RpcMethod = "container.create" | "container.get" | "container.list" | "image.create" | "image.get" | "image.list" | "image.delete" | "image.run" | "image.stop" | "image.update" | "image.messages" | "agent.get" | "agent.list" | "agent.destroy" | "agent.destroyAll" | "agent.interrupt" | "message.send";
296
- /**
297
- * Notification method names (server push)
298
- */
299
- type NotificationMethod = "stream.event" | "control.ack";
300
- /**
301
- * JSON-RPC Request structure
302
- */
303
- interface RpcRequest<M extends RpcMethod = RpcMethod, P = unknown> {
304
- jsonrpc: "2.0";
305
- method: M;
306
- params: P;
307
- id: string | number;
308
- }
309
- /**
310
- * JSON-RPC Success Response structure
311
- */
312
- interface RpcSuccessResponse<R = unknown> {
313
- jsonrpc: "2.0";
314
- result: R;
315
- id: string | number;
316
- }
317
- /**
318
- * JSON-RPC Error Response structure
319
- */
320
- interface RpcErrorResponse {
321
- jsonrpc: "2.0";
322
- error: {
323
- code: number;
324
- message: string;
325
- data?: unknown;
326
- };
327
- id: string | number | null;
328
- }
329
- /**
330
- * JSON-RPC Notification structure (no id, no response expected)
331
- */
332
- interface RpcNotification<M extends NotificationMethod = NotificationMethod, P = unknown> {
333
- jsonrpc: "2.0";
334
- method: M;
335
- params: P;
336
- }
337
- /**
338
- * Stream event notification params
339
- */
340
- interface StreamEventParams {
341
- topic: string;
342
- event: SystemEvent;
343
- }
344
- /**
345
- * Control ACK notification params
346
- */
347
- interface ControlAckParams {
348
- msgId: string;
349
- }
350
- declare const RpcErrorCodes: {
351
- readonly PARSE_ERROR: -32700;
352
- readonly INVALID_REQUEST: -32600;
353
- readonly METHOD_NOT_FOUND: -32601;
354
- readonly INVALID_PARAMS: -32602;
355
- readonly INTERNAL_ERROR: -32603;
356
- readonly SERVER_ERROR: -32000;
357
- readonly NOT_FOUND: 404;
358
- readonly UNAUTHORIZED: 401;
359
- readonly FORBIDDEN: 403;
360
- readonly TIMEOUT: 408;
361
- };
362
- /**
363
- * Create a JSON-RPC request
364
- */
365
- declare function createRequest(id: string | number, method: RpcMethod | string, params: unknown): JsonRpc;
366
- /**
367
- * Create a JSON-RPC notification (no response expected)
368
- */
369
- declare function createNotification(method: NotificationMethod | string, params: unknown): JsonRpc;
370
- /**
371
- * Create a stream event notification
372
- */
373
- declare function createStreamEvent(topic: string, event: SystemEvent): JsonRpc;
374
- /**
375
- * Create an ACK notification
376
- */
377
- declare function createAckNotification(msgId: string): JsonRpc;
378
- /**
379
- * Create a success response
380
- */
381
- declare function createSuccessResponse(id: string | number, result: unknown): JsonRpc;
382
- /**
383
- * Create an error response
384
- */
385
- declare function createErrorResponse(id: string | number | null, code: number, message: string, data?: unknown): JsonRpc;
386
- /**
387
- * Parse a JSON-RPC message string
388
- */
389
- declare function parseMessage(message: string): IParsedObject | IParsedObject[];
390
- /**
391
- * Parse a JSON-RPC message object
392
- */
393
- declare function parseMessageObject(obj: unknown): IParsedObject;
394
- /**
395
- * Check if parsed message is a request
396
- */
397
- declare function isRequest(parsed: IParsedObject): boolean;
398
- /**
399
- * Check if parsed message is a notification
400
- */
401
- declare function isNotification(parsed: IParsedObject): boolean;
402
- /**
403
- * Check if parsed message is a success response
404
- */
405
- declare function isSuccessResponse(parsed: IParsedObject): boolean;
406
- /**
407
- * Check if parsed message is an error response
408
- */
409
- declare function isErrorResponse(parsed: IParsedObject): boolean;
410
- /**
411
- * Check if parsed message is invalid
412
- */
413
- declare function isInvalid(parsed: IParsedObject): boolean;
414
- /**
415
- * Check if notification is a stream event
416
- */
417
- declare function isStreamEvent(parsed: IParsedObject): parsed is IParsedObject & {
418
- payload: RpcNotification<"stream.event", StreamEventParams>;
419
- };
420
- /**
421
- * Check if notification is a control ACK
422
- */
423
- declare function isControlAck(parsed: IParsedObject): parsed is IParsedObject & {
424
- payload: RpcNotification<"control.ack", ControlAckParams>;
425
- };
426
- /**
427
- * Map old event type names to new RPC method names
428
- */
429
- declare const eventTypeToRpcMethod: Record<string, RpcMethod>;
430
- /**
431
- * Map RPC method names back to response event types
432
- */
433
- declare const rpcMethodToResponseType: Record<RpcMethod, string>;
434
-
435
- /**
436
- * RpcClient - JSON-RPC 2.0 Client over WebSocket
437
- *
438
- * Provides:
439
- * - Request/Response with automatic ID matching
440
- * - Notification handling (stream events)
441
- * - Timeout management
442
- * - Reconnection support
443
- *
444
- * @example
445
- * ```typescript
446
- * const client = new RpcClient({ url: "ws://localhost:5200" });
447
- * await client.connect();
448
- *
449
- * // RPC call
450
- * const result = await client.call("container.list", {});
451
- *
452
- * // Stream events
453
- * client.onNotification("stream.event", (params) => {
454
- * console.log("Event:", params.event);
455
- * });
456
- *
457
- * // Subscribe to topic
458
- * client.notify("subscribe", { topic: "session-123" });
459
- * ```
460
- */
461
-
462
- /**
463
- * RpcClient configuration
464
- */
465
- interface RpcClientConfig {
466
- /**
467
- * WebSocket URL
468
- */
469
- url: string;
470
- /**
471
- * Request timeout in milliseconds (default: 30000)
472
- */
473
- timeout?: number;
474
- /**
475
- * Auto reconnect on disconnect (default: true)
476
- */
477
- autoReconnect?: boolean;
478
- /**
479
- * Reconnect delay in milliseconds (default: 3000)
480
- */
481
- reconnectDelay?: number;
482
- /**
483
- * Headers for authentication (Node.js only, sent in first message for browser)
484
- */
485
- headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
486
- /**
487
- * Debug logging
488
- */
489
- debug?: boolean;
490
- }
491
- /**
492
- * Notification handler
493
- */
494
- type NotificationHandler = (method: string, params: unknown) => void;
495
- /**
496
- * Stream event handler
497
- */
498
- type StreamEventHandler = (topic: string, event: SystemEvent) => void;
499
- /**
500
- * Connection state
501
- */
502
- type RpcClientState = "disconnected" | "connecting" | "connected";
503
- /**
504
- * JSON-RPC 2.0 Client
505
- */
506
- declare class RpcClient {
507
- private readonly config;
508
- private readonly timeout;
509
- private readonly pendingRequests;
510
- private readonly notificationHandlers;
511
- private readonly streamEventHandlers;
512
- private ws;
513
- private state;
514
- private requestId;
515
- private reconnectTimer;
516
- private disposed;
517
- constructor(config: RpcClientConfig);
518
- /**
519
- * Current connection state
520
- */
521
- get connectionState(): RpcClientState;
522
- /**
523
- * Whether client is connected
524
- */
525
- get connected(): boolean;
526
- /**
527
- * Connect to server
528
- */
529
- connect(): Promise<void>;
530
- /**
531
- * Disconnect from server
532
- */
533
- disconnect(): void;
534
- /**
535
- * Dispose client and clean up resources
536
- */
537
- dispose(): void;
538
- private scheduleReconnect;
539
- /**
540
- * Call an RPC method and wait for response
541
- */
542
- call<T = unknown>(method: RpcMethod, params: unknown): Promise<T>;
543
- /**
544
- * Send a notification (no response expected)
545
- */
546
- notify(method: NotificationMethod | string, params: unknown): void;
547
- /**
548
- * Subscribe to a topic (convenience method)
549
- */
550
- subscribe(topic: string): void;
551
- /**
552
- * Unsubscribe from a topic (convenience method)
553
- */
554
- unsubscribe(topic: string): void;
555
- /**
556
- * Register handler for all notifications
557
- */
558
- onNotification(handler: NotificationHandler): () => void;
559
- /**
560
- * Register handler for stream events
561
- */
562
- onStreamEvent(handler: StreamEventHandler): () => void;
563
- private handleMessage;
564
- private handleParsedMessage;
565
- }
566
-
567
- export { type AckMessage, type ChannelClient, type ChannelClientOptions, type ChannelClientProvider, type ChannelConnection, type ChannelServer, type ChannelServerOptions, type ChannelServerProvider, type ConnectionState, type ControlAckParams, type MinimalHTTPServer, type NotificationMethod, type ReliableWrapper, RpcClient, type RpcClientConfig, type RpcClientState, RpcErrorCodes, type RpcErrorResponse, type RpcMethod, type RpcNotification, type RpcRequest, type RpcSuccessResponse, type SendReliableOptions, type StreamEventParams, type Unsubscribe, createAck, createAckNotification, createErrorResponse, createNotification, createRequest, createStreamEvent, createSuccessResponse, eventTypeToRpcMethod, generateMessageId, isAckMessage, isControlAck, isErrorResponse, isInvalid, isNotification, isReliableWrapper, isRequest, isStreamEvent, isSuccessResponse, parseMessage, parseMessageObject, rpcMethodToResponseType, unwrapMessage, wrapMessage };
279
+ export { type AckMessage, type ChannelClient, type ChannelClientOptions, type ChannelClientProvider, type ChannelConnection, type ChannelServer, type ChannelServerOptions, type ChannelServerProvider, type ConnectionState, type MinimalHTTPServer, type ReliableWrapper, type SendReliableOptions, type Unsubscribe, createAck, generateMessageId, isAckMessage, isReliableWrapper, unwrapMessage, wrapMessage };
@@ -1,37 +1,12 @@
1
- import "../chunk-7D4SUZUM.js";
2
-
3
- // src/network/protocol.ts
4
- function isReliableWrapper(data) {
5
- return typeof data === "object" && data !== null && "__msgId" in data && "__payload" in data;
6
- }
7
- function isAckMessage(data) {
8
- return typeof data === "object" && data !== null && "__ack" in data;
9
- }
10
- function wrapMessage(msgId, payload) {
11
- return { __msgId: msgId, __payload: payload };
12
- }
13
- function createAck(msgId) {
14
- return { __ack: msgId };
15
- }
16
- function unwrapMessage(wrapper) {
17
- return wrapper.__payload;
18
- }
19
- function generateMessageId() {
20
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
21
- return crypto.randomUUID();
22
- }
23
- return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
24
- }
25
-
26
1
  // src/network/jsonrpc.ts
27
2
  import {
28
- request as jsonrpcRequest,
29
- notification as jsonrpcNotification,
30
- success as jsonrpcSuccess,
3
+ JsonRpcError,
31
4
  error as jsonrpcError,
5
+ notification as jsonrpcNotification,
32
6
  parse as jsonrpcParse,
33
7
  parseObject as jsonrpcParseObject,
34
- JsonRpcError
8
+ request as jsonrpcRequest,
9
+ success as jsonrpcSuccess
35
10
  } from "jsonrpc-lite";
36
11
  var RpcErrorCodes = {
37
12
  // Standard JSON-RPC errors
@@ -144,11 +119,30 @@ var rpcMethodToResponseType = {
144
119
  "message.send": "message_send_response"
145
120
  };
146
121
 
147
- // src/network/RpcClient.ts
148
- function isBrowser() {
149
- const globalWindow = typeof globalThis !== "undefined" ? globalThis.window : void 0;
150
- return globalWindow?.document !== void 0;
122
+ // src/network/protocol.ts
123
+ function isReliableWrapper(data) {
124
+ return typeof data === "object" && data !== null && "__msgId" in data && "__payload" in data;
125
+ }
126
+ function isAckMessage(data) {
127
+ return typeof data === "object" && data !== null && "__ack" in data;
151
128
  }
129
+ function wrapMessage(msgId, payload) {
130
+ return { __msgId: msgId, __payload: payload };
131
+ }
132
+ function createAck(msgId) {
133
+ return { __ack: msgId };
134
+ }
135
+ function unwrapMessage(wrapper) {
136
+ return wrapper.__payload;
137
+ }
138
+ function generateMessageId() {
139
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
140
+ return crypto.randomUUID();
141
+ }
142
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
143
+ }
144
+
145
+ // src/network/RpcClient.ts
152
146
  var RpcClient = class {
153
147
  config;
154
148
  timeout;
@@ -190,13 +184,8 @@ var RpcClient = class {
190
184
  }
191
185
  this.state = "connecting";
192
186
  const url = this.config.url;
193
- let ws;
194
- if (isBrowser()) {
195
- ws = new WebSocket(url);
196
- } else {
197
- const { default: WS } = await import("../wrapper-Y3UTVU2E.js");
198
- ws = new WS(url);
199
- }
187
+ const factory = this.config.createWebSocket ?? ((u) => new WebSocket(u));
188
+ const ws = factory(url);
200
189
  this.ws = ws;
201
190
  return new Promise((resolve, reject) => {
202
191
  ws.onopen = async () => {
@@ -204,7 +193,7 @@ var RpcClient = class {
204
193
  if (this.config.debug) {
205
194
  console.log("[RpcClient] Connected to", url);
206
195
  }
207
- if (isBrowser() && this.config.headers) {
196
+ if (this.config.headers) {
208
197
  const headers = typeof this.config.headers === "function" ? await this.config.headers() : this.config.headers;
209
198
  this.notify("auth", { headers });
210
199
  }