@agentxjs/runtime 0.1.1 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +6 -6
package/dist/index.js
CHANGED
|
@@ -1,6 +1,176 @@
|
|
|
1
1
|
// src/internal/SystemBusImpl.ts
|
|
2
2
|
import { Subject } from "rxjs";
|
|
3
|
-
|
|
3
|
+
|
|
4
|
+
// ../common/dist/index.js
|
|
5
|
+
var __defProp = Object.defineProperty;
|
|
6
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
7
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
8
|
+
var _ConsoleLogger = class _ConsoleLogger2 {
|
|
9
|
+
constructor(name, options = {}) {
|
|
10
|
+
__publicField(this, "name");
|
|
11
|
+
__publicField(this, "level");
|
|
12
|
+
__publicField(this, "colors");
|
|
13
|
+
__publicField(this, "timestamps");
|
|
14
|
+
this.name = name;
|
|
15
|
+
this.level = options.level ?? "info";
|
|
16
|
+
this.colors = options.colors ?? this.isNodeEnvironment();
|
|
17
|
+
this.timestamps = options.timestamps ?? true;
|
|
18
|
+
}
|
|
19
|
+
debug(message, context) {
|
|
20
|
+
if (this.isDebugEnabled()) {
|
|
21
|
+
this.log("DEBUG", message, context);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
info(message, context) {
|
|
25
|
+
if (this.isInfoEnabled()) {
|
|
26
|
+
this.log("INFO", message, context);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
warn(message, context) {
|
|
30
|
+
if (this.isWarnEnabled()) {
|
|
31
|
+
this.log("WARN", message, context);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
error(message, context) {
|
|
35
|
+
if (this.isErrorEnabled()) {
|
|
36
|
+
if (message instanceof Error) {
|
|
37
|
+
this.log("ERROR", message.message, { ...context, stack: message.stack });
|
|
38
|
+
} else {
|
|
39
|
+
this.log("ERROR", message, context);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
isDebugEnabled() {
|
|
44
|
+
return this.getLevelValue(this.level) <= this.getLevelValue("debug");
|
|
45
|
+
}
|
|
46
|
+
isInfoEnabled() {
|
|
47
|
+
return this.getLevelValue(this.level) <= this.getLevelValue("info");
|
|
48
|
+
}
|
|
49
|
+
isWarnEnabled() {
|
|
50
|
+
return this.getLevelValue(this.level) <= this.getLevelValue("warn");
|
|
51
|
+
}
|
|
52
|
+
isErrorEnabled() {
|
|
53
|
+
return this.getLevelValue(this.level) <= this.getLevelValue("error");
|
|
54
|
+
}
|
|
55
|
+
getLevelValue(level) {
|
|
56
|
+
const levels = {
|
|
57
|
+
debug: 0,
|
|
58
|
+
info: 1,
|
|
59
|
+
warn: 2,
|
|
60
|
+
error: 3,
|
|
61
|
+
silent: 4
|
|
62
|
+
};
|
|
63
|
+
return levels[level];
|
|
64
|
+
}
|
|
65
|
+
log(level, message, context) {
|
|
66
|
+
const parts = [];
|
|
67
|
+
if (this.timestamps) {
|
|
68
|
+
parts.push((/* @__PURE__ */ new Date()).toISOString());
|
|
69
|
+
}
|
|
70
|
+
if (this.colors) {
|
|
71
|
+
const color = _ConsoleLogger2.COLORS[level];
|
|
72
|
+
parts.push(`${color}${level.padEnd(5)}${_ConsoleLogger2.COLORS.RESET}`);
|
|
73
|
+
} else {
|
|
74
|
+
parts.push(level.padEnd(5));
|
|
75
|
+
}
|
|
76
|
+
parts.push(`[${this.name}]`);
|
|
77
|
+
parts.push(message);
|
|
78
|
+
const logLine = parts.join(" ");
|
|
79
|
+
const consoleMethod = this.getConsoleMethod(level);
|
|
80
|
+
if (context && Object.keys(context).length > 0) {
|
|
81
|
+
consoleMethod(logLine, context);
|
|
82
|
+
} else {
|
|
83
|
+
consoleMethod(logLine);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
getConsoleMethod(level) {
|
|
87
|
+
switch (level) {
|
|
88
|
+
case "DEBUG":
|
|
89
|
+
return console.debug.bind(console);
|
|
90
|
+
case "INFO":
|
|
91
|
+
return console.info.bind(console);
|
|
92
|
+
case "WARN":
|
|
93
|
+
return console.warn.bind(console);
|
|
94
|
+
case "ERROR":
|
|
95
|
+
return console.error.bind(console);
|
|
96
|
+
default:
|
|
97
|
+
return console.log.bind(console);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
isNodeEnvironment() {
|
|
101
|
+
return typeof process !== "undefined" && process.versions?.node !== void 0;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
__publicField(_ConsoleLogger, "COLORS", {
|
|
105
|
+
DEBUG: "\x1B[36m",
|
|
106
|
+
INFO: "\x1B[32m",
|
|
107
|
+
WARN: "\x1B[33m",
|
|
108
|
+
ERROR: "\x1B[31m",
|
|
109
|
+
RESET: "\x1B[0m"
|
|
110
|
+
});
|
|
111
|
+
var ConsoleLogger = _ConsoleLogger;
|
|
112
|
+
var externalFactory = null;
|
|
113
|
+
var LoggerFactoryImpl = class {
|
|
114
|
+
static getLogger(nameOrClass) {
|
|
115
|
+
const name = typeof nameOrClass === "string" ? nameOrClass : nameOrClass.name;
|
|
116
|
+
if (this.loggers.has(name)) {
|
|
117
|
+
return this.loggers.get(name);
|
|
118
|
+
}
|
|
119
|
+
const lazyLogger = this.createLazyLogger(name);
|
|
120
|
+
this.loggers.set(name, lazyLogger);
|
|
121
|
+
return lazyLogger;
|
|
122
|
+
}
|
|
123
|
+
static configure(config) {
|
|
124
|
+
this.config = { ...this.config, ...config };
|
|
125
|
+
}
|
|
126
|
+
static reset() {
|
|
127
|
+
this.loggers.clear();
|
|
128
|
+
this.config = { defaultLevel: "info" };
|
|
129
|
+
externalFactory = null;
|
|
130
|
+
}
|
|
131
|
+
static createLazyLogger(name) {
|
|
132
|
+
let realLogger = null;
|
|
133
|
+
const getRealLogger = () => {
|
|
134
|
+
if (!realLogger) {
|
|
135
|
+
realLogger = this.createLogger(name);
|
|
136
|
+
}
|
|
137
|
+
return realLogger;
|
|
138
|
+
};
|
|
139
|
+
return {
|
|
140
|
+
name,
|
|
141
|
+
level: this.config.defaultLevel || "info",
|
|
142
|
+
debug: (message, context) => getRealLogger().debug(message, context),
|
|
143
|
+
info: (message, context) => getRealLogger().info(message, context),
|
|
144
|
+
warn: (message, context) => getRealLogger().warn(message, context),
|
|
145
|
+
error: (message, context) => getRealLogger().error(message, context),
|
|
146
|
+
isDebugEnabled: () => getRealLogger().isDebugEnabled(),
|
|
147
|
+
isInfoEnabled: () => getRealLogger().isInfoEnabled(),
|
|
148
|
+
isWarnEnabled: () => getRealLogger().isWarnEnabled(),
|
|
149
|
+
isErrorEnabled: () => getRealLogger().isErrorEnabled()
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
static createLogger(name) {
|
|
153
|
+
if (externalFactory) {
|
|
154
|
+
return externalFactory.getLogger(name);
|
|
155
|
+
}
|
|
156
|
+
if (this.config.defaultImplementation) {
|
|
157
|
+
return this.config.defaultImplementation(name);
|
|
158
|
+
}
|
|
159
|
+
return new ConsoleLogger(name, {
|
|
160
|
+
level: this.config.defaultLevel,
|
|
161
|
+
...this.config.consoleOptions
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
__publicField(LoggerFactoryImpl, "loggers", /* @__PURE__ */ new Map());
|
|
166
|
+
__publicField(LoggerFactoryImpl, "config", {
|
|
167
|
+
defaultLevel: "info"
|
|
168
|
+
});
|
|
169
|
+
function createLogger(name) {
|
|
170
|
+
return LoggerFactoryImpl.getLogger(name);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// src/internal/SystemBusImpl.ts
|
|
4
174
|
var logger = createLogger("runtime/SystemBusImpl");
|
|
5
175
|
var SystemBusImpl = class {
|
|
6
176
|
subject = new Subject();
|
|
@@ -159,8 +329,7 @@ var SystemBusImpl = class {
|
|
|
159
329
|
};
|
|
160
330
|
|
|
161
331
|
// src/internal/BusDriver.ts
|
|
162
|
-
|
|
163
|
-
var logger2 = createLogger2("runtime/BusDriver");
|
|
332
|
+
var logger2 = createLogger("runtime/BusDriver");
|
|
164
333
|
var BusDriver = class {
|
|
165
334
|
name = "BusDriver";
|
|
166
335
|
description = "Driver that listens to SystemBus for DriveableEvents";
|
|
@@ -345,8 +514,7 @@ var BusDriver = class {
|
|
|
345
514
|
};
|
|
346
515
|
|
|
347
516
|
// src/internal/AgentInteractor.ts
|
|
348
|
-
|
|
349
|
-
var logger3 = createLogger3("runtime/AgentInteractor");
|
|
517
|
+
var logger3 = createLogger("runtime/AgentInteractor");
|
|
350
518
|
var AgentInteractor = class {
|
|
351
519
|
producer;
|
|
352
520
|
session;
|
|
@@ -437,13 +605,1006 @@ var AgentInteractor = class {
|
|
|
437
605
|
}
|
|
438
606
|
};
|
|
439
607
|
|
|
440
|
-
//
|
|
441
|
-
|
|
442
|
-
|
|
608
|
+
// ../types/dist/agent.js
|
|
609
|
+
function isStateEvent(event) {
|
|
610
|
+
const stateTypes = [
|
|
611
|
+
"conversation_queued",
|
|
612
|
+
"conversation_start",
|
|
613
|
+
"conversation_thinking",
|
|
614
|
+
"conversation_responding",
|
|
615
|
+
"conversation_end",
|
|
616
|
+
"conversation_interrupted",
|
|
617
|
+
"tool_planned",
|
|
618
|
+
"tool_executing",
|
|
619
|
+
"tool_completed",
|
|
620
|
+
"tool_failed",
|
|
621
|
+
"error_occurred"
|
|
622
|
+
];
|
|
623
|
+
return stateTypes.includes(event.type);
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
// ../agent/dist/index.js
|
|
627
|
+
var MemoryStore = class {
|
|
628
|
+
states = /* @__PURE__ */ new Map();
|
|
629
|
+
get(id) {
|
|
630
|
+
return this.states.get(id);
|
|
631
|
+
}
|
|
632
|
+
set(id, state) {
|
|
633
|
+
this.states.set(id, state);
|
|
634
|
+
}
|
|
635
|
+
delete(id) {
|
|
636
|
+
this.states.delete(id);
|
|
637
|
+
}
|
|
638
|
+
has(id) {
|
|
639
|
+
return this.states.has(id);
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Clear all stored states
|
|
643
|
+
*/
|
|
644
|
+
clear() {
|
|
645
|
+
this.states.clear();
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Get the number of stored states
|
|
649
|
+
*/
|
|
650
|
+
get size() {
|
|
651
|
+
return this.states.size;
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Get all stored IDs
|
|
655
|
+
*/
|
|
656
|
+
keys() {
|
|
657
|
+
return this.states.keys();
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
createLogger("engine/Mealy");
|
|
661
|
+
function combineProcessors(processors) {
|
|
662
|
+
return (state, event) => {
|
|
663
|
+
const newState = {};
|
|
664
|
+
const allOutputs = [];
|
|
665
|
+
for (const key in processors) {
|
|
666
|
+
const processor = processors[key];
|
|
667
|
+
const subState = state[key];
|
|
668
|
+
const [newSubState, outputs] = processor(subState, event);
|
|
669
|
+
newState[key] = newSubState;
|
|
670
|
+
allOutputs.push(...outputs);
|
|
671
|
+
}
|
|
672
|
+
return [newState, allOutputs];
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
function combineInitialStates(initialStates) {
|
|
676
|
+
return () => {
|
|
677
|
+
const state = {};
|
|
678
|
+
for (const key in initialStates) {
|
|
679
|
+
state[key] = initialStates[key]();
|
|
680
|
+
}
|
|
681
|
+
return state;
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
function createInitialMessageAssemblerState() {
|
|
685
|
+
return {
|
|
686
|
+
currentMessageId: null,
|
|
687
|
+
messageStartTime: null,
|
|
688
|
+
pendingContents: {},
|
|
689
|
+
pendingToolCalls: {}
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
function generateId() {
|
|
693
|
+
return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
694
|
+
}
|
|
695
|
+
var messageAssemblerProcessor = (state, input) => {
|
|
696
|
+
switch (input.type) {
|
|
697
|
+
case "message_start":
|
|
698
|
+
return handleMessageStart(state, input);
|
|
699
|
+
case "text_delta":
|
|
700
|
+
return handleTextDelta(state, input);
|
|
701
|
+
case "tool_use_start":
|
|
702
|
+
return handleToolUseStart(state, input);
|
|
703
|
+
case "input_json_delta":
|
|
704
|
+
return handleInputJsonDelta(state, input);
|
|
705
|
+
case "tool_use_stop":
|
|
706
|
+
return handleToolUseStop(state);
|
|
707
|
+
case "tool_result":
|
|
708
|
+
return handleToolResult(state, input);
|
|
709
|
+
case "message_stop":
|
|
710
|
+
return handleMessageStop(state, input);
|
|
711
|
+
case "error_received":
|
|
712
|
+
return handleErrorReceived(state, input);
|
|
713
|
+
default:
|
|
714
|
+
return [state, []];
|
|
715
|
+
}
|
|
716
|
+
};
|
|
717
|
+
function handleMessageStart(state, event) {
|
|
718
|
+
const data = event.data;
|
|
719
|
+
return [
|
|
720
|
+
{
|
|
721
|
+
...state,
|
|
722
|
+
currentMessageId: data.messageId,
|
|
723
|
+
messageStartTime: event.timestamp,
|
|
724
|
+
pendingContents: {}
|
|
725
|
+
},
|
|
726
|
+
[]
|
|
727
|
+
];
|
|
728
|
+
}
|
|
729
|
+
function handleTextDelta(state, event) {
|
|
730
|
+
const data = event.data;
|
|
731
|
+
const index = 0;
|
|
732
|
+
const existingContent = state.pendingContents[index];
|
|
733
|
+
const pendingContent = existingContent?.type === "text" ? {
|
|
734
|
+
...existingContent,
|
|
735
|
+
textDeltas: [...existingContent.textDeltas || [], data.text]
|
|
736
|
+
} : {
|
|
737
|
+
type: "text",
|
|
738
|
+
index,
|
|
739
|
+
textDeltas: [data.text]
|
|
740
|
+
};
|
|
741
|
+
return [
|
|
742
|
+
{
|
|
743
|
+
...state,
|
|
744
|
+
pendingContents: {
|
|
745
|
+
...state.pendingContents,
|
|
746
|
+
[index]: pendingContent
|
|
747
|
+
}
|
|
748
|
+
},
|
|
749
|
+
[]
|
|
750
|
+
];
|
|
751
|
+
}
|
|
752
|
+
function handleToolUseStart(state, event) {
|
|
753
|
+
const data = event.data;
|
|
754
|
+
const index = 1;
|
|
755
|
+
const pendingContent = {
|
|
756
|
+
type: "tool_use",
|
|
757
|
+
index,
|
|
758
|
+
toolId: data.toolCallId,
|
|
759
|
+
toolName: data.toolName,
|
|
760
|
+
toolInputJson: ""
|
|
761
|
+
};
|
|
762
|
+
return [
|
|
763
|
+
{
|
|
764
|
+
...state,
|
|
765
|
+
pendingContents: {
|
|
766
|
+
...state.pendingContents,
|
|
767
|
+
[index]: pendingContent
|
|
768
|
+
}
|
|
769
|
+
},
|
|
770
|
+
[]
|
|
771
|
+
];
|
|
772
|
+
}
|
|
773
|
+
function handleInputJsonDelta(state, event) {
|
|
774
|
+
const data = event.data;
|
|
775
|
+
const index = 1;
|
|
776
|
+
const existingContent = state.pendingContents[index];
|
|
777
|
+
if (!existingContent || existingContent.type !== "tool_use") {
|
|
778
|
+
return [state, []];
|
|
779
|
+
}
|
|
780
|
+
const pendingContent = {
|
|
781
|
+
...existingContent,
|
|
782
|
+
toolInputJson: (existingContent.toolInputJson || "") + data.partialJson
|
|
783
|
+
};
|
|
784
|
+
return [
|
|
785
|
+
{
|
|
786
|
+
...state,
|
|
787
|
+
pendingContents: {
|
|
788
|
+
...state.pendingContents,
|
|
789
|
+
[index]: pendingContent
|
|
790
|
+
}
|
|
791
|
+
},
|
|
792
|
+
[]
|
|
793
|
+
];
|
|
794
|
+
}
|
|
795
|
+
function handleToolUseStop(state, _event) {
|
|
796
|
+
const index = 1;
|
|
797
|
+
const pendingContent = state.pendingContents[index];
|
|
798
|
+
if (!pendingContent || pendingContent.type !== "tool_use") {
|
|
799
|
+
return [state, []];
|
|
800
|
+
}
|
|
801
|
+
const toolId = pendingContent.toolId || "";
|
|
802
|
+
const toolName = pendingContent.toolName || "";
|
|
803
|
+
let toolInput = {};
|
|
804
|
+
try {
|
|
805
|
+
toolInput = pendingContent.toolInputJson ? JSON.parse(pendingContent.toolInputJson) : {};
|
|
806
|
+
} catch {
|
|
807
|
+
toolInput = {};
|
|
808
|
+
}
|
|
809
|
+
const toolCall = {
|
|
810
|
+
type: "tool-call",
|
|
811
|
+
id: toolId,
|
|
812
|
+
name: toolName,
|
|
813
|
+
input: toolInput
|
|
814
|
+
};
|
|
815
|
+
const toolCallMessageEvent = {
|
|
816
|
+
type: "tool_call_message",
|
|
817
|
+
timestamp: Date.now(),
|
|
818
|
+
data: {
|
|
819
|
+
messageId: generateId(),
|
|
820
|
+
toolCalls: [toolCall],
|
|
821
|
+
timestamp: Date.now()
|
|
822
|
+
}
|
|
823
|
+
};
|
|
824
|
+
const { [index]: _, ...remainingContents } = state.pendingContents;
|
|
825
|
+
return [
|
|
826
|
+
{
|
|
827
|
+
...state,
|
|
828
|
+
pendingContents: remainingContents,
|
|
829
|
+
pendingToolCalls: {
|
|
830
|
+
...state.pendingToolCalls,
|
|
831
|
+
[toolId]: { id: toolId, name: toolName }
|
|
832
|
+
}
|
|
833
|
+
},
|
|
834
|
+
[toolCallMessageEvent]
|
|
835
|
+
];
|
|
836
|
+
}
|
|
837
|
+
function handleToolResult(state, event) {
|
|
838
|
+
const data = event.data;
|
|
839
|
+
const { toolCallId, result, isError } = data;
|
|
840
|
+
const pendingToolCall = state.pendingToolCalls[toolCallId];
|
|
841
|
+
const toolName = pendingToolCall?.name || "unknown";
|
|
842
|
+
const toolResult = {
|
|
843
|
+
type: "tool-result",
|
|
844
|
+
id: toolCallId,
|
|
845
|
+
name: toolName,
|
|
846
|
+
output: {
|
|
847
|
+
type: isError ? "error-text" : "text",
|
|
848
|
+
value: typeof result === "string" ? result : JSON.stringify(result)
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
const toolResultMessageEvent = {
|
|
852
|
+
type: "tool_result_message",
|
|
853
|
+
timestamp: Date.now(),
|
|
854
|
+
data: {
|
|
855
|
+
messageId: generateId(),
|
|
856
|
+
results: [toolResult],
|
|
857
|
+
timestamp: Date.now()
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
const { [toolCallId]: _, ...remainingToolCalls } = state.pendingToolCalls;
|
|
861
|
+
return [
|
|
862
|
+
{
|
|
863
|
+
...state,
|
|
864
|
+
pendingToolCalls: remainingToolCalls
|
|
865
|
+
},
|
|
866
|
+
[toolResultMessageEvent]
|
|
867
|
+
];
|
|
868
|
+
}
|
|
869
|
+
function handleMessageStop(state, event) {
|
|
870
|
+
const data = event.data;
|
|
871
|
+
if (!state.currentMessageId) {
|
|
872
|
+
return [state, []];
|
|
873
|
+
}
|
|
874
|
+
const textParts = [];
|
|
875
|
+
const sortedContents = Object.values(state.pendingContents).sort((a, b) => a.index - b.index);
|
|
876
|
+
for (const pending of sortedContents) {
|
|
877
|
+
if (pending.type === "text" && pending.textDeltas) {
|
|
878
|
+
textParts.push(pending.textDeltas.join(""));
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
const textContent = textParts.join("");
|
|
882
|
+
const stopReason = data.stopReason;
|
|
883
|
+
if (!textContent || textContent.trim().length === 0) {
|
|
884
|
+
const shouldPreserveToolCalls2 = stopReason === "tool_use";
|
|
885
|
+
return [
|
|
886
|
+
{
|
|
887
|
+
...createInitialMessageAssemblerState(),
|
|
888
|
+
pendingToolCalls: shouldPreserveToolCalls2 ? state.pendingToolCalls : {}
|
|
889
|
+
},
|
|
890
|
+
[]
|
|
891
|
+
];
|
|
892
|
+
}
|
|
893
|
+
const contentParts = [
|
|
894
|
+
{
|
|
895
|
+
type: "text",
|
|
896
|
+
text: textContent
|
|
897
|
+
}
|
|
898
|
+
];
|
|
899
|
+
const assistantEvent = {
|
|
900
|
+
type: "assistant_message",
|
|
901
|
+
timestamp: Date.now(),
|
|
902
|
+
data: {
|
|
903
|
+
messageId: state.currentMessageId,
|
|
904
|
+
content: contentParts,
|
|
905
|
+
stopReason,
|
|
906
|
+
timestamp: state.messageStartTime || Date.now()
|
|
907
|
+
}
|
|
908
|
+
};
|
|
909
|
+
const shouldPreserveToolCalls = stopReason === "tool_use";
|
|
910
|
+
return [
|
|
911
|
+
{
|
|
912
|
+
...createInitialMessageAssemblerState(),
|
|
913
|
+
pendingToolCalls: shouldPreserveToolCalls ? state.pendingToolCalls : {}
|
|
914
|
+
},
|
|
915
|
+
[assistantEvent]
|
|
916
|
+
];
|
|
917
|
+
}
|
|
918
|
+
function handleErrorReceived(_state, event) {
|
|
919
|
+
const data = event.data;
|
|
920
|
+
const errorMessageEvent = {
|
|
921
|
+
type: "error_message",
|
|
922
|
+
timestamp: Date.now(),
|
|
923
|
+
data: {
|
|
924
|
+
messageId: generateId(),
|
|
925
|
+
content: data.message,
|
|
926
|
+
errorCode: data.errorCode,
|
|
927
|
+
timestamp: Date.now()
|
|
928
|
+
}
|
|
929
|
+
};
|
|
930
|
+
return [createInitialMessageAssemblerState(), [errorMessageEvent]];
|
|
931
|
+
}
|
|
932
|
+
var logger22 = createLogger("engine/stateEventProcessor");
|
|
933
|
+
function createInitialStateEventProcessorContext() {
|
|
934
|
+
return {};
|
|
935
|
+
}
|
|
936
|
+
var stateEventProcessor = (context, input) => {
|
|
937
|
+
logger22.debug(`[Stream Event] ${input.type}`, {
|
|
938
|
+
context,
|
|
939
|
+
eventData: "data" in input ? input.data : void 0
|
|
940
|
+
});
|
|
941
|
+
switch (input.type) {
|
|
942
|
+
case "message_start":
|
|
943
|
+
return handleMessageStart2(context, input);
|
|
944
|
+
case "message_delta":
|
|
945
|
+
return handleMessageDelta(context);
|
|
946
|
+
case "message_stop":
|
|
947
|
+
return handleMessageStop2(context, input);
|
|
948
|
+
case "text_delta":
|
|
949
|
+
return handleTextDelta2(context);
|
|
950
|
+
case "tool_use_start":
|
|
951
|
+
return handleToolUseStart2(context, input);
|
|
952
|
+
case "tool_use_stop":
|
|
953
|
+
return handleToolUseStop2(context);
|
|
954
|
+
case "error_received":
|
|
955
|
+
return handleErrorReceived2(context, input);
|
|
956
|
+
default:
|
|
957
|
+
logger22.debug(`[Stream Event] ${input.type} (unhandled)`);
|
|
958
|
+
return [context, []];
|
|
959
|
+
}
|
|
960
|
+
};
|
|
961
|
+
function handleMessageStart2(context, event) {
|
|
962
|
+
const data = event.data;
|
|
963
|
+
const conversationStartEvent = {
|
|
964
|
+
type: "conversation_start",
|
|
965
|
+
timestamp: Date.now(),
|
|
966
|
+
data: {
|
|
967
|
+
messageId: data.messageId
|
|
968
|
+
}
|
|
969
|
+
};
|
|
970
|
+
return [context, [conversationStartEvent]];
|
|
971
|
+
}
|
|
972
|
+
function handleMessageDelta(context) {
|
|
973
|
+
return [context, []];
|
|
974
|
+
}
|
|
975
|
+
function handleMessageStop2(context, event) {
|
|
976
|
+
const data = event.data;
|
|
977
|
+
const stopReason = data.stopReason;
|
|
978
|
+
logger22.debug("message_stop received", { stopReason });
|
|
979
|
+
if (stopReason === "tool_use") {
|
|
980
|
+
logger22.debug("Skipping conversation_end (tool_use in progress)");
|
|
981
|
+
return [context, []];
|
|
982
|
+
}
|
|
983
|
+
const conversationEndEvent = {
|
|
984
|
+
type: "conversation_end",
|
|
985
|
+
timestamp: Date.now(),
|
|
986
|
+
data: {
|
|
987
|
+
reason: "completed"
|
|
988
|
+
}
|
|
989
|
+
};
|
|
990
|
+
return [context, [conversationEndEvent]];
|
|
991
|
+
}
|
|
992
|
+
function handleTextDelta2(context) {
|
|
993
|
+
const respondingEvent = {
|
|
994
|
+
type: "conversation_responding",
|
|
995
|
+
timestamp: Date.now(),
|
|
996
|
+
data: {}
|
|
997
|
+
};
|
|
998
|
+
return [context, [respondingEvent]];
|
|
999
|
+
}
|
|
1000
|
+
function handleToolUseStart2(context, event) {
|
|
1001
|
+
const data = event.data;
|
|
1002
|
+
const outputs = [];
|
|
1003
|
+
const toolPlannedEvent = {
|
|
1004
|
+
type: "tool_planned",
|
|
1005
|
+
timestamp: Date.now(),
|
|
1006
|
+
data: {
|
|
1007
|
+
toolId: data.toolCallId,
|
|
1008
|
+
toolName: data.toolName
|
|
1009
|
+
}
|
|
1010
|
+
};
|
|
1011
|
+
outputs.push(toolPlannedEvent);
|
|
1012
|
+
const toolExecutingEvent = {
|
|
1013
|
+
type: "tool_executing",
|
|
1014
|
+
timestamp: Date.now(),
|
|
1015
|
+
data: {
|
|
1016
|
+
toolId: data.toolCallId,
|
|
1017
|
+
toolName: data.toolName,
|
|
1018
|
+
input: {}
|
|
1019
|
+
}
|
|
1020
|
+
};
|
|
1021
|
+
outputs.push(toolExecutingEvent);
|
|
1022
|
+
return [context, outputs];
|
|
1023
|
+
}
|
|
1024
|
+
function handleToolUseStop2(context) {
|
|
1025
|
+
return [context, []];
|
|
1026
|
+
}
|
|
1027
|
+
function handleErrorReceived2(context, event) {
|
|
1028
|
+
const data = event.data;
|
|
1029
|
+
const errorOccurredEvent = {
|
|
1030
|
+
type: "error_occurred",
|
|
1031
|
+
timestamp: Date.now(),
|
|
1032
|
+
data: {
|
|
1033
|
+
code: data.errorCode || "unknown_error",
|
|
1034
|
+
message: data.message,
|
|
1035
|
+
recoverable: true
|
|
1036
|
+
}
|
|
1037
|
+
};
|
|
1038
|
+
return [context, [errorOccurredEvent]];
|
|
1039
|
+
}
|
|
1040
|
+
function createInitialTurnTrackerState() {
|
|
1041
|
+
return {
|
|
1042
|
+
pendingTurn: null,
|
|
1043
|
+
costPerInputToken: 3e-6,
|
|
1044
|
+
// $3 per 1M tokens
|
|
1045
|
+
costPerOutputToken: 15e-6
|
|
1046
|
+
// $15 per 1M tokens
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
function generateId2() {
|
|
1050
|
+
return `turn_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
1051
|
+
}
|
|
1052
|
+
var turnTrackerProcessor = (state, input) => {
|
|
1053
|
+
switch (input.type) {
|
|
1054
|
+
case "user_message":
|
|
1055
|
+
return handleUserMessage(state, input);
|
|
1056
|
+
case "message_stop":
|
|
1057
|
+
return handleMessageStop3(state, input);
|
|
1058
|
+
case "assistant_message":
|
|
1059
|
+
return [state, []];
|
|
1060
|
+
default:
|
|
1061
|
+
return [state, []];
|
|
1062
|
+
}
|
|
1063
|
+
};
|
|
1064
|
+
function handleUserMessage(state, event) {
|
|
1065
|
+
const data = event.data;
|
|
1066
|
+
const turnId = generateId2();
|
|
1067
|
+
const pendingTurn = {
|
|
1068
|
+
turnId,
|
|
1069
|
+
messageId: data.messageId,
|
|
1070
|
+
content: data.content,
|
|
1071
|
+
requestedAt: event.timestamp
|
|
1072
|
+
};
|
|
1073
|
+
const turnRequestEvent = {
|
|
1074
|
+
type: "turn_request",
|
|
1075
|
+
timestamp: Date.now(),
|
|
1076
|
+
data: {
|
|
1077
|
+
turnId,
|
|
1078
|
+
messageId: data.messageId,
|
|
1079
|
+
content: data.content,
|
|
1080
|
+
timestamp: event.timestamp
|
|
1081
|
+
}
|
|
1082
|
+
};
|
|
1083
|
+
return [
|
|
1084
|
+
{
|
|
1085
|
+
...state,
|
|
1086
|
+
pendingTurn
|
|
1087
|
+
},
|
|
1088
|
+
[turnRequestEvent]
|
|
1089
|
+
];
|
|
1090
|
+
}
|
|
1091
|
+
function handleMessageStop3(state, event) {
|
|
1092
|
+
if (!state.pendingTurn) {
|
|
1093
|
+
return [state, []];
|
|
1094
|
+
}
|
|
1095
|
+
const data = event.data;
|
|
1096
|
+
const stopReason = data.stopReason;
|
|
1097
|
+
if (stopReason === "end_turn" || stopReason === "max_tokens" || stopReason === "stop_sequence") {
|
|
1098
|
+
return completeTurn(state, event.timestamp);
|
|
1099
|
+
}
|
|
1100
|
+
return [state, []];
|
|
1101
|
+
}
|
|
1102
|
+
function completeTurn(state, completedAt) {
|
|
1103
|
+
if (!state.pendingTurn) {
|
|
1104
|
+
return [state, []];
|
|
1105
|
+
}
|
|
1106
|
+
const { turnId, messageId, requestedAt } = state.pendingTurn;
|
|
1107
|
+
const duration = completedAt - requestedAt;
|
|
1108
|
+
const usage = { inputTokens: 0, outputTokens: 0 };
|
|
1109
|
+
const turnResponseEvent = {
|
|
1110
|
+
type: "turn_response",
|
|
1111
|
+
timestamp: Date.now(),
|
|
1112
|
+
data: {
|
|
1113
|
+
turnId,
|
|
1114
|
+
messageId,
|
|
1115
|
+
duration,
|
|
1116
|
+
usage,
|
|
1117
|
+
timestamp: completedAt
|
|
1118
|
+
}
|
|
1119
|
+
};
|
|
1120
|
+
return [
|
|
1121
|
+
{
|
|
1122
|
+
...state,
|
|
1123
|
+
pendingTurn: null
|
|
1124
|
+
},
|
|
1125
|
+
[turnResponseEvent]
|
|
1126
|
+
];
|
|
1127
|
+
}
|
|
1128
|
+
var agentProcessor = combineProcessors({
|
|
1129
|
+
messageAssembler: messageAssemblerProcessor,
|
|
1130
|
+
stateEventProcessor,
|
|
1131
|
+
turnTracker: turnTrackerProcessor
|
|
1132
|
+
});
|
|
1133
|
+
var createInitialAgentEngineState = combineInitialStates({
|
|
1134
|
+
messageAssembler: createInitialMessageAssemblerState,
|
|
1135
|
+
stateEventProcessor: createInitialStateEventProcessorContext,
|
|
1136
|
+
turnTracker: createInitialTurnTrackerState
|
|
1137
|
+
});
|
|
1138
|
+
var logger32 = createLogger("engine/MealyMachine");
|
|
1139
|
+
var MealyMachine = class {
|
|
1140
|
+
store;
|
|
1141
|
+
constructor() {
|
|
1142
|
+
this.store = new MemoryStore();
|
|
1143
|
+
logger32.debug("MealyMachine initialized");
|
|
1144
|
+
}
|
|
1145
|
+
/**
|
|
1146
|
+
* Process a single driveable event and return output events
|
|
1147
|
+
*
|
|
1148
|
+
* This is the core Mealy Machine operation:
|
|
1149
|
+
* process(agentId, event) → outputs[]
|
|
1150
|
+
*
|
|
1151
|
+
* @param agentId - The agent identifier (for state isolation)
|
|
1152
|
+
* @param event - StreamEvent to process
|
|
1153
|
+
* @returns Array of output events (state, message, turn events)
|
|
1154
|
+
*/
|
|
1155
|
+
process(agentId, event) {
|
|
1156
|
+
const eventType = event.type || "unknown";
|
|
1157
|
+
logger32.debug("Processing event", { agentId, eventType });
|
|
1158
|
+
const isNewState = !this.store.has(agentId);
|
|
1159
|
+
let state = this.store.get(agentId) ?? createInitialAgentEngineState();
|
|
1160
|
+
if (isNewState) {
|
|
1161
|
+
logger32.debug("Created initial state for agent", { agentId });
|
|
1162
|
+
}
|
|
1163
|
+
const allOutputs = [];
|
|
1164
|
+
allOutputs.push(event);
|
|
1165
|
+
const [newState, outputs] = agentProcessor(state, event);
|
|
1166
|
+
state = newState;
|
|
1167
|
+
for (const output of outputs) {
|
|
1168
|
+
allOutputs.push(output);
|
|
1169
|
+
const [chainedState, chainedOutputs] = this.processChained(state, output);
|
|
1170
|
+
state = chainedState;
|
|
1171
|
+
allOutputs.push(...chainedOutputs);
|
|
1172
|
+
}
|
|
1173
|
+
this.store.set(agentId, state);
|
|
1174
|
+
if (outputs.length > 0) {
|
|
1175
|
+
logger32.debug("Produced outputs", {
|
|
1176
|
+
agentId,
|
|
1177
|
+
inputEvent: eventType,
|
|
1178
|
+
outputCount: allOutputs.length,
|
|
1179
|
+
processorOutputs: outputs.length
|
|
1180
|
+
});
|
|
1181
|
+
}
|
|
1182
|
+
return allOutputs;
|
|
1183
|
+
}
|
|
1184
|
+
/**
|
|
1185
|
+
* Process chained events recursively
|
|
1186
|
+
*
|
|
1187
|
+
* Some processors produce events that trigger other processors:
|
|
1188
|
+
* - MessageAssembler produces MessageEvents
|
|
1189
|
+
* - TurnTracker consumes MessageEvents to produce TurnEvents
|
|
1190
|
+
*/
|
|
1191
|
+
processChained(state, event) {
|
|
1192
|
+
const [newState, outputs] = agentProcessor(state, event);
|
|
1193
|
+
if (outputs.length === 0) {
|
|
1194
|
+
return [newState, []];
|
|
1195
|
+
}
|
|
1196
|
+
const allOutputs = [...outputs];
|
|
1197
|
+
let currentState = newState;
|
|
1198
|
+
for (const output of outputs) {
|
|
1199
|
+
const [chainedState, chainedOutputs] = this.processChained(currentState, output);
|
|
1200
|
+
currentState = chainedState;
|
|
1201
|
+
allOutputs.push(...chainedOutputs);
|
|
1202
|
+
}
|
|
1203
|
+
return [currentState, allOutputs];
|
|
1204
|
+
}
|
|
1205
|
+
/**
|
|
1206
|
+
* Clear state for an agent
|
|
1207
|
+
*
|
|
1208
|
+
* Call this when an agent is destroyed to free memory.
|
|
1209
|
+
*/
|
|
1210
|
+
clearState(agentId) {
|
|
1211
|
+
logger32.debug("Clearing state", { agentId });
|
|
1212
|
+
this.store.delete(agentId);
|
|
1213
|
+
}
|
|
1214
|
+
/**
|
|
1215
|
+
* Check if state exists for an agent
|
|
1216
|
+
*/
|
|
1217
|
+
hasState(agentId) {
|
|
1218
|
+
return this.store.has(agentId);
|
|
1219
|
+
}
|
|
1220
|
+
};
|
|
1221
|
+
var logger4 = createLogger("agent/AgentStateMachine");
|
|
1222
|
+
var AgentStateMachine = class {
|
|
1223
|
+
_state = "idle";
|
|
1224
|
+
handlers = /* @__PURE__ */ new Set();
|
|
1225
|
+
/**
|
|
1226
|
+
* Current agent state
|
|
1227
|
+
*/
|
|
1228
|
+
get state() {
|
|
1229
|
+
return this._state;
|
|
1230
|
+
}
|
|
1231
|
+
/**
|
|
1232
|
+
* Process an event and update internal state if it's a StateEvent
|
|
1233
|
+
*
|
|
1234
|
+
* @param event - Event from MealyMachine (could be any AgentOutput)
|
|
1235
|
+
*/
|
|
1236
|
+
process(event) {
|
|
1237
|
+
if (!isStateEvent(event)) {
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1240
|
+
const prev = this._state;
|
|
1241
|
+
const next = this.mapEventToState(event);
|
|
1242
|
+
if (next !== null && prev !== next) {
|
|
1243
|
+
this._state = next;
|
|
1244
|
+
logger4.debug("State transition", {
|
|
1245
|
+
eventType: event.type,
|
|
1246
|
+
from: prev,
|
|
1247
|
+
to: next
|
|
1248
|
+
});
|
|
1249
|
+
this.notifyHandlers({ prev, current: next });
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
/**
|
|
1253
|
+
* Subscribe to state changes
|
|
1254
|
+
*
|
|
1255
|
+
* @param handler - Callback receiving { prev, current } state change
|
|
1256
|
+
* @returns Unsubscribe function
|
|
1257
|
+
*/
|
|
1258
|
+
onStateChange(handler) {
|
|
1259
|
+
this.handlers.add(handler);
|
|
1260
|
+
return () => {
|
|
1261
|
+
this.handlers.delete(handler);
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
/**
|
|
1265
|
+
* Reset state machine (used on destroy)
|
|
1266
|
+
*/
|
|
1267
|
+
reset() {
|
|
1268
|
+
const prev = this._state;
|
|
1269
|
+
this._state = "idle";
|
|
1270
|
+
if (prev !== "idle") {
|
|
1271
|
+
this.notifyHandlers({ prev, current: "idle" });
|
|
1272
|
+
}
|
|
1273
|
+
this.handlers.clear();
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* Map StateEvent type to AgentState
|
|
1277
|
+
*
|
|
1278
|
+
* @param event - StateEvent from MealyMachine
|
|
1279
|
+
* @returns New AgentState or null if no transition needed
|
|
1280
|
+
*/
|
|
1281
|
+
mapEventToState(event) {
|
|
1282
|
+
switch (event.type) {
|
|
1283
|
+
// Conversation lifecycle
|
|
1284
|
+
case "conversation_start":
|
|
1285
|
+
return "thinking";
|
|
1286
|
+
case "conversation_thinking":
|
|
1287
|
+
return "thinking";
|
|
1288
|
+
case "conversation_responding":
|
|
1289
|
+
return "responding";
|
|
1290
|
+
case "conversation_end":
|
|
1291
|
+
return "idle";
|
|
1292
|
+
case "conversation_interrupted":
|
|
1293
|
+
return "idle";
|
|
1294
|
+
// Tool lifecycle
|
|
1295
|
+
case "tool_planned":
|
|
1296
|
+
return "planning_tool";
|
|
1297
|
+
case "tool_executing":
|
|
1298
|
+
return "awaiting_tool_result";
|
|
1299
|
+
case "tool_completed":
|
|
1300
|
+
return "responding";
|
|
1301
|
+
case "tool_failed":
|
|
1302
|
+
return "responding";
|
|
1303
|
+
// Error
|
|
1304
|
+
case "error_occurred":
|
|
1305
|
+
return "error";
|
|
1306
|
+
default:
|
|
1307
|
+
return null;
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
/**
|
|
1311
|
+
* Notify all registered handlers of state change
|
|
1312
|
+
*/
|
|
1313
|
+
notifyHandlers(change) {
|
|
1314
|
+
for (const handler of this.handlers) {
|
|
1315
|
+
try {
|
|
1316
|
+
handler(change);
|
|
1317
|
+
} catch (error) {
|
|
1318
|
+
logger4.error("State change handler error", {
|
|
1319
|
+
from: change.prev,
|
|
1320
|
+
to: change.current,
|
|
1321
|
+
error
|
|
1322
|
+
});
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
};
|
|
1327
|
+
var logger5 = createLogger("agent/SimpleAgent");
|
|
1328
|
+
function generateAgentId() {
|
|
1329
|
+
return `agent_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
1330
|
+
}
|
|
1331
|
+
var SimpleMessageQueue = class {
|
|
1332
|
+
queue = [];
|
|
1333
|
+
get length() {
|
|
1334
|
+
return this.queue.length;
|
|
1335
|
+
}
|
|
1336
|
+
get isEmpty() {
|
|
1337
|
+
return this.queue.length === 0;
|
|
1338
|
+
}
|
|
1339
|
+
enqueue(message) {
|
|
1340
|
+
this.queue.push(message);
|
|
1341
|
+
}
|
|
1342
|
+
dequeue() {
|
|
1343
|
+
return this.queue.shift();
|
|
1344
|
+
}
|
|
1345
|
+
clear() {
|
|
1346
|
+
this.queue = [];
|
|
1347
|
+
}
|
|
1348
|
+
};
|
|
1349
|
+
var SimpleAgent = class {
|
|
1350
|
+
agentId;
|
|
1351
|
+
createdAt;
|
|
1352
|
+
messageQueue;
|
|
1353
|
+
_messageQueue = new SimpleMessageQueue();
|
|
1354
|
+
driver;
|
|
1355
|
+
presenter;
|
|
1356
|
+
machine;
|
|
1357
|
+
stateMachine;
|
|
1358
|
+
handlers = /* @__PURE__ */ new Set();
|
|
1359
|
+
typeHandlers = /* @__PURE__ */ new Map();
|
|
1360
|
+
readyHandlers = /* @__PURE__ */ new Set();
|
|
1361
|
+
destroyHandlers = /* @__PURE__ */ new Set();
|
|
1362
|
+
middlewares = [];
|
|
1363
|
+
interceptors = [];
|
|
1364
|
+
isProcessing = false;
|
|
1365
|
+
constructor(options) {
|
|
1366
|
+
this.agentId = generateAgentId();
|
|
1367
|
+
this.createdAt = Date.now();
|
|
1368
|
+
this.messageQueue = this._messageQueue;
|
|
1369
|
+
this.driver = options.driver;
|
|
1370
|
+
this.presenter = options.presenter;
|
|
1371
|
+
this.machine = new MealyMachine();
|
|
1372
|
+
this.stateMachine = new AgentStateMachine();
|
|
1373
|
+
}
|
|
1374
|
+
get state() {
|
|
1375
|
+
return this.stateMachine.state;
|
|
1376
|
+
}
|
|
1377
|
+
async receive(message) {
|
|
1378
|
+
console.log(
|
|
1379
|
+
"[SimpleAgent.receive] CALLED with message:",
|
|
1380
|
+
typeof message === "string" ? message : message.content
|
|
1381
|
+
);
|
|
1382
|
+
const userMessage = typeof message === "string" ? {
|
|
1383
|
+
id: `msg_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
|
|
1384
|
+
role: "user",
|
|
1385
|
+
subtype: "user",
|
|
1386
|
+
content: message,
|
|
1387
|
+
timestamp: Date.now()
|
|
1388
|
+
} : message;
|
|
1389
|
+
this._messageQueue.enqueue(userMessage);
|
|
1390
|
+
console.log("[SimpleAgent.receive] Message queued, isProcessing:", this.isProcessing);
|
|
1391
|
+
if (this.isProcessing) {
|
|
1392
|
+
return new Promise((resolve, reject) => {
|
|
1393
|
+
userMessage._resolve = resolve;
|
|
1394
|
+
userMessage._reject = reject;
|
|
1395
|
+
});
|
|
1396
|
+
}
|
|
1397
|
+
console.log("[SimpleAgent.receive] Starting processQueue");
|
|
1398
|
+
await this.processQueue();
|
|
1399
|
+
}
|
|
1400
|
+
async processQueue() {
|
|
1401
|
+
if (this.isProcessing) return;
|
|
1402
|
+
this.isProcessing = true;
|
|
1403
|
+
console.log("[SimpleAgent.processQueue] Starting, queue size:", this._messageQueue.length);
|
|
1404
|
+
while (!this._messageQueue.isEmpty) {
|
|
1405
|
+
const message = this._messageQueue.dequeue();
|
|
1406
|
+
if (!message) break;
|
|
1407
|
+
console.log("[SimpleAgent.processQueue] Processing message:", message.id);
|
|
1408
|
+
try {
|
|
1409
|
+
await this.processMessage(message);
|
|
1410
|
+
if (message._resolve) {
|
|
1411
|
+
message._resolve();
|
|
1412
|
+
}
|
|
1413
|
+
} catch (error) {
|
|
1414
|
+
if (message._reject) {
|
|
1415
|
+
message._reject(error);
|
|
1416
|
+
}
|
|
1417
|
+
throw error;
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
this.isProcessing = false;
|
|
1421
|
+
console.log("[SimpleAgent.processQueue] Finished");
|
|
1422
|
+
}
|
|
1423
|
+
async processMessage(message) {
|
|
1424
|
+
console.log("[SimpleAgent.processMessage] START, message:", message.id);
|
|
1425
|
+
let processedMessage = message;
|
|
1426
|
+
for (const middleware of this.middlewares) {
|
|
1427
|
+
let nextCalled = false;
|
|
1428
|
+
await middleware(processedMessage, async (msg) => {
|
|
1429
|
+
nextCalled = true;
|
|
1430
|
+
processedMessage = msg;
|
|
1431
|
+
});
|
|
1432
|
+
if (!nextCalled) {
|
|
1433
|
+
console.log("[SimpleAgent.processMessage] Middleware blocked message");
|
|
1434
|
+
return;
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
console.log("[SimpleAgent.processMessage] Getting driver stream...");
|
|
1438
|
+
const driverStream = this.driver.receive(processedMessage);
|
|
1439
|
+
console.log("[SimpleAgent.processMessage] Driver stream:", driverStream);
|
|
1440
|
+
try {
|
|
1441
|
+
console.log("[SimpleAgent.processMessage] Starting for-await loop...");
|
|
1442
|
+
for await (const streamEvent of driverStream) {
|
|
1443
|
+
this.handleStreamEvent(streamEvent);
|
|
1444
|
+
}
|
|
1445
|
+
console.log("[SimpleAgent.processMessage] For-await loop completed");
|
|
1446
|
+
} catch (error) {
|
|
1447
|
+
console.log("[SimpleAgent.processMessage] ERROR:", error);
|
|
1448
|
+
throw error;
|
|
1449
|
+
}
|
|
1450
|
+
console.log("[SimpleAgent.processMessage] END");
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* Handle a stream event from the driver (push-based API)
|
|
1454
|
+
*
|
|
1455
|
+
* This method processes a single StreamEvent through the MealyMachine
|
|
1456
|
+
* and emits all resulting outputs to presenter and handlers.
|
|
1457
|
+
*/
|
|
1458
|
+
handleStreamEvent(event) {
|
|
1459
|
+
logger5.info("handleStreamEvent", { type: event.type });
|
|
1460
|
+
const outputs = this.machine.process(this.agentId, event);
|
|
1461
|
+
logger5.info("MealyMachine outputs", {
|
|
1462
|
+
count: outputs.length,
|
|
1463
|
+
types: outputs.map((o) => o.type)
|
|
1464
|
+
});
|
|
1465
|
+
for (const output of outputs) {
|
|
1466
|
+
this.stateMachine.process(output);
|
|
1467
|
+
this.emitOutput(output);
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
emitOutput(output) {
|
|
1471
|
+
let currentOutput = output;
|
|
1472
|
+
const runInterceptor = (index, out) => {
|
|
1473
|
+
if (index >= this.interceptors.length) {
|
|
1474
|
+
currentOutput = out;
|
|
1475
|
+
return;
|
|
1476
|
+
}
|
|
1477
|
+
this.interceptors[index](out, (nextOut) => {
|
|
1478
|
+
runInterceptor(index + 1, nextOut);
|
|
1479
|
+
});
|
|
1480
|
+
};
|
|
1481
|
+
runInterceptor(0, output);
|
|
1482
|
+
if (!currentOutput) return;
|
|
1483
|
+
this.presenter.present(this.agentId, currentOutput);
|
|
1484
|
+
for (const handler of this.handlers) {
|
|
1485
|
+
try {
|
|
1486
|
+
handler(currentOutput);
|
|
1487
|
+
} catch (e) {
|
|
1488
|
+
console.error("Event handler error:", e);
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
const typeSet = this.typeHandlers.get(currentOutput.type);
|
|
1492
|
+
if (typeSet) {
|
|
1493
|
+
for (const handler of typeSet) {
|
|
1494
|
+
try {
|
|
1495
|
+
handler(currentOutput);
|
|
1496
|
+
} catch (e) {
|
|
1497
|
+
console.error("Event handler error:", e);
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
on(typeOrHandler, handler) {
|
|
1503
|
+
if (typeof typeOrHandler === "function") {
|
|
1504
|
+
this.handlers.add(typeOrHandler);
|
|
1505
|
+
return () => this.handlers.delete(typeOrHandler);
|
|
1506
|
+
}
|
|
1507
|
+
if (typeof typeOrHandler === "object" && !Array.isArray(typeOrHandler)) {
|
|
1508
|
+
const unsubscribes = [];
|
|
1509
|
+
for (const [type, h2] of Object.entries(typeOrHandler)) {
|
|
1510
|
+
if (h2) {
|
|
1511
|
+
unsubscribes.push(this.on(type, h2));
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
return () => unsubscribes.forEach((u) => u());
|
|
1515
|
+
}
|
|
1516
|
+
const types = Array.isArray(typeOrHandler) ? typeOrHandler : [typeOrHandler];
|
|
1517
|
+
const h = handler;
|
|
1518
|
+
for (const type of types) {
|
|
1519
|
+
if (!this.typeHandlers.has(type)) {
|
|
1520
|
+
this.typeHandlers.set(type, /* @__PURE__ */ new Set());
|
|
1521
|
+
}
|
|
1522
|
+
this.typeHandlers.get(type).add(h);
|
|
1523
|
+
}
|
|
1524
|
+
return () => {
|
|
1525
|
+
for (const type of types) {
|
|
1526
|
+
this.typeHandlers.get(type)?.delete(h);
|
|
1527
|
+
}
|
|
1528
|
+
};
|
|
1529
|
+
}
|
|
1530
|
+
onStateChange(handler) {
|
|
1531
|
+
return this.stateMachine.onStateChange(handler);
|
|
1532
|
+
}
|
|
1533
|
+
react(handlers) {
|
|
1534
|
+
const eventHandlerMap = {};
|
|
1535
|
+
for (const [key, handler] of Object.entries(handlers)) {
|
|
1536
|
+
if (handler && key.startsWith("on")) {
|
|
1537
|
+
const eventType = key.slice(2).replace(/([A-Z])/g, "_$1").toLowerCase().slice(1);
|
|
1538
|
+
eventHandlerMap[eventType] = handler;
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
return this.on(eventHandlerMap);
|
|
1542
|
+
}
|
|
1543
|
+
onReady(handler) {
|
|
1544
|
+
try {
|
|
1545
|
+
handler();
|
|
1546
|
+
} catch (e) {
|
|
1547
|
+
console.error("onReady handler error:", e);
|
|
1548
|
+
}
|
|
1549
|
+
this.readyHandlers.add(handler);
|
|
1550
|
+
return () => this.readyHandlers.delete(handler);
|
|
1551
|
+
}
|
|
1552
|
+
onDestroy(handler) {
|
|
1553
|
+
this.destroyHandlers.add(handler);
|
|
1554
|
+
return () => this.destroyHandlers.delete(handler);
|
|
1555
|
+
}
|
|
1556
|
+
use(middleware) {
|
|
1557
|
+
this.middlewares.push(middleware);
|
|
1558
|
+
return () => {
|
|
1559
|
+
const index = this.middlewares.indexOf(middleware);
|
|
1560
|
+
if (index >= 0) {
|
|
1561
|
+
this.middlewares.splice(index, 1);
|
|
1562
|
+
}
|
|
1563
|
+
};
|
|
1564
|
+
}
|
|
1565
|
+
intercept(interceptor) {
|
|
1566
|
+
this.interceptors.push(interceptor);
|
|
1567
|
+
return () => {
|
|
1568
|
+
const index = this.interceptors.indexOf(interceptor);
|
|
1569
|
+
if (index >= 0) {
|
|
1570
|
+
this.interceptors.splice(index, 1);
|
|
1571
|
+
}
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
interrupt() {
|
|
1575
|
+
if (this.state === "idle") {
|
|
1576
|
+
return;
|
|
1577
|
+
}
|
|
1578
|
+
this.driver.interrupt();
|
|
1579
|
+
}
|
|
1580
|
+
async destroy() {
|
|
1581
|
+
if (this.state !== "idle") {
|
|
1582
|
+
this.interrupt();
|
|
1583
|
+
}
|
|
1584
|
+
for (const handler of this.destroyHandlers) {
|
|
1585
|
+
try {
|
|
1586
|
+
handler();
|
|
1587
|
+
} catch (e) {
|
|
1588
|
+
console.error("onDestroy handler error:", e);
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
this.machine.clearState(this.agentId);
|
|
1592
|
+
this.stateMachine.reset();
|
|
1593
|
+
this._messageQueue.clear();
|
|
1594
|
+
this.handlers.clear();
|
|
1595
|
+
this.typeHandlers.clear();
|
|
1596
|
+
this.readyHandlers.clear();
|
|
1597
|
+
this.destroyHandlers.clear();
|
|
1598
|
+
this.middlewares.length = 0;
|
|
1599
|
+
this.interceptors.length = 0;
|
|
1600
|
+
}
|
|
1601
|
+
};
|
|
1602
|
+
function createAgent(options) {
|
|
1603
|
+
return new SimpleAgent(options);
|
|
1604
|
+
}
|
|
443
1605
|
|
|
444
1606
|
// src/environment/ClaudeReceptor.ts
|
|
445
|
-
|
|
446
|
-
var logger4 = createLogger4("ecosystem/ClaudeReceptor");
|
|
1607
|
+
var logger6 = createLogger("ecosystem/ClaudeReceptor");
|
|
447
1608
|
var ClaudeReceptor = class {
|
|
448
1609
|
producer = null;
|
|
449
1610
|
currentMeta = null;
|
|
@@ -461,7 +1622,7 @@ var ClaudeReceptor = class {
|
|
|
461
1622
|
*/
|
|
462
1623
|
connect(producer) {
|
|
463
1624
|
this.producer = producer;
|
|
464
|
-
|
|
1625
|
+
logger6.debug("ClaudeReceptor connected to SystemBusProducer");
|
|
465
1626
|
}
|
|
466
1627
|
/**
|
|
467
1628
|
* Feed SDK message to receptor with correlation metadata
|
|
@@ -579,7 +1740,7 @@ var ClaudeReceptor = class {
|
|
|
579
1740
|
case "content_block_start": {
|
|
580
1741
|
const contentBlock = event.content_block;
|
|
581
1742
|
this.blockContext.currentBlockIndex = event.index;
|
|
582
|
-
|
|
1743
|
+
logger6.debug("content_block_start received", { contentBlock, index: event.index });
|
|
583
1744
|
if (contentBlock.type === "text") {
|
|
584
1745
|
this.blockContext.currentBlockType = "text";
|
|
585
1746
|
this.emitToBus({
|
|
@@ -716,7 +1877,6 @@ var ClaudeReceptor = class {
|
|
|
716
1877
|
// src/environment/ClaudeEffector.ts
|
|
717
1878
|
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
718
1879
|
import { Subject as Subject2 } from "rxjs";
|
|
719
|
-
import { createLogger as createLogger5 } from "@agentxjs/common";
|
|
720
1880
|
|
|
721
1881
|
// src/environment/buildOptions.ts
|
|
722
1882
|
function buildOptions(context, abortController) {
|
|
@@ -835,7 +1995,7 @@ async function* observableToAsyncIterable(observable) {
|
|
|
835
1995
|
}
|
|
836
1996
|
|
|
837
1997
|
// src/environment/ClaudeEffector.ts
|
|
838
|
-
var
|
|
1998
|
+
var logger7 = createLogger("ecosystem/ClaudeEffector");
|
|
839
1999
|
var DEFAULT_TIMEOUT = 3e4;
|
|
840
2000
|
var ClaudeEffector = class {
|
|
841
2001
|
config;
|
|
@@ -854,12 +2014,12 @@ var ClaudeEffector = class {
|
|
|
854
2014
|
* Connect to SystemBus consumer to subscribe to events
|
|
855
2015
|
*/
|
|
856
2016
|
connect(consumer) {
|
|
857
|
-
|
|
2017
|
+
logger7.debug("ClaudeEffector connected to SystemBusConsumer", {
|
|
858
2018
|
agentId: this.config.agentId
|
|
859
2019
|
});
|
|
860
2020
|
consumer.on("user_message", async (event) => {
|
|
861
2021
|
const typedEvent = event;
|
|
862
|
-
|
|
2022
|
+
logger7.debug("user_message event received", {
|
|
863
2023
|
eventAgentId: typedEvent.context?.agentId,
|
|
864
2024
|
myAgentId: this.config.agentId,
|
|
865
2025
|
matches: typedEvent.context?.agentId === this.config.agentId
|
|
@@ -895,14 +2055,14 @@ var ClaudeEffector = class {
|
|
|
895
2055
|
this.currentMeta = meta;
|
|
896
2056
|
const timeout = this.config.timeout ?? DEFAULT_TIMEOUT;
|
|
897
2057
|
const timeoutId = setTimeout(() => {
|
|
898
|
-
|
|
2058
|
+
logger7.warn("Request timeout", { timeout });
|
|
899
2059
|
this.currentAbortController?.abort(new Error(`Request timeout after ${timeout}ms`));
|
|
900
2060
|
}, timeout);
|
|
901
2061
|
try {
|
|
902
2062
|
await this.initialize(this.currentAbortController);
|
|
903
2063
|
const sessionId = this.config.sessionId || "default";
|
|
904
2064
|
const sdkUserMessage = buildSDKUserMessage(message, sessionId);
|
|
905
|
-
|
|
2065
|
+
logger7.debug("Sending message to Claude", {
|
|
906
2066
|
content: typeof message.content === "string" ? message.content.substring(0, 80) : "[structured]",
|
|
907
2067
|
timeout,
|
|
908
2068
|
requestId: meta.requestId
|
|
@@ -919,13 +2079,13 @@ var ClaudeEffector = class {
|
|
|
919
2079
|
*/
|
|
920
2080
|
interrupt(meta) {
|
|
921
2081
|
if (this.claudeQuery) {
|
|
922
|
-
|
|
2082
|
+
logger7.debug("Interrupting Claude query", { requestId: meta?.requestId });
|
|
923
2083
|
this.wasInterrupted = true;
|
|
924
2084
|
if (meta) {
|
|
925
2085
|
this.currentMeta = meta;
|
|
926
2086
|
}
|
|
927
2087
|
this.claudeQuery.interrupt().catch((err) => {
|
|
928
|
-
|
|
2088
|
+
logger7.debug("SDK interrupt() error (may be expected)", { error: err });
|
|
929
2089
|
});
|
|
930
2090
|
}
|
|
931
2091
|
}
|
|
@@ -934,7 +2094,7 @@ var ClaudeEffector = class {
|
|
|
934
2094
|
*/
|
|
935
2095
|
async initialize(abortController) {
|
|
936
2096
|
if (this.isInitialized) return;
|
|
937
|
-
|
|
2097
|
+
logger7.info("Initializing ClaudeEffector");
|
|
938
2098
|
const context = {
|
|
939
2099
|
apiKey: this.config.apiKey,
|
|
940
2100
|
baseUrl: this.config.baseUrl,
|
|
@@ -951,7 +2111,7 @@ var ClaudeEffector = class {
|
|
|
951
2111
|
});
|
|
952
2112
|
this.isInitialized = true;
|
|
953
2113
|
this.startBackgroundListener();
|
|
954
|
-
|
|
2114
|
+
logger7.info("ClaudeEffector initialized");
|
|
955
2115
|
}
|
|
956
2116
|
/**
|
|
957
2117
|
* Start background listener for SDK responses
|
|
@@ -960,7 +2120,7 @@ var ClaudeEffector = class {
|
|
|
960
2120
|
(async () => {
|
|
961
2121
|
try {
|
|
962
2122
|
for await (const sdkMsg of this.claudeQuery) {
|
|
963
|
-
|
|
2123
|
+
logger7.debug("SDK message received", {
|
|
964
2124
|
type: sdkMsg.type,
|
|
965
2125
|
subtype: sdkMsg.subtype,
|
|
966
2126
|
sessionId: sdkMsg.session_id,
|
|
@@ -977,10 +2137,10 @@ var ClaudeEffector = class {
|
|
|
977
2137
|
}
|
|
978
2138
|
if (sdkMsg.type === "result") {
|
|
979
2139
|
const resultMsg = sdkMsg;
|
|
980
|
-
|
|
2140
|
+
logger7.info("SDK result received (full)", {
|
|
981
2141
|
fullResult: JSON.stringify(sdkMsg, null, 2)
|
|
982
2142
|
});
|
|
983
|
-
|
|
2143
|
+
logger7.info("SDK result received", {
|
|
984
2144
|
subtype: resultMsg.subtype,
|
|
985
2145
|
isError: resultMsg.is_error,
|
|
986
2146
|
errors: resultMsg.errors,
|
|
@@ -998,10 +2158,10 @@ var ClaudeEffector = class {
|
|
|
998
2158
|
}
|
|
999
2159
|
} catch (error) {
|
|
1000
2160
|
if (this.isAbortError(error)) {
|
|
1001
|
-
|
|
2161
|
+
logger7.debug("Background listener aborted (expected during interrupt)");
|
|
1002
2162
|
this.resetState();
|
|
1003
2163
|
} else {
|
|
1004
|
-
|
|
2164
|
+
logger7.error("Background listener error", { error });
|
|
1005
2165
|
if (this.currentMeta) {
|
|
1006
2166
|
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
|
|
1007
2167
|
this.receptor.emitError(errorMessage, "runtime_error", this.currentMeta);
|
|
@@ -1033,7 +2193,7 @@ var ClaudeEffector = class {
|
|
|
1033
2193
|
* Dispose and cleanup resources
|
|
1034
2194
|
*/
|
|
1035
2195
|
dispose() {
|
|
1036
|
-
|
|
2196
|
+
logger7.debug("Disposing ClaudeEffector");
|
|
1037
2197
|
if (this.currentAbortController) {
|
|
1038
2198
|
this.currentAbortController.abort();
|
|
1039
2199
|
}
|
|
@@ -1064,7 +2224,7 @@ var ClaudeEnvironment = class {
|
|
|
1064
2224
|
};
|
|
1065
2225
|
|
|
1066
2226
|
// src/internal/RuntimeAgent.ts
|
|
1067
|
-
var
|
|
2227
|
+
var logger8 = createLogger("runtime/RuntimeAgent");
|
|
1068
2228
|
var BusPresenter = class {
|
|
1069
2229
|
constructor(producer, session, agentId, imageId, containerId) {
|
|
1070
2230
|
this.producer = producer;
|
|
@@ -1101,7 +2261,7 @@ var BusPresenter = class {
|
|
|
1101
2261
|
this.producer.emit(systemEvent);
|
|
1102
2262
|
if (category === "message") {
|
|
1103
2263
|
this.session.addMessage(data).catch((err) => {
|
|
1104
|
-
|
|
2264
|
+
logger8.error("Failed to persist message", { error: err, messageType: output.type });
|
|
1105
2265
|
});
|
|
1106
2266
|
}
|
|
1107
2267
|
}
|
|
@@ -1159,7 +2319,7 @@ var BusPresenter = class {
|
|
|
1159
2319
|
};
|
|
1160
2320
|
}
|
|
1161
2321
|
default:
|
|
1162
|
-
|
|
2322
|
+
logger8.warn("Unknown message type, passing through", { type: output.type });
|
|
1163
2323
|
return eventData;
|
|
1164
2324
|
}
|
|
1165
2325
|
}
|
|
@@ -1219,7 +2379,7 @@ var RuntimeAgent = class {
|
|
|
1219
2379
|
});
|
|
1220
2380
|
this.environment.receptor.connect(config.bus.asProducer());
|
|
1221
2381
|
this.environment.effector.connect(config.bus.asConsumer());
|
|
1222
|
-
|
|
2382
|
+
logger8.info("ClaudeEnvironment created for agent", {
|
|
1223
2383
|
agentId: this.agentId,
|
|
1224
2384
|
imageId: this.imageId,
|
|
1225
2385
|
resumeSessionId: resumeSessionId ?? "none",
|
|
@@ -1253,14 +2413,14 @@ var RuntimeAgent = class {
|
|
|
1253
2413
|
this.driver = new BusDriver(config.bus.asConsumer(), {
|
|
1254
2414
|
agentId: this.agentId,
|
|
1255
2415
|
onStreamEvent: (event) => {
|
|
1256
|
-
|
|
2416
|
+
logger8.debug("BusDriver \u2192 Engine.handleStreamEvent", { type: event.type });
|
|
1257
2417
|
this.engine.handleStreamEvent(event);
|
|
1258
2418
|
},
|
|
1259
2419
|
onStreamComplete: (reason) => {
|
|
1260
|
-
|
|
2420
|
+
logger8.debug("Stream completed", { reason, agentId: this.agentId });
|
|
1261
2421
|
}
|
|
1262
2422
|
});
|
|
1263
|
-
|
|
2423
|
+
logger8.debug("RuntimeAgent created", {
|
|
1264
2424
|
agentId: this.agentId,
|
|
1265
2425
|
imageId: this.imageId
|
|
1266
2426
|
});
|
|
@@ -1269,13 +2429,13 @@ var RuntimeAgent = class {
|
|
|
1269
2429
|
* Save SDK session ID to image metadata for future resume
|
|
1270
2430
|
*/
|
|
1271
2431
|
saveSessionId(sdkSessionId) {
|
|
1272
|
-
|
|
2432
|
+
logger8.info("Saving SDK session ID to image metadata", {
|
|
1273
2433
|
agentId: this.agentId,
|
|
1274
2434
|
imageId: this.imageId,
|
|
1275
2435
|
sdkSessionId
|
|
1276
2436
|
});
|
|
1277
2437
|
this.imageRepository.updateMetadata(this.imageId, { claudeSdkSessionId: sdkSessionId }).catch((err) => {
|
|
1278
|
-
|
|
2438
|
+
logger8.error("Failed to save SDK session ID", { error: err, imageId: this.imageId });
|
|
1279
2439
|
});
|
|
1280
2440
|
}
|
|
1281
2441
|
get lifecycle() {
|
|
@@ -1288,7 +2448,7 @@ var RuntimeAgent = class {
|
|
|
1288
2448
|
* @param requestId - Request ID for correlation
|
|
1289
2449
|
*/
|
|
1290
2450
|
async receive(content, requestId) {
|
|
1291
|
-
|
|
2451
|
+
logger8.debug("RuntimeAgent.receive called", {
|
|
1292
2452
|
agentId: this.agentId,
|
|
1293
2453
|
contentPreview: content.substring(0, 50),
|
|
1294
2454
|
requestId
|
|
@@ -1297,13 +2457,13 @@ var RuntimeAgent = class {
|
|
|
1297
2457
|
throw new Error(`Cannot send message to ${this._lifecycle} agent`);
|
|
1298
2458
|
}
|
|
1299
2459
|
await this.interactor.receive(content, requestId || `req_${Date.now()}`);
|
|
1300
|
-
|
|
2460
|
+
logger8.debug("RuntimeAgent.receive completed", { agentId: this.agentId });
|
|
1301
2461
|
}
|
|
1302
2462
|
/**
|
|
1303
2463
|
* Interrupt current operation
|
|
1304
2464
|
*/
|
|
1305
2465
|
interrupt(requestId) {
|
|
1306
|
-
|
|
2466
|
+
logger8.debug("RuntimeAgent.interrupt called", { agentId: this.agentId, requestId });
|
|
1307
2467
|
this.interactor.interrupt(requestId);
|
|
1308
2468
|
this.producer.emit({
|
|
1309
2469
|
type: "interrupted",
|
|
@@ -1498,8 +2658,7 @@ var RuntimeSandbox = class {
|
|
|
1498
2658
|
};
|
|
1499
2659
|
|
|
1500
2660
|
// src/internal/RuntimeImage.ts
|
|
1501
|
-
|
|
1502
|
-
var logger7 = createLogger7("runtime/RuntimeImage");
|
|
2661
|
+
var logger9 = createLogger("runtime/RuntimeImage");
|
|
1503
2662
|
var RuntimeImage = class _RuntimeImage {
|
|
1504
2663
|
constructor(record, context) {
|
|
1505
2664
|
this.record = record;
|
|
@@ -1556,7 +2715,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
1556
2715
|
createdAt: now,
|
|
1557
2716
|
updatedAt: now
|
|
1558
2717
|
});
|
|
1559
|
-
|
|
2718
|
+
logger9.info("Image created", {
|
|
1560
2719
|
imageId,
|
|
1561
2720
|
sessionId,
|
|
1562
2721
|
containerId: config.containerId,
|
|
@@ -1570,10 +2729,10 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
1570
2729
|
static async load(imageId, context) {
|
|
1571
2730
|
const record = await context.imageRepository.findImageById(imageId);
|
|
1572
2731
|
if (!record) {
|
|
1573
|
-
|
|
2732
|
+
logger9.debug("Image not found", { imageId });
|
|
1574
2733
|
return null;
|
|
1575
2734
|
}
|
|
1576
|
-
|
|
2735
|
+
logger9.debug("Image loaded", { imageId, name: record.name });
|
|
1577
2736
|
return new _RuntimeImage(record, context);
|
|
1578
2737
|
}
|
|
1579
2738
|
/**
|
|
@@ -1607,7 +2766,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
1607
2766
|
updatedAt: now
|
|
1608
2767
|
};
|
|
1609
2768
|
await this.context.imageRepository.saveImage(updatedRecord);
|
|
1610
|
-
|
|
2769
|
+
logger9.info("Image updated", { imageId: this.imageId, updates });
|
|
1611
2770
|
return new _RuntimeImage(updatedRecord, this.context);
|
|
1612
2771
|
}
|
|
1613
2772
|
/**
|
|
@@ -1616,7 +2775,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
1616
2775
|
async delete() {
|
|
1617
2776
|
await this.context.sessionRepository.deleteSession(this.sessionId);
|
|
1618
2777
|
await this.context.imageRepository.deleteImage(this.imageId);
|
|
1619
|
-
|
|
2778
|
+
logger9.info("Image deleted", { imageId: this.imageId, sessionId: this.sessionId });
|
|
1620
2779
|
}
|
|
1621
2780
|
/**
|
|
1622
2781
|
* Get the underlying record
|
|
@@ -1638,8 +2797,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
1638
2797
|
};
|
|
1639
2798
|
|
|
1640
2799
|
// src/internal/RuntimeContainer.ts
|
|
1641
|
-
|
|
1642
|
-
var logger8 = createLogger8("runtime/RuntimeContainer");
|
|
2800
|
+
var logger10 = createLogger("runtime/RuntimeContainer");
|
|
1643
2801
|
var RuntimeContainer = class _RuntimeContainer {
|
|
1644
2802
|
containerId;
|
|
1645
2803
|
createdAt;
|
|
@@ -1679,7 +2837,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1679
2837
|
containerId
|
|
1680
2838
|
}
|
|
1681
2839
|
});
|
|
1682
|
-
|
|
2840
|
+
logger10.info("Container created", { containerId });
|
|
1683
2841
|
return container;
|
|
1684
2842
|
}
|
|
1685
2843
|
/**
|
|
@@ -1688,7 +2846,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1688
2846
|
static async load(containerId, context) {
|
|
1689
2847
|
const record = await context.persistence.containers.findContainerById(containerId);
|
|
1690
2848
|
if (!record) return null;
|
|
1691
|
-
|
|
2849
|
+
logger10.info("Container loaded", { containerId });
|
|
1692
2850
|
return new _RuntimeContainer(containerId, record.createdAt, context);
|
|
1693
2851
|
}
|
|
1694
2852
|
// ==================== Image → Agent Lifecycle ====================
|
|
@@ -1701,7 +2859,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1701
2859
|
if (existingAgentId) {
|
|
1702
2860
|
const existingAgent = this.agents.get(existingAgentId);
|
|
1703
2861
|
if (existingAgent) {
|
|
1704
|
-
|
|
2862
|
+
logger10.info("Reusing existing agent for image", {
|
|
1705
2863
|
containerId: this.containerId,
|
|
1706
2864
|
imageId: image.imageId,
|
|
1707
2865
|
agentId: existingAgentId
|
|
@@ -1760,7 +2918,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1760
2918
|
agentId
|
|
1761
2919
|
}
|
|
1762
2920
|
});
|
|
1763
|
-
|
|
2921
|
+
logger10.info("Agent created for image", {
|
|
1764
2922
|
containerId: this.containerId,
|
|
1765
2923
|
imageId: image.imageId,
|
|
1766
2924
|
agentId
|
|
@@ -1773,17 +2931,17 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1773
2931
|
async stopImage(imageId) {
|
|
1774
2932
|
const agentId = this.imageToAgent.get(imageId);
|
|
1775
2933
|
if (!agentId) {
|
|
1776
|
-
|
|
2934
|
+
logger10.debug("Image not running, nothing to stop", {
|
|
1777
2935
|
imageId,
|
|
1778
2936
|
containerId: this.containerId
|
|
1779
2937
|
});
|
|
1780
2938
|
return false;
|
|
1781
2939
|
}
|
|
1782
|
-
|
|
2940
|
+
logger10.info("Stopping image", { imageId, agentId, containerId: this.containerId });
|
|
1783
2941
|
const success = await this.destroyAgent(agentId);
|
|
1784
2942
|
if (success) {
|
|
1785
2943
|
this.imageToAgent.delete(imageId);
|
|
1786
|
-
|
|
2944
|
+
logger10.info("Image stopped", { imageId, agentId, containerId: this.containerId });
|
|
1787
2945
|
}
|
|
1788
2946
|
return success;
|
|
1789
2947
|
}
|
|
@@ -1840,7 +2998,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1840
2998
|
agentId
|
|
1841
2999
|
}
|
|
1842
3000
|
});
|
|
1843
|
-
|
|
3001
|
+
logger10.info("Agent destroyed", { containerId: this.containerId, agentId });
|
|
1844
3002
|
return true;
|
|
1845
3003
|
}
|
|
1846
3004
|
async destroyAllAgents() {
|
|
@@ -1868,7 +3026,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1868
3026
|
}
|
|
1869
3027
|
});
|
|
1870
3028
|
this.context.onDisposed?.(this.containerId);
|
|
1871
|
-
|
|
3029
|
+
logger10.info("Container disposed", { containerId: this.containerId, agentCount });
|
|
1872
3030
|
}
|
|
1873
3031
|
// ==================== Private Helpers ====================
|
|
1874
3032
|
generateAgentId() {
|
|
@@ -1879,8 +3037,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
1879
3037
|
};
|
|
1880
3038
|
|
|
1881
3039
|
// src/internal/BaseEventHandler.ts
|
|
1882
|
-
|
|
1883
|
-
var logger9 = createLogger9("runtime/BaseEventHandler");
|
|
3040
|
+
var logger11 = createLogger("runtime/BaseEventHandler");
|
|
1884
3041
|
var BaseEventHandler = class {
|
|
1885
3042
|
bus;
|
|
1886
3043
|
unsubscribes = [];
|
|
@@ -1919,7 +3076,7 @@ var BaseEventHandler = class {
|
|
|
1919
3076
|
handleError(err, context) {
|
|
1920
3077
|
const message = err instanceof Error ? err.message : String(err);
|
|
1921
3078
|
const stack = err instanceof Error ? err.stack : void 0;
|
|
1922
|
-
|
|
3079
|
+
logger11.error(`Error in ${context.operation || "handler"}`, {
|
|
1923
3080
|
message,
|
|
1924
3081
|
requestId: context.requestId,
|
|
1925
3082
|
details: context.details
|
|
@@ -1946,7 +3103,7 @@ var BaseEventHandler = class {
|
|
|
1946
3103
|
try {
|
|
1947
3104
|
context.onError(err);
|
|
1948
3105
|
} catch (callbackErr) {
|
|
1949
|
-
|
|
3106
|
+
logger11.error("Error in onError callback", { error: callbackErr });
|
|
1950
3107
|
}
|
|
1951
3108
|
}
|
|
1952
3109
|
}
|
|
@@ -1964,13 +3121,12 @@ var BaseEventHandler = class {
|
|
|
1964
3121
|
unsubscribe();
|
|
1965
3122
|
}
|
|
1966
3123
|
this.unsubscribes = [];
|
|
1967
|
-
|
|
3124
|
+
logger11.debug(`${this.constructor.name} disposed`);
|
|
1968
3125
|
}
|
|
1969
3126
|
};
|
|
1970
3127
|
|
|
1971
3128
|
// src/internal/CommandHandler.ts
|
|
1972
|
-
|
|
1973
|
-
var logger10 = createLogger10("runtime/CommandHandler");
|
|
3129
|
+
var logger12 = createLogger("runtime/CommandHandler");
|
|
1974
3130
|
function createResponse(type, data) {
|
|
1975
3131
|
return {
|
|
1976
3132
|
type,
|
|
@@ -2003,7 +3159,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2003
3159
|
super(bus);
|
|
2004
3160
|
this.ops = operations;
|
|
2005
3161
|
this.bindHandlers();
|
|
2006
|
-
|
|
3162
|
+
logger12.debug("CommandHandler created");
|
|
2007
3163
|
}
|
|
2008
3164
|
/**
|
|
2009
3165
|
* Log error and emit system_error event
|
|
@@ -2011,7 +3167,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2011
3167
|
emitError(operation, err, requestId, context) {
|
|
2012
3168
|
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
2013
3169
|
const stack = err instanceof Error ? err.stack : void 0;
|
|
2014
|
-
|
|
3170
|
+
logger12.error(operation, {
|
|
2015
3171
|
requestId,
|
|
2016
3172
|
...context,
|
|
2017
3173
|
error: errorMessage,
|
|
@@ -2068,12 +3224,12 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2068
3224
|
this.subscribe(
|
|
2069
3225
|
this.bus.onCommand("image_messages_request", (event) => this.handleImageMessages(event))
|
|
2070
3226
|
);
|
|
2071
|
-
|
|
3227
|
+
logger12.debug("Command handlers bound");
|
|
2072
3228
|
}
|
|
2073
3229
|
// ==================== Container Handlers ====================
|
|
2074
3230
|
async handleContainerCreate(event) {
|
|
2075
3231
|
const { requestId, containerId } = event.data;
|
|
2076
|
-
|
|
3232
|
+
logger12.debug("Handling container_create_request", { requestId, containerId });
|
|
2077
3233
|
try {
|
|
2078
3234
|
await this.ops.createContainer(containerId);
|
|
2079
3235
|
this.bus.emit(
|
|
@@ -2095,7 +3251,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2095
3251
|
}
|
|
2096
3252
|
handleContainerGet(event) {
|
|
2097
3253
|
const { requestId, containerId } = event.data;
|
|
2098
|
-
|
|
3254
|
+
logger12.debug("Handling container_get_request", { requestId, containerId });
|
|
2099
3255
|
const container = this.ops.getContainer(containerId);
|
|
2100
3256
|
this.bus.emit(
|
|
2101
3257
|
createResponse("container_get_response", {
|
|
@@ -2107,7 +3263,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2107
3263
|
}
|
|
2108
3264
|
handleContainerList(event) {
|
|
2109
3265
|
const { requestId } = event.data;
|
|
2110
|
-
|
|
3266
|
+
logger12.debug("Handling container_list_request", { requestId });
|
|
2111
3267
|
const containers = this.ops.listContainers();
|
|
2112
3268
|
this.bus.emit(
|
|
2113
3269
|
createResponse("container_list_response", {
|
|
@@ -2119,7 +3275,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2119
3275
|
// ==================== Agent Handlers ====================
|
|
2120
3276
|
handleAgentGet(event) {
|
|
2121
3277
|
const { requestId, agentId } = event.data;
|
|
2122
|
-
|
|
3278
|
+
logger12.debug("Handling agent_get_request", { requestId, agentId });
|
|
2123
3279
|
const agent = this.ops.getAgent(agentId);
|
|
2124
3280
|
this.bus.emit(
|
|
2125
3281
|
createResponse("agent_get_response", {
|
|
@@ -2132,7 +3288,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2132
3288
|
}
|
|
2133
3289
|
handleAgentList(event) {
|
|
2134
3290
|
const { requestId, containerId } = event.data;
|
|
2135
|
-
|
|
3291
|
+
logger12.debug("Handling agent_list_request", { requestId, containerId });
|
|
2136
3292
|
const agents = this.ops.listAgents(containerId);
|
|
2137
3293
|
this.bus.emit(
|
|
2138
3294
|
createResponse("agent_list_response", {
|
|
@@ -2147,7 +3303,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2147
3303
|
}
|
|
2148
3304
|
async handleAgentDestroy(event) {
|
|
2149
3305
|
const { requestId, agentId } = event.data;
|
|
2150
|
-
|
|
3306
|
+
logger12.debug("Handling agent_destroy_request", { requestId, agentId });
|
|
2151
3307
|
try {
|
|
2152
3308
|
const success = await this.ops.destroyAgent(agentId);
|
|
2153
3309
|
this.bus.emit(
|
|
@@ -2171,7 +3327,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2171
3327
|
}
|
|
2172
3328
|
async handleAgentDestroyAll(event) {
|
|
2173
3329
|
const { requestId, containerId } = event.data;
|
|
2174
|
-
|
|
3330
|
+
logger12.debug("Handling agent_destroy_all_request", { requestId, containerId });
|
|
2175
3331
|
try {
|
|
2176
3332
|
await this.ops.destroyAllAgents(containerId);
|
|
2177
3333
|
this.bus.emit(
|
|
@@ -2193,7 +3349,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2193
3349
|
}
|
|
2194
3350
|
async handleMessageSend(event) {
|
|
2195
3351
|
const { requestId, imageId, agentId, content } = event.data;
|
|
2196
|
-
|
|
3352
|
+
logger12.debug("Handling message_send_request", { requestId, imageId, agentId });
|
|
2197
3353
|
try {
|
|
2198
3354
|
const result = await this.ops.receiveMessage(imageId, agentId, content, requestId);
|
|
2199
3355
|
this.bus.emit(
|
|
@@ -2217,7 +3373,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2217
3373
|
}
|
|
2218
3374
|
handleAgentInterrupt(event) {
|
|
2219
3375
|
const { requestId, imageId, agentId } = event.data;
|
|
2220
|
-
|
|
3376
|
+
logger12.debug("Handling agent_interrupt_request", { requestId, imageId, agentId });
|
|
2221
3377
|
try {
|
|
2222
3378
|
const result = this.ops.interruptAgent(imageId, agentId, requestId);
|
|
2223
3379
|
this.bus.emit(
|
|
@@ -2242,7 +3398,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2242
3398
|
// ==================== Image Handlers ====================
|
|
2243
3399
|
async handleImageCreate(event) {
|
|
2244
3400
|
const { requestId, containerId, config } = event.data;
|
|
2245
|
-
|
|
3401
|
+
logger12.debug("Handling image_create_request", { requestId, containerId });
|
|
2246
3402
|
try {
|
|
2247
3403
|
const record = await this.ops.createImage(containerId, config);
|
|
2248
3404
|
this.bus.emit(
|
|
@@ -2264,7 +3420,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2264
3420
|
}
|
|
2265
3421
|
async handleImageRun(event) {
|
|
2266
3422
|
const { requestId, imageId } = event.data;
|
|
2267
|
-
|
|
3423
|
+
logger12.debug("Handling image_run_request", { requestId, imageId });
|
|
2268
3424
|
try {
|
|
2269
3425
|
const result = await this.ops.runImage(imageId);
|
|
2270
3426
|
this.bus.emit(
|
|
@@ -2290,7 +3446,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2290
3446
|
}
|
|
2291
3447
|
async handleImageStop(event) {
|
|
2292
3448
|
const { requestId, imageId } = event.data;
|
|
2293
|
-
|
|
3449
|
+
logger12.debug("Handling image_stop_request", { requestId, imageId });
|
|
2294
3450
|
try {
|
|
2295
3451
|
await this.ops.stopImage(imageId);
|
|
2296
3452
|
this.bus.emit(
|
|
@@ -2312,7 +3468,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2312
3468
|
}
|
|
2313
3469
|
async handleImageUpdate(event) {
|
|
2314
3470
|
const { requestId, imageId, updates } = event.data;
|
|
2315
|
-
|
|
3471
|
+
logger12.debug("Handling image_update_request", { requestId, imageId });
|
|
2316
3472
|
try {
|
|
2317
3473
|
const record = await this.ops.updateImage(imageId, updates);
|
|
2318
3474
|
this.bus.emit(
|
|
@@ -2334,7 +3490,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2334
3490
|
}
|
|
2335
3491
|
async handleImageList(event) {
|
|
2336
3492
|
const { requestId, containerId } = event.data;
|
|
2337
|
-
|
|
3493
|
+
logger12.debug("Handling image_list_request", { requestId, containerId });
|
|
2338
3494
|
try {
|
|
2339
3495
|
const images = await this.ops.listImages(containerId);
|
|
2340
3496
|
this.bus.emit(
|
|
@@ -2356,7 +3512,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2356
3512
|
}
|
|
2357
3513
|
async handleImageGet(event) {
|
|
2358
3514
|
const { requestId, imageId } = event.data;
|
|
2359
|
-
|
|
3515
|
+
logger12.debug("Handling image_get_request", { requestId, imageId });
|
|
2360
3516
|
try {
|
|
2361
3517
|
const image = await this.ops.getImage(imageId);
|
|
2362
3518
|
this.bus.emit(
|
|
@@ -2377,7 +3533,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2377
3533
|
}
|
|
2378
3534
|
async handleImageDelete(event) {
|
|
2379
3535
|
const { requestId, imageId } = event.data;
|
|
2380
|
-
|
|
3536
|
+
logger12.debug("Handling image_delete_request", { requestId, imageId });
|
|
2381
3537
|
try {
|
|
2382
3538
|
await this.ops.deleteImage(imageId);
|
|
2383
3539
|
this.bus.emit(
|
|
@@ -2399,10 +3555,10 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2399
3555
|
}
|
|
2400
3556
|
async handleImageMessages(event) {
|
|
2401
3557
|
const { requestId, imageId } = event.data;
|
|
2402
|
-
|
|
3558
|
+
logger12.info("Handling image_messages_request", { requestId, imageId });
|
|
2403
3559
|
try {
|
|
2404
3560
|
const messages = await this.ops.getImageMessages(imageId);
|
|
2405
|
-
|
|
3561
|
+
logger12.info("Got messages for image", { imageId, count: messages.length });
|
|
2406
3562
|
this.bus.emit(
|
|
2407
3563
|
createResponse("image_messages_response", {
|
|
2408
3564
|
requestId,
|
|
@@ -2410,7 +3566,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2410
3566
|
messages
|
|
2411
3567
|
})
|
|
2412
3568
|
);
|
|
2413
|
-
|
|
3569
|
+
logger12.info("Emitted image_messages_response", { requestId, imageId });
|
|
2414
3570
|
} catch (err) {
|
|
2415
3571
|
this.emitError("Failed to get image messages", err, requestId, { imageId });
|
|
2416
3572
|
this.bus.emit(
|
|
@@ -2427,10 +3583,9 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
2427
3583
|
};
|
|
2428
3584
|
|
|
2429
3585
|
// src/RuntimeImpl.ts
|
|
2430
|
-
import { createLogger as createLogger11 } from "@agentxjs/common";
|
|
2431
3586
|
import { homedir } from "os";
|
|
2432
3587
|
import { join as join2 } from "path";
|
|
2433
|
-
var
|
|
3588
|
+
var logger13 = createLogger("runtime/RuntimeImpl");
|
|
2434
3589
|
var RuntimeImpl = class {
|
|
2435
3590
|
persistence;
|
|
2436
3591
|
llmProvider;
|
|
@@ -2441,20 +3596,20 @@ var RuntimeImpl = class {
|
|
|
2441
3596
|
/** Container registry: containerId -> RuntimeContainer */
|
|
2442
3597
|
containerRegistry = /* @__PURE__ */ new Map();
|
|
2443
3598
|
constructor(config) {
|
|
2444
|
-
|
|
3599
|
+
logger13.info("RuntimeImpl constructor start");
|
|
2445
3600
|
this.persistence = config.persistence;
|
|
2446
3601
|
this.llmProvider = config.llmProvider;
|
|
2447
3602
|
this.basePath = join2(homedir(), ".agentx");
|
|
2448
|
-
|
|
3603
|
+
logger13.info("Creating SystemBus");
|
|
2449
3604
|
this.bus = new SystemBusImpl();
|
|
2450
3605
|
this.llmConfig = this.llmProvider.provide();
|
|
2451
|
-
|
|
3606
|
+
logger13.info("LLM config loaded", {
|
|
2452
3607
|
hasApiKey: !!this.llmConfig.apiKey,
|
|
2453
3608
|
model: this.llmConfig.model
|
|
2454
3609
|
});
|
|
2455
|
-
|
|
3610
|
+
logger13.info("Creating CommandHandler");
|
|
2456
3611
|
this.commandHandler = new CommandHandler(this.bus, this.createRuntimeOperations());
|
|
2457
|
-
|
|
3612
|
+
logger13.info("RuntimeImpl constructor done");
|
|
2458
3613
|
}
|
|
2459
3614
|
// ==================== SystemBus delegation ====================
|
|
2460
3615
|
emit(event) {
|
|
@@ -2537,7 +3692,7 @@ var RuntimeImpl = class {
|
|
|
2537
3692
|
// Agent operations (by imageId - with auto-activation)
|
|
2538
3693
|
receiveMessage: async (imageId, agentId, content, requestId) => {
|
|
2539
3694
|
if (imageId) {
|
|
2540
|
-
|
|
3695
|
+
logger13.debug("Receiving message by imageId", {
|
|
2541
3696
|
imageId,
|
|
2542
3697
|
contentLength: content.length,
|
|
2543
3698
|
requestId
|
|
@@ -2546,7 +3701,7 @@ var RuntimeImpl = class {
|
|
|
2546
3701
|
if (!record) throw new Error(`Image not found: ${imageId}`);
|
|
2547
3702
|
const container = await this.getOrCreateContainer(record.containerId);
|
|
2548
3703
|
const { agent, reused } = await container.runImage(record);
|
|
2549
|
-
|
|
3704
|
+
logger13.info("Message routed to agent", {
|
|
2550
3705
|
imageId,
|
|
2551
3706
|
agentId: agent.agentId,
|
|
2552
3707
|
reused,
|
|
@@ -2556,7 +3711,7 @@ var RuntimeImpl = class {
|
|
|
2556
3711
|
return { agentId: agent.agentId, imageId };
|
|
2557
3712
|
}
|
|
2558
3713
|
if (agentId) {
|
|
2559
|
-
|
|
3714
|
+
logger13.debug("Receiving message by agentId (legacy)", {
|
|
2560
3715
|
agentId,
|
|
2561
3716
|
contentLength: content.length,
|
|
2562
3717
|
requestId
|
|
@@ -2573,12 +3728,12 @@ var RuntimeImpl = class {
|
|
|
2573
3728
|
if (imageId) {
|
|
2574
3729
|
const foundAgentId = this.findAgentIdForImage(imageId);
|
|
2575
3730
|
if (!foundAgentId) {
|
|
2576
|
-
|
|
3731
|
+
logger13.debug("Image is offline, nothing to interrupt", { imageId });
|
|
2577
3732
|
return { imageId, agentId: void 0 };
|
|
2578
3733
|
}
|
|
2579
3734
|
const agent = this.findAgent(foundAgentId);
|
|
2580
3735
|
if (agent) {
|
|
2581
|
-
|
|
3736
|
+
logger13.info("Interrupting agent by imageId", {
|
|
2582
3737
|
imageId,
|
|
2583
3738
|
agentId: foundAgentId,
|
|
2584
3739
|
requestId
|
|
@@ -2590,7 +3745,7 @@ var RuntimeImpl = class {
|
|
|
2590
3745
|
if (agentId) {
|
|
2591
3746
|
const agent = this.findAgent(agentId);
|
|
2592
3747
|
if (!agent) throw new Error(`Agent not found: ${agentId}`);
|
|
2593
|
-
|
|
3748
|
+
logger13.info("Interrupting agent by agentId (legacy)", { agentId, requestId });
|
|
2594
3749
|
agent.interrupt(requestId);
|
|
2595
3750
|
const foundImageId = this.findImageIdForAgent(agentId);
|
|
2596
3751
|
return { agentId, imageId: foundImageId };
|
|
@@ -2599,32 +3754,32 @@ var RuntimeImpl = class {
|
|
|
2599
3754
|
},
|
|
2600
3755
|
// Image operations (new model)
|
|
2601
3756
|
createImage: async (containerId, config) => {
|
|
2602
|
-
|
|
3757
|
+
logger13.debug("Creating image", { containerId, name: config.name });
|
|
2603
3758
|
await this.getOrCreateContainer(containerId);
|
|
2604
3759
|
const image = await RuntimeImage.create(
|
|
2605
3760
|
{ containerId, ...config },
|
|
2606
3761
|
this.createImageContext()
|
|
2607
3762
|
);
|
|
2608
|
-
|
|
3763
|
+
logger13.info("Image created via RuntimeOps", { imageId: image.imageId, containerId });
|
|
2609
3764
|
return this.toImageListItemResult(image.toRecord(), false);
|
|
2610
3765
|
},
|
|
2611
3766
|
runImage: async (imageId) => {
|
|
2612
|
-
|
|
3767
|
+
logger13.debug("Running image", { imageId });
|
|
2613
3768
|
const record = await this.persistence.images.findImageById(imageId);
|
|
2614
3769
|
if (!record) throw new Error(`Image not found: ${imageId}`);
|
|
2615
3770
|
const container = await this.getOrCreateContainer(record.containerId);
|
|
2616
3771
|
const { agent, reused } = await container.runImage(record);
|
|
2617
|
-
|
|
3772
|
+
logger13.info("Image running", { imageId, agentId: agent.agentId, reused });
|
|
2618
3773
|
return { imageId, agentId: agent.agentId, reused };
|
|
2619
3774
|
},
|
|
2620
3775
|
stopImage: async (imageId) => {
|
|
2621
|
-
|
|
3776
|
+
logger13.debug("Stopping image", { imageId });
|
|
2622
3777
|
const record = await this.persistence.images.findImageById(imageId);
|
|
2623
3778
|
if (!record) throw new Error(`Image not found: ${imageId}`);
|
|
2624
3779
|
const container = this.containerRegistry.get(record.containerId);
|
|
2625
3780
|
if (container) {
|
|
2626
3781
|
await container.stopImage(imageId);
|
|
2627
|
-
|
|
3782
|
+
logger13.info("Image stopped via RuntimeOps", { imageId });
|
|
2628
3783
|
}
|
|
2629
3784
|
},
|
|
2630
3785
|
updateImage: async (imageId, updates) => {
|
|
@@ -2648,10 +3803,10 @@ var RuntimeImpl = class {
|
|
|
2648
3803
|
return this.toImageListItemResult(record, online);
|
|
2649
3804
|
},
|
|
2650
3805
|
deleteImage: async (imageId) => {
|
|
2651
|
-
|
|
3806
|
+
logger13.debug("Deleting image", { imageId });
|
|
2652
3807
|
const agentId = this.findAgentIdForImage(imageId);
|
|
2653
3808
|
if (agentId) {
|
|
2654
|
-
|
|
3809
|
+
logger13.debug("Stopping running agent before delete", { imageId, agentId });
|
|
2655
3810
|
for (const container of this.containerRegistry.values()) {
|
|
2656
3811
|
if (container.getAgent(agentId)) {
|
|
2657
3812
|
await container.destroyAgent(agentId);
|
|
@@ -2662,17 +3817,17 @@ var RuntimeImpl = class {
|
|
|
2662
3817
|
const image = await RuntimeImage.load(imageId, this.createImageContext());
|
|
2663
3818
|
if (image) {
|
|
2664
3819
|
await image.delete();
|
|
2665
|
-
|
|
3820
|
+
logger13.info("Image deleted via RuntimeOps", { imageId });
|
|
2666
3821
|
}
|
|
2667
3822
|
},
|
|
2668
3823
|
getImageMessages: async (imageId) => {
|
|
2669
|
-
|
|
3824
|
+
logger13.debug("Getting messages for image", { imageId });
|
|
2670
3825
|
const image = await RuntimeImage.load(imageId, this.createImageContext());
|
|
2671
3826
|
if (!image) {
|
|
2672
3827
|
throw new Error(`Image not found: ${imageId}`);
|
|
2673
3828
|
}
|
|
2674
3829
|
const messages = await image.getMessages();
|
|
2675
|
-
|
|
3830
|
+
logger13.debug("Got messages from storage", { imageId, count: messages.length });
|
|
2676
3831
|
return messages.map((m) => {
|
|
2677
3832
|
let content;
|
|
2678
3833
|
let role = m.role;
|
|
@@ -2789,14 +3944,14 @@ var RuntimeImpl = class {
|
|
|
2789
3944
|
}
|
|
2790
3945
|
// ==================== Lifecycle ====================
|
|
2791
3946
|
async dispose() {
|
|
2792
|
-
|
|
3947
|
+
logger13.info("Disposing RuntimeImpl");
|
|
2793
3948
|
this.commandHandler.dispose();
|
|
2794
3949
|
for (const container of this.containerRegistry.values()) {
|
|
2795
3950
|
await container.dispose();
|
|
2796
3951
|
}
|
|
2797
3952
|
this.bus.destroy();
|
|
2798
3953
|
this.containerRegistry.clear();
|
|
2799
|
-
|
|
3954
|
+
logger13.info("RuntimeImpl disposed");
|
|
2800
3955
|
}
|
|
2801
3956
|
};
|
|
2802
3957
|
|
|
@@ -2807,11 +3962,9 @@ function createRuntime(config) {
|
|
|
2807
3962
|
|
|
2808
3963
|
// src/internal/persistence/PersistenceImpl.ts
|
|
2809
3964
|
import { createStorage } from "unstorage";
|
|
2810
|
-
import { createLogger as createLogger15 } from "@agentxjs/common";
|
|
2811
3965
|
|
|
2812
3966
|
// src/internal/persistence/repository/StorageImageRepository.ts
|
|
2813
|
-
|
|
2814
|
-
var logger12 = createLogger12("persistence/ImageRepository");
|
|
3967
|
+
var logger14 = createLogger("persistence/ImageRepository");
|
|
2815
3968
|
var PREFIX = "images";
|
|
2816
3969
|
var INDEX_BY_NAME = "idx:images:name";
|
|
2817
3970
|
var INDEX_BY_CONTAINER = "idx:images:container";
|
|
@@ -2835,7 +3988,7 @@ var StorageImageRepository = class {
|
|
|
2835
3988
|
this.containerIndexKey(record.containerId, record.imageId),
|
|
2836
3989
|
record.imageId
|
|
2837
3990
|
);
|
|
2838
|
-
|
|
3991
|
+
logger14.debug("Image saved", { imageId: record.imageId });
|
|
2839
3992
|
}
|
|
2840
3993
|
async findImageById(imageId) {
|
|
2841
3994
|
const record = await this.storage.getItem(this.key(imageId));
|
|
@@ -2890,7 +4043,7 @@ var StorageImageRepository = class {
|
|
|
2890
4043
|
await this.storage.removeItem(this.nameIndexKey(record.name, imageId));
|
|
2891
4044
|
await this.storage.removeItem(this.containerIndexKey(record.containerId, imageId));
|
|
2892
4045
|
}
|
|
2893
|
-
|
|
4046
|
+
logger14.debug("Image deleted", { imageId });
|
|
2894
4047
|
}
|
|
2895
4048
|
async imageExists(imageId) {
|
|
2896
4049
|
return await this.storage.hasItem(this.key(imageId));
|
|
@@ -2909,13 +4062,12 @@ var StorageImageRepository = class {
|
|
|
2909
4062
|
updatedAt: Date.now()
|
|
2910
4063
|
};
|
|
2911
4064
|
await this.storage.setItem(this.key(imageId), updatedRecord);
|
|
2912
|
-
|
|
4065
|
+
logger14.debug("Image metadata updated", { imageId, metadata });
|
|
2913
4066
|
}
|
|
2914
4067
|
};
|
|
2915
4068
|
|
|
2916
4069
|
// src/internal/persistence/repository/StorageContainerRepository.ts
|
|
2917
|
-
|
|
2918
|
-
var logger13 = createLogger13("persistence/ContainerRepository");
|
|
4070
|
+
var logger15 = createLogger("persistence/ContainerRepository");
|
|
2919
4071
|
var PREFIX2 = "containers";
|
|
2920
4072
|
var StorageContainerRepository = class {
|
|
2921
4073
|
constructor(storage) {
|
|
@@ -2926,7 +4078,7 @@ var StorageContainerRepository = class {
|
|
|
2926
4078
|
}
|
|
2927
4079
|
async saveContainer(record) {
|
|
2928
4080
|
await this.storage.setItem(this.key(record.containerId), record);
|
|
2929
|
-
|
|
4081
|
+
logger15.debug("Container saved", { containerId: record.containerId });
|
|
2930
4082
|
}
|
|
2931
4083
|
async findContainerById(containerId) {
|
|
2932
4084
|
const record = await this.storage.getItem(this.key(containerId));
|
|
@@ -2945,7 +4097,7 @@ var StorageContainerRepository = class {
|
|
|
2945
4097
|
}
|
|
2946
4098
|
async deleteContainer(containerId) {
|
|
2947
4099
|
await this.storage.removeItem(this.key(containerId));
|
|
2948
|
-
|
|
4100
|
+
logger15.debug("Container deleted", { containerId });
|
|
2949
4101
|
}
|
|
2950
4102
|
async containerExists(containerId) {
|
|
2951
4103
|
return await this.storage.hasItem(this.key(containerId));
|
|
@@ -2953,8 +4105,7 @@ var StorageContainerRepository = class {
|
|
|
2953
4105
|
};
|
|
2954
4106
|
|
|
2955
4107
|
// src/internal/persistence/repository/StorageSessionRepository.ts
|
|
2956
|
-
|
|
2957
|
-
var logger14 = createLogger14("persistence/SessionRepository");
|
|
4108
|
+
var logger16 = createLogger("persistence/SessionRepository");
|
|
2958
4109
|
var PREFIX3 = "sessions";
|
|
2959
4110
|
var MESSAGES_PREFIX = "messages";
|
|
2960
4111
|
var INDEX_BY_IMAGE = "idx:sessions:image";
|
|
@@ -2985,7 +4136,7 @@ var StorageSessionRepository = class {
|
|
|
2985
4136
|
this.containerIndexKey(record.containerId, record.sessionId),
|
|
2986
4137
|
record.sessionId
|
|
2987
4138
|
);
|
|
2988
|
-
|
|
4139
|
+
logger16.debug("Session saved", { sessionId: record.sessionId });
|
|
2989
4140
|
}
|
|
2990
4141
|
async findSessionById(sessionId) {
|
|
2991
4142
|
const record = await this.storage.getItem(this.key(sessionId));
|
|
@@ -3034,7 +4185,7 @@ var StorageSessionRepository = class {
|
|
|
3034
4185
|
await this.storage.removeItem(this.imageIndexKey(record.imageId, sessionId));
|
|
3035
4186
|
await this.storage.removeItem(this.containerIndexKey(record.containerId, sessionId));
|
|
3036
4187
|
}
|
|
3037
|
-
|
|
4188
|
+
logger16.debug("Session deleted", { sessionId });
|
|
3038
4189
|
}
|
|
3039
4190
|
async sessionExists(sessionId) {
|
|
3040
4191
|
return await this.storage.hasItem(this.key(sessionId));
|
|
@@ -3044,13 +4195,13 @@ var StorageSessionRepository = class {
|
|
|
3044
4195
|
const messages = await this.getMessages(sessionId);
|
|
3045
4196
|
messages.push(message);
|
|
3046
4197
|
await this.storage.setItem(this.messagesKey(sessionId), messages);
|
|
3047
|
-
|
|
4198
|
+
logger16.debug("Message added to session", { sessionId, subtype: message.subtype });
|
|
3048
4199
|
}
|
|
3049
4200
|
async getMessages(sessionId) {
|
|
3050
4201
|
const messages = await this.storage.getItem(this.messagesKey(sessionId));
|
|
3051
4202
|
if (!messages || !Array.isArray(messages)) {
|
|
3052
4203
|
if (messages) {
|
|
3053
|
-
|
|
4204
|
+
logger16.warn("Messages data is not an array, resetting", {
|
|
3054
4205
|
sessionId,
|
|
3055
4206
|
type: typeof messages
|
|
3056
4207
|
});
|
|
@@ -3061,12 +4212,12 @@ var StorageSessionRepository = class {
|
|
|
3061
4212
|
}
|
|
3062
4213
|
async clearMessages(sessionId) {
|
|
3063
4214
|
await this.storage.removeItem(this.messagesKey(sessionId));
|
|
3064
|
-
|
|
4215
|
+
logger16.debug("Messages cleared for session", { sessionId });
|
|
3065
4216
|
}
|
|
3066
4217
|
};
|
|
3067
4218
|
|
|
3068
4219
|
// src/internal/persistence/PersistenceImpl.ts
|
|
3069
|
-
var
|
|
4220
|
+
var logger17 = createLogger("persistence/Persistence");
|
|
3070
4221
|
var PersistenceImpl = class _PersistenceImpl {
|
|
3071
4222
|
images;
|
|
3072
4223
|
containers;
|
|
@@ -3080,7 +4231,7 @@ var PersistenceImpl = class _PersistenceImpl {
|
|
|
3080
4231
|
this.images = new StorageImageRepository(this.storage);
|
|
3081
4232
|
this.containers = new StorageContainerRepository(this.storage);
|
|
3082
4233
|
this.sessions = new StorageSessionRepository(this.storage);
|
|
3083
|
-
|
|
4234
|
+
logger17.info("Persistence created", { driver: driverName });
|
|
3084
4235
|
}
|
|
3085
4236
|
/**
|
|
3086
4237
|
* Create a PersistenceImpl instance (async factory)
|
|
@@ -3101,7 +4252,7 @@ var PersistenceImpl = class _PersistenceImpl {
|
|
|
3101
4252
|
*/
|
|
3102
4253
|
async dispose() {
|
|
3103
4254
|
await this.storage.dispose();
|
|
3104
|
-
|
|
4255
|
+
logger17.info("Persistence disposed");
|
|
3105
4256
|
}
|
|
3106
4257
|
};
|
|
3107
4258
|
async function createStorageFromConfig(config) {
|