@agentxjs/core 1.9.1-dev

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 (77) hide show
  1. package/package.json +31 -0
  2. package/src/agent/AgentStateMachine.ts +151 -0
  3. package/src/agent/README.md +296 -0
  4. package/src/agent/__tests__/AgentStateMachine.test.ts +346 -0
  5. package/src/agent/__tests__/createAgent.test.ts +728 -0
  6. package/src/agent/__tests__/engine/internal/messageAssemblerProcessor.test.ts +567 -0
  7. package/src/agent/__tests__/engine/internal/stateEventProcessor.test.ts +315 -0
  8. package/src/agent/__tests__/engine/internal/turnTrackerProcessor.test.ts +340 -0
  9. package/src/agent/__tests__/engine/mealy/Mealy.test.ts +370 -0
  10. package/src/agent/__tests__/engine/mealy/Store.test.ts +123 -0
  11. package/src/agent/__tests__/engine/mealy/combinators.test.ts +322 -0
  12. package/src/agent/createAgent.ts +467 -0
  13. package/src/agent/engine/AgentProcessor.ts +106 -0
  14. package/src/agent/engine/MealyMachine.ts +184 -0
  15. package/src/agent/engine/internal/index.ts +35 -0
  16. package/src/agent/engine/internal/messageAssemblerProcessor.ts +550 -0
  17. package/src/agent/engine/internal/stateEventProcessor.ts +313 -0
  18. package/src/agent/engine/internal/turnTrackerProcessor.ts +239 -0
  19. package/src/agent/engine/mealy/Mealy.ts +308 -0
  20. package/src/agent/engine/mealy/Processor.ts +70 -0
  21. package/src/agent/engine/mealy/Sink.ts +56 -0
  22. package/src/agent/engine/mealy/Source.ts +51 -0
  23. package/src/agent/engine/mealy/Store.ts +98 -0
  24. package/src/agent/engine/mealy/combinators.ts +176 -0
  25. package/src/agent/engine/mealy/index.ts +45 -0
  26. package/src/agent/index.ts +106 -0
  27. package/src/agent/types/engine.ts +395 -0
  28. package/src/agent/types/event.ts +478 -0
  29. package/src/agent/types/index.ts +197 -0
  30. package/src/agent/types/message.ts +387 -0
  31. package/src/common/index.ts +8 -0
  32. package/src/common/logger/ConsoleLogger.ts +137 -0
  33. package/src/common/logger/LoggerFactoryImpl.ts +123 -0
  34. package/src/common/logger/index.ts +26 -0
  35. package/src/common/logger/types.ts +98 -0
  36. package/src/container/Container.ts +185 -0
  37. package/src/container/index.ts +44 -0
  38. package/src/container/types.ts +71 -0
  39. package/src/driver/index.ts +42 -0
  40. package/src/driver/types.ts +363 -0
  41. package/src/event/EventBus.ts +260 -0
  42. package/src/event/README.md +237 -0
  43. package/src/event/__tests__/EventBus.test.ts +251 -0
  44. package/src/event/index.ts +46 -0
  45. package/src/event/types/agent.ts +512 -0
  46. package/src/event/types/base.ts +241 -0
  47. package/src/event/types/bus.ts +429 -0
  48. package/src/event/types/command.ts +749 -0
  49. package/src/event/types/container.ts +471 -0
  50. package/src/event/types/driver.ts +452 -0
  51. package/src/event/types/index.ts +26 -0
  52. package/src/event/types/session.ts +314 -0
  53. package/src/image/Image.ts +203 -0
  54. package/src/image/index.ts +36 -0
  55. package/src/image/types.ts +77 -0
  56. package/src/index.ts +20 -0
  57. package/src/mq/OffsetGenerator.ts +48 -0
  58. package/src/mq/README.md +166 -0
  59. package/src/mq/__tests__/OffsetGenerator.test.ts +121 -0
  60. package/src/mq/index.ts +18 -0
  61. package/src/mq/types.ts +172 -0
  62. package/src/network/RpcClient.ts +455 -0
  63. package/src/network/index.ts +76 -0
  64. package/src/network/jsonrpc.ts +336 -0
  65. package/src/network/protocol.ts +90 -0
  66. package/src/network/types.ts +284 -0
  67. package/src/persistence/index.ts +27 -0
  68. package/src/persistence/types.ts +226 -0
  69. package/src/runtime/AgentXRuntime.ts +501 -0
  70. package/src/runtime/index.ts +56 -0
  71. package/src/runtime/types.ts +236 -0
  72. package/src/session/Session.ts +71 -0
  73. package/src/session/index.ts +25 -0
  74. package/src/session/types.ts +77 -0
  75. package/src/workspace/index.ts +27 -0
  76. package/src/workspace/types.ts +131 -0
  77. package/tsconfig.json +10 -0
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Runtime Types
3
+ *
4
+ * AgentXProvider - Dependency injection container
5
+ * AgentXRuntime - Runtime integration layer
6
+ *
7
+ * Architecture:
8
+ * ```
9
+ * ┌─────────────────────────────────────────────────────────────┐
10
+ * │ AgentXProvider │
11
+ * │ (Dependency Injection - Platform provides implementations) │
12
+ * │ │
13
+ * │ ┌─────────────┐ ┌─────────────┐ ┌───────────────┐ │
14
+ * │ │ Repositories│ │ Workspace │ │ DriverFactory │ │
15
+ * │ │ Container │ │ Provider │ │ (per-Agent) │ │
16
+ * │ │ Image │ │ │ │ │ │
17
+ * │ │ Session │ │ │ │ │ │
18
+ * │ └─────────────┘ └─────────────┘ └─────────────┘ │
19
+ * └─────────────────────────────────────────────────────────────┘
20
+ * │
21
+ * ▼
22
+ * ┌─────────────────────────────────────────────────────────────┐
23
+ * │ AgentXRuntime │
24
+ * │ (Integration - Uses Provider dependencies) │
25
+ * │ │
26
+ * │ ┌─────────────────────────────────────────────────────┐ │
27
+ * │ │ Agent Lifecycle: create / get / destroy │ │
28
+ * │ │ Message Flow: receive → EventBus → Driver │ │
29
+ * │ │ Event Subscription: subscribe to agent events │ │
30
+ * │ └─────────────────────────────────────────────────────┘ │
31
+ * └─────────────────────────────────────────────────────────────┘
32
+ * ```
33
+ */
34
+
35
+ import type { ContainerRepository } from "../container/types";
36
+ import type { ImageRepository } from "../image/types";
37
+ import type { SessionRepository } from "../session/types";
38
+ import type { WorkspaceProvider } from "../workspace/types";
39
+ import type { CreateDriver } from "../driver/types";
40
+ import type { EventBus } from "../event/types";
41
+ import type { UserContentPart } from "../agent/types";
42
+ import type { BusEvent } from "../event/types";
43
+
44
+ // ============================================================================
45
+ // Agent Runtime State
46
+ // ============================================================================
47
+
48
+ /**
49
+ * Agent lifecycle states
50
+ */
51
+ export type AgentLifecycle = "running" | "stopped" | "destroyed";
52
+
53
+ /**
54
+ * Runtime Agent - Active agent instance
55
+ */
56
+ export interface RuntimeAgent {
57
+ readonly agentId: string;
58
+ readonly imageId: string;
59
+ readonly containerId: string;
60
+ readonly sessionId: string;
61
+ readonly name: string;
62
+ readonly lifecycle: AgentLifecycle;
63
+ readonly createdAt: number;
64
+ }
65
+
66
+ // ============================================================================
67
+ // AgentXProvider - Dependency Injection
68
+ // ============================================================================
69
+
70
+ /**
71
+ * AgentXProvider - Collects all dependencies for runtime
72
+ *
73
+ * Platform packages provide implementations of these interfaces.
74
+ * The provider is passed to AgentXRuntime for integration.
75
+ */
76
+ export interface AgentXProvider {
77
+ /**
78
+ * Container repository for persistence
79
+ */
80
+ readonly containerRepository: ContainerRepository;
81
+
82
+ /**
83
+ * Image repository for persistence
84
+ */
85
+ readonly imageRepository: ImageRepository;
86
+
87
+ /**
88
+ * Session repository for persistence
89
+ */
90
+ readonly sessionRepository: SessionRepository;
91
+
92
+ /**
93
+ * Workspace provider for isolated environments
94
+ */
95
+ readonly workspaceProvider: WorkspaceProvider;
96
+
97
+ /**
98
+ * LLM Driver factory function - creates Driver per Agent
99
+ */
100
+ readonly createDriver: CreateDriver;
101
+
102
+ /**
103
+ * Event bus for pub/sub
104
+ */
105
+ readonly eventBus: EventBus;
106
+ }
107
+
108
+ // ============================================================================
109
+ // AgentXRuntime - Integration Layer
110
+ // ============================================================================
111
+
112
+ /**
113
+ * Agent creation options
114
+ */
115
+ export interface CreateAgentOptions {
116
+ /**
117
+ * Image ID to create agent from
118
+ */
119
+ imageId: string;
120
+
121
+ /**
122
+ * Optional agent ID (auto-generated if not provided)
123
+ */
124
+ agentId?: string;
125
+ }
126
+
127
+ /**
128
+ * Event handler for agent events
129
+ */
130
+ export type AgentEventHandler = (event: BusEvent) => void;
131
+
132
+ /**
133
+ * Subscription handle for unsubscribing
134
+ */
135
+ export interface Subscription {
136
+ unsubscribe(): void;
137
+ }
138
+
139
+ /**
140
+ * AgentXRuntime - Runtime integration layer
141
+ *
142
+ * Integrates all components to provide agent lifecycle management
143
+ * and message handling.
144
+ */
145
+ export interface AgentXRuntime {
146
+ /**
147
+ * The provider containing all dependencies
148
+ */
149
+ readonly provider: AgentXProvider;
150
+
151
+ // ==================== Agent Lifecycle ====================
152
+
153
+ /**
154
+ * Create and start an agent from an image
155
+ */
156
+ createAgent(options: CreateAgentOptions): Promise<RuntimeAgent>;
157
+
158
+ /**
159
+ * Get an active agent by ID
160
+ */
161
+ getAgent(agentId: string): RuntimeAgent | undefined;
162
+
163
+ /**
164
+ * Get all active agents
165
+ */
166
+ getAgents(): RuntimeAgent[];
167
+
168
+ /**
169
+ * Get agents by container ID
170
+ */
171
+ getAgentsByContainer(containerId: string): RuntimeAgent[];
172
+
173
+ /**
174
+ * Stop an agent (can be resumed)
175
+ */
176
+ stopAgent(agentId: string): Promise<void>;
177
+
178
+ /**
179
+ * Resume a stopped agent
180
+ */
181
+ resumeAgent(agentId: string): Promise<void>;
182
+
183
+ /**
184
+ * Destroy an agent (cannot be resumed)
185
+ */
186
+ destroyAgent(agentId: string): Promise<void>;
187
+
188
+ // ==================== Message Handling ====================
189
+
190
+ /**
191
+ * Send a message to an agent
192
+ *
193
+ * Emits user_message to EventBus, Driver picks it up and responds.
194
+ */
195
+ receive(agentId: string, content: string | UserContentPart[], requestId?: string): Promise<void>;
196
+
197
+ /**
198
+ * Interrupt an agent's current operation
199
+ */
200
+ interrupt(agentId: string, requestId?: string): void;
201
+
202
+ // ==================== Event Subscription ====================
203
+
204
+ /**
205
+ * Subscribe to events for a specific agent
206
+ */
207
+ subscribe(agentId: string, handler: AgentEventHandler): Subscription;
208
+
209
+ /**
210
+ * Subscribe to all events (all agents)
211
+ */
212
+ subscribeAll(handler: AgentEventHandler): Subscription;
213
+
214
+ // ==================== Cleanup ====================
215
+
216
+ /**
217
+ * Shutdown runtime and cleanup all resources
218
+ */
219
+ shutdown(): Promise<void>;
220
+ }
221
+
222
+ // ============================================================================
223
+ // Factory Types
224
+ // ============================================================================
225
+
226
+ /**
227
+ * Configuration for creating AgentXRuntime
228
+ */
229
+ export interface AgentXRuntimeConfig {
230
+ provider: AgentXProvider;
231
+ }
232
+
233
+ /**
234
+ * Factory function type for creating AgentXRuntime
235
+ */
236
+ export type CreateAgentXRuntime = (config: AgentXRuntimeConfig) => AgentXRuntime;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Session - Manages conversation messages
3
+ *
4
+ * Collects messages and persists to storage via SessionRepository.
5
+ * Pure implementation without EventBus dependency.
6
+ */
7
+
8
+ import type { Message } from "../agent/types";
9
+ import type { Session, SessionConfig, SessionRecord, SessionRepository } from "./types";
10
+
11
+ /**
12
+ * SessionImpl - Session implementation
13
+ */
14
+ export class SessionImpl implements Session {
15
+ readonly sessionId: string;
16
+ readonly imageId: string;
17
+ readonly containerId: string;
18
+ readonly createdAt: number;
19
+
20
+ private readonly repository: SessionRepository;
21
+
22
+ constructor(config: SessionConfig) {
23
+ this.sessionId = config.sessionId;
24
+ this.imageId = config.imageId;
25
+ this.containerId = config.containerId;
26
+ this.createdAt = Date.now();
27
+ this.repository = config.repository;
28
+ }
29
+
30
+ /**
31
+ * Initialize session in storage
32
+ */
33
+ async initialize(): Promise<void> {
34
+ const record: SessionRecord = {
35
+ sessionId: this.sessionId,
36
+ imageId: this.imageId,
37
+ containerId: this.containerId,
38
+ createdAt: this.createdAt,
39
+ updatedAt: this.createdAt,
40
+ };
41
+ await this.repository.saveSession(record);
42
+ }
43
+
44
+ /**
45
+ * Add a message to the session
46
+ */
47
+ async addMessage(message: Message): Promise<void> {
48
+ await this.repository.addMessage(this.sessionId, message);
49
+ }
50
+
51
+ /**
52
+ * Get all messages in the session
53
+ */
54
+ async getMessages(): Promise<Message[]> {
55
+ return this.repository.getMessages(this.sessionId);
56
+ }
57
+
58
+ /**
59
+ * Clear all messages in the session
60
+ */
61
+ async clear(): Promise<void> {
62
+ await this.repository.clearMessages(this.sessionId);
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Create a new Session instance
68
+ */
69
+ export function createSession(config: SessionConfig): Session {
70
+ return new SessionImpl(config);
71
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Session Module
3
+ *
4
+ * Manages conversation messages for an Image.
5
+ *
6
+ * Usage:
7
+ * ```typescript
8
+ * import { createSession, type SessionRepository } from "@agentxjs/core/session";
9
+ *
10
+ * const session = createSession({
11
+ * sessionId: "session-1",
12
+ * imageId: "image-1",
13
+ * containerId: "container-1",
14
+ * repository: mySessionRepository,
15
+ * });
16
+ *
17
+ * await session.initialize();
18
+ * await session.addMessage(message);
19
+ * const messages = await session.getMessages();
20
+ * ```
21
+ */
22
+
23
+ export type { SessionRecord, SessionRepository, Session, SessionConfig } from "./types";
24
+
25
+ export { SessionImpl, createSession } from "./Session";
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Session Types
3
+ *
4
+ * Session manages conversation messages for an Image.
5
+ * Each Image has exactly one Session.
6
+ */
7
+
8
+ import type { Message } from "../agent/types";
9
+
10
+ // ============================================================================
11
+ // Re-export from persistence (storage schema)
12
+ // ============================================================================
13
+
14
+ export type { SessionRecord, SessionRepository } from "../persistence/types";
15
+
16
+ // ============================================================================
17
+ // Session Interface
18
+ // ============================================================================
19
+
20
+ /**
21
+ * Session - Manages conversation messages
22
+ */
23
+ export interface Session {
24
+ /**
25
+ * Unique session identifier
26
+ */
27
+ readonly sessionId: string;
28
+
29
+ /**
30
+ * Associated image ID
31
+ */
32
+ readonly imageId: string;
33
+
34
+ /**
35
+ * Container this session belongs to
36
+ */
37
+ readonly containerId: string;
38
+
39
+ /**
40
+ * Creation timestamp
41
+ */
42
+ readonly createdAt: number;
43
+
44
+ /**
45
+ * Initialize session in storage
46
+ */
47
+ initialize(): Promise<void>;
48
+
49
+ /**
50
+ * Add a message to the session
51
+ */
52
+ addMessage(message: Message): Promise<void>;
53
+
54
+ /**
55
+ * Get all messages in the session
56
+ */
57
+ getMessages(): Promise<Message[]>;
58
+
59
+ /**
60
+ * Clear all messages in the session
61
+ */
62
+ clear(): Promise<void>;
63
+ }
64
+
65
+ // ============================================================================
66
+ // Session Configuration
67
+ // ============================================================================
68
+
69
+ /**
70
+ * Configuration for creating a Session
71
+ */
72
+ export interface SessionConfig {
73
+ sessionId: string;
74
+ imageId: string;
75
+ containerId: string;
76
+ repository: import("../persistence/types").SessionRepository;
77
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Workspace Module
3
+ *
4
+ * Abstraction for isolated working environments.
5
+ * Platform packages provide concrete implementations.
6
+ *
7
+ * Usage:
8
+ * ```typescript
9
+ * import type { Workspace, WorkspaceProvider } from "@agentxjs/core/workspace";
10
+ *
11
+ * // Platform provides implementation
12
+ * const provider: WorkspaceProvider = new FileWorkspaceProvider({
13
+ * basePath: "~/.agentx/workspaces"
14
+ * });
15
+ *
16
+ * // Create workspace for an agent
17
+ * const workspace = await provider.create({
18
+ * containerId: "user-123",
19
+ * imageId: "img_xxx",
20
+ * });
21
+ *
22
+ * await workspace.initialize();
23
+ * console.log(workspace.path); // ~/.agentx/workspaces/user-123/img_xxx
24
+ * ```
25
+ */
26
+
27
+ export type { Workspace, WorkspaceCreateConfig, WorkspaceProvider } from "./types";
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Workspace Types
3
+ *
4
+ * Workspace is an abstraction for isolated working environments.
5
+ * Different platforms provide different implementations:
6
+ * - Node.js: File system based (local directories)
7
+ * - Cloudflare: R2/KV based (cloud storage)
8
+ * - Browser: IndexedDB/Memory based
9
+ *
10
+ * Architecture:
11
+ * ```
12
+ * ┌─────────────────────────────────────────────────────────┐
13
+ * │ core/workspace │
14
+ * │ ┌─────────────────────────────────────────────────────┐│
15
+ * │ │ Workspace (interface) ││
16
+ * │ │ WorkspaceProvider (interface) ││
17
+ * │ └─────────────────────────────────────────────────────┘│
18
+ * └─────────────────────────────────────────────────────────┘
19
+ * │
20
+ * ┌────────────────┼────────────────┐
21
+ * ▼ ▼ ▼
22
+ * ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
23
+ * │ platform-node│ │platform-cf │ │platform-web │
24
+ * │ FileWorkspace│ │ R2Workspace │ │ IDBWorkspace │
25
+ * └──────────────┘ └──────────────┘ └──────────────┘
26
+ * ```
27
+ */
28
+
29
+ // ============================================================================
30
+ // Workspace Interface
31
+ // ============================================================================
32
+
33
+ /**
34
+ * Workspace - Isolated working environment for an Agent
35
+ *
36
+ * Provides a location abstraction for Agent file operations.
37
+ * The actual storage mechanism depends on platform implementation.
38
+ */
39
+ export interface Workspace {
40
+ /**
41
+ * Unique workspace identifier
42
+ */
43
+ readonly id: string;
44
+
45
+ /**
46
+ * Human-readable workspace name
47
+ */
48
+ readonly name: string;
49
+
50
+ /**
51
+ * Workspace path or URI
52
+ *
53
+ * Platform-specific:
54
+ * - Node.js: Absolute file path (e.g., ~/.agentx/workspaces/xxx/)
55
+ * - Cloudflare: R2 bucket prefix (e.g., workspaces/xxx/)
56
+ * - Browser: IndexedDB store name
57
+ */
58
+ readonly path: string;
59
+
60
+ /**
61
+ * Initialize workspace (create if not exists)
62
+ */
63
+ initialize(): Promise<void>;
64
+
65
+ /**
66
+ * Check if workspace exists
67
+ */
68
+ exists(): Promise<boolean>;
69
+
70
+ /**
71
+ * Clean up workspace (optional, for temporary workspaces)
72
+ */
73
+ cleanup?(): Promise<void>;
74
+ }
75
+
76
+ // ============================================================================
77
+ // Workspace Provider Interface
78
+ // ============================================================================
79
+
80
+ /**
81
+ * Configuration for creating a workspace
82
+ */
83
+ export interface WorkspaceCreateConfig {
84
+ /**
85
+ * Associated container ID
86
+ */
87
+ containerId: string;
88
+
89
+ /**
90
+ * Associated image ID
91
+ */
92
+ imageId: string;
93
+
94
+ /**
95
+ * Optional custom workspace name
96
+ */
97
+ name?: string;
98
+ }
99
+
100
+ /**
101
+ * WorkspaceProvider - Factory for creating workspaces
102
+ *
103
+ * Platform implementations provide this interface to create
104
+ * platform-specific workspaces.
105
+ */
106
+ export interface WorkspaceProvider {
107
+ /**
108
+ * Provider name (e.g., "file", "r2", "indexeddb")
109
+ */
110
+ readonly type: string;
111
+
112
+ /**
113
+ * Create a new workspace
114
+ */
115
+ create(config: WorkspaceCreateConfig): Promise<Workspace>;
116
+
117
+ /**
118
+ * Get an existing workspace by ID
119
+ */
120
+ get(workspaceId: string): Promise<Workspace | null>;
121
+
122
+ /**
123
+ * List all workspaces for a container
124
+ */
125
+ listByContainer(containerId: string): Promise<Workspace[]>;
126
+
127
+ /**
128
+ * Delete a workspace
129
+ */
130
+ delete(workspaceId: string): Promise<void>;
131
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ "rootDir": "./src",
6
+ "types": ["bun-types"]
7
+ },
8
+ "include": ["src/**/*"],
9
+ "exclude": ["src/**/__tests__/**/*", "src/**/*.test.ts", "src/**/*.spec.ts"]
10
+ }