@agentxjs/runtime 0.1.1 → 0.1.2
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.cjs +1286 -135
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1284 -133
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -37,8 +37,178 @@ module.exports = __toCommonJS(index_exports);
|
|
|
37
37
|
|
|
38
38
|
// src/internal/SystemBusImpl.ts
|
|
39
39
|
var import_rxjs = require("rxjs");
|
|
40
|
-
|
|
41
|
-
|
|
40
|
+
|
|
41
|
+
// ../common/dist/index.js
|
|
42
|
+
var __defProp2 = Object.defineProperty;
|
|
43
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
44
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
45
|
+
var _ConsoleLogger = class _ConsoleLogger2 {
|
|
46
|
+
constructor(name, options = {}) {
|
|
47
|
+
__publicField(this, "name");
|
|
48
|
+
__publicField(this, "level");
|
|
49
|
+
__publicField(this, "colors");
|
|
50
|
+
__publicField(this, "timestamps");
|
|
51
|
+
this.name = name;
|
|
52
|
+
this.level = options.level ?? "info";
|
|
53
|
+
this.colors = options.colors ?? this.isNodeEnvironment();
|
|
54
|
+
this.timestamps = options.timestamps ?? true;
|
|
55
|
+
}
|
|
56
|
+
debug(message, context) {
|
|
57
|
+
if (this.isDebugEnabled()) {
|
|
58
|
+
this.log("DEBUG", message, context);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
info(message, context) {
|
|
62
|
+
if (this.isInfoEnabled()) {
|
|
63
|
+
this.log("INFO", message, context);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
warn(message, context) {
|
|
67
|
+
if (this.isWarnEnabled()) {
|
|
68
|
+
this.log("WARN", message, context);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
error(message, context) {
|
|
72
|
+
if (this.isErrorEnabled()) {
|
|
73
|
+
if (message instanceof Error) {
|
|
74
|
+
this.log("ERROR", message.message, { ...context, stack: message.stack });
|
|
75
|
+
} else {
|
|
76
|
+
this.log("ERROR", message, context);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
isDebugEnabled() {
|
|
81
|
+
return this.getLevelValue(this.level) <= this.getLevelValue("debug");
|
|
82
|
+
}
|
|
83
|
+
isInfoEnabled() {
|
|
84
|
+
return this.getLevelValue(this.level) <= this.getLevelValue("info");
|
|
85
|
+
}
|
|
86
|
+
isWarnEnabled() {
|
|
87
|
+
return this.getLevelValue(this.level) <= this.getLevelValue("warn");
|
|
88
|
+
}
|
|
89
|
+
isErrorEnabled() {
|
|
90
|
+
return this.getLevelValue(this.level) <= this.getLevelValue("error");
|
|
91
|
+
}
|
|
92
|
+
getLevelValue(level) {
|
|
93
|
+
const levels = {
|
|
94
|
+
debug: 0,
|
|
95
|
+
info: 1,
|
|
96
|
+
warn: 2,
|
|
97
|
+
error: 3,
|
|
98
|
+
silent: 4
|
|
99
|
+
};
|
|
100
|
+
return levels[level];
|
|
101
|
+
}
|
|
102
|
+
log(level, message, context) {
|
|
103
|
+
const parts = [];
|
|
104
|
+
if (this.timestamps) {
|
|
105
|
+
parts.push((/* @__PURE__ */ new Date()).toISOString());
|
|
106
|
+
}
|
|
107
|
+
if (this.colors) {
|
|
108
|
+
const color = _ConsoleLogger2.COLORS[level];
|
|
109
|
+
parts.push(`${color}${level.padEnd(5)}${_ConsoleLogger2.COLORS.RESET}`);
|
|
110
|
+
} else {
|
|
111
|
+
parts.push(level.padEnd(5));
|
|
112
|
+
}
|
|
113
|
+
parts.push(`[${this.name}]`);
|
|
114
|
+
parts.push(message);
|
|
115
|
+
const logLine = parts.join(" ");
|
|
116
|
+
const consoleMethod = this.getConsoleMethod(level);
|
|
117
|
+
if (context && Object.keys(context).length > 0) {
|
|
118
|
+
consoleMethod(logLine, context);
|
|
119
|
+
} else {
|
|
120
|
+
consoleMethod(logLine);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
getConsoleMethod(level) {
|
|
124
|
+
switch (level) {
|
|
125
|
+
case "DEBUG":
|
|
126
|
+
return console.debug.bind(console);
|
|
127
|
+
case "INFO":
|
|
128
|
+
return console.info.bind(console);
|
|
129
|
+
case "WARN":
|
|
130
|
+
return console.warn.bind(console);
|
|
131
|
+
case "ERROR":
|
|
132
|
+
return console.error.bind(console);
|
|
133
|
+
default:
|
|
134
|
+
return console.log.bind(console);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
isNodeEnvironment() {
|
|
138
|
+
return typeof process !== "undefined" && process.versions?.node !== void 0;
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
__publicField(_ConsoleLogger, "COLORS", {
|
|
142
|
+
DEBUG: "\x1B[36m",
|
|
143
|
+
INFO: "\x1B[32m",
|
|
144
|
+
WARN: "\x1B[33m",
|
|
145
|
+
ERROR: "\x1B[31m",
|
|
146
|
+
RESET: "\x1B[0m"
|
|
147
|
+
});
|
|
148
|
+
var ConsoleLogger = _ConsoleLogger;
|
|
149
|
+
var externalFactory = null;
|
|
150
|
+
var LoggerFactoryImpl = class {
|
|
151
|
+
static getLogger(nameOrClass) {
|
|
152
|
+
const name = typeof nameOrClass === "string" ? nameOrClass : nameOrClass.name;
|
|
153
|
+
if (this.loggers.has(name)) {
|
|
154
|
+
return this.loggers.get(name);
|
|
155
|
+
}
|
|
156
|
+
const lazyLogger = this.createLazyLogger(name);
|
|
157
|
+
this.loggers.set(name, lazyLogger);
|
|
158
|
+
return lazyLogger;
|
|
159
|
+
}
|
|
160
|
+
static configure(config) {
|
|
161
|
+
this.config = { ...this.config, ...config };
|
|
162
|
+
}
|
|
163
|
+
static reset() {
|
|
164
|
+
this.loggers.clear();
|
|
165
|
+
this.config = { defaultLevel: "info" };
|
|
166
|
+
externalFactory = null;
|
|
167
|
+
}
|
|
168
|
+
static createLazyLogger(name) {
|
|
169
|
+
let realLogger = null;
|
|
170
|
+
const getRealLogger = () => {
|
|
171
|
+
if (!realLogger) {
|
|
172
|
+
realLogger = this.createLogger(name);
|
|
173
|
+
}
|
|
174
|
+
return realLogger;
|
|
175
|
+
};
|
|
176
|
+
return {
|
|
177
|
+
name,
|
|
178
|
+
level: this.config.defaultLevel || "info",
|
|
179
|
+
debug: (message, context) => getRealLogger().debug(message, context),
|
|
180
|
+
info: (message, context) => getRealLogger().info(message, context),
|
|
181
|
+
warn: (message, context) => getRealLogger().warn(message, context),
|
|
182
|
+
error: (message, context) => getRealLogger().error(message, context),
|
|
183
|
+
isDebugEnabled: () => getRealLogger().isDebugEnabled(),
|
|
184
|
+
isInfoEnabled: () => getRealLogger().isInfoEnabled(),
|
|
185
|
+
isWarnEnabled: () => getRealLogger().isWarnEnabled(),
|
|
186
|
+
isErrorEnabled: () => getRealLogger().isErrorEnabled()
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
static createLogger(name) {
|
|
190
|
+
if (externalFactory) {
|
|
191
|
+
return externalFactory.getLogger(name);
|
|
192
|
+
}
|
|
193
|
+
if (this.config.defaultImplementation) {
|
|
194
|
+
return this.config.defaultImplementation(name);
|
|
195
|
+
}
|
|
196
|
+
return new ConsoleLogger(name, {
|
|
197
|
+
level: this.config.defaultLevel,
|
|
198
|
+
...this.config.consoleOptions
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
__publicField(LoggerFactoryImpl, "loggers", /* @__PURE__ */ new Map());
|
|
203
|
+
__publicField(LoggerFactoryImpl, "config", {
|
|
204
|
+
defaultLevel: "info"
|
|
205
|
+
});
|
|
206
|
+
function createLogger(name) {
|
|
207
|
+
return LoggerFactoryImpl.getLogger(name);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// src/internal/SystemBusImpl.ts
|
|
211
|
+
var logger = createLogger("runtime/SystemBusImpl");
|
|
42
212
|
var SystemBusImpl = class {
|
|
43
213
|
subject = new import_rxjs.Subject();
|
|
44
214
|
subscriptions = [];
|
|
@@ -196,8 +366,7 @@ var SystemBusImpl = class {
|
|
|
196
366
|
};
|
|
197
367
|
|
|
198
368
|
// src/internal/BusDriver.ts
|
|
199
|
-
var
|
|
200
|
-
var logger2 = (0, import_common2.createLogger)("runtime/BusDriver");
|
|
369
|
+
var logger2 = createLogger("runtime/BusDriver");
|
|
201
370
|
var BusDriver = class {
|
|
202
371
|
name = "BusDriver";
|
|
203
372
|
description = "Driver that listens to SystemBus for DriveableEvents";
|
|
@@ -382,8 +551,7 @@ var BusDriver = class {
|
|
|
382
551
|
};
|
|
383
552
|
|
|
384
553
|
// src/internal/AgentInteractor.ts
|
|
385
|
-
var
|
|
386
|
-
var logger3 = (0, import_common3.createLogger)("runtime/AgentInteractor");
|
|
554
|
+
var logger3 = createLogger("runtime/AgentInteractor");
|
|
387
555
|
var AgentInteractor = class {
|
|
388
556
|
producer;
|
|
389
557
|
session;
|
|
@@ -474,13 +642,1006 @@ var AgentInteractor = class {
|
|
|
474
642
|
}
|
|
475
643
|
};
|
|
476
644
|
|
|
477
|
-
//
|
|
478
|
-
|
|
479
|
-
|
|
645
|
+
// ../types/dist/agent.js
|
|
646
|
+
function isStateEvent(event) {
|
|
647
|
+
const stateTypes = [
|
|
648
|
+
"conversation_queued",
|
|
649
|
+
"conversation_start",
|
|
650
|
+
"conversation_thinking",
|
|
651
|
+
"conversation_responding",
|
|
652
|
+
"conversation_end",
|
|
653
|
+
"conversation_interrupted",
|
|
654
|
+
"tool_planned",
|
|
655
|
+
"tool_executing",
|
|
656
|
+
"tool_completed",
|
|
657
|
+
"tool_failed",
|
|
658
|
+
"error_occurred"
|
|
659
|
+
];
|
|
660
|
+
return stateTypes.includes(event.type);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// ../agent/dist/index.js
|
|
664
|
+
var MemoryStore = class {
|
|
665
|
+
states = /* @__PURE__ */ new Map();
|
|
666
|
+
get(id) {
|
|
667
|
+
return this.states.get(id);
|
|
668
|
+
}
|
|
669
|
+
set(id, state) {
|
|
670
|
+
this.states.set(id, state);
|
|
671
|
+
}
|
|
672
|
+
delete(id) {
|
|
673
|
+
this.states.delete(id);
|
|
674
|
+
}
|
|
675
|
+
has(id) {
|
|
676
|
+
return this.states.has(id);
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Clear all stored states
|
|
680
|
+
*/
|
|
681
|
+
clear() {
|
|
682
|
+
this.states.clear();
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Get the number of stored states
|
|
686
|
+
*/
|
|
687
|
+
get size() {
|
|
688
|
+
return this.states.size;
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Get all stored IDs
|
|
692
|
+
*/
|
|
693
|
+
keys() {
|
|
694
|
+
return this.states.keys();
|
|
695
|
+
}
|
|
696
|
+
};
|
|
697
|
+
createLogger("engine/Mealy");
|
|
698
|
+
function combineProcessors(processors) {
|
|
699
|
+
return (state, event) => {
|
|
700
|
+
const newState = {};
|
|
701
|
+
const allOutputs = [];
|
|
702
|
+
for (const key in processors) {
|
|
703
|
+
const processor = processors[key];
|
|
704
|
+
const subState = state[key];
|
|
705
|
+
const [newSubState, outputs] = processor(subState, event);
|
|
706
|
+
newState[key] = newSubState;
|
|
707
|
+
allOutputs.push(...outputs);
|
|
708
|
+
}
|
|
709
|
+
return [newState, allOutputs];
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
function combineInitialStates(initialStates) {
|
|
713
|
+
return () => {
|
|
714
|
+
const state = {};
|
|
715
|
+
for (const key in initialStates) {
|
|
716
|
+
state[key] = initialStates[key]();
|
|
717
|
+
}
|
|
718
|
+
return state;
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
function createInitialMessageAssemblerState() {
|
|
722
|
+
return {
|
|
723
|
+
currentMessageId: null,
|
|
724
|
+
messageStartTime: null,
|
|
725
|
+
pendingContents: {},
|
|
726
|
+
pendingToolCalls: {}
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
function generateId() {
|
|
730
|
+
return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
731
|
+
}
|
|
732
|
+
var messageAssemblerProcessor = (state, input) => {
|
|
733
|
+
switch (input.type) {
|
|
734
|
+
case "message_start":
|
|
735
|
+
return handleMessageStart(state, input);
|
|
736
|
+
case "text_delta":
|
|
737
|
+
return handleTextDelta(state, input);
|
|
738
|
+
case "tool_use_start":
|
|
739
|
+
return handleToolUseStart(state, input);
|
|
740
|
+
case "input_json_delta":
|
|
741
|
+
return handleInputJsonDelta(state, input);
|
|
742
|
+
case "tool_use_stop":
|
|
743
|
+
return handleToolUseStop(state);
|
|
744
|
+
case "tool_result":
|
|
745
|
+
return handleToolResult(state, input);
|
|
746
|
+
case "message_stop":
|
|
747
|
+
return handleMessageStop(state, input);
|
|
748
|
+
case "error_received":
|
|
749
|
+
return handleErrorReceived(state, input);
|
|
750
|
+
default:
|
|
751
|
+
return [state, []];
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
function handleMessageStart(state, event) {
|
|
755
|
+
const data = event.data;
|
|
756
|
+
return [
|
|
757
|
+
{
|
|
758
|
+
...state,
|
|
759
|
+
currentMessageId: data.messageId,
|
|
760
|
+
messageStartTime: event.timestamp,
|
|
761
|
+
pendingContents: {}
|
|
762
|
+
},
|
|
763
|
+
[]
|
|
764
|
+
];
|
|
765
|
+
}
|
|
766
|
+
function handleTextDelta(state, event) {
|
|
767
|
+
const data = event.data;
|
|
768
|
+
const index = 0;
|
|
769
|
+
const existingContent = state.pendingContents[index];
|
|
770
|
+
const pendingContent = existingContent?.type === "text" ? {
|
|
771
|
+
...existingContent,
|
|
772
|
+
textDeltas: [...existingContent.textDeltas || [], data.text]
|
|
773
|
+
} : {
|
|
774
|
+
type: "text",
|
|
775
|
+
index,
|
|
776
|
+
textDeltas: [data.text]
|
|
777
|
+
};
|
|
778
|
+
return [
|
|
779
|
+
{
|
|
780
|
+
...state,
|
|
781
|
+
pendingContents: {
|
|
782
|
+
...state.pendingContents,
|
|
783
|
+
[index]: pendingContent
|
|
784
|
+
}
|
|
785
|
+
},
|
|
786
|
+
[]
|
|
787
|
+
];
|
|
788
|
+
}
|
|
789
|
+
function handleToolUseStart(state, event) {
|
|
790
|
+
const data = event.data;
|
|
791
|
+
const index = 1;
|
|
792
|
+
const pendingContent = {
|
|
793
|
+
type: "tool_use",
|
|
794
|
+
index,
|
|
795
|
+
toolId: data.toolCallId,
|
|
796
|
+
toolName: data.toolName,
|
|
797
|
+
toolInputJson: ""
|
|
798
|
+
};
|
|
799
|
+
return [
|
|
800
|
+
{
|
|
801
|
+
...state,
|
|
802
|
+
pendingContents: {
|
|
803
|
+
...state.pendingContents,
|
|
804
|
+
[index]: pendingContent
|
|
805
|
+
}
|
|
806
|
+
},
|
|
807
|
+
[]
|
|
808
|
+
];
|
|
809
|
+
}
|
|
810
|
+
function handleInputJsonDelta(state, event) {
|
|
811
|
+
const data = event.data;
|
|
812
|
+
const index = 1;
|
|
813
|
+
const existingContent = state.pendingContents[index];
|
|
814
|
+
if (!existingContent || existingContent.type !== "tool_use") {
|
|
815
|
+
return [state, []];
|
|
816
|
+
}
|
|
817
|
+
const pendingContent = {
|
|
818
|
+
...existingContent,
|
|
819
|
+
toolInputJson: (existingContent.toolInputJson || "") + data.partialJson
|
|
820
|
+
};
|
|
821
|
+
return [
|
|
822
|
+
{
|
|
823
|
+
...state,
|
|
824
|
+
pendingContents: {
|
|
825
|
+
...state.pendingContents,
|
|
826
|
+
[index]: pendingContent
|
|
827
|
+
}
|
|
828
|
+
},
|
|
829
|
+
[]
|
|
830
|
+
];
|
|
831
|
+
}
|
|
832
|
+
function handleToolUseStop(state, _event) {
|
|
833
|
+
const index = 1;
|
|
834
|
+
const pendingContent = state.pendingContents[index];
|
|
835
|
+
if (!pendingContent || pendingContent.type !== "tool_use") {
|
|
836
|
+
return [state, []];
|
|
837
|
+
}
|
|
838
|
+
const toolId = pendingContent.toolId || "";
|
|
839
|
+
const toolName = pendingContent.toolName || "";
|
|
840
|
+
let toolInput = {};
|
|
841
|
+
try {
|
|
842
|
+
toolInput = pendingContent.toolInputJson ? JSON.parse(pendingContent.toolInputJson) : {};
|
|
843
|
+
} catch {
|
|
844
|
+
toolInput = {};
|
|
845
|
+
}
|
|
846
|
+
const toolCall = {
|
|
847
|
+
type: "tool-call",
|
|
848
|
+
id: toolId,
|
|
849
|
+
name: toolName,
|
|
850
|
+
input: toolInput
|
|
851
|
+
};
|
|
852
|
+
const toolCallMessageEvent = {
|
|
853
|
+
type: "tool_call_message",
|
|
854
|
+
timestamp: Date.now(),
|
|
855
|
+
data: {
|
|
856
|
+
messageId: generateId(),
|
|
857
|
+
toolCalls: [toolCall],
|
|
858
|
+
timestamp: Date.now()
|
|
859
|
+
}
|
|
860
|
+
};
|
|
861
|
+
const { [index]: _, ...remainingContents } = state.pendingContents;
|
|
862
|
+
return [
|
|
863
|
+
{
|
|
864
|
+
...state,
|
|
865
|
+
pendingContents: remainingContents,
|
|
866
|
+
pendingToolCalls: {
|
|
867
|
+
...state.pendingToolCalls,
|
|
868
|
+
[toolId]: { id: toolId, name: toolName }
|
|
869
|
+
}
|
|
870
|
+
},
|
|
871
|
+
[toolCallMessageEvent]
|
|
872
|
+
];
|
|
873
|
+
}
|
|
874
|
+
function handleToolResult(state, event) {
|
|
875
|
+
const data = event.data;
|
|
876
|
+
const { toolCallId, result, isError } = data;
|
|
877
|
+
const pendingToolCall = state.pendingToolCalls[toolCallId];
|
|
878
|
+
const toolName = pendingToolCall?.name || "unknown";
|
|
879
|
+
const toolResult = {
|
|
880
|
+
type: "tool-result",
|
|
881
|
+
id: toolCallId,
|
|
882
|
+
name: toolName,
|
|
883
|
+
output: {
|
|
884
|
+
type: isError ? "error-text" : "text",
|
|
885
|
+
value: typeof result === "string" ? result : JSON.stringify(result)
|
|
886
|
+
}
|
|
887
|
+
};
|
|
888
|
+
const toolResultMessageEvent = {
|
|
889
|
+
type: "tool_result_message",
|
|
890
|
+
timestamp: Date.now(),
|
|
891
|
+
data: {
|
|
892
|
+
messageId: generateId(),
|
|
893
|
+
results: [toolResult],
|
|
894
|
+
timestamp: Date.now()
|
|
895
|
+
}
|
|
896
|
+
};
|
|
897
|
+
const { [toolCallId]: _, ...remainingToolCalls } = state.pendingToolCalls;
|
|
898
|
+
return [
|
|
899
|
+
{
|
|
900
|
+
...state,
|
|
901
|
+
pendingToolCalls: remainingToolCalls
|
|
902
|
+
},
|
|
903
|
+
[toolResultMessageEvent]
|
|
904
|
+
];
|
|
905
|
+
}
|
|
906
|
+
function handleMessageStop(state, event) {
|
|
907
|
+
const data = event.data;
|
|
908
|
+
if (!state.currentMessageId) {
|
|
909
|
+
return [state, []];
|
|
910
|
+
}
|
|
911
|
+
const textParts = [];
|
|
912
|
+
const sortedContents = Object.values(state.pendingContents).sort((a, b) => a.index - b.index);
|
|
913
|
+
for (const pending of sortedContents) {
|
|
914
|
+
if (pending.type === "text" && pending.textDeltas) {
|
|
915
|
+
textParts.push(pending.textDeltas.join(""));
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
const textContent = textParts.join("");
|
|
919
|
+
const stopReason = data.stopReason;
|
|
920
|
+
if (!textContent || textContent.trim().length === 0) {
|
|
921
|
+
const shouldPreserveToolCalls2 = stopReason === "tool_use";
|
|
922
|
+
return [
|
|
923
|
+
{
|
|
924
|
+
...createInitialMessageAssemblerState(),
|
|
925
|
+
pendingToolCalls: shouldPreserveToolCalls2 ? state.pendingToolCalls : {}
|
|
926
|
+
},
|
|
927
|
+
[]
|
|
928
|
+
];
|
|
929
|
+
}
|
|
930
|
+
const contentParts = [
|
|
931
|
+
{
|
|
932
|
+
type: "text",
|
|
933
|
+
text: textContent
|
|
934
|
+
}
|
|
935
|
+
];
|
|
936
|
+
const assistantEvent = {
|
|
937
|
+
type: "assistant_message",
|
|
938
|
+
timestamp: Date.now(),
|
|
939
|
+
data: {
|
|
940
|
+
messageId: state.currentMessageId,
|
|
941
|
+
content: contentParts,
|
|
942
|
+
stopReason,
|
|
943
|
+
timestamp: state.messageStartTime || Date.now()
|
|
944
|
+
}
|
|
945
|
+
};
|
|
946
|
+
const shouldPreserveToolCalls = stopReason === "tool_use";
|
|
947
|
+
return [
|
|
948
|
+
{
|
|
949
|
+
...createInitialMessageAssemblerState(),
|
|
950
|
+
pendingToolCalls: shouldPreserveToolCalls ? state.pendingToolCalls : {}
|
|
951
|
+
},
|
|
952
|
+
[assistantEvent]
|
|
953
|
+
];
|
|
954
|
+
}
|
|
955
|
+
function handleErrorReceived(_state, event) {
|
|
956
|
+
const data = event.data;
|
|
957
|
+
const errorMessageEvent = {
|
|
958
|
+
type: "error_message",
|
|
959
|
+
timestamp: Date.now(),
|
|
960
|
+
data: {
|
|
961
|
+
messageId: generateId(),
|
|
962
|
+
content: data.message,
|
|
963
|
+
errorCode: data.errorCode,
|
|
964
|
+
timestamp: Date.now()
|
|
965
|
+
}
|
|
966
|
+
};
|
|
967
|
+
return [createInitialMessageAssemblerState(), [errorMessageEvent]];
|
|
968
|
+
}
|
|
969
|
+
var logger22 = createLogger("engine/stateEventProcessor");
|
|
970
|
+
function createInitialStateEventProcessorContext() {
|
|
971
|
+
return {};
|
|
972
|
+
}
|
|
973
|
+
var stateEventProcessor = (context, input) => {
|
|
974
|
+
logger22.debug(`[Stream Event] ${input.type}`, {
|
|
975
|
+
context,
|
|
976
|
+
eventData: "data" in input ? input.data : void 0
|
|
977
|
+
});
|
|
978
|
+
switch (input.type) {
|
|
979
|
+
case "message_start":
|
|
980
|
+
return handleMessageStart2(context, input);
|
|
981
|
+
case "message_delta":
|
|
982
|
+
return handleMessageDelta(context);
|
|
983
|
+
case "message_stop":
|
|
984
|
+
return handleMessageStop2(context, input);
|
|
985
|
+
case "text_delta":
|
|
986
|
+
return handleTextDelta2(context);
|
|
987
|
+
case "tool_use_start":
|
|
988
|
+
return handleToolUseStart2(context, input);
|
|
989
|
+
case "tool_use_stop":
|
|
990
|
+
return handleToolUseStop2(context);
|
|
991
|
+
case "error_received":
|
|
992
|
+
return handleErrorReceived2(context, input);
|
|
993
|
+
default:
|
|
994
|
+
logger22.debug(`[Stream Event] ${input.type} (unhandled)`);
|
|
995
|
+
return [context, []];
|
|
996
|
+
}
|
|
997
|
+
};
|
|
998
|
+
function handleMessageStart2(context, event) {
|
|
999
|
+
const data = event.data;
|
|
1000
|
+
const conversationStartEvent = {
|
|
1001
|
+
type: "conversation_start",
|
|
1002
|
+
timestamp: Date.now(),
|
|
1003
|
+
data: {
|
|
1004
|
+
messageId: data.messageId
|
|
1005
|
+
}
|
|
1006
|
+
};
|
|
1007
|
+
return [context, [conversationStartEvent]];
|
|
1008
|
+
}
|
|
1009
|
+
function handleMessageDelta(context) {
|
|
1010
|
+
return [context, []];
|
|
1011
|
+
}
|
|
1012
|
+
function handleMessageStop2(context, event) {
|
|
1013
|
+
const data = event.data;
|
|
1014
|
+
const stopReason = data.stopReason;
|
|
1015
|
+
logger22.debug("message_stop received", { stopReason });
|
|
1016
|
+
if (stopReason === "tool_use") {
|
|
1017
|
+
logger22.debug("Skipping conversation_end (tool_use in progress)");
|
|
1018
|
+
return [context, []];
|
|
1019
|
+
}
|
|
1020
|
+
const conversationEndEvent = {
|
|
1021
|
+
type: "conversation_end",
|
|
1022
|
+
timestamp: Date.now(),
|
|
1023
|
+
data: {
|
|
1024
|
+
reason: "completed"
|
|
1025
|
+
}
|
|
1026
|
+
};
|
|
1027
|
+
return [context, [conversationEndEvent]];
|
|
1028
|
+
}
|
|
1029
|
+
function handleTextDelta2(context) {
|
|
1030
|
+
const respondingEvent = {
|
|
1031
|
+
type: "conversation_responding",
|
|
1032
|
+
timestamp: Date.now(),
|
|
1033
|
+
data: {}
|
|
1034
|
+
};
|
|
1035
|
+
return [context, [respondingEvent]];
|
|
1036
|
+
}
|
|
1037
|
+
function handleToolUseStart2(context, event) {
|
|
1038
|
+
const data = event.data;
|
|
1039
|
+
const outputs = [];
|
|
1040
|
+
const toolPlannedEvent = {
|
|
1041
|
+
type: "tool_planned",
|
|
1042
|
+
timestamp: Date.now(),
|
|
1043
|
+
data: {
|
|
1044
|
+
toolId: data.toolCallId,
|
|
1045
|
+
toolName: data.toolName
|
|
1046
|
+
}
|
|
1047
|
+
};
|
|
1048
|
+
outputs.push(toolPlannedEvent);
|
|
1049
|
+
const toolExecutingEvent = {
|
|
1050
|
+
type: "tool_executing",
|
|
1051
|
+
timestamp: Date.now(),
|
|
1052
|
+
data: {
|
|
1053
|
+
toolId: data.toolCallId,
|
|
1054
|
+
toolName: data.toolName,
|
|
1055
|
+
input: {}
|
|
1056
|
+
}
|
|
1057
|
+
};
|
|
1058
|
+
outputs.push(toolExecutingEvent);
|
|
1059
|
+
return [context, outputs];
|
|
1060
|
+
}
|
|
1061
|
+
function handleToolUseStop2(context) {
|
|
1062
|
+
return [context, []];
|
|
1063
|
+
}
|
|
1064
|
+
function handleErrorReceived2(context, event) {
|
|
1065
|
+
const data = event.data;
|
|
1066
|
+
const errorOccurredEvent = {
|
|
1067
|
+
type: "error_occurred",
|
|
1068
|
+
timestamp: Date.now(),
|
|
1069
|
+
data: {
|
|
1070
|
+
code: data.errorCode || "unknown_error",
|
|
1071
|
+
message: data.message,
|
|
1072
|
+
recoverable: true
|
|
1073
|
+
}
|
|
1074
|
+
};
|
|
1075
|
+
return [context, [errorOccurredEvent]];
|
|
1076
|
+
}
|
|
1077
|
+
function createInitialTurnTrackerState() {
|
|
1078
|
+
return {
|
|
1079
|
+
pendingTurn: null,
|
|
1080
|
+
costPerInputToken: 3e-6,
|
|
1081
|
+
// $3 per 1M tokens
|
|
1082
|
+
costPerOutputToken: 15e-6
|
|
1083
|
+
// $15 per 1M tokens
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
function generateId2() {
|
|
1087
|
+
return `turn_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
1088
|
+
}
|
|
1089
|
+
var turnTrackerProcessor = (state, input) => {
|
|
1090
|
+
switch (input.type) {
|
|
1091
|
+
case "user_message":
|
|
1092
|
+
return handleUserMessage(state, input);
|
|
1093
|
+
case "message_stop":
|
|
1094
|
+
return handleMessageStop3(state, input);
|
|
1095
|
+
case "assistant_message":
|
|
1096
|
+
return [state, []];
|
|
1097
|
+
default:
|
|
1098
|
+
return [state, []];
|
|
1099
|
+
}
|
|
1100
|
+
};
|
|
1101
|
+
function handleUserMessage(state, event) {
|
|
1102
|
+
const data = event.data;
|
|
1103
|
+
const turnId = generateId2();
|
|
1104
|
+
const pendingTurn = {
|
|
1105
|
+
turnId,
|
|
1106
|
+
messageId: data.messageId,
|
|
1107
|
+
content: data.content,
|
|
1108
|
+
requestedAt: event.timestamp
|
|
1109
|
+
};
|
|
1110
|
+
const turnRequestEvent = {
|
|
1111
|
+
type: "turn_request",
|
|
1112
|
+
timestamp: Date.now(),
|
|
1113
|
+
data: {
|
|
1114
|
+
turnId,
|
|
1115
|
+
messageId: data.messageId,
|
|
1116
|
+
content: data.content,
|
|
1117
|
+
timestamp: event.timestamp
|
|
1118
|
+
}
|
|
1119
|
+
};
|
|
1120
|
+
return [
|
|
1121
|
+
{
|
|
1122
|
+
...state,
|
|
1123
|
+
pendingTurn
|
|
1124
|
+
},
|
|
1125
|
+
[turnRequestEvent]
|
|
1126
|
+
];
|
|
1127
|
+
}
|
|
1128
|
+
function handleMessageStop3(state, event) {
|
|
1129
|
+
if (!state.pendingTurn) {
|
|
1130
|
+
return [state, []];
|
|
1131
|
+
}
|
|
1132
|
+
const data = event.data;
|
|
1133
|
+
const stopReason = data.stopReason;
|
|
1134
|
+
if (stopReason === "end_turn" || stopReason === "max_tokens" || stopReason === "stop_sequence") {
|
|
1135
|
+
return completeTurn(state, event.timestamp);
|
|
1136
|
+
}
|
|
1137
|
+
return [state, []];
|
|
1138
|
+
}
|
|
1139
|
+
function completeTurn(state, completedAt) {
|
|
1140
|
+
if (!state.pendingTurn) {
|
|
1141
|
+
return [state, []];
|
|
1142
|
+
}
|
|
1143
|
+
const { turnId, messageId, requestedAt } = state.pendingTurn;
|
|
1144
|
+
const duration = completedAt - requestedAt;
|
|
1145
|
+
const usage = { inputTokens: 0, outputTokens: 0 };
|
|
1146
|
+
const turnResponseEvent = {
|
|
1147
|
+
type: "turn_response",
|
|
1148
|
+
timestamp: Date.now(),
|
|
1149
|
+
data: {
|
|
1150
|
+
turnId,
|
|
1151
|
+
messageId,
|
|
1152
|
+
duration,
|
|
1153
|
+
usage,
|
|
1154
|
+
timestamp: completedAt
|
|
1155
|
+
}
|
|
1156
|
+
};
|
|
1157
|
+
return [
|
|
1158
|
+
{
|
|
1159
|
+
...state,
|
|
1160
|
+
pendingTurn: null
|
|
1161
|
+
},
|
|
1162
|
+
[turnResponseEvent]
|
|
1163
|
+
];
|
|
1164
|
+
}
|
|
1165
|
+
var agentProcessor = combineProcessors({
|
|
1166
|
+
messageAssembler: messageAssemblerProcessor,
|
|
1167
|
+
stateEventProcessor,
|
|
1168
|
+
turnTracker: turnTrackerProcessor
|
|
1169
|
+
});
|
|
1170
|
+
var createInitialAgentEngineState = combineInitialStates({
|
|
1171
|
+
messageAssembler: createInitialMessageAssemblerState,
|
|
1172
|
+
stateEventProcessor: createInitialStateEventProcessorContext,
|
|
1173
|
+
turnTracker: createInitialTurnTrackerState
|
|
1174
|
+
});
|
|
1175
|
+
var logger32 = createLogger("engine/MealyMachine");
|
|
1176
|
+
var MealyMachine = class {
|
|
1177
|
+
store;
|
|
1178
|
+
constructor() {
|
|
1179
|
+
this.store = new MemoryStore();
|
|
1180
|
+
logger32.debug("MealyMachine initialized");
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* Process a single driveable event and return output events
|
|
1184
|
+
*
|
|
1185
|
+
* This is the core Mealy Machine operation:
|
|
1186
|
+
* process(agentId, event) → outputs[]
|
|
1187
|
+
*
|
|
1188
|
+
* @param agentId - The agent identifier (for state isolation)
|
|
1189
|
+
* @param event - StreamEvent to process
|
|
1190
|
+
* @returns Array of output events (state, message, turn events)
|
|
1191
|
+
*/
|
|
1192
|
+
process(agentId, event) {
|
|
1193
|
+
const eventType = event.type || "unknown";
|
|
1194
|
+
logger32.debug("Processing event", { agentId, eventType });
|
|
1195
|
+
const isNewState = !this.store.has(agentId);
|
|
1196
|
+
let state = this.store.get(agentId) ?? createInitialAgentEngineState();
|
|
1197
|
+
if (isNewState) {
|
|
1198
|
+
logger32.debug("Created initial state for agent", { agentId });
|
|
1199
|
+
}
|
|
1200
|
+
const allOutputs = [];
|
|
1201
|
+
allOutputs.push(event);
|
|
1202
|
+
const [newState, outputs] = agentProcessor(state, event);
|
|
1203
|
+
state = newState;
|
|
1204
|
+
for (const output of outputs) {
|
|
1205
|
+
allOutputs.push(output);
|
|
1206
|
+
const [chainedState, chainedOutputs] = this.processChained(state, output);
|
|
1207
|
+
state = chainedState;
|
|
1208
|
+
allOutputs.push(...chainedOutputs);
|
|
1209
|
+
}
|
|
1210
|
+
this.store.set(agentId, state);
|
|
1211
|
+
if (outputs.length > 0) {
|
|
1212
|
+
logger32.debug("Produced outputs", {
|
|
1213
|
+
agentId,
|
|
1214
|
+
inputEvent: eventType,
|
|
1215
|
+
outputCount: allOutputs.length,
|
|
1216
|
+
processorOutputs: outputs.length
|
|
1217
|
+
});
|
|
1218
|
+
}
|
|
1219
|
+
return allOutputs;
|
|
1220
|
+
}
|
|
1221
|
+
/**
|
|
1222
|
+
* Process chained events recursively
|
|
1223
|
+
*
|
|
1224
|
+
* Some processors produce events that trigger other processors:
|
|
1225
|
+
* - MessageAssembler produces MessageEvents
|
|
1226
|
+
* - TurnTracker consumes MessageEvents to produce TurnEvents
|
|
1227
|
+
*/
|
|
1228
|
+
processChained(state, event) {
|
|
1229
|
+
const [newState, outputs] = agentProcessor(state, event);
|
|
1230
|
+
if (outputs.length === 0) {
|
|
1231
|
+
return [newState, []];
|
|
1232
|
+
}
|
|
1233
|
+
const allOutputs = [...outputs];
|
|
1234
|
+
let currentState = newState;
|
|
1235
|
+
for (const output of outputs) {
|
|
1236
|
+
const [chainedState, chainedOutputs] = this.processChained(currentState, output);
|
|
1237
|
+
currentState = chainedState;
|
|
1238
|
+
allOutputs.push(...chainedOutputs);
|
|
1239
|
+
}
|
|
1240
|
+
return [currentState, allOutputs];
|
|
1241
|
+
}
|
|
1242
|
+
/**
|
|
1243
|
+
* Clear state for an agent
|
|
1244
|
+
*
|
|
1245
|
+
* Call this when an agent is destroyed to free memory.
|
|
1246
|
+
*/
|
|
1247
|
+
clearState(agentId) {
|
|
1248
|
+
logger32.debug("Clearing state", { agentId });
|
|
1249
|
+
this.store.delete(agentId);
|
|
1250
|
+
}
|
|
1251
|
+
/**
|
|
1252
|
+
* Check if state exists for an agent
|
|
1253
|
+
*/
|
|
1254
|
+
hasState(agentId) {
|
|
1255
|
+
return this.store.has(agentId);
|
|
1256
|
+
}
|
|
1257
|
+
};
|
|
1258
|
+
var logger4 = createLogger("agent/AgentStateMachine");
|
|
1259
|
+
var AgentStateMachine = class {
|
|
1260
|
+
_state = "idle";
|
|
1261
|
+
handlers = /* @__PURE__ */ new Set();
|
|
1262
|
+
/**
|
|
1263
|
+
* Current agent state
|
|
1264
|
+
*/
|
|
1265
|
+
get state() {
|
|
1266
|
+
return this._state;
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* Process an event and update internal state if it's a StateEvent
|
|
1270
|
+
*
|
|
1271
|
+
* @param event - Event from MealyMachine (could be any AgentOutput)
|
|
1272
|
+
*/
|
|
1273
|
+
process(event) {
|
|
1274
|
+
if (!isStateEvent(event)) {
|
|
1275
|
+
return;
|
|
1276
|
+
}
|
|
1277
|
+
const prev = this._state;
|
|
1278
|
+
const next = this.mapEventToState(event);
|
|
1279
|
+
if (next !== null && prev !== next) {
|
|
1280
|
+
this._state = next;
|
|
1281
|
+
logger4.debug("State transition", {
|
|
1282
|
+
eventType: event.type,
|
|
1283
|
+
from: prev,
|
|
1284
|
+
to: next
|
|
1285
|
+
});
|
|
1286
|
+
this.notifyHandlers({ prev, current: next });
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
/**
|
|
1290
|
+
* Subscribe to state changes
|
|
1291
|
+
*
|
|
1292
|
+
* @param handler - Callback receiving { prev, current } state change
|
|
1293
|
+
* @returns Unsubscribe function
|
|
1294
|
+
*/
|
|
1295
|
+
onStateChange(handler) {
|
|
1296
|
+
this.handlers.add(handler);
|
|
1297
|
+
return () => {
|
|
1298
|
+
this.handlers.delete(handler);
|
|
1299
|
+
};
|
|
1300
|
+
}
|
|
1301
|
+
/**
|
|
1302
|
+
* Reset state machine (used on destroy)
|
|
1303
|
+
*/
|
|
1304
|
+
reset() {
|
|
1305
|
+
const prev = this._state;
|
|
1306
|
+
this._state = "idle";
|
|
1307
|
+
if (prev !== "idle") {
|
|
1308
|
+
this.notifyHandlers({ prev, current: "idle" });
|
|
1309
|
+
}
|
|
1310
|
+
this.handlers.clear();
|
|
1311
|
+
}
|
|
1312
|
+
/**
|
|
1313
|
+
* Map StateEvent type to AgentState
|
|
1314
|
+
*
|
|
1315
|
+
* @param event - StateEvent from MealyMachine
|
|
1316
|
+
* @returns New AgentState or null if no transition needed
|
|
1317
|
+
*/
|
|
1318
|
+
mapEventToState(event) {
|
|
1319
|
+
switch (event.type) {
|
|
1320
|
+
// Conversation lifecycle
|
|
1321
|
+
case "conversation_start":
|
|
1322
|
+
return "thinking";
|
|
1323
|
+
case "conversation_thinking":
|
|
1324
|
+
return "thinking";
|
|
1325
|
+
case "conversation_responding":
|
|
1326
|
+
return "responding";
|
|
1327
|
+
case "conversation_end":
|
|
1328
|
+
return "idle";
|
|
1329
|
+
case "conversation_interrupted":
|
|
1330
|
+
return "idle";
|
|
1331
|
+
// Tool lifecycle
|
|
1332
|
+
case "tool_planned":
|
|
1333
|
+
return "planning_tool";
|
|
1334
|
+
case "tool_executing":
|
|
1335
|
+
return "awaiting_tool_result";
|
|
1336
|
+
case "tool_completed":
|
|
1337
|
+
return "responding";
|
|
1338
|
+
case "tool_failed":
|
|
1339
|
+
return "responding";
|
|
1340
|
+
// Error
|
|
1341
|
+
case "error_occurred":
|
|
1342
|
+
return "error";
|
|
1343
|
+
default:
|
|
1344
|
+
return null;
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
/**
|
|
1348
|
+
* Notify all registered handlers of state change
|
|
1349
|
+
*/
|
|
1350
|
+
notifyHandlers(change) {
|
|
1351
|
+
for (const handler of this.handlers) {
|
|
1352
|
+
try {
|
|
1353
|
+
handler(change);
|
|
1354
|
+
} catch (error) {
|
|
1355
|
+
logger4.error("State change handler error", {
|
|
1356
|
+
from: change.prev,
|
|
1357
|
+
to: change.current,
|
|
1358
|
+
error
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
};
|
|
1364
|
+
var logger5 = createLogger("agent/SimpleAgent");
|
|
1365
|
+
function generateAgentId() {
|
|
1366
|
+
return `agent_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
1367
|
+
}
|
|
1368
|
+
var SimpleMessageQueue = class {
|
|
1369
|
+
queue = [];
|
|
1370
|
+
get length() {
|
|
1371
|
+
return this.queue.length;
|
|
1372
|
+
}
|
|
1373
|
+
get isEmpty() {
|
|
1374
|
+
return this.queue.length === 0;
|
|
1375
|
+
}
|
|
1376
|
+
enqueue(message) {
|
|
1377
|
+
this.queue.push(message);
|
|
1378
|
+
}
|
|
1379
|
+
dequeue() {
|
|
1380
|
+
return this.queue.shift();
|
|
1381
|
+
}
|
|
1382
|
+
clear() {
|
|
1383
|
+
this.queue = [];
|
|
1384
|
+
}
|
|
1385
|
+
};
|
|
1386
|
+
var SimpleAgent = class {
|
|
1387
|
+
agentId;
|
|
1388
|
+
createdAt;
|
|
1389
|
+
messageQueue;
|
|
1390
|
+
_messageQueue = new SimpleMessageQueue();
|
|
1391
|
+
driver;
|
|
1392
|
+
presenter;
|
|
1393
|
+
machine;
|
|
1394
|
+
stateMachine;
|
|
1395
|
+
handlers = /* @__PURE__ */ new Set();
|
|
1396
|
+
typeHandlers = /* @__PURE__ */ new Map();
|
|
1397
|
+
readyHandlers = /* @__PURE__ */ new Set();
|
|
1398
|
+
destroyHandlers = /* @__PURE__ */ new Set();
|
|
1399
|
+
middlewares = [];
|
|
1400
|
+
interceptors = [];
|
|
1401
|
+
isProcessing = false;
|
|
1402
|
+
constructor(options) {
|
|
1403
|
+
this.agentId = generateAgentId();
|
|
1404
|
+
this.createdAt = Date.now();
|
|
1405
|
+
this.messageQueue = this._messageQueue;
|
|
1406
|
+
this.driver = options.driver;
|
|
1407
|
+
this.presenter = options.presenter;
|
|
1408
|
+
this.machine = new MealyMachine();
|
|
1409
|
+
this.stateMachine = new AgentStateMachine();
|
|
1410
|
+
}
|
|
1411
|
+
get state() {
|
|
1412
|
+
return this.stateMachine.state;
|
|
1413
|
+
}
|
|
1414
|
+
async receive(message) {
|
|
1415
|
+
console.log(
|
|
1416
|
+
"[SimpleAgent.receive] CALLED with message:",
|
|
1417
|
+
typeof message === "string" ? message : message.content
|
|
1418
|
+
);
|
|
1419
|
+
const userMessage = typeof message === "string" ? {
|
|
1420
|
+
id: `msg_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
|
|
1421
|
+
role: "user",
|
|
1422
|
+
subtype: "user",
|
|
1423
|
+
content: message,
|
|
1424
|
+
timestamp: Date.now()
|
|
1425
|
+
} : message;
|
|
1426
|
+
this._messageQueue.enqueue(userMessage);
|
|
1427
|
+
console.log("[SimpleAgent.receive] Message queued, isProcessing:", this.isProcessing);
|
|
1428
|
+
if (this.isProcessing) {
|
|
1429
|
+
return new Promise((resolve, reject) => {
|
|
1430
|
+
userMessage._resolve = resolve;
|
|
1431
|
+
userMessage._reject = reject;
|
|
1432
|
+
});
|
|
1433
|
+
}
|
|
1434
|
+
console.log("[SimpleAgent.receive] Starting processQueue");
|
|
1435
|
+
await this.processQueue();
|
|
1436
|
+
}
|
|
1437
|
+
async processQueue() {
|
|
1438
|
+
if (this.isProcessing) return;
|
|
1439
|
+
this.isProcessing = true;
|
|
1440
|
+
console.log("[SimpleAgent.processQueue] Starting, queue size:", this._messageQueue.length);
|
|
1441
|
+
while (!this._messageQueue.isEmpty) {
|
|
1442
|
+
const message = this._messageQueue.dequeue();
|
|
1443
|
+
if (!message) break;
|
|
1444
|
+
console.log("[SimpleAgent.processQueue] Processing message:", message.id);
|
|
1445
|
+
try {
|
|
1446
|
+
await this.processMessage(message);
|
|
1447
|
+
if (message._resolve) {
|
|
1448
|
+
message._resolve();
|
|
1449
|
+
}
|
|
1450
|
+
} catch (error) {
|
|
1451
|
+
if (message._reject) {
|
|
1452
|
+
message._reject(error);
|
|
1453
|
+
}
|
|
1454
|
+
throw error;
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
this.isProcessing = false;
|
|
1458
|
+
console.log("[SimpleAgent.processQueue] Finished");
|
|
1459
|
+
}
|
|
1460
|
+
async processMessage(message) {
|
|
1461
|
+
console.log("[SimpleAgent.processMessage] START, message:", message.id);
|
|
1462
|
+
let processedMessage = message;
|
|
1463
|
+
for (const middleware of this.middlewares) {
|
|
1464
|
+
let nextCalled = false;
|
|
1465
|
+
await middleware(processedMessage, async (msg) => {
|
|
1466
|
+
nextCalled = true;
|
|
1467
|
+
processedMessage = msg;
|
|
1468
|
+
});
|
|
1469
|
+
if (!nextCalled) {
|
|
1470
|
+
console.log("[SimpleAgent.processMessage] Middleware blocked message");
|
|
1471
|
+
return;
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
console.log("[SimpleAgent.processMessage] Getting driver stream...");
|
|
1475
|
+
const driverStream = this.driver.receive(processedMessage);
|
|
1476
|
+
console.log("[SimpleAgent.processMessage] Driver stream:", driverStream);
|
|
1477
|
+
try {
|
|
1478
|
+
console.log("[SimpleAgent.processMessage] Starting for-await loop...");
|
|
1479
|
+
for await (const streamEvent of driverStream) {
|
|
1480
|
+
this.handleStreamEvent(streamEvent);
|
|
1481
|
+
}
|
|
1482
|
+
console.log("[SimpleAgent.processMessage] For-await loop completed");
|
|
1483
|
+
} catch (error) {
|
|
1484
|
+
console.log("[SimpleAgent.processMessage] ERROR:", error);
|
|
1485
|
+
throw error;
|
|
1486
|
+
}
|
|
1487
|
+
console.log("[SimpleAgent.processMessage] END");
|
|
1488
|
+
}
|
|
1489
|
+
/**
|
|
1490
|
+
* Handle a stream event from the driver (push-based API)
|
|
1491
|
+
*
|
|
1492
|
+
* This method processes a single StreamEvent through the MealyMachine
|
|
1493
|
+
* and emits all resulting outputs to presenter and handlers.
|
|
1494
|
+
*/
|
|
1495
|
+
handleStreamEvent(event) {
|
|
1496
|
+
logger5.info("handleStreamEvent", { type: event.type });
|
|
1497
|
+
const outputs = this.machine.process(this.agentId, event);
|
|
1498
|
+
logger5.info("MealyMachine outputs", {
|
|
1499
|
+
count: outputs.length,
|
|
1500
|
+
types: outputs.map((o) => o.type)
|
|
1501
|
+
});
|
|
1502
|
+
for (const output of outputs) {
|
|
1503
|
+
this.stateMachine.process(output);
|
|
1504
|
+
this.emitOutput(output);
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
emitOutput(output) {
|
|
1508
|
+
let currentOutput = output;
|
|
1509
|
+
const runInterceptor = (index, out) => {
|
|
1510
|
+
if (index >= this.interceptors.length) {
|
|
1511
|
+
currentOutput = out;
|
|
1512
|
+
return;
|
|
1513
|
+
}
|
|
1514
|
+
this.interceptors[index](out, (nextOut) => {
|
|
1515
|
+
runInterceptor(index + 1, nextOut);
|
|
1516
|
+
});
|
|
1517
|
+
};
|
|
1518
|
+
runInterceptor(0, output);
|
|
1519
|
+
if (!currentOutput) return;
|
|
1520
|
+
this.presenter.present(this.agentId, currentOutput);
|
|
1521
|
+
for (const handler of this.handlers) {
|
|
1522
|
+
try {
|
|
1523
|
+
handler(currentOutput);
|
|
1524
|
+
} catch (e) {
|
|
1525
|
+
console.error("Event handler error:", e);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
const typeSet = this.typeHandlers.get(currentOutput.type);
|
|
1529
|
+
if (typeSet) {
|
|
1530
|
+
for (const handler of typeSet) {
|
|
1531
|
+
try {
|
|
1532
|
+
handler(currentOutput);
|
|
1533
|
+
} catch (e) {
|
|
1534
|
+
console.error("Event handler error:", e);
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
on(typeOrHandler, handler) {
|
|
1540
|
+
if (typeof typeOrHandler === "function") {
|
|
1541
|
+
this.handlers.add(typeOrHandler);
|
|
1542
|
+
return () => this.handlers.delete(typeOrHandler);
|
|
1543
|
+
}
|
|
1544
|
+
if (typeof typeOrHandler === "object" && !Array.isArray(typeOrHandler)) {
|
|
1545
|
+
const unsubscribes = [];
|
|
1546
|
+
for (const [type, h2] of Object.entries(typeOrHandler)) {
|
|
1547
|
+
if (h2) {
|
|
1548
|
+
unsubscribes.push(this.on(type, h2));
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
return () => unsubscribes.forEach((u) => u());
|
|
1552
|
+
}
|
|
1553
|
+
const types = Array.isArray(typeOrHandler) ? typeOrHandler : [typeOrHandler];
|
|
1554
|
+
const h = handler;
|
|
1555
|
+
for (const type of types) {
|
|
1556
|
+
if (!this.typeHandlers.has(type)) {
|
|
1557
|
+
this.typeHandlers.set(type, /* @__PURE__ */ new Set());
|
|
1558
|
+
}
|
|
1559
|
+
this.typeHandlers.get(type).add(h);
|
|
1560
|
+
}
|
|
1561
|
+
return () => {
|
|
1562
|
+
for (const type of types) {
|
|
1563
|
+
this.typeHandlers.get(type)?.delete(h);
|
|
1564
|
+
}
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
onStateChange(handler) {
|
|
1568
|
+
return this.stateMachine.onStateChange(handler);
|
|
1569
|
+
}
|
|
1570
|
+
react(handlers) {
|
|
1571
|
+
const eventHandlerMap = {};
|
|
1572
|
+
for (const [key, handler] of Object.entries(handlers)) {
|
|
1573
|
+
if (handler && key.startsWith("on")) {
|
|
1574
|
+
const eventType = key.slice(2).replace(/([A-Z])/g, "_$1").toLowerCase().slice(1);
|
|
1575
|
+
eventHandlerMap[eventType] = handler;
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
return this.on(eventHandlerMap);
|
|
1579
|
+
}
|
|
1580
|
+
onReady(handler) {
|
|
1581
|
+
try {
|
|
1582
|
+
handler();
|
|
1583
|
+
} catch (e) {
|
|
1584
|
+
console.error("onReady handler error:", e);
|
|
1585
|
+
}
|
|
1586
|
+
this.readyHandlers.add(handler);
|
|
1587
|
+
return () => this.readyHandlers.delete(handler);
|
|
1588
|
+
}
|
|
1589
|
+
onDestroy(handler) {
|
|
1590
|
+
this.destroyHandlers.add(handler);
|
|
1591
|
+
return () => this.destroyHandlers.delete(handler);
|
|
1592
|
+
}
|
|
1593
|
+
use(middleware) {
|
|
1594
|
+
this.middlewares.push(middleware);
|
|
1595
|
+
return () => {
|
|
1596
|
+
const index = this.middlewares.indexOf(middleware);
|
|
1597
|
+
if (index >= 0) {
|
|
1598
|
+
this.middlewares.splice(index, 1);
|
|
1599
|
+
}
|
|
1600
|
+
};
|
|
1601
|
+
}
|
|
1602
|
+
intercept(interceptor) {
|
|
1603
|
+
this.interceptors.push(interceptor);
|
|
1604
|
+
return () => {
|
|
1605
|
+
const index = this.interceptors.indexOf(interceptor);
|
|
1606
|
+
if (index >= 0) {
|
|
1607
|
+
this.interceptors.splice(index, 1);
|
|
1608
|
+
}
|
|
1609
|
+
};
|
|
1610
|
+
}
|
|
1611
|
+
interrupt() {
|
|
1612
|
+
if (this.state === "idle") {
|
|
1613
|
+
return;
|
|
1614
|
+
}
|
|
1615
|
+
this.driver.interrupt();
|
|
1616
|
+
}
|
|
1617
|
+
async destroy() {
|
|
1618
|
+
if (this.state !== "idle") {
|
|
1619
|
+
this.interrupt();
|
|
1620
|
+
}
|
|
1621
|
+
for (const handler of this.destroyHandlers) {
|
|
1622
|
+
try {
|
|
1623
|
+
handler();
|
|
1624
|
+
} catch (e) {
|
|
1625
|
+
console.error("onDestroy handler error:", e);
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
this.machine.clearState(this.agentId);
|
|
1629
|
+
this.stateMachine.reset();
|
|
1630
|
+
this._messageQueue.clear();
|
|
1631
|
+
this.handlers.clear();
|
|
1632
|
+
this.typeHandlers.clear();
|
|
1633
|
+
this.readyHandlers.clear();
|
|
1634
|
+
this.destroyHandlers.clear();
|
|
1635
|
+
this.middlewares.length = 0;
|
|
1636
|
+
this.interceptors.length = 0;
|
|
1637
|
+
}
|
|
1638
|
+
};
|
|
1639
|
+
function createAgent(options) {
|
|
1640
|
+
return new SimpleAgent(options);
|
|
1641
|
+
}
|
|
480
1642
|
|
|
481
1643
|
// src/environment/ClaudeReceptor.ts
|
|
482
|
-
var
|
|
483
|
-
var logger4 = (0, import_common4.createLogger)("ecosystem/ClaudeReceptor");
|
|
1644
|
+
var logger6 = createLogger("ecosystem/ClaudeReceptor");
|
|
484
1645
|
var ClaudeReceptor = class {
|
|
485
1646
|
producer = null;
|
|
486
1647
|
currentMeta = null;
|
|
@@ -498,7 +1659,7 @@ var ClaudeReceptor = class {
|
|
|
498
1659
|
*/
|
|
499
1660
|
connect(producer) {
|
|
500
1661
|
this.producer = producer;
|
|
501
|
-
|
|
1662
|
+
logger6.debug("ClaudeReceptor connected to SystemBusProducer");
|
|
502
1663
|
}
|
|
503
1664
|
/**
|
|
504
1665
|
* Feed SDK message to receptor with correlation metadata
|
|
@@ -616,7 +1777,7 @@ var ClaudeReceptor = class {
|
|
|
616
1777
|
case "content_block_start": {
|
|
617
1778
|
const contentBlock = event.content_block;
|
|
618
1779
|
this.blockContext.currentBlockIndex = event.index;
|
|
619
|
-
|
|
1780
|
+
logger6.debug("content_block_start received", { contentBlock, index: event.index });
|
|
620
1781
|
if (contentBlock.type === "text") {
|
|
621
1782
|
this.blockContext.currentBlockType = "text";
|
|
622
1783
|
this.emitToBus({
|
|
@@ -753,7 +1914,6 @@ var ClaudeReceptor = class {
|
|
|
753
1914
|
// src/environment/ClaudeEffector.ts
|
|
754
1915
|
var import_claude_agent_sdk = require("@anthropic-ai/claude-agent-sdk");
|
|
755
1916
|
var import_rxjs2 = require("rxjs");
|
|
756
|
-
var import_common5 = require("@agentxjs/common");
|
|
757
1917
|
|
|
758
1918
|
// src/environment/buildOptions.ts
|
|
759
1919
|
function buildOptions(context, abortController) {
|
|
@@ -872,7 +2032,7 @@ async function* observableToAsyncIterable(observable) {
|
|
|
872
2032
|
}
|
|
873
2033
|
|
|
874
2034
|
// src/environment/ClaudeEffector.ts
|
|
875
|
-
var
|
|
2035
|
+
var logger7 = createLogger("ecosystem/ClaudeEffector");
|
|
876
2036
|
var DEFAULT_TIMEOUT = 3e4;
|
|
877
2037
|
var ClaudeEffector = class {
|
|
878
2038
|
config;
|
|
@@ -891,12 +2051,12 @@ var ClaudeEffector = class {
|
|
|
891
2051
|
* Connect to SystemBus consumer to subscribe to events
|
|
892
2052
|
*/
|
|
893
2053
|
connect(consumer) {
|
|
894
|
-
|
|
2054
|
+
logger7.debug("ClaudeEffector connected to SystemBusConsumer", {
|
|
895
2055
|
agentId: this.config.agentId
|
|
896
2056
|
});
|
|
897
2057
|
consumer.on("user_message", async (event) => {
|
|
898
2058
|
const typedEvent = event;
|
|
899
|
-
|
|
2059
|
+
logger7.debug("user_message event received", {
|
|
900
2060
|
eventAgentId: typedEvent.context?.agentId,
|
|
901
2061
|
myAgentId: this.config.agentId,
|
|
902
2062
|
matches: typedEvent.context?.agentId === this.config.agentId
|
|
@@ -932,14 +2092,14 @@ var ClaudeEffector = class {
|
|
|
932
2092
|
this.currentMeta = meta;
|
|
933
2093
|
const timeout = this.config.timeout ?? DEFAULT_TIMEOUT;
|
|
934
2094
|
const timeoutId = setTimeout(() => {
|
|
935
|
-
|
|
2095
|
+
logger7.warn("Request timeout", { timeout });
|
|
936
2096
|
this.currentAbortController?.abort(new Error(`Request timeout after ${timeout}ms`));
|
|
937
2097
|
}, timeout);
|
|
938
2098
|
try {
|
|
939
2099
|
await this.initialize(this.currentAbortController);
|
|
940
2100
|
const sessionId = this.config.sessionId || "default";
|
|
941
2101
|
const sdkUserMessage = buildSDKUserMessage(message, sessionId);
|
|
942
|
-
|
|
2102
|
+
logger7.debug("Sending message to Claude", {
|
|
943
2103
|
content: typeof message.content === "string" ? message.content.substring(0, 80) : "[structured]",
|
|
944
2104
|
timeout,
|
|
945
2105
|
requestId: meta.requestId
|
|
@@ -956,13 +2116,13 @@ var ClaudeEffector = class {
|
|
|
956
2116
|
*/
|
|
957
2117
|
interrupt(meta) {
|
|
958
2118
|
if (this.claudeQuery) {
|
|
959
|
-
|
|
2119
|
+
logger7.debug("Interrupting Claude query", { requestId: meta?.requestId });
|
|
960
2120
|
this.wasInterrupted = true;
|
|
961
2121
|
if (meta) {
|
|
962
2122
|
this.currentMeta = meta;
|
|
963
2123
|
}
|
|
964
2124
|
this.claudeQuery.interrupt().catch((err) => {
|
|
965
|
-
|
|
2125
|
+
logger7.debug("SDK interrupt() error (may be expected)", { error: err });
|
|
966
2126
|
});
|
|
967
2127
|
}
|
|
968
2128
|
}
|
|
@@ -971,7 +2131,7 @@ var ClaudeEffector = class {
|
|
|
971
2131
|
*/
|
|
972
2132
|
async initialize(abortController) {
|
|
973
2133
|
if (this.isInitialized) return;
|
|
974
|
-
|
|
2134
|
+
logger7.info("Initializing ClaudeEffector");
|
|
975
2135
|
const context = {
|
|
976
2136
|
apiKey: this.config.apiKey,
|
|
977
2137
|
baseUrl: this.config.baseUrl,
|
|
@@ -988,7 +2148,7 @@ var ClaudeEffector = class {
|
|
|
988
2148
|
});
|
|
989
2149
|
this.isInitialized = true;
|
|
990
2150
|
this.startBackgroundListener();
|
|
991
|
-
|
|
2151
|
+
logger7.info("ClaudeEffector initialized");
|
|
992
2152
|
}
|
|
993
2153
|
/**
|
|
994
2154
|
* Start background listener for SDK responses
|
|
@@ -997,7 +2157,7 @@ var ClaudeEffector = class {
|
|
|
997
2157
|
(async () => {
|
|
998
2158
|
try {
|
|
999
2159
|
for await (const sdkMsg of this.claudeQuery) {
|
|
1000
|
-
|
|
2160
|
+
logger7.debug("SDK message received", {
|
|
1001
2161
|
type: sdkMsg.type,
|
|
1002
2162
|
subtype: sdkMsg.subtype,
|
|
1003
2163
|
sessionId: sdkMsg.session_id,
|
|
@@ -1014,10 +2174,10 @@ var ClaudeEffector = class {
|
|
|
1014
2174
|
}
|
|
1015
2175
|
if (sdkMsg.type === "result") {
|
|
1016
2176
|
const resultMsg = sdkMsg;
|
|
1017
|
-
|
|
2177
|
+
logger7.info("SDK result received (full)", {
|
|
1018
2178
|
fullResult: JSON.stringify(sdkMsg, null, 2)
|
|
1019
2179
|
});
|
|
1020
|
-
|
|
2180
|
+
logger7.info("SDK result received", {
|
|
1021
2181
|
subtype: resultMsg.subtype,
|
|
1022
2182
|
isError: resultMsg.is_error,
|
|
1023
2183
|
errors: resultMsg.errors,
|
|
@@ -1035,10 +2195,10 @@ var ClaudeEffector = class {
|
|
|
1035
2195
|
}
|
|
1036
2196
|
} catch (error) {
|
|
1037
2197
|
if (this.isAbortError(error)) {
|
|
1038
|
-
|
|
2198
|
+
logger7.debug("Background listener aborted (expected during interrupt)");
|
|
1039
2199
|
this.resetState();
|
|
1040
2200
|
} else {
|
|
1041
|
-
|
|
2201
|
+
logger7.error("Background listener error", { error });
|
|
1042
2202
|
if (this.currentMeta) {
|
|
1043
2203
|
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
|
|
1044
2204
|
this.receptor.emitError(errorMessage, "runtime_error", this.currentMeta);
|
|
@@ -1070,7 +2230,7 @@ var ClaudeEffector = class {
|
|
|
1070
2230
|
* Dispose and cleanup resources
|
|
1071
2231
|
*/
|
|
1072
2232
|
dispose() {
|
|
1073
|
-
|
|
2233
|
+
logger7.debug("Disposing ClaudeEffector");
|
|
1074
2234
|
if (this.currentAbortController) {
|
|
1075
2235
|
this.currentAbortController.abort();
|
|
1076
2236
|
}
|
|
@@ -1101,7 +2261,7 @@ var ClaudeEnvironment = class {
|
|
|
1101
2261
|
};
|
|
1102
2262
|
|
|
1103
2263
|
// src/internal/RuntimeAgent.ts
|
|
1104
|
-
var
|
|
2264
|
+
var logger8 = createLogger("runtime/RuntimeAgent");
|
|
1105
2265
|
var BusPresenter = class {
|
|
1106
2266
|
constructor(producer, session, agentId, imageId, containerId) {
|
|
1107
2267
|
this.producer = producer;
|
|
@@ -1138,7 +2298,7 @@ var BusPresenter = class {
|
|
|
1138
2298
|
this.producer.emit(systemEvent);
|
|
1139
2299
|
if (category === "message") {
|
|
1140
2300
|
this.session.addMessage(data).catch((err) => {
|
|
1141
|
-
|
|
2301
|
+
logger8.error("Failed to persist message", { error: err, messageType: output.type });
|
|
1142
2302
|
});
|
|
1143
2303
|
}
|
|
1144
2304
|
}
|
|
@@ -1196,7 +2356,7 @@ var BusPresenter = class {
|
|
|
1196
2356
|
};
|
|
1197
2357
|
}
|
|
1198
2358
|
default:
|
|
1199
|
-
|
|
2359
|
+
logger8.warn("Unknown message type, passing through", { type: output.type });
|
|
1200
2360
|
return eventData;
|
|
1201
2361
|
}
|
|
1202
2362
|
}
|
|
@@ -1256,7 +2416,7 @@ var RuntimeAgent = class {
|
|
|
1256
2416
|
});
|
|
1257
2417
|
this.environment.receptor.connect(config.bus.asProducer());
|
|
1258
2418
|
this.environment.effector.connect(config.bus.asConsumer());
|
|
1259
|
-
|
|
2419
|
+
logger8.info("ClaudeEnvironment created for agent", {
|
|
1260
2420
|
agentId: this.agentId,
|
|
1261
2421
|
imageId: this.imageId,
|
|
1262
2422
|
resumeSessionId: resumeSessionId ?? "none",
|
|
@@ -1270,7 +2430,7 @@ var RuntimeAgent = class {
|
|
|
1270
2430
|
this.imageId,
|
|
1271
2431
|
this.containerId
|
|
1272
2432
|
);
|
|
1273
|
-
this.engine =
|
|
2433
|
+
this.engine = createAgent({
|
|
1274
2434
|
driver: {
|
|
1275
2435
|
name: "DummyDriver",
|
|
1276
2436
|
description: "Placeholder driver for push-based event handling",
|
|
@@ -1290,14 +2450,14 @@ var RuntimeAgent = class {
|
|
|
1290
2450
|
this.driver = new BusDriver(config.bus.asConsumer(), {
|
|
1291
2451
|
agentId: this.agentId,
|
|
1292
2452
|
onStreamEvent: (event) => {
|
|
1293
|
-
|
|
2453
|
+
logger8.debug("BusDriver \u2192 Engine.handleStreamEvent", { type: event.type });
|
|
1294
2454
|
this.engine.handleStreamEvent(event);
|
|
1295
2455
|
},
|
|
1296
2456
|
onStreamComplete: (reason) => {
|
|
1297
|
-
|
|
2457
|
+
logger8.debug("Stream completed", { reason, agentId: this.agentId });
|
|
1298
2458
|
}
|
|
1299
2459
|
});
|
|
1300
|
-
|
|
2460
|
+
logger8.debug("RuntimeAgent created", {
|
|
1301
2461
|
agentId: this.agentId,
|
|
1302
2462
|
imageId: this.imageId
|
|
1303
2463
|
});
|
|
@@ -1306,13 +2466,13 @@ var RuntimeAgent = class {
|
|
|
1306
2466
|
* Save SDK session ID to image metadata for future resume
|
|
1307
2467
|
*/
|
|
1308
2468
|
saveSessionId(sdkSessionId) {
|
|
1309
|
-
|
|
2469
|
+
logger8.info("Saving SDK session ID to image metadata", {
|
|
1310
2470
|
agentId: this.agentId,
|
|
1311
2471
|
imageId: this.imageId,
|
|
1312
2472
|
sdkSessionId
|
|
1313
2473
|
});
|
|
1314
2474
|
this.imageRepository.updateMetadata(this.imageId, { claudeSdkSessionId: sdkSessionId }).catch((err) => {
|
|
1315
|
-
|
|
2475
|
+
logger8.error("Failed to save SDK session ID", { error: err, imageId: this.imageId });
|
|
1316
2476
|
});
|
|
1317
2477
|
}
|
|
1318
2478
|
get lifecycle() {
|
|
@@ -1325,7 +2485,7 @@ var RuntimeAgent = class {
|
|
|
1325
2485
|
* @param requestId - Request ID for correlation
|
|
1326
2486
|
*/
|
|
1327
2487
|
async receive(content, requestId) {
|
|
1328
|
-
|
|
2488
|
+
logger8.debug("RuntimeAgent.receive called", {
|
|
1329
2489
|
agentId: this.agentId,
|
|
1330
2490
|
contentPreview: content.substring(0, 50),
|
|
1331
2491
|
requestId
|
|
@@ -1334,13 +2494,13 @@ var RuntimeAgent = class {
|
|
|
1334
2494
|
throw new Error(`Cannot send message to ${this._lifecycle} agent`);
|
|
1335
2495
|
}
|
|
1336
2496
|
await this.interactor.receive(content, requestId || `req_${Date.now()}`);
|
|
1337
|
-
|
|
2497
|
+
logger8.debug("RuntimeAgent.receive completed", { agentId: this.agentId });
|
|
1338
2498
|
}
|
|
1339
2499
|
/**
|
|
1340
2500
|
* Interrupt current operation
|
|
1341
2501
|
*/
|
|
1342
2502
|
interrupt(requestId) {
|
|
1343
|
-
|
|
2503
|
+
logger8.debug("RuntimeAgent.interrupt called", { agentId: this.agentId, requestId });
|
|
1344
2504
|
this.interactor.interrupt(requestId);
|
|
1345
2505
|
this.producer.emit({
|
|
1346
2506
|
type: "interrupted",
|
|
@@ -1535,8 +2695,7 @@ var RuntimeSandbox = class {
|
|
|
1535
2695
|
};
|
|
1536
2696
|
|
|
1537
2697
|
// src/internal/RuntimeImage.ts
|
|
1538
|
-
var
|
|
1539
|
-
var logger7 = (0, import_common7.createLogger)("runtime/RuntimeImage");
|
|
2698
|
+
var logger9 = createLogger("runtime/RuntimeImage");
|
|
1540
2699
|
var RuntimeImage = class _RuntimeImage {
|
|
1541
2700
|
constructor(record, context) {
|
|
1542
2701
|
this.record = record;
|
|
@@ -1593,7 +2752,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
1593
2752
|
createdAt: now,
|
|
1594
2753
|
updatedAt: now
|
|
1595
2754
|
});
|
|
1596
|
-
|
|
2755
|
+
logger9.info("Image created", {
|
|
1597
2756
|
imageId,
|
|
1598
2757
|
sessionId,
|
|
1599
2758
|
containerId: config.containerId,
|
|
@@ -1607,10 +2766,10 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
1607
2766
|
static async load(imageId, context) {
|
|
1608
2767
|
const record = await context.imageRepository.findImageById(imageId);
|
|
1609
2768
|
if (!record) {
|
|
1610
|
-
|
|
2769
|
+
logger9.debug("Image not found", { imageId });
|
|
1611
2770
|
return null;
|
|
1612
2771
|
}
|
|
1613
|
-
|
|
2772
|
+
logger9.debug("Image loaded", { imageId, name: record.name });
|
|
1614
2773
|
return new _RuntimeImage(record, context);
|
|
1615
2774
|
}
|
|
1616
2775
|
/**
|
|
@@ -1644,7 +2803,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
1644
2803
|
updatedAt: now
|
|
1645
2804
|
};
|
|
1646
2805
|
await this.context.imageRepository.saveImage(updatedRecord);
|
|
1647
|
-
|
|
2806
|
+
logger9.info("Image updated", { imageId: this.imageId, updates });
|
|
1648
2807
|
return new _RuntimeImage(updatedRecord, this.context);
|
|
1649
2808
|
}
|
|
1650
2809
|
/**
|
|
@@ -1653,7 +2812,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
1653
2812
|
async delete() {
|
|
1654
2813
|
await this.context.sessionRepository.deleteSession(this.sessionId);
|
|
1655
2814
|
await this.context.imageRepository.deleteImage(this.imageId);
|
|
1656
|
-
|
|
2815
|
+
logger9.info("Image deleted", { imageId: this.imageId, sessionId: this.sessionId });
|
|
1657
2816
|
}
|
|
1658
2817
|
/**
|
|
1659
2818
|
* Get the underlying record
|
|
@@ -1675,8 +2834,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
1675
2834
|
};
|
|
1676
2835
|
|
|
1677
2836
|
// src/internal/RuntimeContainer.ts
|
|
1678
|
-
var
|
|
1679
|
-
var logger8 = (0, import_common8.createLogger)("runtime/RuntimeContainer");
|
|
2837
|
+
var logger10 = createLogger("runtime/RuntimeContainer");
|
|
1680
2838
|
var RuntimeContainer = class _RuntimeContainer {
|
|
1681
2839
|
containerId;
|
|
1682
2840
|
createdAt;
|
|
@@ -1716,7 +2874,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1716
2874
|
containerId
|
|
1717
2875
|
}
|
|
1718
2876
|
});
|
|
1719
|
-
|
|
2877
|
+
logger10.info("Container created", { containerId });
|
|
1720
2878
|
return container;
|
|
1721
2879
|
}
|
|
1722
2880
|
/**
|
|
@@ -1725,7 +2883,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1725
2883
|
static async load(containerId, context) {
|
|
1726
2884
|
const record = await context.persistence.containers.findContainerById(containerId);
|
|
1727
2885
|
if (!record) return null;
|
|
1728
|
-
|
|
2886
|
+
logger10.info("Container loaded", { containerId });
|
|
1729
2887
|
return new _RuntimeContainer(containerId, record.createdAt, context);
|
|
1730
2888
|
}
|
|
1731
2889
|
// ==================== Image → Agent Lifecycle ====================
|
|
@@ -1738,7 +2896,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1738
2896
|
if (existingAgentId) {
|
|
1739
2897
|
const existingAgent = this.agents.get(existingAgentId);
|
|
1740
2898
|
if (existingAgent) {
|
|
1741
|
-
|
|
2899
|
+
logger10.info("Reusing existing agent for image", {
|
|
1742
2900
|
containerId: this.containerId,
|
|
1743
2901
|
imageId: image.imageId,
|
|
1744
2902
|
agentId: existingAgentId
|
|
@@ -1797,7 +2955,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1797
2955
|
agentId
|
|
1798
2956
|
}
|
|
1799
2957
|
});
|
|
1800
|
-
|
|
2958
|
+
logger10.info("Agent created for image", {
|
|
1801
2959
|
containerId: this.containerId,
|
|
1802
2960
|
imageId: image.imageId,
|
|
1803
2961
|
agentId
|
|
@@ -1810,17 +2968,17 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1810
2968
|
async stopImage(imageId) {
|
|
1811
2969
|
const agentId = this.imageToAgent.get(imageId);
|
|
1812
2970
|
if (!agentId) {
|
|
1813
|
-
|
|
2971
|
+
logger10.debug("Image not running, nothing to stop", {
|
|
1814
2972
|
imageId,
|
|
1815
2973
|
containerId: this.containerId
|
|
1816
2974
|
});
|
|
1817
2975
|
return false;
|
|
1818
2976
|
}
|
|
1819
|
-
|
|
2977
|
+
logger10.info("Stopping image", { imageId, agentId, containerId: this.containerId });
|
|
1820
2978
|
const success = await this.destroyAgent(agentId);
|
|
1821
2979
|
if (success) {
|
|
1822
2980
|
this.imageToAgent.delete(imageId);
|
|
1823
|
-
|
|
2981
|
+
logger10.info("Image stopped", { imageId, agentId, containerId: this.containerId });
|
|
1824
2982
|
}
|
|
1825
2983
|
return success;
|
|
1826
2984
|
}
|
|
@@ -1877,7 +3035,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1877
3035
|
agentId
|
|
1878
3036
|
}
|
|
1879
3037
|
});
|
|
1880
|
-
|
|
3038
|
+
logger10.info("Agent destroyed", { containerId: this.containerId, agentId });
|
|
1881
3039
|
return true;
|
|
1882
3040
|
}
|
|
1883
3041
|
async destroyAllAgents() {
|
|
@@ -1905,7 +3063,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1905
3063
|
}
|
|
1906
3064
|
});
|
|
1907
3065
|
this.context.onDisposed?.(this.containerId);
|
|
1908
|
-
|
|
3066
|
+
logger10.info("Container disposed", { containerId: this.containerId, agentCount });
|
|
1909
3067
|
}
|
|
1910
3068
|
// ==================== Private Helpers ====================
|
|
1911
3069
|
generateAgentId() {
|
|
@@ -1916,8 +3074,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1916
3074
|
};
|
|
1917
3075
|
|
|
1918
3076
|
// src/internal/BaseEventHandler.ts
|
|
1919
|
-
var
|
|
1920
|
-
var logger9 = (0, import_common9.createLogger)("runtime/BaseEventHandler");
|
|
3077
|
+
var logger11 = createLogger("runtime/BaseEventHandler");
|
|
1921
3078
|
var BaseEventHandler = class {
|
|
1922
3079
|
bus;
|
|
1923
3080
|
unsubscribes = [];
|
|
@@ -1956,7 +3113,7 @@ var BaseEventHandler = class {
|
|
|
1956
3113
|
handleError(err, context) {
|
|
1957
3114
|
const message = err instanceof Error ? err.message : String(err);
|
|
1958
3115
|
const stack = err instanceof Error ? err.stack : void 0;
|
|
1959
|
-
|
|
3116
|
+
logger11.error(`Error in ${context.operation || "handler"}`, {
|
|
1960
3117
|
message,
|
|
1961
3118
|
requestId: context.requestId,
|
|
1962
3119
|
details: context.details
|
|
@@ -1983,7 +3140,7 @@ var BaseEventHandler = class {
|
|
|
1983
3140
|
try {
|
|
1984
3141
|
context.onError(err);
|
|
1985
3142
|
} catch (callbackErr) {
|
|
1986
|
-
|
|
3143
|
+
logger11.error("Error in onError callback", { error: callbackErr });
|
|
1987
3144
|
}
|
|
1988
3145
|
}
|
|
1989
3146
|
}
|
|
@@ -2001,13 +3158,12 @@ var BaseEventHandler = class {
|
|
|
2001
3158
|
unsubscribe();
|
|
2002
3159
|
}
|
|
2003
3160
|
this.unsubscribes = [];
|
|
2004
|
-
|
|
3161
|
+
logger11.debug(`${this.constructor.name} disposed`);
|
|
2005
3162
|
}
|
|
2006
3163
|
};
|
|
2007
3164
|
|
|
2008
3165
|
// src/internal/CommandHandler.ts
|
|
2009
|
-
var
|
|
2010
|
-
var logger10 = (0, import_common10.createLogger)("runtime/CommandHandler");
|
|
3166
|
+
var logger12 = createLogger("runtime/CommandHandler");
|
|
2011
3167
|
function createResponse(type, data) {
|
|
2012
3168
|
return {
|
|
2013
3169
|
type,
|
|
@@ -2040,7 +3196,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2040
3196
|
super(bus);
|
|
2041
3197
|
this.ops = operations;
|
|
2042
3198
|
this.bindHandlers();
|
|
2043
|
-
|
|
3199
|
+
logger12.debug("CommandHandler created");
|
|
2044
3200
|
}
|
|
2045
3201
|
/**
|
|
2046
3202
|
* Log error and emit system_error event
|
|
@@ -2048,7 +3204,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2048
3204
|
emitError(operation, err, requestId, context) {
|
|
2049
3205
|
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
2050
3206
|
const stack = err instanceof Error ? err.stack : void 0;
|
|
2051
|
-
|
|
3207
|
+
logger12.error(operation, {
|
|
2052
3208
|
requestId,
|
|
2053
3209
|
...context,
|
|
2054
3210
|
error: errorMessage,
|
|
@@ -2105,12 +3261,12 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2105
3261
|
this.subscribe(
|
|
2106
3262
|
this.bus.onCommand("image_messages_request", (event) => this.handleImageMessages(event))
|
|
2107
3263
|
);
|
|
2108
|
-
|
|
3264
|
+
logger12.debug("Command handlers bound");
|
|
2109
3265
|
}
|
|
2110
3266
|
// ==================== Container Handlers ====================
|
|
2111
3267
|
async handleContainerCreate(event) {
|
|
2112
3268
|
const { requestId, containerId } = event.data;
|
|
2113
|
-
|
|
3269
|
+
logger12.debug("Handling container_create_request", { requestId, containerId });
|
|
2114
3270
|
try {
|
|
2115
3271
|
await this.ops.createContainer(containerId);
|
|
2116
3272
|
this.bus.emit(
|
|
@@ -2132,7 +3288,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2132
3288
|
}
|
|
2133
3289
|
handleContainerGet(event) {
|
|
2134
3290
|
const { requestId, containerId } = event.data;
|
|
2135
|
-
|
|
3291
|
+
logger12.debug("Handling container_get_request", { requestId, containerId });
|
|
2136
3292
|
const container = this.ops.getContainer(containerId);
|
|
2137
3293
|
this.bus.emit(
|
|
2138
3294
|
createResponse("container_get_response", {
|
|
@@ -2144,7 +3300,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2144
3300
|
}
|
|
2145
3301
|
handleContainerList(event) {
|
|
2146
3302
|
const { requestId } = event.data;
|
|
2147
|
-
|
|
3303
|
+
logger12.debug("Handling container_list_request", { requestId });
|
|
2148
3304
|
const containers = this.ops.listContainers();
|
|
2149
3305
|
this.bus.emit(
|
|
2150
3306
|
createResponse("container_list_response", {
|
|
@@ -2156,7 +3312,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2156
3312
|
// ==================== Agent Handlers ====================
|
|
2157
3313
|
handleAgentGet(event) {
|
|
2158
3314
|
const { requestId, agentId } = event.data;
|
|
2159
|
-
|
|
3315
|
+
logger12.debug("Handling agent_get_request", { requestId, agentId });
|
|
2160
3316
|
const agent = this.ops.getAgent(agentId);
|
|
2161
3317
|
this.bus.emit(
|
|
2162
3318
|
createResponse("agent_get_response", {
|
|
@@ -2169,7 +3325,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2169
3325
|
}
|
|
2170
3326
|
handleAgentList(event) {
|
|
2171
3327
|
const { requestId, containerId } = event.data;
|
|
2172
|
-
|
|
3328
|
+
logger12.debug("Handling agent_list_request", { requestId, containerId });
|
|
2173
3329
|
const agents = this.ops.listAgents(containerId);
|
|
2174
3330
|
this.bus.emit(
|
|
2175
3331
|
createResponse("agent_list_response", {
|
|
@@ -2184,7 +3340,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2184
3340
|
}
|
|
2185
3341
|
async handleAgentDestroy(event) {
|
|
2186
3342
|
const { requestId, agentId } = event.data;
|
|
2187
|
-
|
|
3343
|
+
logger12.debug("Handling agent_destroy_request", { requestId, agentId });
|
|
2188
3344
|
try {
|
|
2189
3345
|
const success = await this.ops.destroyAgent(agentId);
|
|
2190
3346
|
this.bus.emit(
|
|
@@ -2208,7 +3364,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2208
3364
|
}
|
|
2209
3365
|
async handleAgentDestroyAll(event) {
|
|
2210
3366
|
const { requestId, containerId } = event.data;
|
|
2211
|
-
|
|
3367
|
+
logger12.debug("Handling agent_destroy_all_request", { requestId, containerId });
|
|
2212
3368
|
try {
|
|
2213
3369
|
await this.ops.destroyAllAgents(containerId);
|
|
2214
3370
|
this.bus.emit(
|
|
@@ -2230,7 +3386,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2230
3386
|
}
|
|
2231
3387
|
async handleMessageSend(event) {
|
|
2232
3388
|
const { requestId, imageId, agentId, content } = event.data;
|
|
2233
|
-
|
|
3389
|
+
logger12.debug("Handling message_send_request", { requestId, imageId, agentId });
|
|
2234
3390
|
try {
|
|
2235
3391
|
const result = await this.ops.receiveMessage(imageId, agentId, content, requestId);
|
|
2236
3392
|
this.bus.emit(
|
|
@@ -2254,7 +3410,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2254
3410
|
}
|
|
2255
3411
|
handleAgentInterrupt(event) {
|
|
2256
3412
|
const { requestId, imageId, agentId } = event.data;
|
|
2257
|
-
|
|
3413
|
+
logger12.debug("Handling agent_interrupt_request", { requestId, imageId, agentId });
|
|
2258
3414
|
try {
|
|
2259
3415
|
const result = this.ops.interruptAgent(imageId, agentId, requestId);
|
|
2260
3416
|
this.bus.emit(
|
|
@@ -2279,7 +3435,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2279
3435
|
// ==================== Image Handlers ====================
|
|
2280
3436
|
async handleImageCreate(event) {
|
|
2281
3437
|
const { requestId, containerId, config } = event.data;
|
|
2282
|
-
|
|
3438
|
+
logger12.debug("Handling image_create_request", { requestId, containerId });
|
|
2283
3439
|
try {
|
|
2284
3440
|
const record = await this.ops.createImage(containerId, config);
|
|
2285
3441
|
this.bus.emit(
|
|
@@ -2301,7 +3457,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2301
3457
|
}
|
|
2302
3458
|
async handleImageRun(event) {
|
|
2303
3459
|
const { requestId, imageId } = event.data;
|
|
2304
|
-
|
|
3460
|
+
logger12.debug("Handling image_run_request", { requestId, imageId });
|
|
2305
3461
|
try {
|
|
2306
3462
|
const result = await this.ops.runImage(imageId);
|
|
2307
3463
|
this.bus.emit(
|
|
@@ -2327,7 +3483,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2327
3483
|
}
|
|
2328
3484
|
async handleImageStop(event) {
|
|
2329
3485
|
const { requestId, imageId } = event.data;
|
|
2330
|
-
|
|
3486
|
+
logger12.debug("Handling image_stop_request", { requestId, imageId });
|
|
2331
3487
|
try {
|
|
2332
3488
|
await this.ops.stopImage(imageId);
|
|
2333
3489
|
this.bus.emit(
|
|
@@ -2349,7 +3505,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2349
3505
|
}
|
|
2350
3506
|
async handleImageUpdate(event) {
|
|
2351
3507
|
const { requestId, imageId, updates } = event.data;
|
|
2352
|
-
|
|
3508
|
+
logger12.debug("Handling image_update_request", { requestId, imageId });
|
|
2353
3509
|
try {
|
|
2354
3510
|
const record = await this.ops.updateImage(imageId, updates);
|
|
2355
3511
|
this.bus.emit(
|
|
@@ -2371,7 +3527,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2371
3527
|
}
|
|
2372
3528
|
async handleImageList(event) {
|
|
2373
3529
|
const { requestId, containerId } = event.data;
|
|
2374
|
-
|
|
3530
|
+
logger12.debug("Handling image_list_request", { requestId, containerId });
|
|
2375
3531
|
try {
|
|
2376
3532
|
const images = await this.ops.listImages(containerId);
|
|
2377
3533
|
this.bus.emit(
|
|
@@ -2393,7 +3549,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2393
3549
|
}
|
|
2394
3550
|
async handleImageGet(event) {
|
|
2395
3551
|
const { requestId, imageId } = event.data;
|
|
2396
|
-
|
|
3552
|
+
logger12.debug("Handling image_get_request", { requestId, imageId });
|
|
2397
3553
|
try {
|
|
2398
3554
|
const image = await this.ops.getImage(imageId);
|
|
2399
3555
|
this.bus.emit(
|
|
@@ -2414,7 +3570,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2414
3570
|
}
|
|
2415
3571
|
async handleImageDelete(event) {
|
|
2416
3572
|
const { requestId, imageId } = event.data;
|
|
2417
|
-
|
|
3573
|
+
logger12.debug("Handling image_delete_request", { requestId, imageId });
|
|
2418
3574
|
try {
|
|
2419
3575
|
await this.ops.deleteImage(imageId);
|
|
2420
3576
|
this.bus.emit(
|
|
@@ -2436,10 +3592,10 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2436
3592
|
}
|
|
2437
3593
|
async handleImageMessages(event) {
|
|
2438
3594
|
const { requestId, imageId } = event.data;
|
|
2439
|
-
|
|
3595
|
+
logger12.info("Handling image_messages_request", { requestId, imageId });
|
|
2440
3596
|
try {
|
|
2441
3597
|
const messages = await this.ops.getImageMessages(imageId);
|
|
2442
|
-
|
|
3598
|
+
logger12.info("Got messages for image", { imageId, count: messages.length });
|
|
2443
3599
|
this.bus.emit(
|
|
2444
3600
|
createResponse("image_messages_response", {
|
|
2445
3601
|
requestId,
|
|
@@ -2447,7 +3603,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2447
3603
|
messages
|
|
2448
3604
|
})
|
|
2449
3605
|
);
|
|
2450
|
-
|
|
3606
|
+
logger12.info("Emitted image_messages_response", { requestId, imageId });
|
|
2451
3607
|
} catch (err) {
|
|
2452
3608
|
this.emitError("Failed to get image messages", err, requestId, { imageId });
|
|
2453
3609
|
this.bus.emit(
|
|
@@ -2464,10 +3620,9 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2464
3620
|
};
|
|
2465
3621
|
|
|
2466
3622
|
// src/RuntimeImpl.ts
|
|
2467
|
-
var import_common11 = require("@agentxjs/common");
|
|
2468
3623
|
var import_node_os = require("os");
|
|
2469
3624
|
var import_node_path2 = require("path");
|
|
2470
|
-
var
|
|
3625
|
+
var logger13 = createLogger("runtime/RuntimeImpl");
|
|
2471
3626
|
var RuntimeImpl = class {
|
|
2472
3627
|
persistence;
|
|
2473
3628
|
llmProvider;
|
|
@@ -2478,20 +3633,20 @@ var RuntimeImpl = class {
|
|
|
2478
3633
|
/** Container registry: containerId -> RuntimeContainer */
|
|
2479
3634
|
containerRegistry = /* @__PURE__ */ new Map();
|
|
2480
3635
|
constructor(config) {
|
|
2481
|
-
|
|
3636
|
+
logger13.info("RuntimeImpl constructor start");
|
|
2482
3637
|
this.persistence = config.persistence;
|
|
2483
3638
|
this.llmProvider = config.llmProvider;
|
|
2484
3639
|
this.basePath = (0, import_node_path2.join)((0, import_node_os.homedir)(), ".agentx");
|
|
2485
|
-
|
|
3640
|
+
logger13.info("Creating SystemBus");
|
|
2486
3641
|
this.bus = new SystemBusImpl();
|
|
2487
3642
|
this.llmConfig = this.llmProvider.provide();
|
|
2488
|
-
|
|
3643
|
+
logger13.info("LLM config loaded", {
|
|
2489
3644
|
hasApiKey: !!this.llmConfig.apiKey,
|
|
2490
3645
|
model: this.llmConfig.model
|
|
2491
3646
|
});
|
|
2492
|
-
|
|
3647
|
+
logger13.info("Creating CommandHandler");
|
|
2493
3648
|
this.commandHandler = new CommandHandler(this.bus, this.createRuntimeOperations());
|
|
2494
|
-
|
|
3649
|
+
logger13.info("RuntimeImpl constructor done");
|
|
2495
3650
|
}
|
|
2496
3651
|
// ==================== SystemBus delegation ====================
|
|
2497
3652
|
emit(event) {
|
|
@@ -2574,7 +3729,7 @@ var RuntimeImpl = class {
|
|
|
2574
3729
|
// Agent operations (by imageId - with auto-activation)
|
|
2575
3730
|
receiveMessage: async (imageId, agentId, content, requestId) => {
|
|
2576
3731
|
if (imageId) {
|
|
2577
|
-
|
|
3732
|
+
logger13.debug("Receiving message by imageId", {
|
|
2578
3733
|
imageId,
|
|
2579
3734
|
contentLength: content.length,
|
|
2580
3735
|
requestId
|
|
@@ -2583,7 +3738,7 @@ var RuntimeImpl = class {
|
|
|
2583
3738
|
if (!record) throw new Error(`Image not found: ${imageId}`);
|
|
2584
3739
|
const container = await this.getOrCreateContainer(record.containerId);
|
|
2585
3740
|
const { agent, reused } = await container.runImage(record);
|
|
2586
|
-
|
|
3741
|
+
logger13.info("Message routed to agent", {
|
|
2587
3742
|
imageId,
|
|
2588
3743
|
agentId: agent.agentId,
|
|
2589
3744
|
reused,
|
|
@@ -2593,7 +3748,7 @@ var RuntimeImpl = class {
|
|
|
2593
3748
|
return { agentId: agent.agentId, imageId };
|
|
2594
3749
|
}
|
|
2595
3750
|
if (agentId) {
|
|
2596
|
-
|
|
3751
|
+
logger13.debug("Receiving message by agentId (legacy)", {
|
|
2597
3752
|
agentId,
|
|
2598
3753
|
contentLength: content.length,
|
|
2599
3754
|
requestId
|
|
@@ -2610,12 +3765,12 @@ var RuntimeImpl = class {
|
|
|
2610
3765
|
if (imageId) {
|
|
2611
3766
|
const foundAgentId = this.findAgentIdForImage(imageId);
|
|
2612
3767
|
if (!foundAgentId) {
|
|
2613
|
-
|
|
3768
|
+
logger13.debug("Image is offline, nothing to interrupt", { imageId });
|
|
2614
3769
|
return { imageId, agentId: void 0 };
|
|
2615
3770
|
}
|
|
2616
3771
|
const agent = this.findAgent(foundAgentId);
|
|
2617
3772
|
if (agent) {
|
|
2618
|
-
|
|
3773
|
+
logger13.info("Interrupting agent by imageId", {
|
|
2619
3774
|
imageId,
|
|
2620
3775
|
agentId: foundAgentId,
|
|
2621
3776
|
requestId
|
|
@@ -2627,7 +3782,7 @@ var RuntimeImpl = class {
|
|
|
2627
3782
|
if (agentId) {
|
|
2628
3783
|
const agent = this.findAgent(agentId);
|
|
2629
3784
|
if (!agent) throw new Error(`Agent not found: ${agentId}`);
|
|
2630
|
-
|
|
3785
|
+
logger13.info("Interrupting agent by agentId (legacy)", { agentId, requestId });
|
|
2631
3786
|
agent.interrupt(requestId);
|
|
2632
3787
|
const foundImageId = this.findImageIdForAgent(agentId);
|
|
2633
3788
|
return { agentId, imageId: foundImageId };
|
|
@@ -2636,32 +3791,32 @@ var RuntimeImpl = class {
|
|
|
2636
3791
|
},
|
|
2637
3792
|
// Image operations (new model)
|
|
2638
3793
|
createImage: async (containerId, config) => {
|
|
2639
|
-
|
|
3794
|
+
logger13.debug("Creating image", { containerId, name: config.name });
|
|
2640
3795
|
await this.getOrCreateContainer(containerId);
|
|
2641
3796
|
const image = await RuntimeImage.create(
|
|
2642
3797
|
{ containerId, ...config },
|
|
2643
3798
|
this.createImageContext()
|
|
2644
3799
|
);
|
|
2645
|
-
|
|
3800
|
+
logger13.info("Image created via RuntimeOps", { imageId: image.imageId, containerId });
|
|
2646
3801
|
return this.toImageListItemResult(image.toRecord(), false);
|
|
2647
3802
|
},
|
|
2648
3803
|
runImage: async (imageId) => {
|
|
2649
|
-
|
|
3804
|
+
logger13.debug("Running image", { imageId });
|
|
2650
3805
|
const record = await this.persistence.images.findImageById(imageId);
|
|
2651
3806
|
if (!record) throw new Error(`Image not found: ${imageId}`);
|
|
2652
3807
|
const container = await this.getOrCreateContainer(record.containerId);
|
|
2653
3808
|
const { agent, reused } = await container.runImage(record);
|
|
2654
|
-
|
|
3809
|
+
logger13.info("Image running", { imageId, agentId: agent.agentId, reused });
|
|
2655
3810
|
return { imageId, agentId: agent.agentId, reused };
|
|
2656
3811
|
},
|
|
2657
3812
|
stopImage: async (imageId) => {
|
|
2658
|
-
|
|
3813
|
+
logger13.debug("Stopping image", { imageId });
|
|
2659
3814
|
const record = await this.persistence.images.findImageById(imageId);
|
|
2660
3815
|
if (!record) throw new Error(`Image not found: ${imageId}`);
|
|
2661
3816
|
const container = this.containerRegistry.get(record.containerId);
|
|
2662
3817
|
if (container) {
|
|
2663
3818
|
await container.stopImage(imageId);
|
|
2664
|
-
|
|
3819
|
+
logger13.info("Image stopped via RuntimeOps", { imageId });
|
|
2665
3820
|
}
|
|
2666
3821
|
},
|
|
2667
3822
|
updateImage: async (imageId, updates) => {
|
|
@@ -2685,10 +3840,10 @@ var RuntimeImpl = class {
|
|
|
2685
3840
|
return this.toImageListItemResult(record, online);
|
|
2686
3841
|
},
|
|
2687
3842
|
deleteImage: async (imageId) => {
|
|
2688
|
-
|
|
3843
|
+
logger13.debug("Deleting image", { imageId });
|
|
2689
3844
|
const agentId = this.findAgentIdForImage(imageId);
|
|
2690
3845
|
if (agentId) {
|
|
2691
|
-
|
|
3846
|
+
logger13.debug("Stopping running agent before delete", { imageId, agentId });
|
|
2692
3847
|
for (const container of this.containerRegistry.values()) {
|
|
2693
3848
|
if (container.getAgent(agentId)) {
|
|
2694
3849
|
await container.destroyAgent(agentId);
|
|
@@ -2699,17 +3854,17 @@ var RuntimeImpl = class {
|
|
|
2699
3854
|
const image = await RuntimeImage.load(imageId, this.createImageContext());
|
|
2700
3855
|
if (image) {
|
|
2701
3856
|
await image.delete();
|
|
2702
|
-
|
|
3857
|
+
logger13.info("Image deleted via RuntimeOps", { imageId });
|
|
2703
3858
|
}
|
|
2704
3859
|
},
|
|
2705
3860
|
getImageMessages: async (imageId) => {
|
|
2706
|
-
|
|
3861
|
+
logger13.debug("Getting messages for image", { imageId });
|
|
2707
3862
|
const image = await RuntimeImage.load(imageId, this.createImageContext());
|
|
2708
3863
|
if (!image) {
|
|
2709
3864
|
throw new Error(`Image not found: ${imageId}`);
|
|
2710
3865
|
}
|
|
2711
3866
|
const messages = await image.getMessages();
|
|
2712
|
-
|
|
3867
|
+
logger13.debug("Got messages from storage", { imageId, count: messages.length });
|
|
2713
3868
|
return messages.map((m) => {
|
|
2714
3869
|
let content;
|
|
2715
3870
|
let role = m.role;
|
|
@@ -2826,14 +3981,14 @@ var RuntimeImpl = class {
|
|
|
2826
3981
|
}
|
|
2827
3982
|
// ==================== Lifecycle ====================
|
|
2828
3983
|
async dispose() {
|
|
2829
|
-
|
|
3984
|
+
logger13.info("Disposing RuntimeImpl");
|
|
2830
3985
|
this.commandHandler.dispose();
|
|
2831
3986
|
for (const container of this.containerRegistry.values()) {
|
|
2832
3987
|
await container.dispose();
|
|
2833
3988
|
}
|
|
2834
3989
|
this.bus.destroy();
|
|
2835
3990
|
this.containerRegistry.clear();
|
|
2836
|
-
|
|
3991
|
+
logger13.info("RuntimeImpl disposed");
|
|
2837
3992
|
}
|
|
2838
3993
|
};
|
|
2839
3994
|
|
|
@@ -2844,11 +3999,9 @@ function createRuntime(config) {
|
|
|
2844
3999
|
|
|
2845
4000
|
// src/internal/persistence/PersistenceImpl.ts
|
|
2846
4001
|
var import_unstorage = require("unstorage");
|
|
2847
|
-
var import_common15 = require("@agentxjs/common");
|
|
2848
4002
|
|
|
2849
4003
|
// src/internal/persistence/repository/StorageImageRepository.ts
|
|
2850
|
-
var
|
|
2851
|
-
var logger12 = (0, import_common12.createLogger)("persistence/ImageRepository");
|
|
4004
|
+
var logger14 = createLogger("persistence/ImageRepository");
|
|
2852
4005
|
var PREFIX = "images";
|
|
2853
4006
|
var INDEX_BY_NAME = "idx:images:name";
|
|
2854
4007
|
var INDEX_BY_CONTAINER = "idx:images:container";
|
|
@@ -2872,7 +4025,7 @@ var StorageImageRepository = class {
|
|
|
2872
4025
|
this.containerIndexKey(record.containerId, record.imageId),
|
|
2873
4026
|
record.imageId
|
|
2874
4027
|
);
|
|
2875
|
-
|
|
4028
|
+
logger14.debug("Image saved", { imageId: record.imageId });
|
|
2876
4029
|
}
|
|
2877
4030
|
async findImageById(imageId) {
|
|
2878
4031
|
const record = await this.storage.getItem(this.key(imageId));
|
|
@@ -2927,7 +4080,7 @@ var StorageImageRepository = class {
|
|
|
2927
4080
|
await this.storage.removeItem(this.nameIndexKey(record.name, imageId));
|
|
2928
4081
|
await this.storage.removeItem(this.containerIndexKey(record.containerId, imageId));
|
|
2929
4082
|
}
|
|
2930
|
-
|
|
4083
|
+
logger14.debug("Image deleted", { imageId });
|
|
2931
4084
|
}
|
|
2932
4085
|
async imageExists(imageId) {
|
|
2933
4086
|
return await this.storage.hasItem(this.key(imageId));
|
|
@@ -2946,13 +4099,12 @@ var StorageImageRepository = class {
|
|
|
2946
4099
|
updatedAt: Date.now()
|
|
2947
4100
|
};
|
|
2948
4101
|
await this.storage.setItem(this.key(imageId), updatedRecord);
|
|
2949
|
-
|
|
4102
|
+
logger14.debug("Image metadata updated", { imageId, metadata });
|
|
2950
4103
|
}
|
|
2951
4104
|
};
|
|
2952
4105
|
|
|
2953
4106
|
// src/internal/persistence/repository/StorageContainerRepository.ts
|
|
2954
|
-
var
|
|
2955
|
-
var logger13 = (0, import_common13.createLogger)("persistence/ContainerRepository");
|
|
4107
|
+
var logger15 = createLogger("persistence/ContainerRepository");
|
|
2956
4108
|
var PREFIX2 = "containers";
|
|
2957
4109
|
var StorageContainerRepository = class {
|
|
2958
4110
|
constructor(storage) {
|
|
@@ -2963,7 +4115,7 @@ var StorageContainerRepository = class {
|
|
|
2963
4115
|
}
|
|
2964
4116
|
async saveContainer(record) {
|
|
2965
4117
|
await this.storage.setItem(this.key(record.containerId), record);
|
|
2966
|
-
|
|
4118
|
+
logger15.debug("Container saved", { containerId: record.containerId });
|
|
2967
4119
|
}
|
|
2968
4120
|
async findContainerById(containerId) {
|
|
2969
4121
|
const record = await this.storage.getItem(this.key(containerId));
|
|
@@ -2982,7 +4134,7 @@ var StorageContainerRepository = class {
|
|
|
2982
4134
|
}
|
|
2983
4135
|
async deleteContainer(containerId) {
|
|
2984
4136
|
await this.storage.removeItem(this.key(containerId));
|
|
2985
|
-
|
|
4137
|
+
logger15.debug("Container deleted", { containerId });
|
|
2986
4138
|
}
|
|
2987
4139
|
async containerExists(containerId) {
|
|
2988
4140
|
return await this.storage.hasItem(this.key(containerId));
|
|
@@ -2990,8 +4142,7 @@ var StorageContainerRepository = class {
|
|
|
2990
4142
|
};
|
|
2991
4143
|
|
|
2992
4144
|
// src/internal/persistence/repository/StorageSessionRepository.ts
|
|
2993
|
-
var
|
|
2994
|
-
var logger14 = (0, import_common14.createLogger)("persistence/SessionRepository");
|
|
4145
|
+
var logger16 = createLogger("persistence/SessionRepository");
|
|
2995
4146
|
var PREFIX3 = "sessions";
|
|
2996
4147
|
var MESSAGES_PREFIX = "messages";
|
|
2997
4148
|
var INDEX_BY_IMAGE = "idx:sessions:image";
|
|
@@ -3022,7 +4173,7 @@ var StorageSessionRepository = class {
|
|
|
3022
4173
|
this.containerIndexKey(record.containerId, record.sessionId),
|
|
3023
4174
|
record.sessionId
|
|
3024
4175
|
);
|
|
3025
|
-
|
|
4176
|
+
logger16.debug("Session saved", { sessionId: record.sessionId });
|
|
3026
4177
|
}
|
|
3027
4178
|
async findSessionById(sessionId) {
|
|
3028
4179
|
const record = await this.storage.getItem(this.key(sessionId));
|
|
@@ -3071,7 +4222,7 @@ var StorageSessionRepository = class {
|
|
|
3071
4222
|
await this.storage.removeItem(this.imageIndexKey(record.imageId, sessionId));
|
|
3072
4223
|
await this.storage.removeItem(this.containerIndexKey(record.containerId, sessionId));
|
|
3073
4224
|
}
|
|
3074
|
-
|
|
4225
|
+
logger16.debug("Session deleted", { sessionId });
|
|
3075
4226
|
}
|
|
3076
4227
|
async sessionExists(sessionId) {
|
|
3077
4228
|
return await this.storage.hasItem(this.key(sessionId));
|
|
@@ -3081,13 +4232,13 @@ var StorageSessionRepository = class {
|
|
|
3081
4232
|
const messages = await this.getMessages(sessionId);
|
|
3082
4233
|
messages.push(message);
|
|
3083
4234
|
await this.storage.setItem(this.messagesKey(sessionId), messages);
|
|
3084
|
-
|
|
4235
|
+
logger16.debug("Message added to session", { sessionId, subtype: message.subtype });
|
|
3085
4236
|
}
|
|
3086
4237
|
async getMessages(sessionId) {
|
|
3087
4238
|
const messages = await this.storage.getItem(this.messagesKey(sessionId));
|
|
3088
4239
|
if (!messages || !Array.isArray(messages)) {
|
|
3089
4240
|
if (messages) {
|
|
3090
|
-
|
|
4241
|
+
logger16.warn("Messages data is not an array, resetting", {
|
|
3091
4242
|
sessionId,
|
|
3092
4243
|
type: typeof messages
|
|
3093
4244
|
});
|
|
@@ -3098,12 +4249,12 @@ var StorageSessionRepository = class {
|
|
|
3098
4249
|
}
|
|
3099
4250
|
async clearMessages(sessionId) {
|
|
3100
4251
|
await this.storage.removeItem(this.messagesKey(sessionId));
|
|
3101
|
-
|
|
4252
|
+
logger16.debug("Messages cleared for session", { sessionId });
|
|
3102
4253
|
}
|
|
3103
4254
|
};
|
|
3104
4255
|
|
|
3105
4256
|
// src/internal/persistence/PersistenceImpl.ts
|
|
3106
|
-
var
|
|
4257
|
+
var logger17 = createLogger("persistence/Persistence");
|
|
3107
4258
|
var PersistenceImpl = class _PersistenceImpl {
|
|
3108
4259
|
images;
|
|
3109
4260
|
containers;
|
|
@@ -3117,7 +4268,7 @@ var PersistenceImpl = class _PersistenceImpl {
|
|
|
3117
4268
|
this.images = new StorageImageRepository(this.storage);
|
|
3118
4269
|
this.containers = new StorageContainerRepository(this.storage);
|
|
3119
4270
|
this.sessions = new StorageSessionRepository(this.storage);
|
|
3120
|
-
|
|
4271
|
+
logger17.info("Persistence created", { driver: driverName });
|
|
3121
4272
|
}
|
|
3122
4273
|
/**
|
|
3123
4274
|
* Create a PersistenceImpl instance (async factory)
|
|
@@ -3138,7 +4289,7 @@ var PersistenceImpl = class _PersistenceImpl {
|
|
|
3138
4289
|
*/
|
|
3139
4290
|
async dispose() {
|
|
3140
4291
|
await this.storage.dispose();
|
|
3141
|
-
|
|
4292
|
+
logger17.info("Persistence disposed");
|
|
3142
4293
|
}
|
|
3143
4294
|
};
|
|
3144
4295
|
async function createStorageFromConfig(config) {
|