@agentxjs/runtime 1.0.2 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +146 -1370
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +144 -1368
- package/dist/index.js.map +1 -1
- package/package.json +15 -15
- package/LICENSE +0 -21
package/dist/index.cjs
CHANGED
|
@@ -37,178 +37,8 @@ module.exports = __toCommonJS(index_exports);
|
|
|
37
37
|
|
|
38
38
|
// src/internal/SystemBusImpl.ts
|
|
39
39
|
var import_rxjs = require("rxjs");
|
|
40
|
-
|
|
41
|
-
|
|
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");
|
|
40
|
+
var import_common = require("@agentxjs/common");
|
|
41
|
+
var logger = (0, import_common.createLogger)("runtime/SystemBusImpl");
|
|
212
42
|
var SystemBusImpl = class {
|
|
213
43
|
subject = new import_rxjs.Subject();
|
|
214
44
|
subscriptions = [];
|
|
@@ -366,7 +196,8 @@ var SystemBusImpl = class {
|
|
|
366
196
|
};
|
|
367
197
|
|
|
368
198
|
// src/internal/BusDriver.ts
|
|
369
|
-
var
|
|
199
|
+
var import_common2 = require("@agentxjs/common");
|
|
200
|
+
var logger2 = (0, import_common2.createLogger)("runtime/BusDriver");
|
|
370
201
|
var BusDriver = class {
|
|
371
202
|
name = "BusDriver";
|
|
372
203
|
description = "Driver that listens to SystemBus for DriveableEvents";
|
|
@@ -551,7 +382,8 @@ var BusDriver = class {
|
|
|
551
382
|
};
|
|
552
383
|
|
|
553
384
|
// src/internal/AgentInteractor.ts
|
|
554
|
-
var
|
|
385
|
+
var import_common3 = require("@agentxjs/common");
|
|
386
|
+
var logger3 = (0, import_common3.createLogger)("runtime/AgentInteractor");
|
|
555
387
|
var AgentInteractor = class {
|
|
556
388
|
producer;
|
|
557
389
|
session;
|
|
@@ -642,1006 +474,13 @@ var AgentInteractor = class {
|
|
|
642
474
|
}
|
|
643
475
|
};
|
|
644
476
|
|
|
645
|
-
//
|
|
646
|
-
|
|
647
|
-
|
|
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
|
-
}
|
|
477
|
+
// src/internal/RuntimeAgent.ts
|
|
478
|
+
var import_agent = require("@agentxjs/agent");
|
|
479
|
+
var import_common7 = require("@agentxjs/common");
|
|
1642
480
|
|
|
1643
481
|
// src/environment/ClaudeReceptor.ts
|
|
1644
|
-
var
|
|
482
|
+
var import_common4 = require("@agentxjs/common");
|
|
483
|
+
var logger4 = (0, import_common4.createLogger)("ecosystem/ClaudeReceptor");
|
|
1645
484
|
var ClaudeReceptor = class {
|
|
1646
485
|
producer = null;
|
|
1647
486
|
currentMeta = null;
|
|
@@ -1659,7 +498,7 @@ var ClaudeReceptor = class {
|
|
|
1659
498
|
*/
|
|
1660
499
|
connect(producer) {
|
|
1661
500
|
this.producer = producer;
|
|
1662
|
-
|
|
501
|
+
logger4.debug("ClaudeReceptor connected to SystemBusProducer");
|
|
1663
502
|
}
|
|
1664
503
|
/**
|
|
1665
504
|
* Feed SDK message to receptor with correlation metadata
|
|
@@ -1777,7 +616,7 @@ var ClaudeReceptor = class {
|
|
|
1777
616
|
case "content_block_start": {
|
|
1778
617
|
const contentBlock = event.content_block;
|
|
1779
618
|
this.blockContext.currentBlockIndex = event.index;
|
|
1780
|
-
|
|
619
|
+
logger4.debug("content_block_start received", { contentBlock, index: event.index });
|
|
1781
620
|
if (contentBlock.type === "text") {
|
|
1782
621
|
this.blockContext.currentBlockType = "text";
|
|
1783
622
|
this.emitToBus({
|
|
@@ -1914,9 +753,11 @@ var ClaudeReceptor = class {
|
|
|
1914
753
|
// src/environment/ClaudeEffector.ts
|
|
1915
754
|
var import_claude_agent_sdk = require("@anthropic-ai/claude-agent-sdk");
|
|
1916
755
|
var import_rxjs2 = require("rxjs");
|
|
756
|
+
var import_common6 = require("@agentxjs/common");
|
|
1917
757
|
|
|
1918
758
|
// src/environment/buildOptions.ts
|
|
1919
|
-
var
|
|
759
|
+
var import_common5 = require("@agentxjs/common");
|
|
760
|
+
var logger5 = (0, import_common5.createLogger)("environment/buildOptions");
|
|
1920
761
|
function buildOptions(context, abortController) {
|
|
1921
762
|
const options = {
|
|
1922
763
|
abortController,
|
|
@@ -1941,7 +782,7 @@ function buildOptions(context, abortController) {
|
|
|
1941
782
|
env.ANTHROPIC_API_KEY = context.apiKey;
|
|
1942
783
|
}
|
|
1943
784
|
options.env = env;
|
|
1944
|
-
|
|
785
|
+
logger5.info("buildOptions called", {
|
|
1945
786
|
hasPath: !!env.PATH,
|
|
1946
787
|
pathLength: env.PATH?.length,
|
|
1947
788
|
hasApiKey: !!env.ANTHROPIC_API_KEY,
|
|
@@ -1952,7 +793,7 @@ function buildOptions(context, abortController) {
|
|
|
1952
793
|
cwd: context.cwd
|
|
1953
794
|
});
|
|
1954
795
|
options.stderr = (data) => {
|
|
1955
|
-
|
|
796
|
+
logger5.info("SDK stderr", { data: data.trim() });
|
|
1956
797
|
};
|
|
1957
798
|
if (context.model) options.model = context.model;
|
|
1958
799
|
if (context.systemPrompt) options.systemPrompt = context.systemPrompt;
|
|
@@ -2055,7 +896,7 @@ async function* observableToAsyncIterable(observable) {
|
|
|
2055
896
|
}
|
|
2056
897
|
|
|
2057
898
|
// src/environment/ClaudeEffector.ts
|
|
2058
|
-
var
|
|
899
|
+
var logger6 = (0, import_common6.createLogger)("ecosystem/ClaudeEffector");
|
|
2059
900
|
var DEFAULT_TIMEOUT = 3e4;
|
|
2060
901
|
var ClaudeEffector = class {
|
|
2061
902
|
config;
|
|
@@ -2074,12 +915,12 @@ var ClaudeEffector = class {
|
|
|
2074
915
|
* Connect to SystemBus consumer to subscribe to events
|
|
2075
916
|
*/
|
|
2076
917
|
connect(consumer) {
|
|
2077
|
-
|
|
918
|
+
logger6.debug("ClaudeEffector connected to SystemBusConsumer", {
|
|
2078
919
|
agentId: this.config.agentId
|
|
2079
920
|
});
|
|
2080
921
|
consumer.on("user_message", async (event) => {
|
|
2081
922
|
const typedEvent = event;
|
|
2082
|
-
|
|
923
|
+
logger6.debug("user_message event received", {
|
|
2083
924
|
eventAgentId: typedEvent.context?.agentId,
|
|
2084
925
|
myAgentId: this.config.agentId,
|
|
2085
926
|
matches: typedEvent.context?.agentId === this.config.agentId
|
|
@@ -2115,14 +956,14 @@ var ClaudeEffector = class {
|
|
|
2115
956
|
this.currentMeta = meta;
|
|
2116
957
|
const timeout = this.config.timeout ?? DEFAULT_TIMEOUT;
|
|
2117
958
|
const timeoutId = setTimeout(() => {
|
|
2118
|
-
|
|
959
|
+
logger6.warn("Request timeout", { timeout });
|
|
2119
960
|
this.currentAbortController?.abort(new Error(`Request timeout after ${timeout}ms`));
|
|
2120
961
|
}, timeout);
|
|
2121
962
|
try {
|
|
2122
963
|
await this.initialize(this.currentAbortController);
|
|
2123
964
|
const sessionId = this.config.sessionId || "default";
|
|
2124
965
|
const sdkUserMessage = buildSDKUserMessage(message, sessionId);
|
|
2125
|
-
|
|
966
|
+
logger6.debug("Sending message to Claude", {
|
|
2126
967
|
content: typeof message.content === "string" ? message.content.substring(0, 80) : "[structured]",
|
|
2127
968
|
timeout,
|
|
2128
969
|
requestId: meta.requestId
|
|
@@ -2139,13 +980,13 @@ var ClaudeEffector = class {
|
|
|
2139
980
|
*/
|
|
2140
981
|
interrupt(meta) {
|
|
2141
982
|
if (this.claudeQuery) {
|
|
2142
|
-
|
|
983
|
+
logger6.debug("Interrupting Claude query", { requestId: meta?.requestId });
|
|
2143
984
|
this.wasInterrupted = true;
|
|
2144
985
|
if (meta) {
|
|
2145
986
|
this.currentMeta = meta;
|
|
2146
987
|
}
|
|
2147
988
|
this.claudeQuery.interrupt().catch((err) => {
|
|
2148
|
-
|
|
989
|
+
logger6.debug("SDK interrupt() error (may be expected)", { error: err });
|
|
2149
990
|
});
|
|
2150
991
|
}
|
|
2151
992
|
}
|
|
@@ -2154,7 +995,7 @@ var ClaudeEffector = class {
|
|
|
2154
995
|
*/
|
|
2155
996
|
async initialize(abortController) {
|
|
2156
997
|
if (this.isInitialized) return;
|
|
2157
|
-
|
|
998
|
+
logger6.info("Initializing ClaudeEffector");
|
|
2158
999
|
const context = {
|
|
2159
1000
|
apiKey: this.config.apiKey,
|
|
2160
1001
|
baseUrl: this.config.baseUrl,
|
|
@@ -2171,7 +1012,7 @@ var ClaudeEffector = class {
|
|
|
2171
1012
|
});
|
|
2172
1013
|
this.isInitialized = true;
|
|
2173
1014
|
this.startBackgroundListener();
|
|
2174
|
-
|
|
1015
|
+
logger6.info("ClaudeEffector initialized");
|
|
2175
1016
|
}
|
|
2176
1017
|
/**
|
|
2177
1018
|
* Start background listener for SDK responses
|
|
@@ -2180,7 +1021,7 @@ var ClaudeEffector = class {
|
|
|
2180
1021
|
(async () => {
|
|
2181
1022
|
try {
|
|
2182
1023
|
for await (const sdkMsg of this.claudeQuery) {
|
|
2183
|
-
|
|
1024
|
+
logger6.debug("SDK message received", {
|
|
2184
1025
|
type: sdkMsg.type,
|
|
2185
1026
|
subtype: sdkMsg.subtype,
|
|
2186
1027
|
sessionId: sdkMsg.session_id,
|
|
@@ -2197,10 +1038,10 @@ var ClaudeEffector = class {
|
|
|
2197
1038
|
}
|
|
2198
1039
|
if (sdkMsg.type === "result") {
|
|
2199
1040
|
const resultMsg = sdkMsg;
|
|
2200
|
-
|
|
1041
|
+
logger6.info("SDK result received (full)", {
|
|
2201
1042
|
fullResult: JSON.stringify(sdkMsg, null, 2)
|
|
2202
1043
|
});
|
|
2203
|
-
|
|
1044
|
+
logger6.info("SDK result received", {
|
|
2204
1045
|
subtype: resultMsg.subtype,
|
|
2205
1046
|
isError: resultMsg.is_error,
|
|
2206
1047
|
errors: resultMsg.errors,
|
|
@@ -2218,10 +1059,10 @@ var ClaudeEffector = class {
|
|
|
2218
1059
|
}
|
|
2219
1060
|
} catch (error) {
|
|
2220
1061
|
if (this.isAbortError(error)) {
|
|
2221
|
-
|
|
1062
|
+
logger6.debug("Background listener aborted (expected during interrupt)");
|
|
2222
1063
|
this.resetState();
|
|
2223
1064
|
} else {
|
|
2224
|
-
|
|
1065
|
+
logger6.error("Background listener error", { error });
|
|
2225
1066
|
if (this.currentMeta) {
|
|
2226
1067
|
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
|
|
2227
1068
|
this.receptor.emitError(errorMessage, "runtime_error", this.currentMeta);
|
|
@@ -2253,7 +1094,7 @@ var ClaudeEffector = class {
|
|
|
2253
1094
|
* Dispose and cleanup resources
|
|
2254
1095
|
*/
|
|
2255
1096
|
dispose() {
|
|
2256
|
-
|
|
1097
|
+
logger6.debug("Disposing ClaudeEffector");
|
|
2257
1098
|
if (this.currentAbortController) {
|
|
2258
1099
|
this.currentAbortController.abort();
|
|
2259
1100
|
}
|
|
@@ -2284,7 +1125,7 @@ var ClaudeEnvironment = class {
|
|
|
2284
1125
|
};
|
|
2285
1126
|
|
|
2286
1127
|
// src/internal/RuntimeAgent.ts
|
|
2287
|
-
var
|
|
1128
|
+
var logger7 = (0, import_common7.createLogger)("runtime/RuntimeAgent");
|
|
2288
1129
|
var BusPresenter = class {
|
|
2289
1130
|
constructor(producer, session, agentId, imageId, containerId) {
|
|
2290
1131
|
this.producer = producer;
|
|
@@ -2321,67 +1162,18 @@ var BusPresenter = class {
|
|
|
2321
1162
|
this.producer.emit(systemEvent);
|
|
2322
1163
|
if (category === "message") {
|
|
2323
1164
|
this.session.addMessage(data).catch((err) => {
|
|
2324
|
-
|
|
1165
|
+
logger7.error("Failed to persist message", { error: err, messageType: output.type });
|
|
2325
1166
|
});
|
|
2326
1167
|
}
|
|
2327
1168
|
}
|
|
2328
1169
|
/**
|
|
2329
1170
|
* Convert AgentOutput to proper Message type for persistence
|
|
1171
|
+
*
|
|
1172
|
+
* Since messageAssemblerProcessor now emits complete Message objects,
|
|
1173
|
+
* we can directly use the data field without transformation.
|
|
2330
1174
|
*/
|
|
2331
1175
|
convertToMessage(output) {
|
|
2332
|
-
|
|
2333
|
-
const messageId = eventData.messageId ?? eventData.id;
|
|
2334
|
-
const timestamp = eventData.timestamp || output.timestamp;
|
|
2335
|
-
switch (output.type) {
|
|
2336
|
-
case "assistant_message": {
|
|
2337
|
-
const content = eventData.content;
|
|
2338
|
-
return {
|
|
2339
|
-
id: messageId,
|
|
2340
|
-
role: "assistant",
|
|
2341
|
-
subtype: "assistant",
|
|
2342
|
-
content,
|
|
2343
|
-
timestamp
|
|
2344
|
-
};
|
|
2345
|
-
}
|
|
2346
|
-
case "tool_call_message": {
|
|
2347
|
-
const toolCalls = eventData.toolCalls;
|
|
2348
|
-
const toolCall = toolCalls[0];
|
|
2349
|
-
return {
|
|
2350
|
-
id: messageId,
|
|
2351
|
-
role: "assistant",
|
|
2352
|
-
subtype: "tool-call",
|
|
2353
|
-
toolCall,
|
|
2354
|
-
timestamp
|
|
2355
|
-
};
|
|
2356
|
-
}
|
|
2357
|
-
case "tool_result_message": {
|
|
2358
|
-
const results = eventData.results;
|
|
2359
|
-
const toolResult = results[0];
|
|
2360
|
-
return {
|
|
2361
|
-
id: messageId,
|
|
2362
|
-
role: "tool",
|
|
2363
|
-
subtype: "tool-result",
|
|
2364
|
-
toolCallId: toolResult.id,
|
|
2365
|
-
toolResult,
|
|
2366
|
-
timestamp
|
|
2367
|
-
};
|
|
2368
|
-
}
|
|
2369
|
-
case "error_message": {
|
|
2370
|
-
const content = eventData.content;
|
|
2371
|
-
const errorCode = eventData.errorCode;
|
|
2372
|
-
return {
|
|
2373
|
-
id: messageId,
|
|
2374
|
-
role: "error",
|
|
2375
|
-
subtype: "error",
|
|
2376
|
-
content,
|
|
2377
|
-
errorCode,
|
|
2378
|
-
timestamp
|
|
2379
|
-
};
|
|
2380
|
-
}
|
|
2381
|
-
default:
|
|
2382
|
-
logger9.warn("Unknown message type, passing through", { type: output.type });
|
|
2383
|
-
return eventData;
|
|
2384
|
-
}
|
|
1176
|
+
return output.data;
|
|
2385
1177
|
}
|
|
2386
1178
|
/**
|
|
2387
1179
|
* Determine event category from output type
|
|
@@ -2440,7 +1232,7 @@ var RuntimeAgent = class {
|
|
|
2440
1232
|
});
|
|
2441
1233
|
this.environment.receptor.connect(config.bus.asProducer());
|
|
2442
1234
|
this.environment.effector.connect(config.bus.asConsumer());
|
|
2443
|
-
|
|
1235
|
+
logger7.info("ClaudeEnvironment created for agent", {
|
|
2444
1236
|
agentId: this.agentId,
|
|
2445
1237
|
imageId: this.imageId,
|
|
2446
1238
|
cwd: config.sandbox.workdir.path,
|
|
@@ -2455,7 +1247,7 @@ var RuntimeAgent = class {
|
|
|
2455
1247
|
this.imageId,
|
|
2456
1248
|
this.containerId
|
|
2457
1249
|
);
|
|
2458
|
-
this.engine = createAgent({
|
|
1250
|
+
this.engine = (0, import_agent.createAgent)({
|
|
2459
1251
|
driver: {
|
|
2460
1252
|
name: "DummyDriver",
|
|
2461
1253
|
description: "Placeholder driver for push-based event handling",
|
|
@@ -2475,14 +1267,14 @@ var RuntimeAgent = class {
|
|
|
2475
1267
|
this.driver = new BusDriver(config.bus.asConsumer(), {
|
|
2476
1268
|
agentId: this.agentId,
|
|
2477
1269
|
onStreamEvent: (event) => {
|
|
2478
|
-
|
|
1270
|
+
logger7.debug("BusDriver \u2192 Engine.handleStreamEvent", { type: event.type });
|
|
2479
1271
|
this.engine.handleStreamEvent(event);
|
|
2480
1272
|
},
|
|
2481
1273
|
onStreamComplete: (reason) => {
|
|
2482
|
-
|
|
1274
|
+
logger7.debug("Stream completed", { reason, agentId: this.agentId });
|
|
2483
1275
|
}
|
|
2484
1276
|
});
|
|
2485
|
-
|
|
1277
|
+
logger7.debug("RuntimeAgent created", {
|
|
2486
1278
|
agentId: this.agentId,
|
|
2487
1279
|
imageId: this.imageId
|
|
2488
1280
|
});
|
|
@@ -2491,13 +1283,13 @@ var RuntimeAgent = class {
|
|
|
2491
1283
|
* Save SDK session ID to image metadata for future resume
|
|
2492
1284
|
*/
|
|
2493
1285
|
saveSessionId(sdkSessionId) {
|
|
2494
|
-
|
|
1286
|
+
logger7.info("Saving SDK session ID to image metadata", {
|
|
2495
1287
|
agentId: this.agentId,
|
|
2496
1288
|
imageId: this.imageId,
|
|
2497
1289
|
sdkSessionId
|
|
2498
1290
|
});
|
|
2499
1291
|
this.imageRepository.updateMetadata(this.imageId, { claudeSdkSessionId: sdkSessionId }).catch((err) => {
|
|
2500
|
-
|
|
1292
|
+
logger7.error("Failed to save SDK session ID", { error: err, imageId: this.imageId });
|
|
2501
1293
|
});
|
|
2502
1294
|
}
|
|
2503
1295
|
get lifecycle() {
|
|
@@ -2510,7 +1302,7 @@ var RuntimeAgent = class {
|
|
|
2510
1302
|
* @param requestId - Request ID for correlation
|
|
2511
1303
|
*/
|
|
2512
1304
|
async receive(content, requestId) {
|
|
2513
|
-
|
|
1305
|
+
logger7.debug("RuntimeAgent.receive called", {
|
|
2514
1306
|
agentId: this.agentId,
|
|
2515
1307
|
contentPreview: content.substring(0, 50),
|
|
2516
1308
|
requestId
|
|
@@ -2519,13 +1311,13 @@ var RuntimeAgent = class {
|
|
|
2519
1311
|
throw new Error(`Cannot send message to ${this._lifecycle} agent`);
|
|
2520
1312
|
}
|
|
2521
1313
|
await this.interactor.receive(content, requestId || `req_${Date.now()}`);
|
|
2522
|
-
|
|
1314
|
+
logger7.debug("RuntimeAgent.receive completed", { agentId: this.agentId });
|
|
2523
1315
|
}
|
|
2524
1316
|
/**
|
|
2525
1317
|
* Interrupt current operation
|
|
2526
1318
|
*/
|
|
2527
1319
|
interrupt(requestId) {
|
|
2528
|
-
|
|
1320
|
+
logger7.debug("RuntimeAgent.interrupt called", { agentId: this.agentId, requestId });
|
|
2529
1321
|
this.interactor.interrupt(requestId);
|
|
2530
1322
|
this.producer.emit({
|
|
2531
1323
|
type: "interrupted",
|
|
@@ -2700,7 +1492,7 @@ var RuntimeSandbox = class {
|
|
|
2700
1492
|
"containers",
|
|
2701
1493
|
config.containerId,
|
|
2702
1494
|
"workdirs",
|
|
2703
|
-
config.
|
|
1495
|
+
config.imageId
|
|
2704
1496
|
);
|
|
2705
1497
|
this.workdir = new RuntimeWorkdir(config.agentId, workdirPath);
|
|
2706
1498
|
}
|
|
@@ -2720,7 +1512,8 @@ var RuntimeSandbox = class {
|
|
|
2720
1512
|
};
|
|
2721
1513
|
|
|
2722
1514
|
// src/internal/RuntimeImage.ts
|
|
2723
|
-
var
|
|
1515
|
+
var import_common8 = require("@agentxjs/common");
|
|
1516
|
+
var logger8 = (0, import_common8.createLogger)("runtime/RuntimeImage");
|
|
2724
1517
|
var RuntimeImage = class _RuntimeImage {
|
|
2725
1518
|
constructor(record, context) {
|
|
2726
1519
|
this.record = record;
|
|
@@ -2777,7 +1570,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
2777
1570
|
createdAt: now,
|
|
2778
1571
|
updatedAt: now
|
|
2779
1572
|
});
|
|
2780
|
-
|
|
1573
|
+
logger8.info("Image created", {
|
|
2781
1574
|
imageId,
|
|
2782
1575
|
sessionId,
|
|
2783
1576
|
containerId: config.containerId,
|
|
@@ -2791,10 +1584,10 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
2791
1584
|
static async load(imageId, context) {
|
|
2792
1585
|
const record = await context.imageRepository.findImageById(imageId);
|
|
2793
1586
|
if (!record) {
|
|
2794
|
-
|
|
1587
|
+
logger8.debug("Image not found", { imageId });
|
|
2795
1588
|
return null;
|
|
2796
1589
|
}
|
|
2797
|
-
|
|
1590
|
+
logger8.debug("Image loaded", { imageId, name: record.name });
|
|
2798
1591
|
return new _RuntimeImage(record, context);
|
|
2799
1592
|
}
|
|
2800
1593
|
/**
|
|
@@ -2828,7 +1621,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
2828
1621
|
updatedAt: now
|
|
2829
1622
|
};
|
|
2830
1623
|
await this.context.imageRepository.saveImage(updatedRecord);
|
|
2831
|
-
|
|
1624
|
+
logger8.info("Image updated", { imageId: this.imageId, updates });
|
|
2832
1625
|
return new _RuntimeImage(updatedRecord, this.context);
|
|
2833
1626
|
}
|
|
2834
1627
|
/**
|
|
@@ -2837,7 +1630,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
2837
1630
|
async delete() {
|
|
2838
1631
|
await this.context.sessionRepository.deleteSession(this.sessionId);
|
|
2839
1632
|
await this.context.imageRepository.deleteImage(this.imageId);
|
|
2840
|
-
|
|
1633
|
+
logger8.info("Image deleted", { imageId: this.imageId, sessionId: this.sessionId });
|
|
2841
1634
|
}
|
|
2842
1635
|
/**
|
|
2843
1636
|
* Get the underlying record
|
|
@@ -2859,7 +1652,8 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
2859
1652
|
};
|
|
2860
1653
|
|
|
2861
1654
|
// src/internal/RuntimeContainer.ts
|
|
2862
|
-
var
|
|
1655
|
+
var import_common9 = require("@agentxjs/common");
|
|
1656
|
+
var logger9 = (0, import_common9.createLogger)("runtime/RuntimeContainer");
|
|
2863
1657
|
var RuntimeContainer = class _RuntimeContainer {
|
|
2864
1658
|
containerId;
|
|
2865
1659
|
createdAt;
|
|
@@ -2899,7 +1693,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
2899
1693
|
containerId
|
|
2900
1694
|
}
|
|
2901
1695
|
});
|
|
2902
|
-
|
|
1696
|
+
logger9.info("Container created", { containerId });
|
|
2903
1697
|
return container;
|
|
2904
1698
|
}
|
|
2905
1699
|
/**
|
|
@@ -2908,7 +1702,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
2908
1702
|
static async load(containerId, context) {
|
|
2909
1703
|
const record = await context.persistence.containers.findContainerById(containerId);
|
|
2910
1704
|
if (!record) return null;
|
|
2911
|
-
|
|
1705
|
+
logger9.info("Container loaded", { containerId });
|
|
2912
1706
|
return new _RuntimeContainer(containerId, record.createdAt, context);
|
|
2913
1707
|
}
|
|
2914
1708
|
// ==================== Image → Agent Lifecycle ====================
|
|
@@ -2921,7 +1715,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
2921
1715
|
if (existingAgentId) {
|
|
2922
1716
|
const existingAgent = this.agents.get(existingAgentId);
|
|
2923
1717
|
if (existingAgent) {
|
|
2924
|
-
|
|
1718
|
+
logger9.info("Reusing existing agent for image", {
|
|
2925
1719
|
containerId: this.containerId,
|
|
2926
1720
|
imageId: image.imageId,
|
|
2927
1721
|
agentId: existingAgentId
|
|
@@ -2933,6 +1727,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
2933
1727
|
const agentId = this.generateAgentId();
|
|
2934
1728
|
const sandbox = new RuntimeSandbox({
|
|
2935
1729
|
agentId,
|
|
1730
|
+
imageId: image.imageId,
|
|
2936
1731
|
containerId: this.containerId,
|
|
2937
1732
|
basePath: this.context.basePath
|
|
2938
1733
|
});
|
|
@@ -2980,7 +1775,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
2980
1775
|
agentId
|
|
2981
1776
|
}
|
|
2982
1777
|
});
|
|
2983
|
-
|
|
1778
|
+
logger9.info("Agent created for image", {
|
|
2984
1779
|
containerId: this.containerId,
|
|
2985
1780
|
imageId: image.imageId,
|
|
2986
1781
|
agentId
|
|
@@ -2993,17 +1788,17 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
2993
1788
|
async stopImage(imageId) {
|
|
2994
1789
|
const agentId = this.imageToAgent.get(imageId);
|
|
2995
1790
|
if (!agentId) {
|
|
2996
|
-
|
|
1791
|
+
logger9.debug("Image not running, nothing to stop", {
|
|
2997
1792
|
imageId,
|
|
2998
1793
|
containerId: this.containerId
|
|
2999
1794
|
});
|
|
3000
1795
|
return false;
|
|
3001
1796
|
}
|
|
3002
|
-
|
|
1797
|
+
logger9.info("Stopping image", { imageId, agentId, containerId: this.containerId });
|
|
3003
1798
|
const success = await this.destroyAgent(agentId);
|
|
3004
1799
|
if (success) {
|
|
3005
1800
|
this.imageToAgent.delete(imageId);
|
|
3006
|
-
|
|
1801
|
+
logger9.info("Image stopped", { imageId, agentId, containerId: this.containerId });
|
|
3007
1802
|
}
|
|
3008
1803
|
return success;
|
|
3009
1804
|
}
|
|
@@ -3060,7 +1855,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
3060
1855
|
agentId
|
|
3061
1856
|
}
|
|
3062
1857
|
});
|
|
3063
|
-
|
|
1858
|
+
logger9.info("Agent destroyed", { containerId: this.containerId, agentId });
|
|
3064
1859
|
return true;
|
|
3065
1860
|
}
|
|
3066
1861
|
async destroyAllAgents() {
|
|
@@ -3088,7 +1883,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
3088
1883
|
}
|
|
3089
1884
|
});
|
|
3090
1885
|
this.context.onDisposed?.(this.containerId);
|
|
3091
|
-
|
|
1886
|
+
logger9.info("Container disposed", { containerId: this.containerId, agentCount });
|
|
3092
1887
|
}
|
|
3093
1888
|
// ==================== Private Helpers ====================
|
|
3094
1889
|
generateAgentId() {
|
|
@@ -3099,7 +1894,8 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
3099
1894
|
};
|
|
3100
1895
|
|
|
3101
1896
|
// src/internal/BaseEventHandler.ts
|
|
3102
|
-
var
|
|
1897
|
+
var import_common10 = require("@agentxjs/common");
|
|
1898
|
+
var logger10 = (0, import_common10.createLogger)("runtime/BaseEventHandler");
|
|
3103
1899
|
var BaseEventHandler = class {
|
|
3104
1900
|
bus;
|
|
3105
1901
|
unsubscribes = [];
|
|
@@ -3138,7 +1934,7 @@ var BaseEventHandler = class {
|
|
|
3138
1934
|
handleError(err, context) {
|
|
3139
1935
|
const message = err instanceof Error ? err.message : String(err);
|
|
3140
1936
|
const stack = err instanceof Error ? err.stack : void 0;
|
|
3141
|
-
|
|
1937
|
+
logger10.error(`Error in ${context.operation || "handler"}`, {
|
|
3142
1938
|
message,
|
|
3143
1939
|
requestId: context.requestId,
|
|
3144
1940
|
details: context.details
|
|
@@ -3165,7 +1961,7 @@ var BaseEventHandler = class {
|
|
|
3165
1961
|
try {
|
|
3166
1962
|
context.onError(err);
|
|
3167
1963
|
} catch (callbackErr) {
|
|
3168
|
-
|
|
1964
|
+
logger10.error("Error in onError callback", { error: callbackErr });
|
|
3169
1965
|
}
|
|
3170
1966
|
}
|
|
3171
1967
|
}
|
|
@@ -3183,12 +1979,13 @@ var BaseEventHandler = class {
|
|
|
3183
1979
|
unsubscribe();
|
|
3184
1980
|
}
|
|
3185
1981
|
this.unsubscribes = [];
|
|
3186
|
-
|
|
1982
|
+
logger10.debug(`${this.constructor.name} disposed`);
|
|
3187
1983
|
}
|
|
3188
1984
|
};
|
|
3189
1985
|
|
|
3190
1986
|
// src/internal/CommandHandler.ts
|
|
3191
|
-
var
|
|
1987
|
+
var import_common11 = require("@agentxjs/common");
|
|
1988
|
+
var logger11 = (0, import_common11.createLogger)("runtime/CommandHandler");
|
|
3192
1989
|
function createResponse(type, data) {
|
|
3193
1990
|
return {
|
|
3194
1991
|
type,
|
|
@@ -3221,7 +2018,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3221
2018
|
super(bus);
|
|
3222
2019
|
this.ops = operations;
|
|
3223
2020
|
this.bindHandlers();
|
|
3224
|
-
|
|
2021
|
+
logger11.debug("CommandHandler created");
|
|
3225
2022
|
}
|
|
3226
2023
|
/**
|
|
3227
2024
|
* Log error and emit system_error event
|
|
@@ -3229,7 +2026,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3229
2026
|
emitError(operation, err, requestId, context) {
|
|
3230
2027
|
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
3231
2028
|
const stack = err instanceof Error ? err.stack : void 0;
|
|
3232
|
-
|
|
2029
|
+
logger11.error(operation, {
|
|
3233
2030
|
requestId,
|
|
3234
2031
|
...context,
|
|
3235
2032
|
error: errorMessage,
|
|
@@ -3286,12 +2083,12 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3286
2083
|
this.subscribe(
|
|
3287
2084
|
this.bus.onCommand("image_messages_request", (event) => this.handleImageMessages(event))
|
|
3288
2085
|
);
|
|
3289
|
-
|
|
2086
|
+
logger11.debug("Command handlers bound");
|
|
3290
2087
|
}
|
|
3291
2088
|
// ==================== Container Handlers ====================
|
|
3292
2089
|
async handleContainerCreate(event) {
|
|
3293
2090
|
const { requestId, containerId } = event.data;
|
|
3294
|
-
|
|
2091
|
+
logger11.debug("Handling container_create_request", { requestId, containerId });
|
|
3295
2092
|
try {
|
|
3296
2093
|
await this.ops.createContainer(containerId);
|
|
3297
2094
|
this.bus.emit(
|
|
@@ -3313,7 +2110,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3313
2110
|
}
|
|
3314
2111
|
handleContainerGet(event) {
|
|
3315
2112
|
const { requestId, containerId } = event.data;
|
|
3316
|
-
|
|
2113
|
+
logger11.debug("Handling container_get_request", { requestId, containerId });
|
|
3317
2114
|
const container = this.ops.getContainer(containerId);
|
|
3318
2115
|
this.bus.emit(
|
|
3319
2116
|
createResponse("container_get_response", {
|
|
@@ -3325,7 +2122,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3325
2122
|
}
|
|
3326
2123
|
handleContainerList(event) {
|
|
3327
2124
|
const { requestId } = event.data;
|
|
3328
|
-
|
|
2125
|
+
logger11.debug("Handling container_list_request", { requestId });
|
|
3329
2126
|
const containers = this.ops.listContainers();
|
|
3330
2127
|
this.bus.emit(
|
|
3331
2128
|
createResponse("container_list_response", {
|
|
@@ -3337,7 +2134,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3337
2134
|
// ==================== Agent Handlers ====================
|
|
3338
2135
|
handleAgentGet(event) {
|
|
3339
2136
|
const { requestId, agentId } = event.data;
|
|
3340
|
-
|
|
2137
|
+
logger11.debug("Handling agent_get_request", { requestId, agentId });
|
|
3341
2138
|
const agent = this.ops.getAgent(agentId);
|
|
3342
2139
|
this.bus.emit(
|
|
3343
2140
|
createResponse("agent_get_response", {
|
|
@@ -3350,7 +2147,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3350
2147
|
}
|
|
3351
2148
|
handleAgentList(event) {
|
|
3352
2149
|
const { requestId, containerId } = event.data;
|
|
3353
|
-
|
|
2150
|
+
logger11.debug("Handling agent_list_request", { requestId, containerId });
|
|
3354
2151
|
const agents = this.ops.listAgents(containerId);
|
|
3355
2152
|
this.bus.emit(
|
|
3356
2153
|
createResponse("agent_list_response", {
|
|
@@ -3365,7 +2162,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3365
2162
|
}
|
|
3366
2163
|
async handleAgentDestroy(event) {
|
|
3367
2164
|
const { requestId, agentId } = event.data;
|
|
3368
|
-
|
|
2165
|
+
logger11.debug("Handling agent_destroy_request", { requestId, agentId });
|
|
3369
2166
|
try {
|
|
3370
2167
|
const success = await this.ops.destroyAgent(agentId);
|
|
3371
2168
|
this.bus.emit(
|
|
@@ -3389,7 +2186,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3389
2186
|
}
|
|
3390
2187
|
async handleAgentDestroyAll(event) {
|
|
3391
2188
|
const { requestId, containerId } = event.data;
|
|
3392
|
-
|
|
2189
|
+
logger11.debug("Handling agent_destroy_all_request", { requestId, containerId });
|
|
3393
2190
|
try {
|
|
3394
2191
|
await this.ops.destroyAllAgents(containerId);
|
|
3395
2192
|
this.bus.emit(
|
|
@@ -3411,7 +2208,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3411
2208
|
}
|
|
3412
2209
|
async handleMessageSend(event) {
|
|
3413
2210
|
const { requestId, imageId, agentId, content } = event.data;
|
|
3414
|
-
|
|
2211
|
+
logger11.debug("Handling message_send_request", { requestId, imageId, agentId });
|
|
3415
2212
|
try {
|
|
3416
2213
|
const result = await this.ops.receiveMessage(imageId, agentId, content, requestId);
|
|
3417
2214
|
this.bus.emit(
|
|
@@ -3435,7 +2232,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3435
2232
|
}
|
|
3436
2233
|
handleAgentInterrupt(event) {
|
|
3437
2234
|
const { requestId, imageId, agentId } = event.data;
|
|
3438
|
-
|
|
2235
|
+
logger11.debug("Handling agent_interrupt_request", { requestId, imageId, agentId });
|
|
3439
2236
|
try {
|
|
3440
2237
|
const result = this.ops.interruptAgent(imageId, agentId, requestId);
|
|
3441
2238
|
this.bus.emit(
|
|
@@ -3460,7 +2257,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3460
2257
|
// ==================== Image Handlers ====================
|
|
3461
2258
|
async handleImageCreate(event) {
|
|
3462
2259
|
const { requestId, containerId, config } = event.data;
|
|
3463
|
-
|
|
2260
|
+
logger11.debug("Handling image_create_request", { requestId, containerId });
|
|
3464
2261
|
try {
|
|
3465
2262
|
const record = await this.ops.createImage(containerId, config);
|
|
3466
2263
|
this.bus.emit(
|
|
@@ -3482,7 +2279,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3482
2279
|
}
|
|
3483
2280
|
async handleImageRun(event) {
|
|
3484
2281
|
const { requestId, imageId } = event.data;
|
|
3485
|
-
|
|
2282
|
+
logger11.debug("Handling image_run_request", { requestId, imageId });
|
|
3486
2283
|
try {
|
|
3487
2284
|
const result = await this.ops.runImage(imageId);
|
|
3488
2285
|
this.bus.emit(
|
|
@@ -3508,7 +2305,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3508
2305
|
}
|
|
3509
2306
|
async handleImageStop(event) {
|
|
3510
2307
|
const { requestId, imageId } = event.data;
|
|
3511
|
-
|
|
2308
|
+
logger11.debug("Handling image_stop_request", { requestId, imageId });
|
|
3512
2309
|
try {
|
|
3513
2310
|
await this.ops.stopImage(imageId);
|
|
3514
2311
|
this.bus.emit(
|
|
@@ -3530,7 +2327,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3530
2327
|
}
|
|
3531
2328
|
async handleImageUpdate(event) {
|
|
3532
2329
|
const { requestId, imageId, updates } = event.data;
|
|
3533
|
-
|
|
2330
|
+
logger11.debug("Handling image_update_request", { requestId, imageId });
|
|
3534
2331
|
try {
|
|
3535
2332
|
const record = await this.ops.updateImage(imageId, updates);
|
|
3536
2333
|
this.bus.emit(
|
|
@@ -3552,7 +2349,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3552
2349
|
}
|
|
3553
2350
|
async handleImageList(event) {
|
|
3554
2351
|
const { requestId, containerId } = event.data;
|
|
3555
|
-
|
|
2352
|
+
logger11.debug("Handling image_list_request", { requestId, containerId });
|
|
3556
2353
|
try {
|
|
3557
2354
|
const images = await this.ops.listImages(containerId);
|
|
3558
2355
|
this.bus.emit(
|
|
@@ -3574,7 +2371,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3574
2371
|
}
|
|
3575
2372
|
async handleImageGet(event) {
|
|
3576
2373
|
const { requestId, imageId } = event.data;
|
|
3577
|
-
|
|
2374
|
+
logger11.debug("Handling image_get_request", { requestId, imageId });
|
|
3578
2375
|
try {
|
|
3579
2376
|
const image = await this.ops.getImage(imageId);
|
|
3580
2377
|
this.bus.emit(
|
|
@@ -3595,7 +2392,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3595
2392
|
}
|
|
3596
2393
|
async handleImageDelete(event) {
|
|
3597
2394
|
const { requestId, imageId } = event.data;
|
|
3598
|
-
|
|
2395
|
+
logger11.debug("Handling image_delete_request", { requestId, imageId });
|
|
3599
2396
|
try {
|
|
3600
2397
|
await this.ops.deleteImage(imageId);
|
|
3601
2398
|
this.bus.emit(
|
|
@@ -3617,10 +2414,10 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3617
2414
|
}
|
|
3618
2415
|
async handleImageMessages(event) {
|
|
3619
2416
|
const { requestId, imageId } = event.data;
|
|
3620
|
-
|
|
2417
|
+
logger11.info("Handling image_messages_request", { requestId, imageId });
|
|
3621
2418
|
try {
|
|
3622
2419
|
const messages = await this.ops.getImageMessages(imageId);
|
|
3623
|
-
|
|
2420
|
+
logger11.info("Got messages for image", { imageId, count: messages.length });
|
|
3624
2421
|
this.bus.emit(
|
|
3625
2422
|
createResponse("image_messages_response", {
|
|
3626
2423
|
requestId,
|
|
@@ -3628,7 +2425,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3628
2425
|
messages
|
|
3629
2426
|
})
|
|
3630
2427
|
);
|
|
3631
|
-
|
|
2428
|
+
logger11.info("Emitted image_messages_response", { requestId, imageId });
|
|
3632
2429
|
} catch (err) {
|
|
3633
2430
|
this.emitError("Failed to get image messages", err, requestId, { imageId });
|
|
3634
2431
|
this.bus.emit(
|
|
@@ -3645,9 +2442,8 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3645
2442
|
};
|
|
3646
2443
|
|
|
3647
2444
|
// src/RuntimeImpl.ts
|
|
3648
|
-
var
|
|
3649
|
-
var
|
|
3650
|
-
var logger14 = createLogger("runtime/RuntimeImpl");
|
|
2445
|
+
var import_common12 = require("@agentxjs/common");
|
|
2446
|
+
var logger12 = (0, import_common12.createLogger)("runtime/RuntimeImpl");
|
|
3651
2447
|
var RuntimeImpl = class {
|
|
3652
2448
|
persistence;
|
|
3653
2449
|
llmProvider;
|
|
@@ -3658,20 +2454,20 @@ var RuntimeImpl = class {
|
|
|
3658
2454
|
/** Container registry: containerId -> RuntimeContainer */
|
|
3659
2455
|
containerRegistry = /* @__PURE__ */ new Map();
|
|
3660
2456
|
constructor(config) {
|
|
3661
|
-
|
|
2457
|
+
logger12.info("RuntimeImpl constructor start");
|
|
3662
2458
|
this.persistence = config.persistence;
|
|
3663
2459
|
this.llmProvider = config.llmProvider;
|
|
3664
|
-
this.basePath =
|
|
3665
|
-
|
|
2460
|
+
this.basePath = config.basePath;
|
|
2461
|
+
logger12.info("Creating SystemBus");
|
|
3666
2462
|
this.bus = new SystemBusImpl();
|
|
3667
2463
|
this.llmConfig = this.llmProvider.provide();
|
|
3668
|
-
|
|
2464
|
+
logger12.info("LLM config loaded", {
|
|
3669
2465
|
hasApiKey: !!this.llmConfig.apiKey,
|
|
3670
2466
|
model: this.llmConfig.model
|
|
3671
2467
|
});
|
|
3672
|
-
|
|
2468
|
+
logger12.info("Creating CommandHandler");
|
|
3673
2469
|
this.commandHandler = new CommandHandler(this.bus, this.createRuntimeOperations());
|
|
3674
|
-
|
|
2470
|
+
logger12.info("RuntimeImpl constructor done");
|
|
3675
2471
|
}
|
|
3676
2472
|
// ==================== SystemBus delegation ====================
|
|
3677
2473
|
emit(event) {
|
|
@@ -3754,7 +2550,7 @@ var RuntimeImpl = class {
|
|
|
3754
2550
|
// Agent operations (by imageId - with auto-activation)
|
|
3755
2551
|
receiveMessage: async (imageId, agentId, content, requestId) => {
|
|
3756
2552
|
if (imageId) {
|
|
3757
|
-
|
|
2553
|
+
logger12.debug("Receiving message by imageId", {
|
|
3758
2554
|
imageId,
|
|
3759
2555
|
contentLength: content.length,
|
|
3760
2556
|
requestId
|
|
@@ -3763,7 +2559,7 @@ var RuntimeImpl = class {
|
|
|
3763
2559
|
if (!record) throw new Error(`Image not found: ${imageId}`);
|
|
3764
2560
|
const container = await this.getOrCreateContainer(record.containerId);
|
|
3765
2561
|
const { agent, reused } = await container.runImage(record);
|
|
3766
|
-
|
|
2562
|
+
logger12.info("Message routed to agent", {
|
|
3767
2563
|
imageId,
|
|
3768
2564
|
agentId: agent.agentId,
|
|
3769
2565
|
reused,
|
|
@@ -3773,7 +2569,7 @@ var RuntimeImpl = class {
|
|
|
3773
2569
|
return { agentId: agent.agentId, imageId };
|
|
3774
2570
|
}
|
|
3775
2571
|
if (agentId) {
|
|
3776
|
-
|
|
2572
|
+
logger12.debug("Receiving message by agentId (legacy)", {
|
|
3777
2573
|
agentId,
|
|
3778
2574
|
contentLength: content.length,
|
|
3779
2575
|
requestId
|
|
@@ -3790,12 +2586,12 @@ var RuntimeImpl = class {
|
|
|
3790
2586
|
if (imageId) {
|
|
3791
2587
|
const foundAgentId = this.findAgentIdForImage(imageId);
|
|
3792
2588
|
if (!foundAgentId) {
|
|
3793
|
-
|
|
2589
|
+
logger12.debug("Image is offline, nothing to interrupt", { imageId });
|
|
3794
2590
|
return { imageId, agentId: void 0 };
|
|
3795
2591
|
}
|
|
3796
2592
|
const agent = this.findAgent(foundAgentId);
|
|
3797
2593
|
if (agent) {
|
|
3798
|
-
|
|
2594
|
+
logger12.info("Interrupting agent by imageId", {
|
|
3799
2595
|
imageId,
|
|
3800
2596
|
agentId: foundAgentId,
|
|
3801
2597
|
requestId
|
|
@@ -3807,7 +2603,7 @@ var RuntimeImpl = class {
|
|
|
3807
2603
|
if (agentId) {
|
|
3808
2604
|
const agent = this.findAgent(agentId);
|
|
3809
2605
|
if (!agent) throw new Error(`Agent not found: ${agentId}`);
|
|
3810
|
-
|
|
2606
|
+
logger12.info("Interrupting agent by agentId (legacy)", { agentId, requestId });
|
|
3811
2607
|
agent.interrupt(requestId);
|
|
3812
2608
|
const foundImageId = this.findImageIdForAgent(agentId);
|
|
3813
2609
|
return { agentId, imageId: foundImageId };
|
|
@@ -3816,32 +2612,32 @@ var RuntimeImpl = class {
|
|
|
3816
2612
|
},
|
|
3817
2613
|
// Image operations (new model)
|
|
3818
2614
|
createImage: async (containerId, config) => {
|
|
3819
|
-
|
|
2615
|
+
logger12.debug("Creating image", { containerId, name: config.name });
|
|
3820
2616
|
await this.getOrCreateContainer(containerId);
|
|
3821
2617
|
const image = await RuntimeImage.create(
|
|
3822
2618
|
{ containerId, ...config },
|
|
3823
2619
|
this.createImageContext()
|
|
3824
2620
|
);
|
|
3825
|
-
|
|
2621
|
+
logger12.info("Image created via RuntimeOps", { imageId: image.imageId, containerId });
|
|
3826
2622
|
return this.toImageListItemResult(image.toRecord(), false);
|
|
3827
2623
|
},
|
|
3828
2624
|
runImage: async (imageId) => {
|
|
3829
|
-
|
|
2625
|
+
logger12.debug("Running image", { imageId });
|
|
3830
2626
|
const record = await this.persistence.images.findImageById(imageId);
|
|
3831
2627
|
if (!record) throw new Error(`Image not found: ${imageId}`);
|
|
3832
2628
|
const container = await this.getOrCreateContainer(record.containerId);
|
|
3833
2629
|
const { agent, reused } = await container.runImage(record);
|
|
3834
|
-
|
|
2630
|
+
logger12.info("Image running", { imageId, agentId: agent.agentId, reused });
|
|
3835
2631
|
return { imageId, agentId: agent.agentId, reused };
|
|
3836
2632
|
},
|
|
3837
2633
|
stopImage: async (imageId) => {
|
|
3838
|
-
|
|
2634
|
+
logger12.debug("Stopping image", { imageId });
|
|
3839
2635
|
const record = await this.persistence.images.findImageById(imageId);
|
|
3840
2636
|
if (!record) throw new Error(`Image not found: ${imageId}`);
|
|
3841
2637
|
const container = this.containerRegistry.get(record.containerId);
|
|
3842
2638
|
if (container) {
|
|
3843
2639
|
await container.stopImage(imageId);
|
|
3844
|
-
|
|
2640
|
+
logger12.info("Image stopped via RuntimeOps", { imageId });
|
|
3845
2641
|
}
|
|
3846
2642
|
},
|
|
3847
2643
|
updateImage: async (imageId, updates) => {
|
|
@@ -3865,10 +2661,10 @@ var RuntimeImpl = class {
|
|
|
3865
2661
|
return this.toImageListItemResult(record, online);
|
|
3866
2662
|
},
|
|
3867
2663
|
deleteImage: async (imageId) => {
|
|
3868
|
-
|
|
2664
|
+
logger12.debug("Deleting image", { imageId });
|
|
3869
2665
|
const agentId = this.findAgentIdForImage(imageId);
|
|
3870
2666
|
if (agentId) {
|
|
3871
|
-
|
|
2667
|
+
logger12.debug("Stopping running agent before delete", { imageId, agentId });
|
|
3872
2668
|
for (const container of this.containerRegistry.values()) {
|
|
3873
2669
|
if (container.getAgent(agentId)) {
|
|
3874
2670
|
await container.destroyAgent(agentId);
|
|
@@ -3879,42 +2675,18 @@ var RuntimeImpl = class {
|
|
|
3879
2675
|
const image = await RuntimeImage.load(imageId, this.createImageContext());
|
|
3880
2676
|
if (image) {
|
|
3881
2677
|
await image.delete();
|
|
3882
|
-
|
|
2678
|
+
logger12.info("Image deleted via RuntimeOps", { imageId });
|
|
3883
2679
|
}
|
|
3884
2680
|
},
|
|
3885
2681
|
getImageMessages: async (imageId) => {
|
|
3886
|
-
|
|
2682
|
+
logger12.debug("Getting messages for image", { imageId });
|
|
3887
2683
|
const image = await RuntimeImage.load(imageId, this.createImageContext());
|
|
3888
2684
|
if (!image) {
|
|
3889
2685
|
throw new Error(`Image not found: ${imageId}`);
|
|
3890
2686
|
}
|
|
3891
2687
|
const messages = await image.getMessages();
|
|
3892
|
-
|
|
3893
|
-
return messages
|
|
3894
|
-
let content;
|
|
3895
|
-
let role = m.role;
|
|
3896
|
-
let errorCode;
|
|
3897
|
-
if (m.subtype === "user" || m.subtype === "assistant") {
|
|
3898
|
-
content = m.content;
|
|
3899
|
-
} else if (m.subtype === "tool-call") {
|
|
3900
|
-
content = m.toolCall;
|
|
3901
|
-
role = "tool_call";
|
|
3902
|
-
} else if (m.subtype === "tool-result") {
|
|
3903
|
-
content = m.toolResult;
|
|
3904
|
-
role = "tool_result";
|
|
3905
|
-
} else if (m.subtype === "error") {
|
|
3906
|
-
content = m.content;
|
|
3907
|
-
role = "error";
|
|
3908
|
-
errorCode = m.errorCode;
|
|
3909
|
-
}
|
|
3910
|
-
return {
|
|
3911
|
-
id: m.id,
|
|
3912
|
-
role,
|
|
3913
|
-
content,
|
|
3914
|
-
timestamp: m.timestamp,
|
|
3915
|
-
errorCode
|
|
3916
|
-
};
|
|
3917
|
-
});
|
|
2688
|
+
logger12.debug("Got messages from storage", { imageId, count: messages.length });
|
|
2689
|
+
return messages;
|
|
3918
2690
|
}
|
|
3919
2691
|
};
|
|
3920
2692
|
}
|
|
@@ -4006,14 +2778,14 @@ var RuntimeImpl = class {
|
|
|
4006
2778
|
}
|
|
4007
2779
|
// ==================== Lifecycle ====================
|
|
4008
2780
|
async dispose() {
|
|
4009
|
-
|
|
2781
|
+
logger12.info("Disposing RuntimeImpl");
|
|
4010
2782
|
this.commandHandler.dispose();
|
|
4011
2783
|
for (const container of this.containerRegistry.values()) {
|
|
4012
2784
|
await container.dispose();
|
|
4013
2785
|
}
|
|
4014
2786
|
this.bus.destroy();
|
|
4015
2787
|
this.containerRegistry.clear();
|
|
4016
|
-
|
|
2788
|
+
logger12.info("RuntimeImpl disposed");
|
|
4017
2789
|
}
|
|
4018
2790
|
};
|
|
4019
2791
|
|
|
@@ -4024,9 +2796,11 @@ function createRuntime(config) {
|
|
|
4024
2796
|
|
|
4025
2797
|
// src/internal/persistence/PersistenceImpl.ts
|
|
4026
2798
|
var import_unstorage = require("unstorage");
|
|
2799
|
+
var import_common16 = require("@agentxjs/common");
|
|
4027
2800
|
|
|
4028
2801
|
// src/internal/persistence/repository/StorageImageRepository.ts
|
|
4029
|
-
var
|
|
2802
|
+
var import_common13 = require("@agentxjs/common");
|
|
2803
|
+
var logger13 = (0, import_common13.createLogger)("persistence/ImageRepository");
|
|
4030
2804
|
var PREFIX = "images";
|
|
4031
2805
|
var INDEX_BY_NAME = "idx:images:name";
|
|
4032
2806
|
var INDEX_BY_CONTAINER = "idx:images:container";
|
|
@@ -4050,7 +2824,7 @@ var StorageImageRepository = class {
|
|
|
4050
2824
|
this.containerIndexKey(record.containerId, record.imageId),
|
|
4051
2825
|
record.imageId
|
|
4052
2826
|
);
|
|
4053
|
-
|
|
2827
|
+
logger13.debug("Image saved", { imageId: record.imageId });
|
|
4054
2828
|
}
|
|
4055
2829
|
async findImageById(imageId) {
|
|
4056
2830
|
const record = await this.storage.getItem(this.key(imageId));
|
|
@@ -4105,7 +2879,7 @@ var StorageImageRepository = class {
|
|
|
4105
2879
|
await this.storage.removeItem(this.nameIndexKey(record.name, imageId));
|
|
4106
2880
|
await this.storage.removeItem(this.containerIndexKey(record.containerId, imageId));
|
|
4107
2881
|
}
|
|
4108
|
-
|
|
2882
|
+
logger13.debug("Image deleted", { imageId });
|
|
4109
2883
|
}
|
|
4110
2884
|
async imageExists(imageId) {
|
|
4111
2885
|
return await this.storage.hasItem(this.key(imageId));
|
|
@@ -4124,12 +2898,13 @@ var StorageImageRepository = class {
|
|
|
4124
2898
|
updatedAt: Date.now()
|
|
4125
2899
|
};
|
|
4126
2900
|
await this.storage.setItem(this.key(imageId), updatedRecord);
|
|
4127
|
-
|
|
2901
|
+
logger13.debug("Image metadata updated", { imageId, metadata });
|
|
4128
2902
|
}
|
|
4129
2903
|
};
|
|
4130
2904
|
|
|
4131
2905
|
// src/internal/persistence/repository/StorageContainerRepository.ts
|
|
4132
|
-
var
|
|
2906
|
+
var import_common14 = require("@agentxjs/common");
|
|
2907
|
+
var logger14 = (0, import_common14.createLogger)("persistence/ContainerRepository");
|
|
4133
2908
|
var PREFIX2 = "containers";
|
|
4134
2909
|
var StorageContainerRepository = class {
|
|
4135
2910
|
constructor(storage) {
|
|
@@ -4140,7 +2915,7 @@ var StorageContainerRepository = class {
|
|
|
4140
2915
|
}
|
|
4141
2916
|
async saveContainer(record) {
|
|
4142
2917
|
await this.storage.setItem(this.key(record.containerId), record);
|
|
4143
|
-
|
|
2918
|
+
logger14.debug("Container saved", { containerId: record.containerId });
|
|
4144
2919
|
}
|
|
4145
2920
|
async findContainerById(containerId) {
|
|
4146
2921
|
const record = await this.storage.getItem(this.key(containerId));
|
|
@@ -4159,7 +2934,7 @@ var StorageContainerRepository = class {
|
|
|
4159
2934
|
}
|
|
4160
2935
|
async deleteContainer(containerId) {
|
|
4161
2936
|
await this.storage.removeItem(this.key(containerId));
|
|
4162
|
-
|
|
2937
|
+
logger14.debug("Container deleted", { containerId });
|
|
4163
2938
|
}
|
|
4164
2939
|
async containerExists(containerId) {
|
|
4165
2940
|
return await this.storage.hasItem(this.key(containerId));
|
|
@@ -4167,7 +2942,8 @@ var StorageContainerRepository = class {
|
|
|
4167
2942
|
};
|
|
4168
2943
|
|
|
4169
2944
|
// src/internal/persistence/repository/StorageSessionRepository.ts
|
|
4170
|
-
var
|
|
2945
|
+
var import_common15 = require("@agentxjs/common");
|
|
2946
|
+
var logger15 = (0, import_common15.createLogger)("persistence/SessionRepository");
|
|
4171
2947
|
var PREFIX3 = "sessions";
|
|
4172
2948
|
var MESSAGES_PREFIX = "messages";
|
|
4173
2949
|
var INDEX_BY_IMAGE = "idx:sessions:image";
|
|
@@ -4198,7 +2974,7 @@ var StorageSessionRepository = class {
|
|
|
4198
2974
|
this.containerIndexKey(record.containerId, record.sessionId),
|
|
4199
2975
|
record.sessionId
|
|
4200
2976
|
);
|
|
4201
|
-
|
|
2977
|
+
logger15.debug("Session saved", { sessionId: record.sessionId });
|
|
4202
2978
|
}
|
|
4203
2979
|
async findSessionById(sessionId) {
|
|
4204
2980
|
const record = await this.storage.getItem(this.key(sessionId));
|
|
@@ -4247,7 +3023,7 @@ var StorageSessionRepository = class {
|
|
|
4247
3023
|
await this.storage.removeItem(this.imageIndexKey(record.imageId, sessionId));
|
|
4248
3024
|
await this.storage.removeItem(this.containerIndexKey(record.containerId, sessionId));
|
|
4249
3025
|
}
|
|
4250
|
-
|
|
3026
|
+
logger15.debug("Session deleted", { sessionId });
|
|
4251
3027
|
}
|
|
4252
3028
|
async sessionExists(sessionId) {
|
|
4253
3029
|
return await this.storage.hasItem(this.key(sessionId));
|
|
@@ -4257,13 +3033,13 @@ var StorageSessionRepository = class {
|
|
|
4257
3033
|
const messages = await this.getMessages(sessionId);
|
|
4258
3034
|
messages.push(message);
|
|
4259
3035
|
await this.storage.setItem(this.messagesKey(sessionId), messages);
|
|
4260
|
-
|
|
3036
|
+
logger15.debug("Message added to session", { sessionId, subtype: message.subtype });
|
|
4261
3037
|
}
|
|
4262
3038
|
async getMessages(sessionId) {
|
|
4263
3039
|
const messages = await this.storage.getItem(this.messagesKey(sessionId));
|
|
4264
3040
|
if (!messages || !Array.isArray(messages)) {
|
|
4265
3041
|
if (messages) {
|
|
4266
|
-
|
|
3042
|
+
logger15.warn("Messages data is not an array, resetting", {
|
|
4267
3043
|
sessionId,
|
|
4268
3044
|
type: typeof messages
|
|
4269
3045
|
});
|
|
@@ -4274,12 +3050,12 @@ var StorageSessionRepository = class {
|
|
|
4274
3050
|
}
|
|
4275
3051
|
async clearMessages(sessionId) {
|
|
4276
3052
|
await this.storage.removeItem(this.messagesKey(sessionId));
|
|
4277
|
-
|
|
3053
|
+
logger15.debug("Messages cleared for session", { sessionId });
|
|
4278
3054
|
}
|
|
4279
3055
|
};
|
|
4280
3056
|
|
|
4281
3057
|
// src/internal/persistence/PersistenceImpl.ts
|
|
4282
|
-
var
|
|
3058
|
+
var logger16 = (0, import_common16.createLogger)("persistence/Persistence");
|
|
4283
3059
|
var PersistenceImpl = class _PersistenceImpl {
|
|
4284
3060
|
images;
|
|
4285
3061
|
containers;
|
|
@@ -4293,7 +3069,7 @@ var PersistenceImpl = class _PersistenceImpl {
|
|
|
4293
3069
|
this.images = new StorageImageRepository(this.storage);
|
|
4294
3070
|
this.containers = new StorageContainerRepository(this.storage);
|
|
4295
3071
|
this.sessions = new StorageSessionRepository(this.storage);
|
|
4296
|
-
|
|
3072
|
+
logger16.info("Persistence created", { driver: driverName });
|
|
4297
3073
|
}
|
|
4298
3074
|
/**
|
|
4299
3075
|
* Create a PersistenceImpl instance (async factory)
|
|
@@ -4314,7 +3090,7 @@ var PersistenceImpl = class _PersistenceImpl {
|
|
|
4314
3090
|
*/
|
|
4315
3091
|
async dispose() {
|
|
4316
3092
|
await this.storage.dispose();
|
|
4317
|
-
|
|
3093
|
+
logger16.info("Persistence disposed");
|
|
4318
3094
|
}
|
|
4319
3095
|
};
|
|
4320
3096
|
async function createStorageFromConfig(config) {
|